Skip to content

[FSSDK-10711] Make use of VUID as an opt-in #950

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 39 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
6b4f556
chore: update devcontainer config
mikechu-optimizely Oct 11, 2024
cc0c730
feat: add enableVuid to ODP options
mikechu-optimizely Oct 11, 2024
e1f2ee1
feat: add vuid removal function
mikechu-optimizely Oct 11, 2024
f4d5ed5
feat: use enableVuid option in BrowserOdpManager
mikechu-optimizely Oct 11, 2024
eed0d9b
doc: update warn when vuid is not enabled
mikechu-optimizely Oct 11, 2024
898c5f5
chore: oops still need jest until merge to `master`
mikechu-optimizely Oct 11, 2024
e15702a
chore: grrr remove vitest extensions for now
mikechu-optimizely Oct 11, 2024
763d387
test: fix jest configs in settings.json for VSCode
mikechu-optimizely Oct 11, 2024
005936b
test: cover explicit enablement of vuid
mikechu-optimizely Oct 11, 2024
8aee289
fix: code to pass tests
mikechu-optimizely Oct 11, 2024
9432c63
test: correct failing tests by enableVuid: true
mikechu-optimizely Oct 11, 2024
be04392
lint: fixes
mikechu-optimizely Oct 11, 2024
1196193
test: add coverage to VUID
mikechu-optimizely Oct 11, 2024
24e2b36
fix: PR requested updates
mikechu-optimizely Oct 14, 2024
9f1f6b8
refactor: WIP moving VUID out of ODP
mikechu-optimizely Oct 15, 2024
059db4c
refactor: remove remaining vuid from ODP Manager
mikechu-optimizely Oct 15, 2024
8cfb58a
refactor: VuidManager to a standard class from singleton
mikechu-optimizely Oct 15, 2024
dd1b434
refactor: ODP managers
mikechu-optimizely Oct 15, 2024
e84d353
refactor: WIP init VuidManager from opti client
mikechu-optimizely Oct 15, 2024
d85ec98
refactor: handle registerVuid
mikechu-optimizely Oct 15, 2024
a24a6af
refactor+doc: make readonly
mikechu-optimizely Oct 15, 2024
cbbf028
refactor: remove `this`
mikechu-optimizely Oct 15, 2024
83b997c
test: fixed + associated code corrections
mikechu-optimizely Oct 15, 2024
dad3a79
chore: include *.tests.js in jest
mikechu-optimizely Oct 15, 2024
26d962b
test: remove test that's no longer valid
mikechu-optimizely Oct 15, 2024
e970500
test: fix them so they run
mikechu-optimizely Oct 15, 2024
4200ff8
fix: PR requested changes
mikechu-optimizely Oct 15, 2024
6991743
chore: another correction to jest config
mikechu-optimizely Oct 15, 2024
ec4ae90
fix: PR requested change
mikechu-optimizely Oct 16, 2024
9b7fee0
test: skipping select tests for future PR.
mikechu-optimizely Oct 16, 2024
eb48fc8
revert: test changes
mikechu-optimizely Oct 16, 2024
640b67d
test: skip non-critical path tests
mikechu-optimizely Oct 16, 2024
67267f6
doc: Put TODOs on skipped test
mikechu-optimizely Oct 16, 2024
295394a
revert: auto-formatting & doc additions for ref readability
mikechu-optimizely Oct 16, 2024
f0d3c22
revert: more auto-format & clean ups (making it dirty again :-)
mikechu-optimizely Oct 16, 2024
339ecfb
revert: even more auto-formatting
mikechu-optimizely Oct 16, 2024
ccbdd4e
revert: last few auto-format put back ins
mikechu-optimizely Oct 16, 2024
0c6e57f
revert: missing import
mikechu-optimizely Oct 16, 2024
f382071
updates
raju-opti Oct 16, 2024
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
1 change: 0 additions & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"dbaeumer.vscode-eslint",
"eamodio.gitlens",
"esbenp.prettier-vscode",
"Gruntfuggly.todo-tree",
"github.vscode-github-actions",
"Orta.vscode-jest",
"ms-vscode.test-adapter-converter"
Expand Down
9 changes: 5 additions & 4 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"jest.rootPath": "/workspaces/javascript-sdk/packages/optimizely-sdk",
"jest.rootPath": "/workspaces/javascript-sdk",
"jest.jestCommandLine": "./node_modules/.bin/jest",
"jest.autoRevealOutput": "on-exec-error",
"editor.tabSize": 2
}
"jest.outputConfig": "test-results-based",
"editor.tabSize": 2,
"jest.runMode": "deferred"
}
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module.exports = {
"transform": {
"^.+\\.(ts|tsx|js|jsx)$": "ts-jest",
},
"testRegex": "(/tests/.*|(\\.|/)(test|spec))\\.tsx?$",
"testRegex": "(/tests/.*|(\\.|/)(test|spec|tests))\\.tsx?$",
moduleNameMapper: {
// Force module uuid to resolve with the CJS entry point, because Jest does not support package.json.exports. See https://github.com/uuidjs/uuid/issues/451
"uuid": require.resolve('uuid'),
Expand Down
4 changes: 1 addition & 3 deletions lib/core/notification_center/notification_registry.tests.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 All @@ -14,9 +14,7 @@
* limitations under the License.
*/

import { describe, it } from 'mocha';
import { expect } from 'chai';

import { NotificationRegistry } from './notification_registry';

describe('Notification Registry', () => {
Expand Down
98 changes: 39 additions & 59 deletions lib/core/odp/odp_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,12 @@
* limitations under the License.
*/

import { LOG_MESSAGES } from './../../utils/enums/index';
import { getLogger, LogHandler, LogLevel } from '../../modules/logging';
import { LogHandler, LogLevel } from '../../modules/logging';
import { ERROR_MESSAGES, ODP_USER_KEY } from '../../utils/enums';

import { VuidManager } from '../../plugins/vuid_manager';

import { OdpConfig, OdpIntegrationConfig, odpIntegrationsAreEqual } from './odp_config';
import { OdpIntegrationConfig, odpIntegrationsAreEqual } from './odp_config';
import { IOdpEventManager } from './odp_event_manager';
import { IOdpSegmentManager } from './odp_segment_manager';
import { OptimizelySegmentOption } from './optimizely_segment_option';
Expand All @@ -47,11 +46,12 @@ export interface IOdpManager {

sendEvent({ type, action, identifiers, data }: OdpEvent): void;

isVuidEnabled(): boolean;

getVuid(): string | undefined;
registerVuid(vuid: string): void;
}

/**
* Possible statuses for the OdpManager
*/
export enum Status {
Running,
Stopped,
Expand All @@ -72,32 +72,40 @@ export abstract class OdpManager implements IOdpManager {
*/
private configPromise: ResolvablePromise<void>;

status: Status = Status.Stopped;
/**
* The current status of the ODP Manager
*/
private status: Status = Status.Stopped;

/**
* 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.
* @private
* @readonly
*/
private segmentManager: IOdpSegmentManager;
private readonly segmentManager: IOdpSegmentManager;

/**
* ODP Event Manager which provides an interface to the remote ODP server (REST API) for events.
* It will queue all pending events (persistent) and send them (in batches of up to 10 events) to the ODP server when possible.
* @protected
* @readonly
*/
private eventManager: IOdpEventManager;
protected readonly eventManager: IOdpEventManager;

/**
* Handler for recording execution logs
* @protected
* @readonly
*/
protected logger: LogHandler;
protected readonly logger: LogHandler;

/**
* ODP configuration settings for identifying the target API and segments
* @protected
*/
odpIntegrationConfig?: OdpIntegrationConfig;
protected odpIntegrationConfig?: OdpIntegrationConfig;

// TODO: Consider accepting logger as a parameter and initializing it in constructor instead
constructor({
odpIntegrationConfig,
segmentManager,
Expand All @@ -112,33 +120,38 @@ export abstract class OdpManager implements IOdpManager {
this.segmentManager = segmentManager;
this.eventManager = eventManager;
this.logger = logger;

this.configPromise = resolvablePromise();

const readinessDependencies: PromiseLike<unknown>[] = [this.configPromise];

if (this.isVuidEnabled()) {
readinessDependencies.push(this.initializeVuid());
}

this.initPromise = Promise.all(readinessDependencies);

this.onReady().then(() => {
this.ready = true;
if (this.isVuidEnabled() && this.status === Status.Running) {
this.registerVuid();
}
});

if (odpIntegrationConfig) {
this.updateSettings(odpIntegrationConfig);
}
}

public getStatus(): Status {
/**
* Register a VUID with the ODP Manager in client side context
* @param {string} vuid - Unique identifier of an anonymous vistor
*/
abstract registerVuid(vuid: string): void;

/**
* @returns {Status} The current status of the ODP Manager
*/
getStatus(): Status {
return this.status;
}

/**
* Starts the ODP Manager
* @returns {Promise<void>} A promise that resolves when starting has completed
*/
async start(): Promise<void> {
if (this.status === Status.Running) {
return;
Expand All @@ -159,6 +172,10 @@ export abstract class OdpManager implements IOdpManager {
return Promise.resolve();
}

/**
* Stops the ODP Manager
* @returns A promise that resolves when stopping has completed
*/
async stop(): Promise<void> {
if (this.status === Status.Stopped) {
return;
Expand Down Expand Up @@ -230,7 +247,7 @@ export abstract class OdpManager implements IOdpManager {
/**
* Identifies a user via the ODP Event Manager
* @param {string} userId (Optional) Custom unique identifier of a target user.
* @param {string} vuid (Optional) Secondary unique identifier of a target user, primarily used by client SDKs.
* @param {string} vuid (Optional) Secondary unique identifier of a target user, used by client SDKs.
* @returns
*/
identifyUser(userId?: string, vuid?: string): void {
Expand Down Expand Up @@ -283,41 +300,4 @@ export abstract class OdpManager implements IOdpManager {

this.eventManager.sendEvent(new OdpEvent(mType, action, identifiers, data));
}

/**
* Identifies if the VUID feature is enabled
*/
abstract isVuidEnabled(): boolean;

/**
* Returns VUID value if it exists
*/
abstract getVuid(): string | undefined;

protected initializeVuid(): Promise<void> {
return Promise.resolve();
}

private registerVuid() {
if (!this.odpIntegrationConfig) {
this.logger.log(LogLevel.ERROR, ERROR_MESSAGES.ODP_CONFIG_NOT_AVAILABLE);
return;
}

if (!this.odpIntegrationConfig.integrated) {
this.logger.log(LogLevel.INFO, ERROR_MESSAGES.ODP_NOT_INTEGRATED);
return;
}

const vuid = this.getVuid();
if (!vuid) {
return;
}

try {
this.eventManager.registerVuid(vuid);
} catch (e) {
this.logger.log(LogLevel.ERROR, ERROR_MESSAGES.ODP_VUID_REGISTRATION_FAILED);
}
}
}
32 changes: 0 additions & 32 deletions lib/index.browser.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -654,38 +654,6 @@ describe('javascript-sdk (Browser)', function() {
sinon.assert.calledWith(logger.log, optimizelyFactory.enums.LOG_LEVEL.INFO, LOG_MESSAGES.ODP_DISABLED);
});

it('should include the VUID instantation promise of Browser ODP Manager in the Optimizely client onReady promise dependency array', () => {
const client = optimizelyFactory.createInstance({
datafile: testData.getTestProjectConfigWithFeatures(),
errorHandler: fakeErrorHandler,
eventDispatcher: fakeEventDispatcher,
eventBatchSize: null,
logger,
odpManager: BrowserOdpManager.createInstance({
logger,
}),
});

client
.onReady()
.then(() => {
assert.isDefined(client.odpManager.initPromise);
client.odpManager.initPromise
.then(() => {
assert.isTrue(true);
})
.catch(() => {
assert.isTrue(false);
});
assert.isDefined(client.odpManager.getVuid());
})
.catch(() => {
assert.isTrue(false);
});

sinon.assert.neverCalledWith(logger.log, optimizelyFactory.enums.LOG_LEVEL.ERROR);
});

it('should accept a valid custom cache size', () => {
const client = optimizelyFactory.createInstance({
datafile: testData.getTestProjectConfigWithFeatures(),
Expand Down
14 changes: 11 additions & 3 deletions lib/index.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,15 @@ import * as loggerPlugin from './plugins/logger';
import eventProcessorConfigValidator from './utils/event_processor_config_validator';
import { createNotificationCenter } from './core/notification_center';
import { default as eventProcessor } from './plugins/event_processor';
import { OptimizelyDecideOption, Client, Config, OptimizelyOptions } from './shared_types';
import { OptimizelyDecideOption, Client, Config, OptimizelyOptions, VuidManagerOptions } from './shared_types';
import { createHttpPollingDatafileManager } from './plugins/datafile_manager/browser_http_polling_datafile_manager';
import { BrowserOdpManager } from './plugins/odp_manager/index.browser';
import Optimizely from './optimizely';
import { IUserAgentParser } from './core/odp/user_agent_parser';
import { getUserAgentParser } from './plugins/odp/user_agent_parser/index.browser';
import * as commonExports from './common_exports';
import { VuidManager } from './plugins/vuid_manager';
import BrowserAsyncStorageCache from './plugins/key_value_cache/browserAsyncStorageCache';

const logger = getLogger();
logHelper.setLogHandler(loggerPlugin.createLogger());
Expand All @@ -51,7 +53,7 @@ let hasRetriedEvents = false;
* @return {Client|null} the Optimizely client object
* 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 Down Expand Up @@ -133,6 +135,11 @@ const createInstance = function(config: Config): Client | null {

const { clientEngine, clientVersion } = config;

const cache = new BrowserAsyncStorageCache();
const vuidManagerOptions: VuidManagerOptions = {
enableVuid: config.vuidManagerOptions?.enableVuid || false,
}

const optimizelyOptions: OptimizelyOptions = {
clientEngine: enums.JAVASCRIPT_CLIENT_ENGINE,
...config,
Expand All @@ -146,6 +153,7 @@ const createInstance = function(config: Config): Client | null {
isValidInstance,
odpManager: odpExplicitlyOff ? undefined
: BrowserOdpManager.createInstance({ logger, odpOptions: config.odpOptions, clientEngine, clientVersion }),
vuidManager: new VuidManager(cache, vuidManagerOptions, logger),
};

const optimizely = new Optimizely(optimizelyOptions);
Expand Down Expand Up @@ -174,7 +182,7 @@ const createInstance = function(config: Config): Client | null {
}
};

const __internalResetRetryState = function(): void {
const __internalResetRetryState = function (): void {
hasRetriedEvents = false;
};

Expand Down
15 changes: 11 additions & 4 deletions lib/index.react_native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ import defaultEventDispatcher from './plugins/event_dispatcher/index.browser';
import eventProcessorConfigValidator from './utils/event_processor_config_validator';
import { createNotificationCenter } from './core/notification_center';
import { createEventProcessor } from './plugins/event_processor/index.react_native';
import { OptimizelyDecideOption, Client, Config } from './shared_types';
import { OptimizelyDecideOption, Client, Config, VuidManagerOptions } from './shared_types';
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';

import { VuidManager } from './plugins/vuid_manager';
import ReactNativeAsyncStorageCache from './plugins/key_value_cache/reactNativeAsyncStorageCache';
import 'fast-text-encoding';
import 'react-native-get-random-values';

Expand All @@ -46,7 +47,7 @@ const DEFAULT_EVENT_MAX_QUEUE_SIZE = 10000;
* @return {Client|null} the Optimizely client object
* 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 Down Expand Up @@ -108,6 +109,11 @@ const createInstance = function(config: Config): Client | null {

const { clientEngine, clientVersion } = config;

const cache = new ReactNativeAsyncStorageCache();
const vuidManagerOptions: VuidManagerOptions = {
enableVuid: config.vuidManagerOptions?.enableVuid || false,
}

const optimizelyOptions = {
clientEngine: enums.REACT_NATIVE_JS_CLIENT_ENGINE,
...config,
Expand All @@ -126,7 +132,8 @@ const createInstance = function(config: Config): Client | null {
notificationCenter,
isValidInstance: isValidInstance,
odpManager: odpExplicitlyOff ? undefined
:BrowserOdpManager.createInstance({ logger, odpOptions: config.odpOptions, clientEngine, clientVersion }),
: BrowserOdpManager.createInstance({ logger, odpOptions: config.odpOptions, clientEngine, clientVersion }),
vuidManager: new VuidManager(cache, vuidManagerOptions, logger),
};

// If client engine is react, convert it to react native.
Expand Down
Loading
Loading