Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account 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

[FSSDK-9987] fix: Conditional ODP instantiation #895

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
10 changes: 5 additions & 5 deletions .github/workflows/javascript.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ jobs:
- name: Set up Node
uses: actions/setup-node@v3
with:
node-version: 14
cache-dependency-path: ./package-lock.json
cache: 'npm'
- name: Run linting
Expand Down Expand Up @@ -46,11 +45,11 @@ jobs:
BROWSER_STACK_USERNAME: ${{ secrets.BROWSERSTACK_USERNAME }}
BROWSER_STACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}
steps:
- uses: actions/checkout@v3
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Node
uses: actions/setup-node@v3
with:
node-version: 14
cache: 'npm'
cache-dependency-path: ./package-lock.json
- name: Cross-browser and umd unit tests
Expand All @@ -63,9 +62,10 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
node: ['14', '16', '18' ]
node: [ '16', '18' ]
steps:
- uses: actions/checkout@v3
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Node ${{ matrix.node }}
uses: actions/setup-node@v3
with:
Expand Down
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"jest.rootPath": "/workspaces/javascript-sdk/packages/optimizely-sdk",
"jest.rootPath": ".",
"jest.jestCommandLine": "./node_modules/.bin/jest",
"jest.autoRevealOutput": "on-exec-error",
"editor.tabSize": 2
Expand Down
43 changes: 9 additions & 34 deletions lib/core/odp/odp_manager.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2023, Optimizely
* Copyright 2023-2024, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -34,8 +34,6 @@ import { OdpEvent } from './odp_event';
export interface IOdpManager {
initPromise?: Promise<void>;

enabled: boolean;

segmentManager: IOdpSegmentManager | undefined;

eventManager: IOdpEventManager | undefined;
Expand Down Expand Up @@ -64,11 +62,6 @@ export abstract class OdpManager implements IOdpManager {
*/
initPromise?: Promise<void>;

/**
* Switch to enable/disable ODP Manager functionality
*/
enabled = true;

/**
* ODP Segment Manager which provides an interface to the remote ODP server (GraphQL API) for audience segments mapping.
* It fetches all qualified segments for the given user context and manages the segments cache for all user contexts.
Expand Down Expand Up @@ -98,10 +91,6 @@ export abstract class OdpManager implements IOdpManager {
* Provides a method to update ODP Manager's ODP Config API Key, API Host, and Audience Segments
*/
updateSettings({ apiKey, apiHost, pixelUrl, segmentsToCheck }: OdpConfig): boolean {
if (!this.enabled) {
return false;
}

if (!this.eventManager) {
this.logger.log(LogLevel.ERROR, ERROR_MESSAGES.ODP_MANAGER_UPDATE_SETTINGS_FAILED_EVENT_MANAGER_MISSING);
return false;
Expand Down Expand Up @@ -130,10 +119,6 @@ export abstract class OdpManager implements IOdpManager {
* Attempts to stop the current instance of ODP Manager's event manager, if it exists and is running.
*/
close(): void {
if (!this.enabled) {
return;
}

this.eventManager?.stop();
}

Expand All @@ -145,11 +130,6 @@ export abstract class OdpManager implements IOdpManager {
* @returns {Promise<string[] | null>} A promise holding either a list of qualified segments or null.
*/
async fetchQualifiedSegments(userId: string, options: Array<OptimizelySegmentOption> = []): Promise<string[] | null> {
if (!this.enabled) {
this.logger.log(LogLevel.ERROR, ERROR_MESSAGES.ODP_NOT_ENABLED);
return null;
}

if (!this.segmentManager) {
this.logger.log(LogLevel.ERROR, ERROR_MESSAGES.ODP_FETCH_QUALIFIED_SEGMENTS_SEGMENTS_MANAGER_MISSING);
return null;
Expand All @@ -169,11 +149,6 @@ export abstract class OdpManager implements IOdpManager {
* @returns
*/
identifyUser(userId?: string, vuid?: string): void {
if (!this.enabled) {
this.logger.log(LogLevel.DEBUG, LOG_MESSAGES.ODP_IDENTIFY_FAILED_ODP_DISABLED);
return;
}

if (!this.odpConfig.isReady()) {
this.logger.log(LogLevel.DEBUG, LOG_MESSAGES.ODP_IDENTIFY_FAILED_ODP_NOT_INTEGRATED);
return;
Expand Down Expand Up @@ -203,24 +178,24 @@ export abstract class OdpManager implements IOdpManager {
mType = 'fullstack';
}

if (!this.enabled) {
throw new Error(ERROR_MESSAGES.ODP_NOT_ENABLED);
}

if (!this.odpConfig.isReady()) {
throw new Error(ERROR_MESSAGES.ODP_NOT_INTEGRATED);
this.logger.log(LogLevel.ERROR, ERROR_MESSAGES.ODP_NOT_INTEGRATED);
return;
}

if (invalidOdpDataFound(data)) {
throw new Error(ERROR_MESSAGES.ODP_INVALID_DATA);
this.logger.log(LogLevel.ERROR, ERROR_MESSAGES.ODP_INVALID_DATA);
return;
}

if (!this.eventManager) {
throw new Error(ERROR_MESSAGES.ODP_SEND_EVENT_FAILED_EVENT_MANAGER_MISSING);
this.logger.log(LogLevel.ERROR, ERROR_MESSAGES.ODP_SEND_EVENT_FAILED_EVENT_MANAGER_MISSING);
return;
}

if (typeof action !== 'string' || action === '') {
throw new Error('ODP action is not valid (cannot be empty).');
this.logger.log(LogLevel.ERROR, 'ODP action is not valid (cannot be empty).');
return;
}

this.eventManager.sendEvent(new OdpEvent(mType, action, identifiers, data));
Expand Down
22 changes: 11 additions & 11 deletions lib/index.browser.tests.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2016-2020, 2022-2023 Optimizely
* Copyright 2016-2020, 2022-2024 Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import logging, { getLogger } from './modules/logging/logger';

import { assert } from 'chai';
Expand Down Expand Up @@ -67,7 +68,7 @@ if (!global.window) {
}
}

const pause = (timeoutMilliseconds) => {
const pause = timeoutMilliseconds => {
return new Promise(resolve => setTimeout(resolve, timeoutMilliseconds));
};

Expand Down Expand Up @@ -846,19 +847,19 @@ describe('javascript-sdk (Browser)', function() {
const userAgentParser = {
parseUserAgentInfo() {
return {
os: { 'name': 'windows', 'version': '11' },
device: { 'type': 'laptop', 'model': 'thinkpad' },
}
}
}
os: { name: 'windows', version: '11' },
device: { type: 'laptop', model: 'thinkpad' },
};
},
};

const fakeRequestHandler = {
makeRequest: sinon.spy(function (requestUrl, headers, method, data) {
makeRequest: sinon.spy(function(requestUrl, headers, method, data) {
return {
abort: () => {},
responsePromise: Promise.resolve({ statusCode: 200 }),
}
})
};
}),
};

const client = optimizelyFactory.createInstance({
Expand Down Expand Up @@ -1050,7 +1051,6 @@ describe('javascript-sdk (Browser)', function() {

client.sendOdpEvent(ODP_EVENT_ACTION.INITIALIZED);

sinon.assert.calledWith(logger.error, 'ODP event send failed.');
sinon.assert.calledWith(logger.log, optimizelyFactory.enums.LOG_LEVEL.INFO, 'ODP Disabled.');
});

Expand Down
11 changes: 8 additions & 3 deletions lib/index.browser.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2016-2017, 2019-2023 Optimizely
* Copyright 2016-2017, 2019-2024 Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -125,6 +125,11 @@ const createInstance = function(config: Config): Client | null {
notificationCenter,
};

const odpExplicitlyOff = config.odpOptions?.disabled === true;
if (odpExplicitlyOff) {
logger.info(enums.LOG_MESSAGES.ODP_DISABLED);
}

const optimizelyOptions: OptimizelyOptions = {
clientEngine: enums.JAVASCRIPT_CLIENT_ENGINE,
...config,
Expand All @@ -135,8 +140,8 @@ const createInstance = function(config: Config): Client | null {
? createHttpPollingDatafileManager(config.sdkKey, logger, config.datafile, config.datafileOptions)
: undefined,
notificationCenter,
isValidInstance: isValidInstance,
odpManager: new BrowserOdpManager({ logger, odpOptions: config.odpOptions }),
isValidInstance,
odpManager: odpExplicitlyOff ? undefined : new BrowserOdpManager({ logger, odpOptions: config.odpOptions }),
};

const optimizely = new Optimizely(optimizelyOptions);
Expand Down
11 changes: 8 additions & 3 deletions lib/index.node.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/****************************************************************************
* Copyright 2016-2017, 2019-2023 Optimizely, Inc. and contributors *
* Copyright 2016-2017, 2019-2024 Optimizely, Inc. and contributors *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
Expand Down Expand Up @@ -101,6 +101,11 @@ const createInstance = function(config: Config): Client | null {

const eventProcessor = createEventProcessor(eventProcessorConfig);

const odpExplicitlyOff = config.odpOptions?.disabled === true;
if (odpExplicitlyOff) {
logger.info(enums.LOG_MESSAGES.ODP_DISABLED);
}

const optimizelyOptions = {
clientEngine: enums.NODE_CLIENT_ENGINE,
...config,
Expand All @@ -111,8 +116,8 @@ const createInstance = function(config: Config): Client | null {
? createHttpPollingDatafileManager(config.sdkKey, logger, config.datafile, config.datafileOptions)
: undefined,
notificationCenter,
isValidInstance: isValidInstance,
odpManager: new NodeOdpManager({ logger, odpOptions: config.odpOptions }),
isValidInstance,
odpManager: odpExplicitlyOff ? undefined : new NodeOdpManager({ logger, odpOptions: config.odpOptions }),
};

return new Optimizely(optimizelyOptions);
Expand Down
36 changes: 18 additions & 18 deletions lib/index.react_native.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2019-2023, Optimizely
* Copyright 2019-2024, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -13,14 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
getLogger,
setErrorHandler,
getErrorHandler,
LogLevel,
setLogHandler,
setLogLevel
} from './modules/logging';

import { getLogger, setErrorHandler, getErrorHandler, LogLevel, setLogHandler, setLogLevel } from './modules/logging';
import * as enums from './utils/enums';
import Optimizely from './optimizely';
import configValidator from './utils/config_validator';
Expand All @@ -31,8 +25,7 @@ import eventProcessorConfigValidator from './utils/event_processor_config_valida
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/react_native_http_polling_datafile_manager';
import { createHttpPollingDatafileManager } from './plugins/datafile_manager/react_native_http_polling_datafile_manager';
import { BrowserOdpManager } from './plugins/odp_manager/index.browser';
import * as commonExports from './common_exports';

Expand Down Expand Up @@ -71,7 +64,7 @@ const createInstance = function(config: Config): Client | null {
configValidator.validate(config);
isValidInstance = true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (ex: any) {
} catch (ex) {
logger.error(ex);
}

Expand Down Expand Up @@ -100,20 +93,27 @@ const createInstance = function(config: Config): Client | null {
batchSize: eventBatchSize,
maxQueueSize: config.eventMaxQueueSize || DEFAULT_EVENT_MAX_QUEUE_SIZE,
notificationCenter,
}
};

const eventProcessor = createEventProcessor(eventProcessorConfig);

const odpExplicitlyOff = config.odpOptions?.disabled === true;
if (odpExplicitlyOff) {
logger.info(enums.LOG_MESSAGES.ODP_DISABLED);
}

const optimizelyOptions = {
clientEngine: enums.REACT_NATIVE_JS_CLIENT_ENGINE,
...config,
eventProcessor,
logger,
errorHandler,
datafileManager: config.sdkKey ? createHttpPollingDatafileManager(config.sdkKey, logger, config.datafile, config.datafileOptions) : undefined,
datafileManager: config.sdkKey
? createHttpPollingDatafileManager(config.sdkKey, logger, config.datafile, config.datafileOptions)
: undefined,
notificationCenter,
isValidInstance: isValidInstance,
odpManager: new BrowserOdpManager({ logger, odpOptions: config.odpOptions }),
isValidInstance,
odpManager: odpExplicitlyOff ? undefined : new BrowserOdpManager({ logger, odpOptions: config.odpOptions }),
};

// If client engine is react, convert it to react native.
Expand All @@ -123,7 +123,7 @@ const createInstance = function(config: Config): Client | null {

return new Optimizely(optimizelyOptions);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
} catch (e) {
logger.error(e);
return null;
}
Expand Down Expand Up @@ -157,4 +157,4 @@ export default {
OptimizelyDecideOption,
};

export * from './export_types'
export * from './export_types';
Loading
Loading