Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
b5fb7e6
WIP: ODP client shell
mikechu-optimizely Aug 16, 2022
5dfb285
Initial implementation of GraphQLManager
mikechu-optimizely Aug 18, 2022
f0e4af8
Rename files
mikechu-optimizely Aug 18, 2022
d32b9ca
WIP schema definition for ODP
mikechu-optimizely Aug 18, 2022
eba32d6
Merge branch 'master' into mike/ats-graphql
mikechu-optimizely Aug 18, 2022
9e7cbe7
Remove renamed files
mikechu-optimizely Aug 18, 2022
1dedf29
ODP response json schema
mikechu-optimizely Aug 18, 2022
68327ec
Add missing props to ODP response schema
mikechu-optimizely Aug 18, 2022
0d3818d
Adjust schema validator to handle injected schemas
mikechu-optimizely Aug 18, 2022
d6ce18a
Implement schema validation for ODP JSON response
mikechu-optimizely Aug 18, 2022
6ee6cb9
WIP Building ODP clients for browser and node
mikechu-optimizely Aug 18, 2022
c132826
Use Axios to support browser and node ODP calls
mikechu-optimizely Aug 19, 2022
a903a70
WIP GraphQLManager testing
mikechu-optimizely Aug 19, 2022
2c7b898
Corrected ODP response schema
mikechu-optimizely Aug 19, 2022
4162506
Handle all non-200 HTTP statuses
mikechu-optimizely Aug 19, 2022
3700344
WIP ODP client test starts
mikechu-optimizely Aug 19, 2022
562581b
Add ODP tests
mikechu-optimizely Aug 22, 2022
3ffd5b1
Switch to using toHaveLength
mikechu-optimizely Aug 22, 2022
f76e131
Fix tests
mikechu-optimizely Aug 22, 2022
2f5af44
Exchange Axios for fetch
mikechu-optimizely Aug 23, 2022
808daac
Resolve code review requests
mikechu-optimizely Aug 24, 2022
5737d21
More code review changes
mikechu-optimizely Aug 24, 2022
fa576b2
Refactors to remove warns
mikechu-optimizely Aug 24, 2022
8e409a8
Pull out fetch & put axios back in
mikechu-optimizely Aug 25, 2022
99e644b
Remove Axios again
mikechu-optimizely Aug 26, 2022
3c201ab
Remove axios from code (WIP tests failing)
mikechu-optimizely Aug 26, 2022
766eb87
WIP (tests failing) Browser vs Node request handling
mikechu-optimizely Aug 26, 2022
45d4ce1
WIP still: cleaned code a bit; tests need attn
mikechu-optimizely Aug 26, 2022
f8557f8
Fix enum string
mikechu-optimizely Aug 26, 2022
4214b91
Merge branch 'master' into mike/ats-graphql
mikechu-optimizely Aug 26, 2022
c4a873b
Trying to get timeout test working
mikechu-optimizely Aug 26, 2022
dba12f3
ODP tests
mikechu-optimizely Aug 29, 2022
738f9ec
WIP nodeRequestHandler tests
mikechu-optimizely Aug 29, 2022
807e257
Handle node request timeouts with tests
mikechu-optimizely Aug 30, 2022
c3c8540
BroswerRequestHandler tests
mikechu-optimizely Aug 30, 2022
c0e427b
Document RequestHandlers
mikechu-optimizely Aug 30, 2022
b8ba347
ODP Client & GraphQL jsdoc
mikechu-optimizely Aug 30, 2022
ef8dc52
Remove `any` in `catch`
mikechu-optimizely Aug 30, 2022
e825064
Revert "Remove `any` in `catch`"
mikechu-optimizely Aug 30, 2022
a07c905
Update packages/optimizely-sdk/lib/plugins/odp/graphql_manager.ts
mikechu-optimizely Aug 30, 2022
6134d84
Update packages/optimizely-sdk/lib/plugins/odp/graphql_manager.ts
mikechu-optimizely Aug 30, 2022
5d0ebb2
Update packages/optimizely-sdk/lib/plugins/odp/query_segments_paramet…
mikechu-optimizely Aug 30, 2022
8308a53
Code review changes
mikechu-optimizely Aug 31, 2022
b4ed7bd
Remove throwError
mikechu-optimizely Aug 31, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ describe('lib/core/project_config/project_config_manager', function() {
var errorMessage = globalStubErrorHandler.handleError.lastCall.args[0].message;
assert.strictEqual(
errorMessage,
sprintf(ERROR_MESSAGES.INVALID_DATAFILE, 'JSON_SCHEMA_VALIDATOR', 'projectId', 'is missing and it is required')
sprintf(ERROR_MESSAGES.INVALID_DATAFILE, 'JSON_SCHEMA_VALIDATOR (Project Config JSON Schema)', 'projectId', 'is missing and it is required'),
);
return manager.onReady().then(function(result) {
assert.include(result, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { JSONSchema4 } from 'json-schema';

var schemaDefinition = {
$schema: 'http://json-schema.org/draft-04/schema#',
title: 'Project Config JSON Schema',
type: 'object',
properties: {
projectId: {
Expand Down
89 changes: 89 additions & 0 deletions packages/optimizely-sdk/lib/plugins/odp/graphql_manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* Copyright 2022, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { ConsoleLogHandler, LogHandler, LogLevel } from '../../modules/logging';
import { Response } from './odp_types';
import { IOdpClient, OdpClient } from './odp_client';
import { validate } from '../../utils/json_schema_validator';
import { OdpResponseSchema } from './odp_response_schema';
import { QuerySegmentsParameters } from './query_segments_parameters';

const QUALIFIED = 'qualified';

export interface IGraphQLManager {
fetchSegments(apiKey: string, apiHost: string, userKey: string, userValue: string, segmentToCheck: string[]): Promise<string[]>;
}

export class GraphqlManager implements IGraphQLManager {
private readonly _logger: LogHandler;
private readonly _odpClient: IOdpClient;

constructor(logger: LogHandler, client: IOdpClient) {
this._logger = logger ?? new ConsoleLogHandler();
this._odpClient = client ?? new OdpClient(this._logger);
}

public async fetchSegments(apiKey: string, apiHost: string, userKey: string, userValue: string, segmentToCheck: string[]): Promise<string[]> {
const parameters = new QuerySegmentsParameters({
ApiKey: apiKey,
ApiHost: apiHost,
UserKey: userKey,
UserValue: userValue,
SegmentsToCheck: segmentToCheck,
});
const segmentsResponse = await this._odpClient.querySegments(parameters);
if (!segmentsResponse) {
this._logger.log(LogLevel.ERROR, 'Audience segments fetch failed (network error)');
return [] as string[];
}

const parsedSegments = this.parseSegmentsResponseJson(segmentsResponse);
if (!parsedSegments) {
this._logger.log(LogLevel.ERROR, 'Audience segments fetch failed (decode error)');
return [] as string[];
}

if (parsedSegments.errors?.length > 0) {
const errors = parsedSegments.errors.map((e) => e.message).join(';');

this._logger.log(LogLevel.WARNING, `Audience segments fetch failed (${errors})`);

return [] as string[];
}

if (parsedSegments?.data?.customer?.audiences?.edges === null) {
this._logger.log(LogLevel.WARNING, 'Audience segments fetch failed (decode error)');

return [] as string[];
}

return parsedSegments.data.customer.audiences.edges.filter(edge => edge.node.state == QUALIFIED).map(edge => edge.node.name);
}

private parseSegmentsResponseJson(jsonResponse: string): Response | undefined {
let jsonObject = {};
try {
jsonObject = JSON.parse(jsonResponse);
} catch {
this._logger.log(LogLevel.ERROR, 'Attempted to parse invalid segment response JSON.');
return;
}
if (validate(jsonObject, OdpResponseSchema, false)) {
return jsonObject as Response;
}
return;
}
}
64 changes: 64 additions & 0 deletions packages/optimizely-sdk/lib/plugins/odp/odp_client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* Copyright 2022, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { LogHandler, LogLevel } from '../../modules/logging';
import { QuerySegmentsParameters } from './query_segments_parameters';

export interface IOdpClient {
querySegments(parameters: QuerySegmentsParameters): Promise<string | undefined>;
}

export class OdpClient implements IOdpClient {
private readonly _logger: LogHandler;

constructor(logger: LogHandler) {
this._logger = logger;
}

public async querySegments(parameters: QuerySegmentsParameters): Promise<string | undefined> {
const emptyResponse = undefined;

if (!parameters?.ApiHost || !parameters?.ApiKey) {
this._logger.log(LogLevel.ERROR, 'No ApiHost or ApiKey set before querying segments');
return emptyResponse;
}

const fetchFailureMessage = 'Audience segments fetch failed';

const method = 'POST';
const headers = {
'Content-Type': 'application/json',
'x-api-key': parameters.ApiKey,
};
const body = parameters.ToJson();

let response: Response;

try {
response = await fetch(parameters.ApiHost, { method, headers, body });
} catch (error) {
this._logger.log(LogLevel.ERROR, `${fetchFailureMessage} (network error)`);
return emptyResponse;
}

if (!response.ok) {
this._logger.log(LogLevel.ERROR, `${fetchFailureMessage} (${response?.status ?? 'network error'})`);
return emptyResponse;
}

return response.json();
}
}
186 changes: 186 additions & 0 deletions packages/optimizely-sdk/lib/plugins/odp/odp_response_schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
/**
* Copyright 2022, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { JSONSchema4 } from 'json-schema';

/**
* ODP Response JSON Schema file used to validate the project json datafile
*/
export const OdpResponseSchema = {
$schema: 'https://json-schema.org/draft/2019-09/schema',
$id: 'https://example.com/example.json',
title: 'ODP Response Schema',
type: 'object',
required: [
'data',
],
properties: {
data: {
title: 'The data Schema',
type: 'object',
required: [
'customer',
],
properties: {
customer: {
title: 'The customer Schema',
type: 'object',
required: [ ],
properties: {
audiences: {
title: 'The audiences Schema',
type: 'object',
required: [
'edges',
],
properties: {
edges: {
title: 'The edges Schema',
type: 'array',
items: {
title: 'A Schema',
type: 'object',
required: [
'node',
],
properties: {
node: {
title: 'The node Schema',
type: 'object',
required: [
'name',
'state',
],
properties: {
name: {
title: 'The name Schema',
type: 'string',
examples: [
'has_email',
'has_email_opted_in',
],
},
state: {
title: 'The state Schema',
type: 'string',
examples: [
'qualified',
],
},
},
examples: [],
},
},
examples: [],
},
examples: [],
},
},
examples: [],
},
},
examples: [],
},
},
examples: [],
},
errors: {
title: 'The errors Schema',
type: 'array',
default: [],
items: {
title: 'A Schema',
type: 'object',
required: [
'message',
'locations',
'extensions'
],
properties: {
message: {
title: 'The message Schema',
type: 'string',
examples: [
'Exception while fetching data (/customer) : java.lang.RuntimeException: could not resolve _fs_user_id = asdsdaddddd'
]
},
locations: {
title: 'The locations Schema',
type: 'array',
items: {
title: 'A Schema',
type: 'object',
required: [
'line',
'column'
],
properties: {
line: {
title: 'The line Schema',
type: 'integer',
examples: [
2
]
},
column: {
title: 'The column Schema',
type: 'integer',
examples: [
3
]
}
},
examples: []
},
examples: []
},
path: {
title: 'The path Schema',
type: 'array',
items: {
title: 'A Schema',
type: 'string',
examples: [
'customer'
]
},
examples: []
},
extensions: {
title: 'The extensions Schema',
type: 'object',
required: [
'classification'
],
properties: {
classification: {
title: 'The classification Schema',
type: 'string',
examples: [
'InvalidIdentifierException'
]
}
},
examples: []
}
},
examples: []
},
examples: []
},
},
examples: [],
} as JSONSchema4;
Loading