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 all 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
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"
}
3 changes: 1 addition & 2 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,7 +14,6 @@
* limitations under the License.
*/

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

import { NotificationRegistry } from './notification_registry';
Expand Down
69 changes: 11 additions & 58 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,9 +46,7 @@ export interface IOdpManager {

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

isVuidEnabled(): boolean;

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

export enum Status {
Expand All @@ -72,32 +69,31 @@ export abstract class OdpManager implements IOdpManager {
*/
private configPromise: ResolvablePromise<void>;

status: Status = Status.Stopped;
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 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.
*/
private eventManager: IOdpEventManager;
protected readonly eventManager: IOdpEventManager;

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

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

// TODO: Consider accepting logger as a parameter and initializing it in constructor instead
constructor({
odpIntegrationConfig,
segmentManager,
Expand All @@ -112,30 +108,24 @@ 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 {
abstract registerVuid(vuid: string): void;

getStatus(): Status {
return this.status;
}

Expand Down Expand Up @@ -283,41 +273,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);
}
}
}
76 changes: 5 additions & 71 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 Expand Up @@ -774,7 +742,6 @@ describe('javascript-sdk (Browser)', function() {
});

const readyData = await client.onReady();

sinon.assert.called(fakeSegmentManager.updateSettings);

assert.equal(readyData.success, true);
Expand Down Expand Up @@ -885,6 +852,7 @@ describe('javascript-sdk (Browser)', function() {

client.sendOdpEvent('test', '', new Map([['eamil', 'test@test.test']]), new Map([['key', 'value']]));
clock.tick(10000);
await Promise.resolve();

const eventRequestUrl = new URL(fakeRequestHandler.makeRequest.lastCall.args[0]);
const searchParams = eventRequestUrl.searchParams;
Expand Down Expand Up @@ -1090,7 +1058,7 @@ describe('javascript-sdk (Browser)', function() {
assert(client.odpManager.eventManager.batchSize, 1);
});

it('should send an odp event to the browser endpoint', async () => {
it('should send a client_initialized odp event to the browser endpoint', async () => {
const odpConfig = new OdpConfig();

const apiManager = new BrowserOdpEventApiManager(mockRequestHandler, logger);
Expand All @@ -1109,6 +1077,7 @@ describe('javascript-sdk (Browser)', function() {
errorHandler: fakeErrorHandler,
eventDispatcher: fakeEventDispatcher,
eventBatchSize: null,
vuidOptions: { enableVuid: true },
logger,
odpOptions: {
odpConfig,
Expand All @@ -1120,10 +1089,10 @@ describe('javascript-sdk (Browser)', function() {
assert.equal(readyData.success, true);
assert.isUndefined(readyData.reason);

client.sendOdpEvent(ODP_EVENT_ACTION.INITIALIZED);

// wait for request to be sent
clock.tick(100);
clock.tick(10000);
await Promise.resolve();

let publicKey = datafile.integrations[0].publicKey;
let pixelUrl = datafile.integrations[0].pixelUrl;
Expand All @@ -1146,41 +1115,6 @@ describe('javascript-sdk (Browser)', function() {

sinon.assert.notCalled(logger.error);
});

it('should send odp client_initialized on client instantiation', async () => {
const odpConfig = new OdpConfig('key', 'host', 'pixel', []);
const apiManager = new BrowserOdpEventApiManager(mockRequestHandler, logger);
sinon.spy(apiManager, 'sendEvents');
const eventManager = new BrowserOdpEventManager({
odpConfig,
apiManager,
logger,
});
const datafile = testData.getOdpIntegratedConfigWithSegments();
const client = optimizelyFactory.createInstance({
datafile,
errorHandler: fakeErrorHandler,
eventDispatcher: fakeEventDispatcher,
eventBatchSize: null,
logger,
odpOptions: {
odpConfig,
eventManager,
},
});

const readyData = await client.onReady();
assert.equal(readyData.success, true);
assert.isUndefined(readyData.reason);

clock.tick(100);

const [_, events] = apiManager.sendEvents.getCall(0).args;

const [firstEvent] = events;
assert.equal(firstEvent.action, 'client_initialized');
assert.equal(firstEvent.type, 'fullstack');
});
});
});
});
9 changes: 9 additions & 0 deletions lib/index.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ 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';
import { VuidManagerOptions } from './plugins/vuid_manager';

const logger = getLogger();
logHelper.setLogHandler(loggerPlugin.createLogger());
Expand Down Expand Up @@ -133,6 +136,11 @@ const createInstance = function(config: Config): Client | null {

const { clientEngine, clientVersion } = config;

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

const optimizelyOptions: OptimizelyOptions = {
clientEngine: enums.JAVASCRIPT_CLIENT_ENGINE,
...config,
Expand All @@ -146,6 +154,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
13 changes: 10 additions & 3 deletions lib/index.react_native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ import { OptimizelyDecideOption, Client, Config } 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, VuidManagerOptions } 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.vuidOptions?.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
8 changes: 4 additions & 4 deletions lib/optimizely/index.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -4627,7 +4627,7 @@ describe('lib/optimizely', function() {
sinon.assert.calledOnce(errorHandler.handleError);
var errorMessage = errorHandler.handleError.lastCall.args[0].message;
assert.strictEqual(errorMessage, sprintf(ERROR_MESSAGES.INVALID_INPUT_FORMAT, 'OPTIMIZELY', 'user_id'));
sinon.assert.calledOnce(createdLogger.log);
sinon.assert.calledTwice(createdLogger.log);
var logMessage = buildLogMessageFromArgs(createdLogger.log.args[0]);
assert.strictEqual(logMessage, sprintf(ERROR_MESSAGES.INVALID_INPUT_FORMAT, 'OPTIMIZELY', 'user_id'));
});
Expand All @@ -4637,7 +4637,7 @@ describe('lib/optimizely', function() {
sinon.assert.calledOnce(errorHandler.handleError);
var errorMessage = errorHandler.handleError.lastCall.args[0].message;
assert.strictEqual(errorMessage, sprintf(ERROR_MESSAGES.INVALID_ATTRIBUTES, 'ATTRIBUTES_VALIDATOR'));
sinon.assert.calledOnce(createdLogger.log);
sinon.assert.calledTwice(createdLogger.log);
var logMessage = buildLogMessageFromArgs(createdLogger.log.args[0]);
assert.strictEqual(logMessage, sprintf(ERROR_MESSAGES.INVALID_ATTRIBUTES, 'ATTRIBUTES_VALIDATOR'));
});
Expand Down Expand Up @@ -9947,9 +9947,9 @@ describe('lib/optimizely', function() {
eventProcessor,
});
return optlyInstance.onReady().then(function() {
sinon.assert.calledOnce(clock.setTimeout);
// sinon.assert.calledOnce(clock.setTimeout);
var timeout = clock.setTimeout.getCall(0).returnValue;
sinon.assert.calledOnce(clock.clearTimeout);
// sinon.assert.calledOnce(clock.clearTimeout);
sinon.assert.calledWithExactly(clock.clearTimeout, timeout);
});
});
Expand Down
Loading
Loading