Skip to content

Commit 9f1f6b8

Browse files
refactor: WIP moving VUID out of ODP
1 parent 24e2b36 commit 9f1f6b8

File tree

10 files changed

+59
-190
lines changed

10 files changed

+59
-190
lines changed

lib/core/odp/odp_manager.ts

Lines changed: 1 addition & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import { ERROR_MESSAGES, ODP_USER_KEY } from '../../utils/enums';
2020

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

23-
import { OdpConfig, OdpIntegrationConfig, odpIntegrationsAreEqual } from './odp_config';
23+
import { OdpIntegrationConfig, odpIntegrationsAreEqual } from './odp_config';
2424
import { IOdpEventManager } from './odp_event_manager';
2525
import { IOdpSegmentManager } from './odp_segment_manager';
2626
import { OptimizelySegmentOption } from './optimizely_segment_option';
@@ -47,10 +47,6 @@ export interface IOdpManager {
4747
identifyUser(userId?: string, vuid?: string): void;
4848

4949
sendEvent({ type, action, identifiers, data }: OdpEvent): void;
50-
51-
isVuidEnabled(): boolean;
52-
53-
getVuid(): string | undefined;
5450
}
5551

5652
export enum Status {
@@ -125,17 +121,10 @@ export abstract class OdpManager implements IOdpManager {
125121

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

128-
if (this.isVuidEnabled()) {
129-
readinessDependencies.push(this.initializeVuid());
130-
}
131-
132124
this.initPromise = Promise.all(readinessDependencies);
133125

134126
this.onReady().then(() => {
135127
this.ready = true;
136-
if (this.isVuidEnabled() && this.status === Status.Running) {
137-
this.registerVuid();
138-
}
139128
});
140129

141130
if (odpIntegrationConfig) {
@@ -291,41 +280,4 @@ export abstract class OdpManager implements IOdpManager {
291280

292281
this.eventManager.sendEvent(new OdpEvent(mType, action, identifiers, data));
293282
}
294-
295-
/**
296-
* Identifies if the VUID feature is enabled
297-
*/
298-
abstract isVuidEnabled(): boolean;
299-
300-
/**
301-
* Returns VUID value if it exists
302-
*/
303-
abstract getVuid(): string | undefined;
304-
305-
protected initializeVuid(): Promise<void> {
306-
return Promise.resolve();
307-
}
308-
309-
private registerVuid() {
310-
if (!this.odpIntegrationConfig) {
311-
this.logger.log(LogLevel.ERROR, ERROR_MESSAGES.ODP_CONFIG_NOT_AVAILABLE);
312-
return;
313-
}
314-
315-
if (!this.odpIntegrationConfig.integrated) {
316-
this.logger.log(LogLevel.INFO, ERROR_MESSAGES.ODP_NOT_INTEGRATED);
317-
return;
318-
}
319-
320-
const vuid = this.getVuid();
321-
if (!vuid) {
322-
return;
323-
}
324-
325-
try {
326-
this.eventManager.registerVuid(vuid);
327-
} catch (e) {
328-
this.logger.log(LogLevel.ERROR, ERROR_MESSAGES.ODP_VUID_REGISTRATION_FAILED);
329-
}
330-
}
331283
}

lib/index.browser.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,15 @@ import * as loggerPlugin from './plugins/logger';
2626
import eventProcessorConfigValidator from './utils/event_processor_config_validator';
2727
import { createNotificationCenter } from './core/notification_center';
2828
import { default as eventProcessor } from './plugins/event_processor';
29-
import { OptimizelyDecideOption, Client, Config, OptimizelyOptions } from './shared_types';
29+
import { OptimizelyDecideOption, Client, Config, OptimizelyOptions, VuidManagerOptions } from './shared_types';
3030
import { createHttpPollingDatafileManager } from './plugins/datafile_manager/browser_http_polling_datafile_manager';
3131
import { BrowserOdpManager } from './plugins/odp_manager/index.browser';
3232
import Optimizely from './optimizely';
3333
import { IUserAgentParser } from './core/odp/user_agent_parser';
3434
import { getUserAgentParser } from './plugins/odp/user_agent_parser/index.browser';
3535
import * as commonExports from './common_exports';
36+
import { VuidManager } from './plugins/vuid_manager';
37+
import BrowserAsyncStorageCache from './plugins/key_value_cache/browserAsyncStorageCache';
3638

3739
const logger = getLogger();
3840
logHelper.setLogHandler(loggerPlugin.createLogger());
@@ -51,7 +53,8 @@ let hasRetriedEvents = false;
5153
* @return {Client|null} the Optimizely client object
5254
* null on error
5355
*/
54-
const createInstance = function(config: Config): Client | null {
56+
// TODO: @raju-opti I'm not sure how to handle async VuidManager.instance() making createInstance async
57+
const createInstance = async function(config: Config): Promise<Client | null> {
5558
try {
5659
// TODO warn about setting per instance errorHandler / logger / logLevel
5760
let isValidInstance = false;
@@ -133,6 +136,11 @@ const createInstance = function(config: Config): Client | null {
133136

134137
const { clientEngine, clientVersion } = config;
135138

139+
const cache = new BrowserAsyncStorageCache();
140+
const vuidManagerOptions: VuidManagerOptions = {
141+
enableVuid: config.vuidManagerOptions?.enableVuid || false,
142+
}
143+
136144
const optimizelyOptions: OptimizelyOptions = {
137145
clientEngine: enums.JAVASCRIPT_CLIENT_ENGINE,
138146
...config,
@@ -146,6 +154,7 @@ const createInstance = function(config: Config): Client | null {
146154
isValidInstance,
147155
odpManager: odpExplicitlyOff ? undefined
148156
: BrowserOdpManager.createInstance({ logger, odpOptions: config.odpOptions, clientEngine, clientVersion }),
157+
vuidManager: await VuidManager.instance(cache, vuidManagerOptions),
149158
};
150159

151160
const optimizely = new Optimizely(optimizelyOptions);

lib/index.react_native.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,12 @@ import defaultEventDispatcher from './plugins/event_dispatcher/index.browser';
2424
import eventProcessorConfigValidator from './utils/event_processor_config_validator';
2525
import { createNotificationCenter } from './core/notification_center';
2626
import { createEventProcessor } from './plugins/event_processor/index.react_native';
27-
import { OptimizelyDecideOption, Client, Config } from './shared_types';
27+
import { OptimizelyDecideOption, Client, Config, VuidManagerOptions } from './shared_types';
2828
import { createHttpPollingDatafileManager } from './plugins/datafile_manager/react_native_http_polling_datafile_manager';
2929
import { BrowserOdpManager } from './plugins/odp_manager/index.browser';
3030
import * as commonExports from './common_exports';
31-
31+
import BrowserAsyncStorageCache from './plugins/key_value_cache/browserAsyncStorageCache';
32+
import { VuidManager } from './plugins/vuid_manager';
3233
import 'fast-text-encoding';
3334
import 'react-native-get-random-values';
3435

@@ -46,7 +47,7 @@ const DEFAULT_EVENT_MAX_QUEUE_SIZE = 10000;
4647
* @return {Client|null} the Optimizely client object
4748
* null on error
4849
*/
49-
const createInstance = function(config: Config): Client | null {
50+
const createInstance = async function(config: Config): Promise<Client | null> {
5051
try {
5152
// TODO warn about setting per instance errorHandler / logger / logLevel
5253
let isValidInstance = false;
@@ -107,6 +108,11 @@ const createInstance = function(config: Config): Client | null {
107108
}
108109

109110
const { clientEngine, clientVersion } = config;
111+
112+
const cache = new BrowserAsyncStorageCache();
113+
const vuidManagerOptions: VuidManagerOptions = {
114+
enableVuid: config.vuidManagerOptions?.enableVuid || false,
115+
}
110116

111117
const optimizelyOptions = {
112118
clientEngine: enums.REACT_NATIVE_JS_CLIENT_ENGINE,
@@ -127,6 +133,7 @@ const createInstance = function(config: Config): Client | null {
127133
isValidInstance: isValidInstance,
128134
odpManager: odpExplicitlyOff ? undefined
129135
:BrowserOdpManager.createInstance({ logger, odpOptions: config.odpOptions, clientEngine, clientVersion }),
136+
vuidManager: await VuidManager.instance(cache, vuidManagerOptions),
130137
};
131138

132139
// If client engine is react, convert it to react native.

lib/optimizely/index.ts

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ import {
6868
FS_USER_ID_ALIAS,
6969
ODP_USER_KEY,
7070
} from '../utils/enums';
71+
import { IVuidManager } from '../plugins/vuid_manager';
7172

7273
const MODULE_NAME = 'OPTIMIZELY';
7374

@@ -95,6 +96,7 @@ export default class Optimizely implements Client {
9596
private eventProcessor: EventProcessor;
9697
private defaultDecideOptions: { [key: string]: boolean };
9798
protected odpManager?: IOdpManager;
99+
protected vuidManager?: IVuidManager;
98100
public notificationCenter: NotificationCenter;
99101

100102
constructor(config: OptimizelyOptions) {
@@ -1440,7 +1442,7 @@ export default class Optimizely implements Client {
14401442
* null if provided inputs are invalid
14411443
*/
14421444
createUserContext(userId?: string, attributes?: UserAttributes): OptimizelyUserContext | null {
1443-
const userIdentifier = userId ?? this.odpManager?.getVuid();
1445+
const userIdentifier = userId ?? this.vuidManager?.vuid;
14441446

14451447
if (userIdentifier === undefined || !this.validateInputs({ user_id: userIdentifier }, attributes)) {
14461448
return null;
@@ -1754,20 +1756,14 @@ export default class Optimizely implements Client {
17541756
}
17551757

17561758
/**
1757-
* @returns {string|undefined} Currently provisioned VUID from local ODP Manager or undefined if
1758-
* ODP Manager has not been instantiated yet for any reason.
1759+
* @returns {string|undefined} Currently provisioned VUID from local ODP Manager or undefined
17591760
*/
17601761
public getVuid(): string | undefined {
1761-
if (!this.odpManager) {
1762-
this.logger?.error('Unable to get VUID - ODP Manager is not instantiated yet.');
1763-
return undefined;
1764-
}
1765-
1766-
if (!this.odpManager.isVuidEnabled()) {
1762+
if (!this.vuidManager?.isVuidEnabled()) {
17671763
this.logger.log(LOG_LEVEL.WARNING, 'getVuid() unavailable for this platform or was not explicitly enabled.', MODULE_NAME);
17681764
return undefined;
17691765
}
17701766

1771-
return this.odpManager.getVuid();
1767+
return this.vuidManager.vuid;
17721768
}
17731769
}

lib/plugins/odp_manager/index.browser.ts

Lines changed: 3 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -16,24 +16,20 @@
1616

1717
import {
1818
CLIENT_VERSION,
19-
ERROR_MESSAGES,
2019
JAVASCRIPT_CLIENT_ENGINE,
21-
ODP_USER_KEY,
2220
REQUEST_TIMEOUT_ODP_SEGMENTS_MS,
2321
REQUEST_TIMEOUT_ODP_EVENTS_MS,
2422
} from '../../utils/enums';
2523
import { getLogger, LogHandler } from '../../modules/logging';
2624

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

29-
import BrowserAsyncStorageCache from '../key_value_cache/browserAsyncStorageCache';
3027
import { BrowserLRUCache } from '../../utils/lru_cache';
3128

3229
import { VuidManager } from './../vuid_manager/index';
3330

3431
import { OdpManager } from '../../core/odp/odp_manager';
35-
import { OdpEvent } from '../../core/odp/odp_event';
36-
import { IOdpEventManager, OdpOptions, VuidManagerOptions } from '../../shared_types';
32+
import { IOdpEventManager, OdpOptions } from '../../shared_types';
3733
import { BrowserOdpEventApiManager } from '../odp/event_api_manager/index.browser';
3834
import { BrowserOdpEventManager } from '../odp/event_manager/index.browser';
3935
import { IOdpSegmentManager, OdpSegmentManager } from '../../core/odp/odp_segment_manager';
@@ -46,26 +42,21 @@ interface BrowserOdpManagerConfig {
4642
logger?: LogHandler;
4743
odpOptions?: OdpOptions;
4844
odpIntegrationConfig?: OdpIntegrationConfig;
49-
vuidManagerOptions?: VuidManagerOptions;
5045
}
5146

5247
// Client-side Browser Plugin for ODP Manager
5348
export class BrowserOdpManager extends OdpManager {
54-
static cache = new BrowserAsyncStorageCache();
55-
vuid?: string;
56-
5749
constructor(options: {
5850
odpIntegrationConfig?: OdpIntegrationConfig;
5951
segmentManager: IOdpSegmentManager;
6052
eventManager: IOdpEventManager;
6153
logger: LogHandler;
62-
vuidManagerOptions?: VuidManagerOptions;
6354
}) {
6455
super(options);
6556
}
6657

6758
static createInstance({
68-
logger, odpOptions, odpIntegrationConfig, clientEngine, clientVersion, vuidManagerOptions,
59+
logger, odpOptions, odpIntegrationConfig, clientEngine, clientVersion,
6960
}: BrowserOdpManagerConfig): BrowserOdpManager {
7061
logger = logger || getLogger();
7162

@@ -135,19 +126,9 @@ export class BrowserOdpManager extends OdpManager {
135126
segmentManager,
136127
eventManager,
137128
logger,
138-
vuidManagerOptions,
139129
});
140130
}
141131

142-
/**
143-
* @override
144-
* accesses or creates new VUID from Browser cache
145-
*/
146-
protected async initializeVuid(): Promise<void> {
147-
const vuidManager = await VuidManager.instance(BrowserOdpManager.cache, this.vuidManagerOptions);
148-
this.vuid = vuidManager.vuid;
149-
}
150-
151132
/**
152133
* @override
153134
* - Still identifies a user via the ODP Event Manager
@@ -165,35 +146,6 @@ export class BrowserOdpManager extends OdpManager {
165146
return;
166147
}
167148

168-
super.identifyUser(fsUserId, vuid || this.vuid);
169-
}
170-
171-
/**
172-
* @override
173-
* - Sends an event to the ODP Server via the ODP Events API
174-
* - Intercepts identifiers and injects VUID before sending event
175-
* - Identifiers must contain at least one key-value pair
176-
* @param {OdpEvent} odpEvent > ODP Event to send to event manager
177-
*/
178-
sendEvent({ type, action, identifiers, data }: OdpEvent): void {
179-
const identifiersWithVuid = new Map<string, string>(identifiers);
180-
181-
if (!identifiers.has(ODP_USER_KEY.VUID)) {
182-
if (this.vuid) {
183-
identifiersWithVuid.set(ODP_USER_KEY.VUID, this.vuid);
184-
} else {
185-
throw new Error(ERROR_MESSAGES.ODP_SEND_EVENT_FAILED_VUID_MISSING);
186-
}
187-
}
188-
189-
super.sendEvent({ type, action, identifiers: identifiersWithVuid, data });
190-
}
191-
192-
isVuidEnabled(): boolean {
193-
return this.vuidManagerOptions?.enableVuid || false;
194-
}
195-
196-
getVuid(): string | undefined {
197-
return this.vuid;
149+
super.identifyUser(fsUserId, vuid);
198150
}
199151
}

lib/plugins/odp_manager/index.node.ts

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import { NodeRequestHandler } from '../../utils/http_request_handler/node_reques
1818

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

21-
import { getLogger, LogHandler, LogLevel } from '../../modules/logging';
21+
import { getLogger, LogHandler } from '../../modules/logging';
2222
import {
2323
NODE_CLIENT_ENGINE,
2424
CLIENT_VERSION,
@@ -133,12 +133,4 @@ export class NodeOdpManager extends OdpManager {
133133
logger,
134134
});
135135
}
136-
137-
public isVuidEnabled(): boolean {
138-
return false;
139-
}
140-
141-
public getVuid(): string | undefined {
142-
return undefined;
143-
}
144136
}

lib/plugins/vuid_manager/index.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,11 @@ export class VuidManager implements IVuidManager {
5353
return this._vuid;
5454
}
5555

56-
private constructor() {
56+
private readonly options: VuidManagerOptions;
57+
58+
private constructor(options: VuidManagerOptions) {
5759
this._vuid = '';
60+
this.options = options;
5861
}
5962

6063
/**
@@ -69,14 +72,13 @@ export class VuidManager implements IVuidManager {
6972
* @param options Options for the VUID Manager
7073
* @returns An instance of VuidManager
7174
*/
72-
static async instance(cache: PersistentKeyValueCache, options?: VuidManagerOptions): Promise<VuidManager> {
75+
static async instance(cache: PersistentKeyValueCache, options: VuidManagerOptions): Promise<VuidManager> {
7376
if (!this._instance) {
74-
this._instance = new VuidManager();
75-
}
77+
this._instance = new VuidManager(options);
7678

77-
if (!options?.enableVuid) {
78-
cache.remove(this._instance._keyForVuid);
79-
return this._instance;
79+
if (!this._instance.options.enableVuid) {
80+
await cache.remove(this._instance._keyForVuid);
81+
}
8082
}
8183

8284
if (!this._instance._vuid) {
@@ -130,6 +132,10 @@ export class VuidManager implements IVuidManager {
130132
await cache.set(this._keyForVuid, vuid);
131133
}
132134

135+
static isVuidEnabled(): boolean {
136+
return this._instance.options.enableVuid || false;
137+
}
138+
133139
/**
134140
* Validates the format of a Visitor Unique Identifier
135141
* @param vuid VistorId to check

0 commit comments

Comments
 (0)