import { IFbClientCore } from "./IFbClientCore.js"; import { IPlatform } from "./platform/IPlatform.js"; import Configuration from "./Configuration.js"; import { ILogger } from "./logging/ILogger.js"; import ClientContext from "./options/ClientContext.js"; import DataSourceUpdates from "./data-sources/DataSourceUpdates.js"; import { createStreamListeners } from "./data-sources/createStreamListeners.js"; import { IEvalDetail } from "./evaluation/IEvalDetail.js"; import WebSocketDataSynchronizer from "./data-sync/WebSocketDataSynchronizer.js"; import PollingDataSynchronizer from "./data-sync/PollingDataSynchronizer.js"; import Requestor from "./data-sync/Requestor.js"; import { IDataSynchronizer } from "./data-sync/IDataSynchronizer.js"; import DataKinds from "./store/DataKinds.js"; import Evaluator from "./evaluation/Evaluator.js"; import { ReasonKinds } from "./evaluation/ReasonKinds.js"; import { ClientError, TimeoutError } from "./errors.js"; import Context from "./Context.js"; import { IConvertResult, ValueConverters } from "./utils/ValueConverters.js"; import { NullDataSynchronizer } from "./data-sync/NullDataSynchronizer.js"; import { IEventProcessor } from "./events/IEventProcessor.js"; import { NullEventProcessor } from "./events/NullEventProcessor.js"; import { DefaultEventProcessor } from "./events/DefaultEventProcessor.js"; import { IStore } from "./platform/IStore.js"; import { IOptions } from "./options/IOptions.js"; import { MetricEvent } from "./events/event.js"; import { DataSyncModeEnum } from "./data-sync/DataSyncMode.js"; import { IUser } from "./options/IUser.js"; import { UserValidator } from "./options/Validators.js"; import { FlagValue, VariationDataType } from "./evaluation/index.js"; import { StoreItemOriginEnum } from "./store/index.js"; import FullSyncPolicy from './data-sync/FullSyncPolicy.js'; import { copyUser } from './utils/copyUser.js'; enum ClientState { Initializing, Initialized, Failed, } export interface IClientCallbacks { onError: (err: Error) => void; onFailed: (err: Error) => void; onReady: () => void; // Called whenever flags change, if there are listeners. onUpdate: (keys: string[]) => void; // Method to check if event listeners have been registered. // If none are registered, then onUpdate will never be called. hasEventListeners: () => boolean; } export class FbClientCore implements IFbClientCore { private readonly fullSync: FullSyncPolicy; private setup: Promise; private contextGeneration = 0; private contextChanging = false; private closed = false; private initializationTimer?: ReturnType; private state: ClientState = ClientState.Initializing; private store?: IStore; private dataSynchronizer?: IDataSynchronizer; private customSynchronizer?: IDataSynchronizer; private eventProcessor?: IEventProcessor; private evaluator?: Evaluator; private initResolve?: (value: IFbClientCore | PromiseLike) => void; private initReject?: (err: Error) => void; private rejectionReason: Error | undefined; private reportedSourceError?: { generation: number; error: unknown }; private initializedPromise?: Promise; private config: Configuration; private dataSourceUpdates?: DataSourceUpdates; private onError: (err: Error) => void; private onFailed: (err: Error) => void; private onReady: () => void; logger?: ILogger; constructor( private options: IOptions, private platform: IPlatform, callbacks: IClientCallbacks ) { this.onError = callbacks.onError; this.onFailed = callbacks.onFailed; this.onReady = callbacks.onReady; const {onUpdate, hasEventListeners} = callbacks; const config = new Configuration(options); if (!config.sdkKey && !config.offline) { throw new Error('You must configure the client with an SDK key'); } if (!config.user) { throw new Error('You must configure the client with a user'); } this.config = config; this.fullSync = new FullSyncPolicy(config.fullSyncInterval); this.config.user = copyUser(config.user); this.logger = config.logger; this.setup = this.init(onUpdate, hasEventListeners).catch(error => this.dataSourceErrorHandler(error)); } private async init(onUpdate: (keys: string[]) => void, hasEventListeners: () => boolean) { const clientContext = new ClientContext(this.config.sdkKey, this.config, this.platform); this.store = this.config.storeFactory(clientContext); this.dataSourceUpdates = new DataSourceUpdates(this.store, hasEventListeners, keys => { if (!this.closed && !this.contextChanging) onUpdate(keys); }, this.logger); await this.store.identify(this.config.user); if (this.closed) return; this.evaluator = new Evaluator(this.store, this.logger); // A restored snapshot, including an empty snapshot or archive markers, takes // precedence over bootstrap just as it does when switching user contexts. if (!this.store.initialized() && Object.keys(this.store.all(DataKinds.Flags)[0]).length === 0) { await this.config.bootstrapProvider.populate(this.config.user.keyId, this.dataSourceUpdates); } if (this.closed) return; if (this.config.offline) { this.eventProcessor = new NullEventProcessor(); this.dataSynchronizer = new NullDataSynchronizer(); this.initSuccess(); } else { if (this.config.disableEvents) { this.eventProcessor = new NullEventProcessor(); } else { this.eventProcessor = new DefaultEventProcessor(clientContext); } const listeners = createStreamListeners(this.dataSourceUpdates, this.logger, { put: () => { this.fullSync.committed(); this.initSuccess(); }, patch: () => this.initSuccess() }); const createPollingSync = () => new PollingDataSynchronizer( this.config, new Requestor(this.config.sdkKey, this.config, this.platform.info, this.platform.requests), () => this.store!.version, listeners, this.fullSync, (e) => this.dataSourceErrorHandler(e), ); const onWebSocketNetworkError = () => { if (this.closed || this.contextChanging) return; this.logger?.warn('WebSocket connection failed on initial attempt, falling back to polling'); this.dataSynchronizer?.stop(); const pollSync = createPollingSync(); this.dataSynchronizer = pollSync; pollSync.start(); }; const dataSynchronizer = this.config.dataSyncMode === DataSyncModeEnum.STREAMING ? new WebSocketDataSynchronizer( this.config.sdkKey, this.config.user, clientContext, this.platform.webSocket, () => this.store!.version, listeners, this.config.webSocketPingInterval, this.fullSync, this.config.enablePollingFallback ? onWebSocketNetworkError : undefined ) : createPollingSync(); this.customSynchronizer = this.config.dataSynchronizerFactory?.( clientContext, this.store, this.dataSourceUpdates, () => this.initSuccess(), (e) => this.dataSourceErrorHandler(e), ); this.dataSynchronizer = this.customSynchronizer ?? dataSynchronizer; } if (!this.contextChanging) this.start(); } async identify(user: IUser) { const validator = new UserValidator(); if (!validator.is(user)) { validator.messages.forEach((error: string) => { this.logger?.warn(error); }); return; } if (this.closed) return; const context = copyUser(user); const generation = ++this.contextGeneration; const isCurrent = () => !this.closed && generation === this.contextGeneration; this.contextChanging = true; this.fullSync.reset(); clearTimeout(this.initializationTimer); this.initReject?.(new Error('Initialization superseded by Identify')); this.initializedPromise = undefined; this.initResolve = this.initReject = undefined; this.rejectionReason = undefined; this.state = ClientState.Initializing; this.dataSourceUpdates?.invalidateContext(); this.dataSynchronizer?.stop(); await this.setup; if (!isCurrent()) return; this.dataSynchronizer?.stop(); const [oldFlags, oldVersion] = this.store!.all(DataKinds.Flags); const oldData = { flags: { ...oldFlags }, version: oldVersion }; this.config.user = context; try { // Drain any previous commit before selecting the new store context. await this.dataSourceUpdates!.identify(context); if (!isCurrent()) return; if (!this.store!.initialized() && Object.keys(this.store!.all(DataKinds.Flags)[0]).length === 0) { await this.config.bootstrapProvider.populate(context.keyId, this.dataSourceUpdates!); } if (!isCurrent()) return; this.contextChanging = false; const [flags, version] = this.store!.all(DataKinds.Flags); this.dataSourceUpdates!.checkUpdates(oldData, { flags, version }); if (!isCurrent()) return; if (this.config.offline) { this.initSuccess(); } else { this.startInitializationTimer(); const synchronizer = this.dataSynchronizer!; try { await synchronizer.identify(context); if (isCurrent() && this.dataSynchronizer === synchronizer && synchronizer === this.customSynchronizer) { // Custom Identify selects the user; start resumes the stopped source. // Readiness still requires its initialization-success callback. synchronizer.start(); } } catch (error) { // Polling fallback now owns readiness; stopping the old stream is not a failure. if (this.dataSynchronizer !== synchronizer) return; throw error; } } } catch (error) { if (isCurrent()) { this.contextChanging = false; // Polling may report the error through its callback before rejecting Identify. if (this.reportedSourceError?.generation !== generation || this.reportedSourceError.error !== error) { this.dataSourceErrorHandler(error); } } } } private start() { if (this.config.offline) { return; } this.dataSynchronizer!.start(); this.startInitializationTimer(); } private startInitializationTimer() { clearTimeout(this.initializationTimer); const generation = this.contextGeneration; this.initializationTimer = setTimeout(() => { if (this.closed || generation !== this.contextGeneration) return; if (!this.initialized()) { const msg = `FbClient failed to start successfully within ${ this.config.startWaitTime } milliseconds. ` + 'This error usually indicates a connection issue with FeatBit or an invalid sdkKey.' + 'Please double-check your sdkKey and streamingUri/pollingUri configuration. ' + 'We will continue to initialize the FbClient, it still have a chance to get to work ' + 'if it\'s a temporary network issue'; const error = new TimeoutError(msg); this.state = ClientState.Failed; this.rejectionReason = error; this.initReject?.(error); return this.logger?.warn(msg); } }, this.config.startWaitTime); } initialized(): boolean { return !this.closed && !this.contextChanging && this.state === ClientState.Initialized; } waitForInitialization(): Promise { if (this.closed) return Promise.reject(new Error('Client closed')); // An initialization promise is only created if someone is going to use that promise. // If we always created an initialization promise, and there was no call waitForInitialization // by the time the promise was rejected, then that would result in an unhandled promise // rejection. // Initialization promise was created by a previous call to waitForInitialization. if (this.initializedPromise) { return this.initializedPromise; } // Initialization completed before waitForInitialization was called, so we have completed // and there was no promise. So we make a resolved promise and return it. if (this.state === ClientState.Initialized) { this.initializedPromise = Promise.resolve(this); return this.initializedPromise; } // Initialization failed before waitForInitialization was called, so we have completed // and there was no promise. So we make a rejected promise and return it. if (this.state === ClientState.Failed) { this.initializedPromise = Promise.reject(this.rejectionReason); return this.initializedPromise; } if (!this.initializedPromise) { this.initializedPromise = new Promise((resolve, reject) => { this.initResolve = resolve; this.initReject = reject; }); } return this.initializedPromise; } boolVariation( key: string, defaultValue: boolean ): boolean { return this.evaluateCore(key, defaultValue, ValueConverters.bool).value!; } boolVariationDetail( key: string, defaultValue: boolean ): IEvalDetail { return this.evaluateCore(key, defaultValue, ValueConverters.bool); } jsonVariation(key: string, defaultValue: FlagValue): FlagValue { return this.evaluateCore(key, defaultValue, ValueConverters.json).value!; } jsonVariationDetail(key: string, defaultValue: FlagValue): IEvalDetail { return this.evaluateCore(key, defaultValue, ValueConverters.json); } numberVariation(key: string, defaultValue: number): number { return this.evaluateCore(key, defaultValue, ValueConverters.number).value!; } numberVariationDetail(key: string, defaultValue: number): IEvalDetail { return this.evaluateCore(key, defaultValue, ValueConverters.number); } stringVariation(key: string, defaultValue: string): string { return this.evaluateCore(key, defaultValue, ValueConverters.string).value!; } stringVariationDetail(key: string, defaultValue: string): IEvalDetail { return this.evaluateCore(key, defaultValue, ValueConverters.string); } variation(key: string, defaultValue: FlagValue): FlagValue { return this.evaluateCore(key, defaultValue).value!; } variationDetail(key: string, defaultValue: FlagValue): IEvalDetail { return this.evaluateCore(key, defaultValue); } getAllVariations(): Promise[]> { if (this.contextChanging || !this.evaluator) return Promise.resolve([]); const context = Context.fromUser(this.config.user); if (!context.valid) { const error = new ClientError( `${ context.message ?? 'User not valid;' } returning default value.`, ); this.onError(error); return Promise.resolve([]); } const [flags, _] = this.store!.all(DataKinds.Flags); const result = Object.keys(flags).map(flagKey => { const evalResult = this.evaluator!.evaluate(flagKey); return {flagKey, kind: evalResult.kind, reason: evalResult.reason, value: evalResult.value?.variation}; }); return Promise.resolve(result); } async close(): Promise { if (this.closed) return; this.closed = true; ++this.contextGeneration; clearTimeout(this.initializationTimer); this.dataSourceUpdates?.invalidateContext(); this.dataSynchronizer?.close(); this.store?.close(); this.initReject?.(new Error('Client closed')); await this.eventProcessor?.close(); } track(eventName: string, metricValue?: number | undefined): void { const metricEvent = new MetricEvent(this.config.user, eventName, this.platform.info.appType, metricValue ?? 1); this.eventProcessor!.record(metricEvent); return; } async flush(callback?: (res: boolean) => void): Promise { try { await this.eventProcessor!.flush(); callback?.(true); return true; } catch (err) { callback?.(false); return false; } } evaluateCore( flagKey: string, defaultValue: TValue, typeConverter?: (value: string) => IConvertResult ): IEvalDetail { if (this.contextChanging || !this.evaluator) { return { flagKey, kind: ReasonKinds.FlagNotFound, reason: 'User context is changing', value: defaultValue }; } const context = Context.fromUser(this.config.user); if (!context.valid) { const error = new ClientError( `${ context.message ?? 'User not valid;' } returning default value.`, ); this.onError(error); return {flagKey, kind: ReasonKinds.Error, reason: error.message, value: defaultValue}; } const evalResult = this.evaluator!.evaluate(flagKey); if (evalResult.kind === ReasonKinds.FlagNotFound) { // flag not found, return default value const error = new ClientError(evalResult.reason!); this.onError(error); return {flagKey, kind: evalResult.kind, reason: evalResult.reason, value: defaultValue}; } if (!this.initialized()) { this.logger?.warn( 'Variation called before FeatBit client initialization completed (did you wait for the' + "'ready' event?)", ); } else { // send event const flag = this.store?.get(DataKinds.Flags, flagKey); if (flag?.origin === StoreItemOriginEnum.Remote && flag.insightsEnabled !== false) { this.eventProcessor!.record(evalResult.toEvalEvent(this.config.user)); } } let converter: (value: string) => IConvertResult; if (!typeConverter) { switch (evalResult.value!.variationType) { case VariationDataType.boolean: converter = ValueConverters.bool; break; case VariationDataType.number: converter = ValueConverters.number; break; case VariationDataType.json: converter = ValueConverters.json; break; case VariationDataType.string: converter = ValueConverters.string; break; default: converter = ValueConverters.string; } } else { converter = typeConverter; } const {isSucceeded, value} = converter(evalResult.value!.variation!); return isSucceeded ? {flagKey, kind: evalResult.kind, reason: evalResult.reason, value} : {flagKey, kind: ReasonKinds.WrongType, reason: 'type mismatch', value: defaultValue}; } private dataSourceErrorHandler(e: any) { if (this.closed || this.contextChanging) return; this.reportedSourceError = { generation: this.contextGeneration, error: e }; const error = e.code === 401 ? new Error('Authentication failed. Double check your SDK key.') : e; this.onError(error); this.onFailed(error); if (!this.initialized()) { this.state = ClientState.Failed; this.rejectionReason = error; this.initReject?.(error); } } private initSuccess() { if (this.closed || this.contextChanging) return; if (!this.initialized()) { clearTimeout(this.initializationTimer); this.state = ClientState.Initialized; this.logger?.info('FbClient started successfully.'); this.initResolve?.(this); this.initResolve = this.initReject = undefined; this.onReady(); } } }