8000 feat: Add ODP GraphQL AP Interface by mikechu-optimizely · Pull Request #778 · optimizely/javascript-sdk · GitHub
[go: up one dir, main page]

Skip to content

feat: Add ODP GraphQL AP Interface #778

New issue

Have a question about this project? Sign up for a free GitHub a 10000 ccount to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 44 commits into from
Aug 31, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
15 changes: 11 additions & 4 deletions packages/optimizely-sdk/lib/index.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* 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,
Expand All @@ -18,9 +18,9 @@ import {
getLogger,
setErrorHandler,
getErrorHandler,
LogLevel
LogLevel,
} from './modules/logging';
import { LocalStoragePendingEventsDispatcher } from '../lib/modules/event_processor';
import { LocalStoragePendingEventsDispatcher } from './modules/event_processor';
import configValidator from './utils/config_validator';
import defaultErrorHandler from './plugins/error_handler';
import defaultEventDispatcher from './plugins/event_dispatcher/index.browser';
Expand All @@ -32,6 +32,8 @@ import { createNotificationCenter } from './core/notification_center';
import { default as eventProcessor } from './plugins/event_processor';
import { OptimizelyDecideOption, Client, Config } from './shared_types';
import { createHttpPollingDatafileManager } from './plugins/datafile_manager/http_polling_datafile_manager';
import { EXECUTION_CONTEXT_TYPE } from './utils/enums';
import { ExecutionContext } from './utils/execution_context';

const logger = getLogger();
logHelper.setLogHandler(loggerPlugin.createLogger());
Expand All @@ -44,11 +46,13 @@ const DEFAULT_EVENT_MAX_QUEUE_SIZE = 10000;

let hasRetriedEvents = false;

ExecutionContext.Current = EXECUTION_CONTEXT_TYPE.BROWSER;

