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

Add Notification Registry for ODP Setting Updates #795

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
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/**
* 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
*
* 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 { describe, it } from 'mocha';
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.undefined;
});

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,68 @@
/**
* 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, LogLevel } 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>();
opti-jnguyen marked this conversation as resolved.
Show resolved Hide resolved

constructor() {}

/**
* Retrieves an SDK Key's corresponding notification center in the registry if it exists, otherwise it creates one
* @param sdkKey SDK Key to be used for the notification center tied to the ODP Manager
* @param logger Logger to be used for the corresponding notification center
* @returns {NotificationCenter | undefined} a notification center instance for ODP Manager if a valid SDK Key is provided, otherwise undefined
*/
public static getNotificationCenter(
sdkKey?: string,
logger: LogHandler = getLogger()
): NotificationCenter | undefined {
if (!sdkKey) {
logger.log(LogLevel.ERROR, 'No SDK key provided to getNotificationCenter.');
return undefined;
}

let notificationCenter;
if (this._notificationCenters.has(sdkKey)) {
notificationCenter = this._notificationCenters.get(sdkKey);
} else {
notificationCenter = createNotificationCenter({
logger,
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);
}
}
}
4 changes: 3 additions & 1 deletion packages/optimizely-sdk/lib/core/odp/odp_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
* limitations under the License.
*/

import { checkArrayEquality } from '../../../lib/utils/fns';

