|
| 1 | +import { |
| 2 | + Configuration, |
| 3 | + Context, |
| 4 | + createDataSourceStatusManager, |
| 5 | + createFDv2DataSource, |
| 6 | + createPollingInitializer, |
| 7 | + createPollingSynchronizer, |
| 8 | + createStreamingBase, |
| 9 | + createStreamingSynchronizer, |
| 10 | + createSynchronizerSlot, |
| 11 | + DataManager, |
| 12 | + DataSourceStatusManager, |
| 13 | + FDv2DataSource, |
| 14 | + fdv2Endpoints, |
| 15 | + fdv2Poll, |
| 16 | + flagEvalPayloadToItemDescriptors, |
| 17 | + FlagManager, |
| 18 | + internal, |
| 19 | + LDEmitter, |
| 20 | + LDHeaders, |
| 21 | + LDIdentifyOptions, |
| 22 | + LDLogger, |
| 23 | + makeFDv2Requestor, |
| 24 | + Platform, |
| 25 | +} from '@launchdarkly/js-client-sdk-common'; |
| 26 | + |
| 27 | +import { BrowserIdentifyOptions } from './BrowserIdentifyOptions'; |
| 28 | + |
| 29 | +const logTag = '[BrowserFDv2DataManager]'; |
| 30 | + |
| 31 | +/** |
| 32 | + * A DataManager that uses the FDv2 protocol for flag delivery. |
| 33 | + * |
| 34 | + * Uses the FDv2DataSource orchestrator with: |
| 35 | + * - Polling initializer (fast one-shot for initial data) |
| 36 | + * - Streaming synchronizer (primary, for live updates) |
| 37 | + * - Polling synchronizer (fallback) |
| 38 | + */ |
| 39 | +export default class BrowserFDv2DataManager implements DataManager { |
| 40 | + private _dataSource?: FDv2DataSource; |
| 41 | + private _selector?: string; |
| 42 | + private _closed = false; |
| 43 | + private readonly _logger: LDLogger; |
| 44 | + private readonly _statusManager: DataSourceStatusManager; |
| 45 | + |
| 46 | + constructor( |
| 47 | + private readonly _platform: Platform, |
| 48 | + private readonly _flagManager: FlagManager, |
| 49 | + private readonly _credential: string, |
| 50 | + private readonly _config: Configuration, |
| 51 | + private readonly _baseHeaders: LDHeaders, |
| 52 | + emitter: LDEmitter, |
| 53 | + ) { |
| 54 | + this._logger = _config.logger; |
| 55 | + this._statusManager = createDataSourceStatusManager(emitter); |
| 56 | + } |
| 57 | + |
| 58 | + async identify( |
| 59 | + identifyResolve: () => void, |
| 60 | + identifyReject: (err: Error) => void, |
| 61 | + context: Context, |
| 62 | + identifyOptions?: LDIdentifyOptions, |
| 63 | + ): Promise<void> { |
| 64 | + if (this._closed) { |
| 65 | + this._logger.debug(`${logTag} Identify called after data manager was closed.`); |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + // Tear down previous data source if any. |
| 70 | + this._dataSource?.close(); |
| 71 | + this._dataSource = undefined; |
| 72 | + this._selector = undefined; |
| 73 | + |
| 74 | + const plainContextString = JSON.stringify(Context.toLDContext(context)); |
| 75 | + const endpoints = fdv2Endpoints(); |
| 76 | + |
| 77 | + // Build query params: auth (required for browser — no auth header) and secure mode hash. |
| 78 | + const queryParams: { key: string; value: string }[] = [ |
| 79 | + { key: 'auth', value: this._credential }, |
| 80 | + ]; |
| 81 | + const browserIdentifyOptions = identifyOptions as BrowserIdentifyOptions | undefined; |
| 82 | + if (browserIdentifyOptions?.hash) { |
| 83 | + queryParams.push({ key: 'h', value: browserIdentifyOptions.hash }); |
| 84 | + } |
| 85 | + |
| 86 | + const requestor = makeFDv2Requestor( |
| 87 | + plainContextString, |
| 88 | + this._config.serviceEndpoints, |
| 89 | + endpoints.polling(), |
| 90 | + this._platform.requests, |
| 91 | + this._platform.encoding!, |
| 92 | + this._baseHeaders, |
| 93 | + queryParams, |
| 94 | + ); |
| 95 | + |
| 96 | + const selectorGetter = () => this._selector; |
| 97 | + |
| 98 | + const dataCallback = (payload: internal.Payload) => { |
| 99 | + this._logger.debug( |
| 100 | + `${logTag} dataCallback: type=${payload.type}, updates=${payload.updates.length}, state=${payload.state}`, |
| 101 | + ); |
| 102 | + |
| 103 | + // Track selector for subsequent basis requests. |
| 104 | + if (payload.state) { |
| 105 | + this._selector = payload.state; |
| 106 | + } |
| 107 | + |
| 108 | + if (payload.type === 'none') { |
| 109 | + // 304 / no changes — nothing to apply. |
| 110 | + return; |
| 111 | + } |
| 112 | + |
| 113 | + const descriptors = flagEvalPayloadToItemDescriptors(payload.updates); |
| 114 | + this._logger.debug(`${logTag} descriptors: ${JSON.stringify(Object.keys(descriptors))}`); |
| 115 | + |
| 116 | + if (payload.type === 'full') { |
| 117 | + this._flagManager.init(context, descriptors); |
| 118 | + } else { |
| 119 | + // 'partial' — incremental updates |
| 120 | + Object.entries(descriptors).forEach(([key, descriptor]) => { |
| 121 | + this._logger.debug(`${logTag} upserting: key=${key}, version=${descriptor.version}`); |
| 122 | + this._flagManager.upsert(context, key, descriptor); |
| 123 | + }); |
| 124 | + } |
| 125 | + }; |
| 126 | + |
| 127 | + // Polling initializer — fast one-shot for initial data. |
| 128 | + const pollingInitFactory = (sg: () => string | undefined) => |
| 129 | + createPollingInitializer(requestor, this._logger, sg); |
| 130 | + |
| 131 | + // Streaming synchronizer — primary, for live updates. |
| 132 | + const streamingEndpoints = endpoints.streaming(); |
| 133 | + const streamingSyncFactory = (_sg: () => string | undefined) => { |
| 134 | + const streamUriPath = streamingEndpoints.pathGet( |
| 135 | + this._platform.encoding!, |
| 136 | + plainContextString, |
| 137 | + ); |
| 138 | + const base = createStreamingBase({ |
| 139 | + requests: this._platform.requests, |
| 140 | + serviceEndpoints: this._config.serviceEndpoints, |
| 141 | + streamUriPath, |
| 142 | + parameters: queryParams, |
| 143 | + headers: this._baseHeaders, |
| 144 | + initialRetryDelayMillis: this._config.streamInitialReconnectDelay * 1000, |
| 145 | + logger: this._logger, |
| 146 | + pingHandler: { |
| 147 | + handlePing: () => fdv2Poll(requestor, selectorGetter(), false, this._logger), |
| 148 | + }, |
| 149 | + }); |
| 150 | + return createStreamingSynchronizer(base); |
| 151 | + }; |
| 152 | + |
| 153 | + // Polling synchronizer — fallback if streaming fails. |
| 154 | + const pollingSyncFactory = (sg: () => string | undefined) => |
| 155 | + createPollingSynchronizer(requestor, this._logger, sg, this._config.pollInterval * 1000); |
| 156 | + |
| 157 | + this._dataSource = createFDv2DataSource({ |
| 158 | + initializerFactories: [pollingInitFactory], |
| 159 | + synchronizerSlots: [ |
| 160 | + createSynchronizerSlot(streamingSyncFactory), |
| 161 | + createSynchronizerSlot(pollingSyncFactory), |
| 162 | + ], |
| 163 | + dataCallback, |
| 164 | + statusManager: this._statusManager, |
| 165 | + selectorGetter, |
| 166 | + logger: this._logger, |
| 167 | + // Shorter fallback for easier manual testing (default is 120s). |
| 168 | + fallbackTimeoutMs: 10_000, |
| 169 | + }); |
| 170 | + |
| 171 | + try { |
| 172 | + await this._dataSource.start(); |
| 173 | + identifyResolve(); |
| 174 | + } catch (err) { |
| 175 | + identifyReject(err instanceof Error ? err : new Error(String(err))); |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + close(): void { |
| 180 | + this._closed = true; |
| 181 | + this._dataSource?.close(); |
| 182 | + this._dataSource = undefined; |
| 183 | + } |
| 184 | +} |
0 commit comments