Skip to content

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

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

Merged
Merged
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
31 changes: 18 additions & 13 deletions lib/index.browser.tests.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
/**
* 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.
* 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,
* 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 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 @@ -1047,11 +1048,15 @@ describe('javascript-sdk (Browser)', function() {
const readyData = await client.onReady();
assert.equal(readyData.success, true);
assert.isUndefined(readyData.reason);
assert.isUndefined(client.odpManager);
sinon.assert.calledWith(logger.log, optimizelyFactory.enums.LOG_LEVEL.INFO, 'ODP Disabled.');

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.');
sinon.assert.calledWith(
logger.error,
optimizelyFactory.enums.ERROR_MESSAGES.ODP_EVENT_FAILED_ODP_MANAGER_MISSING
);
});

it('should log a warning when attempting to use an event batch size other than 1', async () => {
Expand Down
12 changes: 9 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 All @@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import logHelper from './modules/logging/logger';
import { getLogger, setErrorHandler, getErrorHandler, LogLevel } from './modules/logging';
import { LocalStoragePendingEventsDispatcher } from './modules/event_processor';
Expand Down Expand Up @@ -125,6 +126,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 +141,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
14 changes: 10 additions & 4 deletions lib/index.node.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
/****************************************************************************
* 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. *
* You may obtain a copy of the License at *
* *
* https://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, *
* 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 { getLogger, setErrorHandler, getErrorHandler, LogLevel, setLogHandler, setLogLevel } from './modules/logging';
import Optimizely from './optimizely';
import * as enums from './utils/enums';
Expand Down Expand Up @@ -101,6 +102,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 +117,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
34 changes: 17 additions & 17 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 }),
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';
27 changes: 19 additions & 8 deletions lib/optimizely/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/****************************************************************************
* Copyright 2020-2023, Optimizely, Inc. and contributors *
* Copyright 2020-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 @@ -178,10 +178,7 @@ export default class Optimizely implements Client {

const eventProcessorStartedPromise = this.eventProcessor.start();

const dependentPromises: Array<Promise<any>> = [
projectConfigManagerReadyPromise,
eventProcessorStartedPromise,
];
const dependentPromises: Array<Promise<any>> = [projectConfigManagerReadyPromise, eventProcessorStartedPromise];

if (config.odpManager?.initPromise) {
dependentPromises.push(config.odpManager.initPromise);
Expand Down Expand Up @@ -778,7 +775,12 @@ export default class Optimizely implements Client {
* type, or null if the feature key is invalid or
* the variable key is invalid
*/
getFeatureVariable(featureKey: string, variableKey: string, userId: string, attributes?: UserAttributes): FeatureVariableValue {
getFeatureVariable(
featureKey: string,
variableKey: string,
userId: string,
attributes?: UserAttributes
): FeatureVariableValue {
try {
if (!this.isValidInstance()) {
this.logger.log(LOG_LEVEL.ERROR, LOG_MESSAGES.INVALID_OBJECT, MODULE_NAME, 'getFeatureVariable');
Expand Down Expand Up @@ -1684,7 +1686,12 @@ export default class Optimizely implements Client {
const projectConfig = this.projectConfigManager.getConfig();
if (this.odpManager != null && projectConfig != null) {
this.odpManager.updateSettings(
new OdpConfig(projectConfig.publicKeyForOdp, projectConfig.hostForOdp, projectConfig.pixelUrlForOdp, projectConfig.allSegments)
new OdpConfig(
projectConfig.publicKeyForOdp,
projectConfig.hostForOdp,
projectConfig.pixelUrlForOdp,
projectConfig.allSegments
)
);
}
}
Expand Down Expand Up @@ -1758,6 +1765,10 @@ export default class Optimizely implements Client {
options?: Array<OptimizelySegmentOption>
): Promise<string[] | null> {
if (!this.odpManager) {
return null;
}

if (!this.odpManager.enabled) {
this.logger.error(ERROR_MESSAGES.ODP_FETCH_QUALIFIED_SEGMENTS_FAILED_ODP_MANAGER_MISSING);
return null;
}
Expand All @@ -1769,7 +1780,7 @@ export default class Optimizely implements Client {
* @returns {string|undefined} Currently provisioned VUID from local ODP Manager or undefined if
* ODP Manager has not been instantiated yet for any reason.
*/
getVuid(): string | undefined {
public getVuid(): string | undefined {
if (!this.odpManager) {
this.logger?.error('Unable to get VUID - ODP Manager is not instantiated yet.');
return undefined;
Expand Down