export class OdpConfig {
/**
* Host of ODP audience segments API.
Expand Down Expand Up @@ -98,7 +100,7 @@ export class OdpConfig {
return (
this._apiHost == config._apiHost &&
this._apiKey == config._apiKey &&
JSON.stringify(this.segmentsToCheck) == JSON.stringify(config._segmentsToCheck)
checkArrayEquality(this.segmentsToCheck, config._segmentsToCheck)
);
}
}
15 changes: 8 additions & 7 deletions packages/optimizely-sdk/lib/core/odp/odp_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import { OdpEventApiManager } from './odp_event_api_manager';
import { OptimizelySegmentOption } from './optimizely_segment_option';
import { areOdpDataTypesValid } from './odp_types';
import { OdpEvent } from './odp_event';
import { VuidManager } from '../../plugins/vuid_manager';

// Orchestrates segments manager, event manager, and ODP configuration
export class OdpManager {
Expand All @@ -39,6 +38,8 @@ export class OdpManager {
odpConfig: OdpConfig;
logger: LogHandler;

// Note: VuidManager only utilized in Browser variation at /plugins/odp_manager/index.browser.ts

/**
* 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 @@ -107,9 +108,8 @@ export class OdpManager {
}

// Set up Events Manager (Events REST API Interface)
if (eventManager) {
eventManager.updateSettings(this.odpConfig);
this._eventManager = eventManager;
if (this._eventManager) {
this._eventManager.updateSettings(this.odpConfig);
} else {
this._eventManager = new OdpEventManager({
odpConfig: this.odpConfig,
Expand Down Expand Up @@ -154,9 +154,10 @@ export class OdpManager {
/**
* Attempts to fetch and return a list of a user's qualified segments from the local segments cache.
* If no cached data exists for the target user, this fetches and caches data from the ODP server instead.
* @param userId Unique identifier of a target user.
* @param options An array of OptimizelySegmentOption used to ignore and/or reset the cache.
* @returns
* @param {ODP_USER_KEY} userKey - Identifies the user id type.
* @param {string} userId - Unique identifier of a target user.
* @param {Array<OptimizelySegmentOption} options - An array of OptimizelySegmentOption used to ignore and/or reset the cache.
* @returns {Promise<string[] | null>} A promise holding either a list of qualified segments or null.
*/
public async fetchQualifiedSegments(
userKey: ODP_USER_KEY,
Expand Down
6 changes: 3 additions & 3 deletions packages/optimizely-sdk/lib/core/odp/odp_segment_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ import { OptimizelySegmentOption } from './optimizely_segment_option';
// Schedules connections to ODP for audience segmentation and caches the results.
export class OdpSegmentManager {
odpConfig: OdpConfig;
segmentsCache: LRUCache<string, Array<string>>;
segmentsCache: LRUCache<string, string[]>;
odpSegmentApiManager: OdpSegmentApiManager;
logger: LogHandler;

constructor(
odpConfig: OdpConfig,
segmentsCache: LRUCache<string, Array<string>>,
segmentsCache: LRUCache<string, string[]>,
odpSegmentApiManager: OdpSegmentApiManager,
logger?: LogHandler
) {
Expand All @@ -52,7 +52,7 @@ export class OdpSegmentManager {
userKey: ODP_USER_KEY,
userValue: string,
options: Array<OptimizelySegmentOption>
): Promise<Array<string> | null> {
): Promise<string[] | null> {
const { apiHost: odpApiHost, apiKey: odpApiKey } = this.odpConfig;

if (!odpApiKey || !odpApiHost) {
Expand Down
10 changes: 5 additions & 5 deletions packages/optimizely-sdk/lib/core/project_config/index.tests.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
/**
* Copyright 2016-2022, Optimizely
* Copyright 2016-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
* 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 Down Expand Up @@ -836,8 +836,8 @@ describe('lib/core/project_config', function () {
})

it('should contain all expected unique odp segments in allSegments', () => {
assert.equal(config.allSegments.size, 3)
assert.deepEqual(config.allSegments, new Set(['odp-segment-1', 'odp-segment-2', 'odp-segment-3']))
assert.equal(config.allSegments.length, 3)
assert.deepEqual(config.allSegments, ['odp-segment-1', 'odp-segment-2', 'odp-segment-3'])
opti-jnguyen marked this conversation as resolved.
Show resolved Hide resolved
})
});

Expand All @@ -863,7 +863,7 @@ describe('lib/core/project_config', function () {
})

it('should contain all expected unique odp segments in all segments', () => {
assert.equal(config.allSegments.size, 0)
assert.equal(config.allSegments.length, 0)
})
});

Expand Down
10 changes: 5 additions & 5 deletions packages/optimizely-sdk/lib/core/project_config/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
/**
* Copyright 2016-2022, Optimizely
* Copyright 2016-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
* 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 Down Expand Up @@ -103,7 +103,7 @@ export interface ProjectConfig {
integrationKeyMap?: { [key: string]: Integration };
publicKeyForOdp?: string;
hostForOdp?: string;
allSegments: Set<string>;
allSegments: string[];
}

const EXPERIMENT_RUNNING_STATUS = 'Running';
Expand Down Expand Up @@ -167,13 +167,13 @@ export const createProjectConfig = function (
projectConfig.audiencesById = keyBy(projectConfig.audiences, 'id');
assign(projectConfig.audiencesById, keyBy(projectConfig.typedAudiences, 'id'));

projectConfig.allSegments = new Set<string>([])
projectConfig.allSegments = []

Object.keys(projectConfig.audiencesById)
.map((audience) => getAudienceSegments(projectConfig.audiencesById[audience]))
.forEach(audienceSegments => {
audienceSegments.forEach(segment => {
projectConfig.allSegments.add(segment)
projectConfig.allSegments.push(segment)
})
})
opti-jnguyen marked this conversation as resolved.
Show resolved Hide resolved

Expand Down
2 changes: 1 addition & 1 deletion packages/optimizely-sdk/lib/index.browser.tests.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2016-2020, 2022 Optimizely
* Copyright 2016-2020, 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 Down
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 @@ -232,6 +238,9 @@ export default abstract class HttpPollingDatafileManager implements DatafileMana
const datafileUpdate: DatafileUpdate = {
datafile,
};
NotificationRegistry.getNotificationCenter(this.sdkKey, logger)?.sendNotifications(
NOTIFICATION_TYPES.OPTIMIZELY_CONFIG_UPDATE
);
this.emitter.emit(UPDATE_EVT, datafileUpdate);
}
}
Expand Down
Loading