/**
* Creates an instance of the Optimizely class
* @param {Config} config
* @return {Client|null} the Optimizely client object
* null on error
* null on error
*/
const createInstance = function(config: Config): Client | null {
try {
Expand All @@ -70,6 +74,7 @@ const createInstance = function(config: Config): Client | null {
try {
configValidator.validate(config);
isValidInstance = true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (ex: any) {
logger.error(ex);
}
Expand Down Expand Up @@ -141,11 +146,13 @@ const createInstance = function(config: Config): Client | null {
false
);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
logger.error(enums.LOG_MESSAGES.UNABLE_TO_ATTACH_UNLOAD, MODULE_NAME, e.message);
}

return optimizely;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
logger.error(e);
return null;
Expand Down
12 changes: 9 additions & 3 deletions packages/optimizely-sdk/lib/index.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* 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, *
Expand All @@ -32,6 +32,8 @@ import { createNotificationCenter } from './core/notification_center';
import { createEventProcessor } from './plugins/event_processor';
import { OptimizelyDecideOption, Client, Config } from './shared_types';
import { createHttpPollingDatafileManager } from './plugins/datafile_manager/http_polling_datafile_manager';
import { ExecutionContext } from './utils/execution_context';
import { EXECUTION_CONTEXT_TYPE } from './utils/enums';

const logger = getLogger();
setLogLevel(LogLevel.ERROR);
Expand All @@ -40,13 +42,15 @@ const DEFAULT_EVENT_BATCH_SIZE = 10;
const DEFAULT_EVENT_FLUSH_INTERVAL = 30000; // Unit is ms, default is 30s
const DEFAULT_EVENT_MAX_QUEUE_SIZE = 10000;

ExecutionContext.Current = EXECUTION_CONTEXT_TYPE.NODE;

/**
* Creates an instance of the Optimizely class
* @param {Config} config
* @return {Client|null} the Optimizely client object
* null on error
* null on error
*/
const createInstance = function(config: Config): Client | null {
const createInstance = function(config: Config): Client | null {
try {
let hasLogger = false;
let isValidInstance = false;
Expand All @@ -68,6 +72,7 @@ const DEFAULT_EVENT_MAX_QUEUE_SIZE = 10000;
try {
configValidator.validate(config);
isValidInstance = true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (ex: any) {
if (hasLogger) {
logger.error(ex);
Expand Down Expand Up @@ -117,6 +122,7 @@ const DEFAULT_EVENT_MAX_QUEUE_SIZE = 10000;
};

return new Optimizely(optimizelyOptions);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
logger.error(e);
return null;
Expand Down
12 changes: 9 additions & 3 deletions packages/optimizely-sdk/lib/index.react_native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* 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,
Expand All @@ -32,6 +32,8 @@ import { createNotificationCenter } from './core/notification_center';
import { createEventProcessor } from './plugins/event_processor/index.react_native';
import { OptimizelyDecideOption, Client, Config } from './shared_types';
import { createHttpPollingDatafileManager } from './plugins/datafile_manager/http_polling_datafile_manager';
import { EXECUTION_CONTEXT_TYPE } from './utils/enums';
import { ExecutionContext } from './utils/execution_context';

const logger = getLogger();
setLogHandler(loggerPlugin.createLogger());
Expand All @@ -41,13 +43,15 @@ const DEFAULT_EVENT_BATCH_SIZE = 10;
const DEFAULT_EVENT_FLUSH_INTERVAL = 1000; // Unit is ms, default is 1s
const DEFAULT_EVENT_MAX_QUEUE_SIZE = 10000;

ExecutionContext.Current = EXECUTION_CONTEXT_TYPE.BROWSER;

/**
* Creates an instance of the Optimizely class
* @param {Config} config
* @return {Client|null} the Optimizely client object
* null on error
* null on error
*/
const createInstance = function(config: Config): Client | null {
const createInstance = function(config: Config): Client | null {
try {
// TODO warn about setting per instance errorHandler / logger / logLevel
let isValidInstance = false;
Expand All @@ -67,6 +71,7 @@ const DEFAULT_EVENT_MAX_QUEUE_SIZE = 10000;
try {
configValidator.validate(config);
isValidInstance = true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (ex: any) {
logger.error(ex);
}
Expand Down Expand Up @@ -117,6 +122,7 @@ const DEFAULT_EVENT_MAX_QUEUE_SIZE = 10000;
}

return new Optimizely(optimizelyOptions);
< EF5E /td> // eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
logger.error(e);
return null;
Expand Down
137 changes: 137 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,137 @@
/**
* 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 { ErrorHandler, 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';
import { RequestHandlerFactory } from '../../utils/http_request_handler/request_handler_factory';

/**
* Expected value for a qualified/valid segment
*/
const QUALIFIED = 'qualified';
/**
* Return value when no valid segments found
*/
const EMPTY_SEGMENTS_COLLECTION: string[] = [];
/**
* Return value for scenarios with no valid JSON
*/
const EMPTY_JSON_RESPONSE = null;

/**
* Manager for communicating with the Optimizely Data Platform GraphQL endpoint
*/
export interface IGraphQLManager {
fetchSegments(apiKey: string, apiHost: string, userKey: string, userValue: string, segmentsToCheck: string[]): Promise<string[]>;
}

/**
* Concrete implementation for communicating with the Optimizely Data Platform GraphQL endpoint
*/
export class GraphqlManager implements IGraphQLManager {
private readonly _errorHandler: ErrorHandler;
private readonly _logger: LogHandler;
private readonly _odpClient: IOdpClient;

/**
* Retrieves the audience segments from the Optimizely Data Platform (ODP)
* @param errorHandler Handler to record exceptions
* @param logger Collect and record events/errors for this GraphQL implementation
* @param client Client to use to send queries to ODP
*/
constructor(errorHandler: ErrorHandler, logger: LogHandler, client?: IOdpClient) {
this._errorHandler = errorHandler;
this._logger = logger;

this._odpClient = client ?? new OdpClient(this._errorHandler,
this._logger,
RequestHandlerFactory.createHandler(this._logger));
}

/**
* Retrieves the audience segments from ODP
* @param apiKey ODP public key
* @param apiHost Fully-qualified URL of ODP
* @param userKey 'vuid' or 'fs_user_id key'
* @param userValue Associated value to query for the user key
* @param segmentsToCheck Audience segments to check for experiment inclusion
*/
public async fetchSegments(apiKey: string, apiHost: string, userKey: string, userValue: string, segmentsToCheck: string[]): Promise<string[]> {
const parameters = new QuerySegmentsParameters({
apiKey,
apiHost,
userKey,
userValue,
1C6A segmentsToCheck,
});
const segmentsResponse = await this._odpClient.querySegments(parameters);
if (!segmentsResponse) {
this._logger.log(LogLevel.ERROR, 'Audience segments fetch failed (network error)');
return EMPTY_SEGMENTS_COLLECTION;
}

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

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 EMPTY_SEGMENTS_COLLECTION;
}

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

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

/**
* Parses JSON response
* @param jsonResponse JSON response from ODP
* @private
* @returns Response Strongly-typed ODP Response object
*/
private parseSegmentsResponseJson(jsonResponse: string): Response | null {
let jsonObject = {};

try {
jsonObject = JSON.parse(jsonResponse);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
this._errorHandler.handleError(error);
this._logger.log(LogLevel.ERROR, 'Attempted to parse invalid segment response JSON.');
return EMPTY_JSON_RESPONSE;
}

if (validate(jsonObject, OdpResponseSchema, false)) {
return jsonObject as Response;
}

return EMPTY_JSON_RESPONSE;
}
}
Loading
0