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 11 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
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
49 changes: 39 additions & 10 deletions lib/core/odp/odp_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@
* 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';
Expand Down Expand Up @@ -46,8 +45,13 @@ export interface IOdpManager {
identifyUser(userId?: string, vuid?: string): void;

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

registerVuid(vuid: string): void;
}

/**
* Possible statuses for the OdpManager
*/
export enum Status {
Running,
Stopped,
Expand All @@ -68,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 Down Expand Up @@ -123,10 +135,23 @@ export abstract class OdpManager implements IOdpManager {
}
}

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 @@ -147,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 @@ -218,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
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
7 changes: 3 additions & 4 deletions lib/index.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,7 @@ let hasRetriedEvents = false;
* @return {Client|null} the Optimizely client object
* null on error
*/
// TODO: @raju-opti I'm not sure how to handle async VuidManager.instance() making createInstance async
const createInstance = async function(config: Config): Promise<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 @@ -154,7 +153,7 @@ const createInstance = async function(config: Config): Promise<Client | null> {
isValidInstance,
odpManager: odpExplicitlyOff ? undefined
: BrowserOdpManager.createInstance({ logger, odpOptions: config.odpOptions, clientEngine, clientVersion }),
vuidManager: await VuidManager.instance(cache, vuidManagerOptions),
vuidManager: new VuidManager(cache, vuidManagerOptions, logger),
};

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

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

Expand Down
12 changes: 6 additions & 6 deletions lib/index.react_native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ import { OptimizelyDecideOption, Client, Config, VuidManagerOptions } from './sh
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 BrowserAsyncStorageCache from './plugins/key_value_cache/browserAsyncStorageCache';
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 @@ -47,7 +47,7 @@ const DEFAULT_EVENT_MAX_QUEUE_SIZE = 10000;
* @return {Client|null} the Optimizely client object
* null on error
*/
const createInstance = async function(config: Config): Promise<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,8 +108,8 @@ const createInstance = async function(config: Config): Promise<Client | null> {
}

const { clientEngine, clientVersion } = config;
const cache = new BrowserAsyncStorageCache();

