From 76ae29befa2bb6d5000f490e5b8413d2c373080e Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Thu, 19 Nov 2026 17:05:27 -0500 Subject: [PATCH] feat: Add FDv2 data system support to the Electron SDK --- .../ElectronClient.fdv2.network.test.ts | 98 ++++ .../__tests__/ElectronClient.fdv2.test.ts | 431 ++++++++++++++++++ .../__tests__/ElectronClient.ipcMain.test.ts | 10 + .../electron/__tests__/ElectronClient.test.ts | 24 + .../__tests__/bridge/LDClientBridge.test.ts | 11 + .../sdk/electron/__tests__/options.test.ts | 18 + .../renderer/ElectronRendererClient.test.ts | 8 + packages/sdk/electron/src/ElectronClient.ts | 170 ++++++- packages/sdk/electron/src/ElectronOptions.ts | 3 + packages/sdk/electron/src/LDClient.ts | 23 +- packages/sdk/electron/src/bridge/index.ts | 2 +- packages/sdk/electron/src/options.ts | 17 + .../src/renderer/ElectronRendererClient.ts | 2 +- 13 files changed, 804 insertions(+), 13 deletions(-) create mode 100644 packages/sdk/electron/__tests__/ElectronClient.fdv2.network.test.ts create mode 100644 packages/sdk/electron/__tests__/ElectronClient.fdv2.test.ts diff --git a/packages/sdk/electron/__tests__/ElectronClient.fdv2.network.test.ts b/packages/sdk/electron/__tests__/ElectronClient.fdv2.network.test.ts new file mode 100644 index 0000000000..3177aec113 --- /dev/null +++ b/packages/sdk/electron/__tests__/ElectronClient.fdv2.network.test.ts @@ -0,0 +1,98 @@ +import type { FDv2DataManagerControl } from '@launchdarkly/js-client-sdk-common'; + +import { ElectronClient } from '../src/ElectronClient'; +import type { ElectronOptions } from '../src/ElectronOptions'; +import ElectronCrypto from '../src/platform/ElectronCrypto'; +import ElectronEncoding from '../src/platform/ElectronEncoding'; +import ElectronInfo from '../src/platform/ElectronInfo'; +import { createMockLogger } from './testHelpers'; + +// These tests use the real shared FDv2 data manager, so network and override changes go +// through the real debounce and reconcile. +jest.mock('../src/platform/ElectronPlatform', () => ({ + __esModule: true, + default: jest.fn(() => ({ + crypto: new ElectronCrypto(), + info: new ElectronInfo(), + requests: { + createEventSource: jest.fn(() => ({ + addEventListener: jest.fn(), + close: jest.fn(), + })), + fetch: jest.fn(() => new Promise(() => {})), + getEventSourceCapabilities: () => ({ readTimeout: true, headers: true, customMethod: true }), + }, + encoding: new ElectronEncoding(), + storage: { + clear: jest.fn(async () => {}), + get: jest.fn(async () => null), + set: jest.fn(async () => {}), + }, + })), +})); + +const DEBOUNCE_WINDOW_MS = 1500; + +beforeEach(() => { + jest.useFakeTimers(); +}); + +afterEach(() => { + jest.useRealTimers(); +}); + +async function startClient( + dataSystem: ElectronOptions['dataSystem'] = { automaticModeSwitching: true }, +) { + const client = new ElectronClient( + 'client-side-id', + { kind: 'user', key: 'bob' }, + { + useClientSideId: true, + enableIPC: false, + sendEvents: false, + logger: createMockLogger(), + dataSystem, + }, + ); + client.start(); + await jest.advanceTimersByTimeAsync(10); + // @ts-ignore dataManager is protected. + const dataManager = client.dataManager as FDv2DataManagerControl; + return { client, dataManager }; +} + +it('applies an override when the app repeats it within the debounce window', async () => { + const { client, dataManager } = await startClient(); + + await client.setConnectionMode('polling'); + // Each repeat comes before the 1 second debounce window closes. + for (let i = 0; i < 5; i += 1) { + // eslint-disable-next-line no-await-in-loop + await jest.advanceTimersByTimeAsync(900); + // eslint-disable-next-line no-await-in-loop + await client.setConnectionMode('polling'); + } + + expect(dataManager.getCurrentMode()).toBe('polling'); + + await client.close(); +}); + +it('turns event sending off when a cleared override returns to a configured offline mode', async () => { + const { client, dataManager } = await startClient({ + automaticModeSwitching: { type: 'manual', initialConnectionMode: 'offline' }, + }); + const setEventSendingEnabled = jest.spyOn(client as any, 'setEventSendingEnabled'); + + await client.setConnectionMode('streaming'); + expect(setEventSendingEnabled).toHaveBeenLastCalledWith(true, false); + + await client.setConnectionMode(); + await jest.advanceTimersByTimeAsync(DEBOUNCE_WINDOW_MS); + + expect(dataManager.getCurrentMode()).toBe('offline'); + expect(setEventSendingEnabled).toHaveBeenLastCalledWith(false, false); + + await client.close(); +}); diff --git a/packages/sdk/electron/__tests__/ElectronClient.fdv2.test.ts b/packages/sdk/electron/__tests__/ElectronClient.fdv2.test.ts new file mode 100644 index 0000000000..4bf21d72c9 --- /dev/null +++ b/packages/sdk/electron/__tests__/ElectronClient.fdv2.test.ts @@ -0,0 +1,431 @@ +import type { ElectronOptions } from '../src/ElectronOptions'; +import ElectronCrypto from '../src/platform/ElectronCrypto'; +import ElectronEncoding from '../src/platform/ElectronEncoding'; +import ElectronInfo from '../src/platform/ElectronInfo'; +import { createMockLogger } from './testHelpers'; + +jest.mock('../src/platform/ElectronPlatform', () => ({ + __esModule: true, + default: jest.fn(() => ({ + crypto: new ElectronCrypto(), + info: new ElectronInfo(), + requests: { + createEventSource: jest.fn(), + fetch: jest.fn(), + getEventSourceCapabilities: jest.fn(), + }, + encoding: new ElectronEncoding(), + storage: { + clear: jest.fn(), + get: jest.fn(), + set: jest.fn(), + }, + })), +})); + +// The FDv1 data manager is automocked so a test can prove it is never constructed on the +// FDv2 path. +jest.mock('../src/ElectronDataManager'); + +// Tracks the mode last passed to the mock FDv2 data manager. Seeded from opts.foregroundMode +// when createFDv2DataManagerBase is called. +let mockCurrentMode = 'streaming'; + +// Captures the opts passed to createFDv2DataManagerBase so tests can call buildQueryParams +// and inspect the desktop defaults directly. +let capturedFDv2Opts: + | { + foregroundMode?: string; + backgroundMode?: unknown; + buildQueryParams: (opts?: { hash?: string }) => { key: string; value: string }[]; + } + | undefined; + +const mockSetConnectionMode = jest.fn((mode: string) => { + mockCurrentMode = mode; +}); +const mockSetNetworkState = jest.fn(); + +jest.mock('@launchdarkly/js-client-sdk-common', () => ({ + ...jest.requireActual('@launchdarkly/js-client-sdk-common'), + createFDv2DataManagerBase: jest.fn((opts: any) => { + capturedFDv2Opts = opts; + mockCurrentMode = opts.foregroundMode ?? 'streaming'; + return { + identify: jest.fn(), + close: jest.fn(), + setConnectionMode: mockSetConnectionMode, + setNetworkState: mockSetNetworkState, + getCurrentMode: () => mockCurrentMode, + }; + }), +})); + +import { createFDv2DataManagerBase, LDClientImpl } from '@launchdarkly/js-client-sdk-common'; + +import { createClient } from '../src'; +import ElectronDataManager from '../src/ElectronDataManager'; + +const DEFAULT_INITIAL_CONTEXT = { kind: 'user' as const, key: 'bob' }; +let logger: ReturnType; + +beforeAll(() => { + jest.useFakeTimers(); +}); + +afterAll(() => { + jest.useRealTimers(); +}); + +beforeEach(() => { + jest.clearAllMocks(); + capturedFDv2Opts = undefined; + mockCurrentMode = 'streaming'; + logger = createMockLogger(); +}); + +function makeFDv2Client(options: ElectronOptions = {}) { + return createClient('client-side-id', DEFAULT_INITIAL_CONTEXT, { + useClientSideId: true, + enableIPC: false, + dataSystem: {}, + diagnosticOptOut: true, + sendEvents: false, + logger, + ...options, + }); +} + +// ------ Data manager selection ------ + +it('uses the FDv2 data manager when dataSystem is configured', () => { + makeFDv2Client(); + + expect(createFDv2DataManagerBase).toHaveBeenCalledTimes(1); + expect(ElectronDataManager).not.toHaveBeenCalled(); +}); + +it('keeps the FDv1 data manager when dataSystem is not configured', () => { + createClient('client-side-id', DEFAULT_INITIAL_CONTEXT, { + useClientSideId: true, + enableIPC: false, + diagnosticOptOut: true, + sendEvents: false, + logger, + }); + + expect(ElectronDataManager).toHaveBeenCalledTimes(1); + expect(createFDv2DataManagerBase).not.toHaveBeenCalled(); +}); + +it('ignores useReport with a warning and still uses the FDv2 data manager when dataSystem is configured', () => { + makeFDv2Client({ useReport: true }); + + expect(createFDv2DataManagerBase).toHaveBeenCalledTimes(1); + expect(ElectronDataManager).not.toHaveBeenCalled(); + expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('useReport')); +}); + +it('passes the desktop defaults so streaming is the FDv2 foreground mode and there is no background mode', () => { + makeFDv2Client(); + + expect(capturedFDv2Opts).toBeDefined(); + expect(capturedFDv2Opts!.foregroundMode).toBe('streaming'); + expect(capturedFDv2Opts!.backgroundMode).toBeUndefined(); +}); + +// ------ FDv2 initial mode ------ + +it('reports offline at construction when FDv2 manual switching starts offline', () => { + const client = makeFDv2Client({ + dataSystem: { automaticModeSwitching: { type: 'manual', initialConnectionMode: 'offline' } }, + }); + + expect(client.isOffline()).toBe(true); + expect(client.getConnectionMode()).toBe('offline'); +}); + +it('reports polling at construction when FDv2 manual switching starts in polling', () => { + const client = makeFDv2Client({ + dataSystem: { automaticModeSwitching: { type: 'manual', initialConnectionMode: 'polling' } }, + }); + + expect(client.getConnectionMode()).toBe('polling'); + expect(client.isOffline()).toBe(false); +}); + +it('reports streaming at construction with the default FDv2 configuration', () => { + const client = makeFDv2Client(); + + expect(client.getConnectionMode()).toBe('streaming'); + expect(client.isOffline()).toBe(false); +}); + +// ------ buildQueryParams ------ + +it('buildQueryParams returns no parameters in FDv2 mobile key mode', () => { + createClient('mobile-key-123', DEFAULT_INITIAL_CONTEXT, { + enableIPC: false, + dataSystem: {}, + diagnosticOptOut: true, + sendEvents: false, + logger, + }); + + expect(capturedFDv2Opts).toBeDefined(); + expect(capturedFDv2Opts!.buildQueryParams()).toEqual([]); +}); + +it('buildQueryParams ignores a per-identify hash with a warning in FDv2 mobile key mode', () => { + createClient('mobile-key-123', DEFAULT_INITIAL_CONTEXT, { + enableIPC: false, + dataSystem: {}, + diagnosticOptOut: true, + sendEvents: false, + logger, + }); + + expect(capturedFDv2Opts!.buildQueryParams({ hash: 'should-not-leak' })).toEqual([]); + expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('hash')); +}); + +it('buildQueryParams returns the auth parameter in FDv2 client-side ID mode', () => { + makeFDv2Client(); + + expect(capturedFDv2Opts!.buildQueryParams()).toEqual([{ key: 'auth', value: 'client-side-id' }]); +}); + +it('buildQueryParams adds the h parameter when a hash is configured in client-side ID mode', () => { + makeFDv2Client({ hash: 'secure-hash-abc' }); + + expect(capturedFDv2Opts!.buildQueryParams()).toEqual([ + { key: 'auth', value: 'client-side-id' }, + { key: 'h', value: 'secure-hash-abc' }, + ]); +}); + +it('buildQueryParams uses the per-identify hash instead of the construction-time hash', () => { + makeFDv2Client({ hash: 'construction-hash' }); + + expect(capturedFDv2Opts!.buildQueryParams({ hash: 'per-identify-hash' })).toEqual([ + { key: 'auth', value: 'client-side-id' }, + { key: 'h', value: 'per-identify-hash' }, + ]); +}); + +it('buildQueryParams uses the construction-time hash when the per-identify hash is omitted', () => { + makeFDv2Client({ hash: 'construction-hash' }); + + expect(capturedFDv2Opts!.buildQueryParams({})).toEqual([ + { key: 'auth', value: 'client-side-id' }, + { key: 'h', value: 'construction-hash' }, + ]); +}); + +// ------ FDv2 setConnectionMode ------ + +it('setConnectionMode delegates to the FDv2 data manager', async () => { + const client = makeFDv2Client(); + + await client.setConnectionMode('offline'); + + expect(mockSetConnectionMode).toHaveBeenCalledWith('offline'); + expect(client.getConnectionMode()).toBe('offline'); + expect(client.isOffline()).toBe(true); +}); + +it('isOffline returns false after switching back to streaming in FDv2 mode', async () => { + const client = makeFDv2Client(); + + await client.setConnectionMode('offline'); + await client.setConnectionMode('streaming'); + + expect(client.getConnectionMode()).toBe('streaming'); + expect(client.isOffline()).toBe(false); +}); + +it('setConnectionMode forwards the current mode so the FDv2 data manager can dedupe', async () => { + const client = makeFDv2Client(); + + await client.setConnectionMode('streaming'); + + expect(mockSetConnectionMode).toHaveBeenCalledWith('streaming'); + expect(client.getConnectionMode()).toBe('streaming'); +}); + +it('reports the data manager mode when the network moves the data system offline in FDv2', () => { + const client = makeFDv2Client(); + + mockCurrentMode = 'offline'; + + expect(client.getConnectionMode()).toBe('offline'); + expect(client.isOffline()).toBe(true); +}); + +it('falls back to the requested mode when the data manager reports an unsupported mode in FDv2', () => { + const client = makeFDv2Client(); + + mockCurrentMode = 'background'; + + expect(client.getConnectionMode()).toBe('streaming'); + expect(client.isOffline()).toBe(false); +}); + +it('reports a requested mode at once while the data system has not applied it yet in FDv2', async () => { + const client = makeFDv2Client(); + + await client.setConnectionMode('offline'); + + expect(mockCurrentMode).toBe('offline'); + mockCurrentMode = 'streaming'; + expect(client.getConnectionMode()).toBe('offline'); + expect(client.isOffline()).toBe(true); +}); + +it('keeps the requested mode when a later network change moves the data system in FDv2', async () => { + const client = makeFDv2Client(); + await client.setConnectionMode('polling'); + + mockCurrentMode = 'offline'; + + expect(client.getConnectionMode()).toBe('polling'); + expect(client.isOffline()).toBe(false); +}); + +it('clears the FDv2 override when setConnectionMode is called without a mode', async () => { + const client = makeFDv2Client(); + await client.setConnectionMode('polling'); + mockSetConnectionMode.mockClear(); + + await client.setConnectionMode(); + + expect(mockSetConnectionMode).toHaveBeenCalledTimes(1); + expect(mockSetConnectionMode).toHaveBeenCalledWith(undefined); + expect(logger.warn).not.toHaveBeenCalled(); + + // Without the override, the client reports the data system mode again. + mockCurrentMode = 'offline'; + expect(client.getConnectionMode()).toBe('offline'); +}); + +it('setConnectionMode forwards and reports the mode while the data system is offline in FDv2', async () => { + const client = makeFDv2Client(); + await client.setConnectionMode('streaming'); + mockSetConnectionMode.mockClear(); + mockCurrentMode = 'offline'; + + await client.setConnectionMode('streaming'); + + expect(mockSetConnectionMode).toHaveBeenCalledWith('streaming'); + expect(client.getConnectionMode()).toBe('streaming'); +}); + +it('concurrent setConnectionMode calls run in call order in FDv2', async () => { + const client = makeFDv2Client(); + + const p1 = client.setConnectionMode('offline'); + const p2 = client.setConnectionMode('streaming'); + await Promise.all([p1, p2]); + + expect(mockSetConnectionMode.mock.calls).toEqual([['offline'], ['streaming']]); + expect(client.getConnectionMode()).toBe('streaming'); +}); + +it('setConnectionMode after close is a no-op in FDv2', async () => { + const client = makeFDv2Client(); + + await client.close(); + await client.setConnectionMode('offline'); + + expect(mockSetConnectionMode).not.toHaveBeenCalled(); +}); + +it('setConnectionMode with an invalid mode warns and does not delegate in FDv2', async () => { + const client = makeFDv2Client(); + + // @ts-ignore JS callers can pass any string. + await client.setConnectionMode('invalid-mode'); + + expect(mockSetConnectionMode).not.toHaveBeenCalled(); + expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('invalid-mode')); +}); + +it('setConnectionMode rejects and keeps the mode when flush fails on the way offline in FDv2', async () => { + const client = makeFDv2Client(); + const flushSpy = jest + .spyOn(LDClientImpl.prototype, 'flush') + .mockRejectedValueOnce(new Error('flush failed')); + + await expect(client.setConnectionMode('offline')).rejects.toThrow('flush failed'); + + expect(client.getConnectionMode()).toBe('streaming'); + expect(mockSetConnectionMode).not.toHaveBeenCalled(); + flushSpy.mockRestore(); +}); + +it('setConnectionMode queue stays usable after a failed offline transition in FDv2', async () => { + const client = makeFDv2Client(); + const flushSpy = jest + .spyOn(LDClientImpl.prototype, 'flush') + .mockRejectedValueOnce(new Error('flush failed')); + + await expect(client.setConnectionMode('offline')).rejects.toThrow('flush failed'); + flushSpy.mockRestore(); + + await client.setConnectionMode('polling'); + + expect(client.getConnectionMode()).toBe('polling'); + expect(mockSetConnectionMode).toHaveBeenCalledWith('polling'); +}); + +// ------ FDv2 network availability ------ + +it('forwards setNetworkAvailability to the FDv2 data manager when network switching is enabled', () => { + const client = makeFDv2Client({ + dataSystem: { + automaticModeSwitching: { type: 'automatic', lifecycle: false, network: true }, + }, + }); + + client.setNetworkAvailability(false); + client.setNetworkAvailability(true); + + expect(mockSetNetworkState.mock.calls).toEqual([['unavailable'], ['available']]); +}); + +it('forwards setNetworkAvailability when automaticModeSwitching is true', () => { + const client = makeFDv2Client({ dataSystem: { automaticModeSwitching: true } }); + + client.setNetworkAvailability(false); + + expect(mockSetNetworkState).toHaveBeenCalledWith('unavailable'); +}); + +it('ignores setNetworkAvailability when automatic network switching is off, which is the desktop default', () => { + const client = makeFDv2Client(); + + client.setNetworkAvailability(false); + + expect(mockSetNetworkState).not.toHaveBeenCalled(); + expect(logger.debug).toHaveBeenCalledWith(expect.stringContaining('network switching')); +}); + +it('ignores setNetworkAvailability when granular switching leaves network off', () => { + const client = makeFDv2Client({ + dataSystem: { automaticModeSwitching: { type: 'automatic', lifecycle: false } }, + }); + + client.setNetworkAvailability(false); + + expect(mockSetNetworkState).not.toHaveBeenCalled(); +}); + +it('ignores setNetworkAvailability when automatic mode switching is manual', () => { + const client = makeFDv2Client({ + dataSystem: { automaticModeSwitching: { type: 'manual', initialConnectionMode: 'streaming' } }, + }); + + client.setNetworkAvailability(false); + + expect(mockSetNetworkState).not.toHaveBeenCalled(); +}); diff --git a/packages/sdk/electron/__tests__/ElectronClient.ipcMain.test.ts b/packages/sdk/electron/__tests__/ElectronClient.ipcMain.test.ts index 41dfc9233e..dd1bf650c7 100644 --- a/packages/sdk/electron/__tests__/ElectronClient.ipcMain.test.ts +++ b/packages/sdk/electron/__tests__/ElectronClient.ipcMain.test.ts @@ -362,6 +362,16 @@ describe('given an initialized ElectronClient', () => { expect(spy).toHaveBeenNthCalledWith(1, 'streaming'); }); + it('handles setConnectionMode() without a mode as a clear', async () => { + const spy = jest.spyOn(client, 'setConnectionMode'); + spy.mockResolvedValueOnce(); + + await mockIpcMain.getHandler(getEventName('setConnectionMode'))?.({}, undefined); + + expect(spy).toHaveBeenCalledTimes(1); + expect(spy).toHaveBeenNthCalledWith(1, undefined); + }); + it('handles getConnectionMode() call', () => { const spy = jest.spyOn(client, 'getConnectionMode'); spy.mockReturnValueOnce('streaming'); diff --git a/packages/sdk/electron/__tests__/ElectronClient.test.ts b/packages/sdk/electron/__tests__/ElectronClient.test.ts index 9d7813d8ff..7cfa7076aa 100644 --- a/packages/sdk/electron/__tests__/ElectronClient.test.ts +++ b/packages/sdk/electron/__tests__/ElectronClient.test.ts @@ -731,6 +731,30 @@ it('can set connection mode to not offline', async () => { expect(setEventSendingEnabled).toHaveBeenNthCalledWith(1, true, false); }); +it('ignores setConnectionMode without a mode on the default data source', async () => { + const logger: LDLogger = { + debug: jest.fn(), + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + }; + const client = new ElectronClient('client-side-id', DEFAULT_INITIAL_CONTEXT, { + enableIPC: false, + diagnosticOptOut: true, + initialConnectionMode: 'polling', + logger, + }); + const setConnectionMode = jest.spyOn((client as any).dataManager, 'setConnectionMode'); + + await client.setConnectionMode(); + + expect(setConnectionMode).not.toHaveBeenCalled(); + expect(client.getConnectionMode()).toBe('polling'); + expect(logger.warn).toHaveBeenCalledWith( + '[ElectronClient] setConnectionMode without a mode is supported only with the dataSystem option, ignoring.', + ); +}); + it('does not re-enable event sending when the connection mode is set after close', async () => { const client = new ElectronClient('client-side-id', DEFAULT_INITIAL_CONTEXT, { enableIPC: false, diff --git a/packages/sdk/electron/__tests__/bridge/LDClientBridge.test.ts b/packages/sdk/electron/__tests__/bridge/LDClientBridge.test.ts index e5a8de2e14..3098ca7e90 100644 --- a/packages/sdk/electron/__tests__/bridge/LDClientBridge.test.ts +++ b/packages/sdk/electron/__tests__/bridge/LDClientBridge.test.ts @@ -157,6 +157,17 @@ describe('given a registered LDClientBridge', () => { ); }); + it('passes setConnectionMode() without a mode through to ipcRenderer', async () => { + await bridge.setConnectionMode(); + + expect(ipcRenderer.invoke).toHaveBeenCalledTimes(1); + expect(ipcRenderer.invoke).toHaveBeenNthCalledWith( + 1, + getEventName('setConnectionMode'), + undefined, + ); + }); + it('passes getConnectionMode() call through to ipcRenderer', () => { (ipcRenderer.sendSync as jest.Mock).mockReturnValueOnce('streaming'); diff --git a/packages/sdk/electron/__tests__/options.test.ts b/packages/sdk/electron/__tests__/options.test.ts index 17790179de..5b4fdd8159 100644 --- a/packages/sdk/electron/__tests__/options.test.ts +++ b/packages/sdk/electron/__tests__/options.test.ts @@ -208,6 +208,24 @@ it('does not throw when hash is invalid and dropped before the credential check' ); }); +it('warns when both dataSystem and initialConnectionMode are set', () => { + const logger = createMockLogger(); + + validateOptions({ dataSystem: {}, initialConnectionMode: 'polling' }, logger); + + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('initialConnectionMode')); + expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('dataSystem')); +}); + +it('does not warn when only dataSystem is set', () => { + const logger = createMockLogger(); + + validateOptions({ dataSystem: {} }, logger); + + expect(logger.warn).not.toHaveBeenCalled(); +}); + it('applies a custom storage implementation with get, set and clear functions', () => { const logger = createMockLogger(); const storage = { get: jest.fn(), set: jest.fn(), clear: jest.fn() }; diff --git a/packages/sdk/electron/__tests__/renderer/ElectronRendererClient.test.ts b/packages/sdk/electron/__tests__/renderer/ElectronRendererClient.test.ts index 8eb6af11be..8d4d714920 100644 --- a/packages/sdk/electron/__tests__/renderer/ElectronRendererClient.test.ts +++ b/packages/sdk/electron/__tests__/renderer/ElectronRendererClient.test.ts @@ -158,6 +158,14 @@ it('passes setConnectionMode() call through to bridge', async () => { expect(ldClientBridge.setConnectionMode).toHaveBeenNthCalledWith(1, 'streaming'); }); +it('passes setConnectionMode() without a mode through to bridge', async () => { + const client = new ElectronRendererClient(clientSideId); + await client.setConnectionMode(); + + expect(ldClientBridge.setConnectionMode).toHaveBeenCalledTimes(1); + expect(ldClientBridge.setConnectionMode).toHaveBeenNthCalledWith(1, undefined); +}); + it('passes getConnectionMode() call through to bridge', () => { (ldClientBridge.getConnectionMode as jest.Mock).mockReturnValueOnce('streaming'); diff --git a/packages/sdk/electron/src/ElectronClient.ts b/packages/sdk/electron/src/ElectronClient.ts index b24e466907..1f7ef207fe 100644 --- a/packages/sdk/electron/src/ElectronClient.ts +++ b/packages/sdk/electron/src/ElectronClient.ts @@ -7,21 +7,30 @@ import { browserFdv1Endpoints, Configuration, ConnectionMode, + createDefaultSourceFactoryProvider, + createFDv2DataManagerBase, + DESKTOP_DATA_SYSTEM_DEFAULTS, + DESKTOP_TRANSITION_TABLE, + FDv2DataManagerControl, FlagManager, internal, LDClientImpl, + LDClientDataSystemOptions, LDClientInternalOptions, LDContext, LDEmitter, LDEmitterEventName, LDFlagValue, LDHeaders, + LDIdentifyOptions, LDIdentifyResult, LDLogger, LDPluginEnvironmentMetadata, LDWaitForInitializationOptions, LDWaitForInitializationResult, mobileFdv1Endpoints, + MODE_TABLE, + resolveForegroundMode, safeRegisterDebugOverridePlugins, } from '@launchdarkly/js-client-sdk-common'; @@ -44,9 +53,34 @@ import ElectronPlatform from './platform/ElectronPlatform'; const VALID_LOG_LEVELS: ReadonlySet = new Set(['error', 'warn', 'info', 'debug']); +// Desktop defaults automatic switching to off, so a granular config without `network` stays off. +function shouldAutoSwitchNetwork( + config: LDClientDataSystemOptions['automaticModeSwitching'], +): boolean { + if (config === true) { + return true; + } + if (typeof config === 'object' && config.type === 'automatic') { + return config.network ?? false; + } + return false; +} + export class ElectronClient extends LDClientImpl { private readonly _plugins: LDPlugin[]; + // The initial mode, which applies on the FDv2 path before any explicit request. It is also the + // fallback when the data system reports a mode the desktop API does not expose. The FDv1 path + // reads the mode from its data manager. + private _connectionMode: ConnectionMode; + + // The mode set by an explicit setConnectionMode call on the FDv2 path. It stays until a call + // without a mode clears it, or until close. + private _fdv2ModeOverride?: ConnectionMode; + + // Serializes FDv2 mode transitions so concurrent callers cannot interleave flush() and + // setEventSendingEnabled() across the offline branch's await. + private _fdv2ConnectionModeQueue: Promise = Promise.resolve(); private _closed: boolean = false; private _ipcNamespace?: string; @@ -105,6 +139,7 @@ export class ElectronClient extends LDClientImpl { credentialType: useClientSideId ? 'clientSideId' : 'mobileKey', requiresStart: true, initialContext, + dataSystemDefaults: DESKTOP_DATA_SYSTEM_DEFAULTS, }; const derivedNs = deriveNamespace(credential, validatedElectronOptions.namespace); @@ -128,8 +163,54 @@ export class ElectronClient extends LDClientImpl { baseHeaders: LDHeaders, emitter: LDEmitter, diagnosticsManager?: internal.DiagnosticsManager, - ) => - new ElectronDataManager( + ) => { + if (configuration.dataSystem) { + const rawForegroundMode = resolveForegroundMode( + configuration.dataSystem, + DESKTOP_DATA_SYSTEM_DEFAULTS, + ); + // Desktop supports streaming, polling, and offline only. + const foregroundMode = + rawForegroundMode === 'streaming' || + rawForegroundMode === 'polling' || + rawForegroundMode === 'offline' + ? rawForegroundMode + : 'streaming'; + return createFDv2DataManagerBase({ + platform, + flagManager, + credential, + config: configuration, + baseHeaders, + emitter, + transitionTable: DESKTOP_TRANSITION_TABLE, + foregroundMode, + backgroundMode: undefined, + modeTable: MODE_TABLE, + sourceFactoryProvider: createDefaultSourceFactoryProvider(), + fdv1Endpoints: endpoints, + buildQueryParams: (identifyOptions?: LDIdentifyOptions) => { + const perIdentifyHash = (identifyOptions as ElectronIdentifyOptions | undefined) + ?.hash; + if (!useClientSideId) { + // The mobile endpoints do not support secure mode. Mobile key mode sends the + // Authorization header and no query parameters, so there is no place for a hash. + if (perIdentifyHash) { + logger.warn("[ElectronClient] 'hash' is ignored in mobile key mode."); + } + return []; + } + const params: { key: string; value: string }[] = [{ key: 'auth', value: credential }]; + // A per-identify hash replaces the construction-time hash, the same as the FDv1 path. + const hash = perIdentifyHash || validatedElectronOptions.hash; + if (hash) { + params.push({ key: 'h', value: hash }); + } + return params; + }, + }); + } + return new ElectronDataManager( platform, flagManager, credential, @@ -140,10 +221,25 @@ export class ElectronClient extends LDClientImpl { baseHeaders, emitter, diagnosticsManager, - ), + ); + }, internalOptions, ); + if (this.dataSystemConfig) { + const rawMode = resolveForegroundMode(this.dataSystemConfig, DESKTOP_DATA_SYSTEM_DEFAULTS); + if (rawMode !== 'offline' && rawMode !== 'streaming' && rawMode !== 'polling') { + this.logger.warn( + `[ElectronClient] Connection mode '${rawMode}' is not supported; defaulting to 'streaming'.`, + ); + this._connectionMode = 'streaming'; + } else { + this._connectionMode = rawMode; + } + } else { + this._connectionMode = validatedElectronOptions.initialConnectionMode; + } + this._plugins = validatedElectronOptions.plugins; this.setEventSendingEnabled(!this.isOffline(), false); @@ -179,9 +275,9 @@ export class ElectronClient extends LDClientImpl { return super.identifyResult(context, options); } - async setConnectionMode(mode: ConnectionMode): Promise { + async setConnectionMode(mode?: ConnectionMode): Promise { // JS callers and renderers can pass any value. Log it bounded so a long string stays small. - if (mode !== 'offline' && mode !== 'streaming' && mode !== 'polling') { + if (mode !== undefined && mode !== 'offline' && mode !== 'streaming' && mode !== 'polling') { this.logger.warn( `[ElectronClient] Unknown connection mode ${JSON.stringify(String(mode).slice(0, 64))}, ignoring.`, ); @@ -190,6 +286,39 @@ export class ElectronClient extends LDClientImpl { if (this._closed) { return; } + if (this.isFDv2) { + const task = this._fdv2ConnectionModeQueue.then(async () => { + // close() may run while this task waits in the queue. + if (this._closed) { + return; + } + // The FDv2 data manager dedupes. The reported mode can differ from the data system mode + // after a network change, so the mode is always forwarded. + // An undefined mode clears the override. The data system then returns to the configured + // mode, and to network switching when it is enabled. + const targetMode = mode ?? this._connectionMode; + if (targetMode === 'offline') { + await this.flush(); + this.setEventSendingEnabled(false, false); + } + (this.dataManager as FDv2DataManagerControl).setConnectionMode(mode); + this._fdv2ModeOverride = mode; + if (targetMode !== 'offline') { + this.setEventSendingEnabled(true, false); + } + }); + // The failure still reaches this caller. Keep the queue alive for the next one. + this._fdv2ConnectionModeQueue = task.catch(() => {}); + await task; + return; + } + + if (mode === undefined) { + this.logger.warn( + '[ElectronClient] setConnectionMode without a mode is supported only with the dataSystem option, ignoring.', + ); + return; + } if (mode === 'offline') { this.setEventSendingEnabled(false, true); } @@ -202,17 +331,40 @@ export class ElectronClient extends LDClientImpl { } getConnectionMode(): ConnectionMode { - const dataManager = this.dataManager as ElectronDataManager; - return dataManager.getConnectionMode(); + if (this.isFDv2) { + // An explicit request wins over network changes, and the data system applies it after a + // debounce, so the requested mode is reported at once. + if (this._fdv2ModeOverride) { + return this._fdv2ModeOverride; + } + // Without a request, network switching can move the data system offline. + const current = (this.dataManager as FDv2DataManagerControl).getCurrentMode(); + if (current === 'streaming' || current === 'polling' || current === 'offline') { + return current; + } + return this._connectionMode; + } + return (this.dataManager as ElectronDataManager).getConnectionMode(); } isOffline(): boolean { - const dataManager = this.dataManager as ElectronDataManager; - return dataManager.getConnectionMode() === 'offline'; + return this.getConnectionMode() === 'offline'; } setNetworkAvailability(available: boolean): void { const isAvailable = available === true; + if (this.isFDv2) { + if (!shouldAutoSwitchNetwork(this.dataSystemConfig?.automaticModeSwitching)) { + this.logger.debug( + '[ElectronClient] setNetworkAvailability ignored because automatic network switching is disabled in the dataSystem configuration.', + ); + return; + } + (this.dataManager as FDv2DataManagerControl).setNetworkState( + isAvailable ? 'available' : 'unavailable', + ); + return; + } (this.dataManager as ElectronDataManager).setNetworkAvailability(isAvailable); } diff --git a/packages/sdk/electron/src/ElectronOptions.ts b/packages/sdk/electron/src/ElectronOptions.ts index f25d229061..611d29c678 100644 --- a/packages/sdk/electron/src/ElectronOptions.ts +++ b/packages/sdk/electron/src/ElectronOptions.ts @@ -25,6 +25,9 @@ export interface ElectronOptions extends LDOptionsBase { * @remarks * Possible values are offline, streaming, or polling. See {@link ConnectionMode} for more information. * + * This option applies only to the default data source. When the `dataSystem` option is set, the + * SDK ignores it and logs a warning. Use `dataSystem.automaticModeSwitching` instead. + * * Defaults to streaming. */ initialConnectionMode?: ConnectionMode; diff --git a/packages/sdk/electron/src/LDClient.ts b/packages/sdk/electron/src/LDClient.ts index 17f0f38920..22493f60f0 100644 --- a/packages/sdk/electron/src/LDClient.ts +++ b/packages/sdk/electron/src/LDClient.ts @@ -36,7 +36,19 @@ export interface LDClient extends Omit { */ start(options?: LDStartOptions): Promise; - setConnectionMode(mode: ConnectionMode): Promise; + /** + * Sets the connection mode. With the `dataSystem` option, an explicit mode sets an override, + * and the SDK then ignores network changes. Call this method without a mode to clear the + * override. The SDK then returns to the configured mode, and to network switching when it is + * enabled. + * + * The data system applies a mode change after a short delay. {@link getConnectionMode} reports + * an explicit mode at once. After a clear, it reports the data system mode, so it can show the + * previous mode until the change applies. + * + * @param mode The connection mode to use. Omit it to clear the override (`dataSystem` only). + */ + setConnectionMode(mode?: ConnectionMode): Promise; getConnectionMode(): ConnectionMode; @@ -46,7 +58,14 @@ export interface LDClient extends Omit { * Tells the SDK whether the network is available. The SDK does not detect network changes on * its own. Call this from the main process when the application learns of a change. * - * `false` pauses the connection and `true` resumes it in the current connection mode. + * With the default data source, `false` pauses the connection and `true` resumes it in the + * current connection mode. With the `dataSystem` option, the value is forwarded to the data + * system. The data system switches to `offline` and back only when automatic network switching + * is enabled in `dataSystem.automaticModeSwitching`. Otherwise the call is ignored. Desktop + * turns automatic network switching off by default, so with a default `dataSystem` + * configuration this call has no effect. An explicit call to `setConnectionMode` under + * `dataSystem` sets an override, and the SDK then ignores network changes until a call without + * a mode clears the override. * * This method exists on the main-process client only. * diff --git a/packages/sdk/electron/src/bridge/index.ts b/packages/sdk/electron/src/bridge/index.ts index 569cddbeca..c0c52a226a 100644 --- a/packages/sdk/electron/src/bridge/index.ts +++ b/packages/sdk/electron/src/bridge/index.ts @@ -110,7 +110,7 @@ const ldClientBridge = (namespace: string): LDClientBridge => ({ defaultValue, ), - setConnectionMode: (mode: ConnectionMode): Promise => + setConnectionMode: (mode?: ConnectionMode): Promise => ipcRenderer.invoke(getIPCChannelName(namespace, 'setConnectionMode'), mode), getConnectionMode: (): ConnectionMode => diff --git a/packages/sdk/electron/src/options.ts b/packages/sdk/electron/src/options.ts index 8653ccdbd2..e08a0d26a0 100644 --- a/packages/sdk/electron/src/options.ts +++ b/packages/sdk/electron/src/options.ts @@ -108,6 +108,23 @@ export default function validateOptions(opts: ElectronOptions, logger: LDLogger) ); } + const dataSystemConfigured = + typeof opts.dataSystem === 'object' && + opts.dataSystem !== null && + !Array.isArray(opts.dataSystem); + if ( + dataSystemConfigured && + opts.initialConnectionMode !== undefined && + opts.initialConnectionMode !== null + ) { + logger.warn( + 'Both "dataSystem" and "initialConnectionMode" are set. "initialConnectionMode" applies ' + + 'only when the FDv2 data system is not configured and will be ignored. Use ' + + '"dataSystem.automaticModeSwitching.initialConnectionMode" (with automaticModeSwitching.type ' + + 'set to "manual") to set the initial connection mode for the FDv2 data system.', + ); + } + if (output.storage !== undefined && output.encryptStorage) { logger.warn( 'Config option "encryptStorage" has no effect when a custom "storage" is provided.', diff --git a/packages/sdk/electron/src/renderer/ElectronRendererClient.ts b/packages/sdk/electron/src/renderer/ElectronRendererClient.ts index c30009f7bd..ef2d97f84c 100644 --- a/packages/sdk/electron/src/renderer/ElectronRendererClient.ts +++ b/packages/sdk/electron/src/renderer/ElectronRendererClient.ts @@ -124,7 +124,7 @@ export class ElectronRendererClient implements LDRendererClient { return this._ldClientBridge.variationDetail(key, defaultValue); } - setConnectionMode(mode: ConnectionMode): Promise { + setConnectionMode(mode?: ConnectionMode): Promise { return this._ldClientBridge.setConnectionMode(mode); }