Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* Copyright 2023, 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
*
* 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 { expect } from 'chai';

import { NotificationRegistry } from './notification_registry';

describe('Notification Registry', () => {
it('Returns null notification center when SDK Key is null', () => {
const notificationCenter = NotificationRegistry.getNotificationCenter();
expect(notificationCenter).to.be.null;
});

it('Returns the same notification center when SDK Keys are the same and not null', () => {
const sdkKey = 'testSDKKey';
const notificationCenterA = NotificationRegistry.getNotificationCenter(sdkKey);
const notificationCenterB = NotificationRegistry.getNotificationCenter(sdkKey);
expect(notificationCenterA).to.eql(notificationCenterB);
});

it('Returns different notification centers when SDK Keys are not the same', () => {
const sdkKeyA = 'testSDKKeyA';
const sdkKeyB = 'testSDKKeyB';
const notificationCenterA = NotificationRegistry.getNotificationCenter(sdkKeyA);
const notificationCenterB = NotificationRegistry.getNotificationCenter(sdkKeyB);
expect(notificationCenterA).to.not.eql(notificationCenterB);
});

it('Removes old notification centers from the registry when removeNotificationCenter is called on the registry', () => {
const sdkKey = 'testSDKKey';
const notificationCenterA = NotificationRegistry.getNotificationCenter(sdkKey);
NotificationRegistry.removeNotificationCenter(sdkKey);

const notificationCenterB = NotificationRegistry.getNotificationCenter(sdkKey);

expect(notificationCenterA).to.not.eql(notificationCenterB);
});

it('Does not throw an error when calling removeNotificationCenter with a null SDK Key', () => {
const sdkKey = 'testSDKKey';
const notificationCenterA = NotificationRegistry.getNotificationCenter(sdkKey);
NotificationRegistry.removeNotificationCenter();

const notificationCenterB = NotificationRegistry.getNotificationCenter(sdkKey);

expect(notificationCenterA).to.eql(notificationCenterB);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* Copyright 2023, 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
*
* 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, LogHandler } from '../../modules/logging';
import { NotificationCenter, createNotificationCenter } from '../../core/notification_center';

/**
* Internal notification center registry for managing multiple notification centers.
*/
export class NotificationRegistry {
private static _notificationCenters = new Map<string, NotificationCenter>();

constructor() {}

public static getNotificationCenter(sdkKey?: string, logger?: LogHandler): NotificationCenter | null {
if (!sdkKey) return null;

let notificationCenter;
if (this._notificationCenters.has(sdkKey)) {
notificationCenter = this._notificationCenters.get(sdkKey) || null;
} else {
notificationCenter = createNotificationCenter({
logger: logger || getLogger(),
errorHandler: { handleError: () => {} },
});
this._notificationCenters.set(sdkKey, notificationCenter);
}

return notificationCenter;
}

public static removeNotificationCenter(sdkKey?: string): void {
if (!sdkKey) return;

const notificationCenter = this._notificationCenters.get(sdkKey);
if (notificationCenter) {
notificationCenter.clearAllNotificationListeners();
this._notificationCenters.delete(sdkKey);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2022, Optimizely
* Copyright 2022-2023, 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 @@ -23,6 +23,9 @@ import { DEFAULT_UPDATE_INTERVAL, MIN_UPDATE_INTERVAL, DEFAULT_URL_TEMPLATE } fr
import BackoffController from './backoffController';
import PersistentKeyValueCache from './persistentKeyValueCache';

import { NotificationRegistry } from './../../core/notification_center/notification_registry';
import { NOTIFICATION_TYPES } from '../../../lib/utils/enums';

const logger = getLogger('DatafileManager');

const UPDATE_EVT = 'update';
Expand Down Expand Up @@ -95,6 +98,8 @@ export default abstract class HttpPollingDatafileManager implements DatafileMana

private cache: PersistentKeyValueCache;

private sdkKey: string;

// When true, this means the update interval timeout fired before the current
// sync completed. In that case, we should sync again immediately upon
// completion of the current request, instead of waiting another update
Expand All @@ -117,6 +122,7 @@ export default abstract class HttpPollingDatafileManager implements DatafileMana

this.cache = cache;
this.cacheKey = 'opt-datafile-' + sdkKey;
this.sdkKey = sdkKey;
this.isReadyPromiseSettled = false;
this.readyPromiseResolver = (): void => {};
this.readyPromiseRejecter = (): void => {};
Expand Down Expand Up @@ -233,6 +239,7 @@ export default abstract class HttpPollingDatafileManager implements DatafileMana
datafile,
};
this.emitter.emit(UPDATE_EVT, datafileUpdate);
NotificationRegistry.getNotificationCenter(this.sdkKey, logger)?.sendNotifications(NOTIFICATION_TYPES.OPTIMIZELY_CONFIG_UPDATE)
}
}
}
Expand Down
32 changes: 30 additions & 2 deletions packages/optimizely-sdk/lib/optimizely/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/****************************************************************************
* Copyright 2020-2022, Optimizely, Inc. and contributors *
* Copyright 2020-2023, 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 All @@ -17,6 +17,7 @@ import { LoggerFacade, ErrorHandler } from '../modules/logging';
import { sprintf, objectValues } from '../utils/fns';
import { NotificationCenter } from '../core/notification_center';
import { EventProcessor } from '../../lib/modules/event_processor';
import { OdpManager } from './../core/odp/odp_manager';

import {
UserAttributes,
Expand All @@ -29,14 +30,16 @@ import {
FeatureVariable,
OptimizelyOptions,
OptimizelyDecideOption,
OptimizelyDecision
OptimizelyDecision,
NotificationListener
} from '../shared_types';
import { newErrorDecision } from '../optimizely_decision';
import OptimizelyUserContext from '../optimizely_user_context';
import { createProjectConfigManager, ProjectConfigManager } from '../core/project_config/project_config_manager';
import { createDecisionService, DecisionService, DecisionObj } from '../core/decision_service';
import { getImpressionEvent, getConversionEvent } from '../core/event_builder';
import { buildImpressionEvent, buildConversionEvent } from '../core/event_builder/event_helpers';
import { NotificationRegistry } from '../core/notification_center/notification_registry';
import fns from '../utils/fns'
import { validate } from '../utils/attributes_validator';
import * as enums from '../utils/enums';
Expand Down Expand Up @@ -81,6 +84,7 @@ export default class Optimizely {
private decisionService: DecisionService;
private eventProcessor: EventProcessor;
private defaultDecideOptions: { [key: string]: boolean };
private odpManager?: OdpManager;
public notificationCenter: NotificationCenter;

constructor(config: OptimizelyOptions) {
Expand Down Expand Up @@ -175,6 +179,26 @@ export default class Optimizely {

this.readyTimeouts = {};
this.nextReadyTimeoutId = 0;

if (config.odpManager != null) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All this logic should come-up after the readyPromise? How config.sdkKey will be non-null if the datafile is still being fetched.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moving logic into Promise.all.

Also, as discussed, this should catch for both cases where a new Optimizely instance is provided either an SDK Key or manually includes a datafile.

this.odpManager = config.odpManager;
this.odpManager.eventManager?.start();
if (this.projectConfigManager.getConfig() != null) {
this.updateODPSettings();
}
const sdkKey = this.projectConfigManager.getConfig()?.sdkKey;
Copy link
Contributor

@jaeopt jaeopt Jan 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have sdkKey here (not indirectly from projectConfigManager) in line 132.
We can consider remove "getSdkKey()" new method from projectConfigManager and use a local value.
Also, we have to change "sdkKey" as mandatory (not null), which may be a breaking change in the release.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the catch - swapped out .getConfig()?sdkKey references with local config.sdkKey usage.

Regarding changing sdkKey to be mandatory, this will definitely be a breaking change - especially since there's some nuances (for example, the Lite bundle does not expect sdkKey to begin with). Brainstorming on this one.

if (sdkKey != null) {
NotificationRegistry.getNotificationCenter(sdkKey, this.logger)
?.addNotificationListener(enums.NOTIFICATION_TYPES.OPTIMIZELY_CONFIG_UPDATE, () => this.updateODPSettings());
}
}
}

updateODPSettings(): void {
const projectConfig = this.projectConfigManager.getConfig();
if (this.odpManager != null && projectConfig != null) {
this.odpManager.updateSettings(projectConfig.publicKeyForOdp, projectConfig.hostForOdp, projectConfig.allSegments);
}
}

/**
Expand Down Expand Up @@ -1315,6 +1339,10 @@ export default class Optimizely {
*/
close(): Promise<{ success: boolean; reason?: string }> {
try {
this.notificationCenter.clearAllNotificationListeners();
const sdkKey = this.projectConfigManager.getConfig()?.sdkKey;
if (sdkKey) NotificationRegistry.removeNotificationCenter(sdkKey);

const eventProcessorStoppedPromise = this.eventProcessor.stop();
if (this.disposeOnUpdate) {
this.disposeOnUpdate();
Expand Down
6 changes: 5 additions & 1 deletion packages/optimizely-sdk/lib/shared_types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2020-2022, Optimizely
* Copyright 2020-2023, 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 @@ -15,6 +15,7 @@
*/
import { ErrorHandler, LogHandler, LogLevel, LoggerFacade } from '../lib/modules/logging';
import { EventProcessor } from '../lib/modules/event_processor';
import { OdpManager } from './core/odp/odp_manager';

import { NotificationCenter as NotificationCenterImpl } from './core/notification_center'
import { NOTIFICATION_TYPES } from './utils/enums';
Expand Down Expand Up @@ -261,6 +262,7 @@ export interface OptimizelyOptions {
sdkKey?: string;
userProfileService?: UserProfileService | null;
defaultDecideOptions?: OptimizelyDecideOption[];
odpManager?: OdpManager;
notificationCenter: NotificationCenterImpl;
}

Expand Down Expand Up @@ -389,6 +391,8 @@ export interface Config extends ConfigLite {
eventMaxQueueSize?: number;
// sdk key
sdkKey?: string;
// odp manager
odpManager?: OdpManager;
}

/**
Expand Down