const cache = new ReactNativeAsyncStorageCache();
const vuidManagerOptions: VuidManagerOptions = {
enableVuid: config.vuidManagerOptions?.enableVuid || false,
}
Expand All @@ -132,8 +132,8 @@ const createInstance = async function(config: Config): Promise<Client | null> {
notificationCenter,
isValidInstance: isValidInstance,
odpManager: odpExplicitlyOff ? undefined
:BrowserOdpManager.createInstance({ logger, odpOptions: config.odpOptions, clientEngine, clientVersion }),
vuidManager: await VuidManager.instance(cache, vuidManagerOptions),
: 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
17 changes: 10 additions & 7 deletions lib/optimizely/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ export default class Optimizely implements Client {
projectConfigManagerReadyPromise,
eventProcessorStartedPromise,
config.odpManager ? config.odpManager.onReady() : Promise.resolve(),
config.vuidManager?.vuidEnabled ? config.vuidManager?.initialize() : Promise.resolve(),
]).then(promiseResults => {
// Only return status from project config promise because event processor promise does not return any status.
return promiseResults[0];
Expand Down Expand Up @@ -1413,8 +1414,8 @@ export default class Optimizely implements Client {
};

this.readyTimeouts[timeoutId] = {
readyTimeout: readyTimeout,
onClose: onClose,
readyTimeout,
onClose,
};

this.readyPromise.then(() => {
Expand All @@ -1423,13 +1424,15 @@ export default class Optimizely implements Client {
resolveTimeoutPromise({
success: true,
});
const vuid = this.vuidManager?.vuid;
if (vuid) {
this.odpManager?.registerVuid(vuid);
}
});

return Promise.race([this.readyPromise, timeoutPromise]);
}

//============ decide ============//

/**
* Creates a context of the user for which decision APIs will be called.
*
Expand All @@ -1445,6 +1448,7 @@ export default class Optimizely implements Client {
const userIdentifier = userId ?? this.vuidManager?.vuid;

if (userIdentifier === undefined || !this.validateInputs({ user_id: userIdentifier }, attributes)) {
this.logger.log(LOG_LEVEL.ERROR, '%s: Valid User ID or VUID not provided. User context not created.', MODULE_NAME);
return null;
}

Expand Down Expand Up @@ -1759,11 +1763,10 @@ export default class Optimizely implements Client {
* @returns {string|undefined} Currently provisioned VUID from local ODP Manager or undefined
*/
public getVuid(): string | undefined {
if (!this.vuidManager?.isVuidEnabled()) {
if (!this.vuidManager?.vuidEnabled) {
this.logger.log(LOG_LEVEL.WARNING, 'getVuid() unavailable for this platform or was not explicitly enabled.', MODULE_NAME);
return undefined;
}

return this.vuidManager.vuid;
return this.vuidManager?.vuid;
}
}
21 changes: 20 additions & 1 deletion lib/plugins/odp_manager/index.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ import {
JAVASCRIPT_CLIENT_ENGINE,
REQUEST_TIMEOUT_ODP_SEGMENTS_MS,
REQUEST_TIMEOUT_ODP_EVENTS_MS,
ERROR_MESSAGES,
} from '../../utils/enums';
import { getLogger, LogHandler } from '../../modules/logging';
import { getLogger, LogHandler, LogLevel } from '../../modules/logging';

import { BrowserRequestHandler } from './../../utils/http_request_handler/browser_request_handler';

Expand Down Expand Up @@ -148,4 +149,22 @@ export class BrowserOdpManager extends OdpManager {

super.identifyUser(fsUserId, vuid);
}

registerVuid(vuid: string): void {
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;
}

try {
this.eventManager.registerVuid(vuid);
} catch (e) {
this.logger.log(LogLevel.ERROR, ERROR_MESSAGES.ODP_VUID_REGISTRATION_FAILED);
}
}
}
16 changes: 10 additions & 6 deletions lib/plugins/odp_manager/index.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { NodeRequestHandler } from '../../utils/http_request_handler/node_reques

import { ServerLRUCache } from './../../utils/lru_cache/server_lru_cache';

import { getLogger, LogHandler } from '../../modules/logging';
import { getLogger, LogHandler, LogLevel } from '../../modules/logging';
import {
NODE_CLIENT_ENGINE,
CLIENT_VERSION,
Expand Down Expand Up @@ -64,7 +64,7 @@ export class NodeOdpManager extends OdpManager {
clientEngine = clientEngine || NODE_CLIENT_ENGINE;
clientVersion = clientVersion || CLIENT_VERSION;

let odpConfig : OdpConfig | undefined = undefined;
let odpConfig: OdpConfig | undefined = undefined;
if (odpIntegrationConfig?.integrated) {
odpConfig = odpIntegrationConfig.odpConfig;
}
Expand All @@ -87,10 +87,10 @@ export class NodeOdpManager extends OdpManager {
} else {
segmentManager = new OdpSegmentManager(
odpOptions?.segmentsCache ||
new ServerLRUCache<string, string[]>({
maxSize: odpOptions?.segmentsCacheSize,
timeout: odpOptions?.segmentsCacheTimeout,
}),
new ServerLRUCache<string, string[]>({
maxSize: odpOptions?.segmentsCacheSize,
timeout: odpOptions?.segmentsCacheTimeout,
}),
new OdpSegmentApiManager(customSegmentRequestHandler, logger),
logger,
odpConfig
Expand Down Expand Up @@ -133,4 +133,8 @@ export class NodeOdpManager extends OdpManager {
logger,
});
}

registerVuid(vuid: string): void {
this.logger.log(LogLevel.ERROR, `Unable to registerVuid ${vuid} in a node server context`);
}
}
Loading
Loading