diff --git a/packages/sdk/browser/__tests__/BrowserClient.test.ts b/packages/sdk/browser/__tests__/BrowserClient.test.ts index c7e1bdfcef..8291f2fe33 100644 --- a/packages/sdk/browser/__tests__/BrowserClient.test.ts +++ b/packages/sdk/browser/__tests__/BrowserClient.test.ts @@ -881,6 +881,31 @@ describe('given a mock platform for a BrowserClient', () => { expect(fetchUrl).toContain('/sdk/poll/eval/'); }); + it('sends the payload filter on FDv1 requests', async () => { + const client = makeClient( + 'client-side-id', + { key: 'user-key', kind: 'user' }, + AutoEnvAttributes.Disabled, + { + streaming: false, + logger, + diagnosticOptOut: true, + sendEvents: false, + fetchGoals: false, + payloadFilterKey: 'microservice-1', + }, + platform, + ); + + // Start the client so that it polls for flags. + await client.start(); + + // The FDv1 request carries the filter. + const fetchUrl = platform.requests.fetch.mock.calls[0][0]; + expect(fetchUrl).toContain('/sdk/evalx/'); + expect(fetchUrl).toContain('filter=microservice-1'); + }); + it('validates dataSystem options and applies browser defaults', async () => { const client = makeClient( 'client-side-id', diff --git a/packages/shared/sdk-client/__tests__/configuration/Configuration.test.ts b/packages/shared/sdk-client/__tests__/configuration/Configuration.test.ts index 03c9d75830..6917806fe8 100644 --- a/packages/shared/sdk-client/__tests__/configuration/Configuration.test.ts +++ b/packages/shared/sdk-client/__tests__/configuration/Configuration.test.ts @@ -212,6 +212,62 @@ describe('dataSystem validation', () => { expect(config.dataSystem!.automaticModeSwitching).toBe(false); }); + it('omits the payload filter key and warns when the FDv2 data system is selected', () => { + const logger = { + error: jest.fn(), + warn: jest.fn(), + info: jest.fn(), + debug: jest.fn(), + }; + const config = new ConfigurationImpl( + // @ts-ignore dataSystem is @internal + { payloadFilterKey: 'microservice-1', dataSystem: {}, logger }, + { + getImplementationHooks: () => [], + credentialType: 'clientSideId', + }, + ); + + expect(config.serviceEndpoints.payloadFilterKey).toBeUndefined(); + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn).toHaveBeenCalledWith( + '[FDv2DataManagerBase] Payload filtering is not supported with the FDv2 data system; the configured payload filter has no effect on FDv2 requests', + ); + }); + + it('does not warn when the FDv2 data system has no payload filter key', () => { + const logger = { + error: jest.fn(), + warn: jest.fn(), + info: jest.fn(), + debug: jest.fn(), + }; + const config = new ConfigurationImpl( + // @ts-ignore dataSystem is @internal + { dataSystem: {}, logger }, + { + getImplementationHooks: () => [], + credentialType: 'clientSideId', + }, + ); + + expect(config.serviceEndpoints.payloadFilterKey).toBeUndefined(); + expect(logger.warn).not.toHaveBeenCalled(); + }); + + it('keeps the payload filter key without warning when the FDv1 data system is selected', () => { + const logger = { + error: jest.fn(), + warn: jest.fn(), + info: jest.fn(), + debug: jest.fn(), + }; + const config = new ConfigurationImpl({ payloadFilterKey: 'microservice-1', logger }); + + expect(config.serviceEndpoints.payloadFilterKey).toBe('microservice-1'); + expect(logger.warn).not.toHaveBeenCalled(); + }); + it('forces useReport to false and warns when dataSystem is also set', () => { const logger = { error: jest.fn(), diff --git a/packages/shared/sdk-client/__tests__/datasource/FDv2DataManagerBase.test.ts b/packages/shared/sdk-client/__tests__/datasource/FDv2DataManagerBase.test.ts index ba71e67866..b847ab833e 100644 --- a/packages/shared/sdk-client/__tests__/datasource/FDv2DataManagerBase.test.ts +++ b/packages/shared/sdk-client/__tests__/datasource/FDv2DataManagerBase.test.ts @@ -1,4 +1,4 @@ -import { Context, ServiceEndpoints } from '@launchdarkly/js-sdk-common'; +import { Context } from '@launchdarkly/js-sdk-common'; import { MODE_TABLE } from '../../src/datasource/ConnectionModeConfig'; import { createFDv1PollingSynchronizer } from '../../src/datasource/fdv2/FDv1PollingSynchronizer'; @@ -69,7 +69,14 @@ function makePlatform() { function makeConfig(overrides: Partial = {}) { return { logger: makeLogger(), - serviceEndpoints: new ServiceEndpoints('https://stream', 'https://poll', 'https://events'), + serviceEndpoints: { + streaming: 'https://stream', + polling: 'https://poll', + events: 'https://events', + analyticsEventPath: '/bulk', + diagnosticEventPath: '/diagnostic', + includeAuthorizationHeader: true, + }, withReasons: false, useReport: false, streamInitialReconnectDelay: 1, @@ -1204,38 +1211,6 @@ it('populates polling and streaming config in the factory context', async () => manager.close(); }); -it('warns when a payload filter key is configured', () => { - const config = makeConfig({ - serviceEndpoints: new ServiceEndpoints( - 'https://stream', - 'https://poll', - 'https://events', - '/bulk', - '/diagnostic', - true, - 'microservice-1', - ), - }); - - const manager = createFDv2DataManagerBase(makeBaseConfig({ config })); - - expect(config.logger.warn).toHaveBeenCalledWith( - expect.stringContaining('Payload filtering is not supported with the FDv2 data system'), - ); - - manager.close(); -}); - -it('does not warn when no payload filter key is configured', () => { - const config = makeConfig(); - - const manager = createFDv2DataManagerBase(makeBaseConfig({ config })); - - expect(config.logger.warn).not.toHaveBeenCalled(); - - manager.close(); -}); - function useActualDataSources() { const actual = jest.requireActual('../../src/datasource/fdv2/FDv2DataSource'); mockCreateFDv2DataSource.mockImplementation((cfg: any) => { @@ -1348,3 +1323,47 @@ it('does not fail a new identify when the previous data source closes before it manager.close(); }); + +it('builds the FDv1 fallback requestor with override endpoints', async () => { + const fdv1Endpoints = { + polling: jest.fn(() => ({ + pathGet: jest.fn(), + pathReport: jest.fn(), + pathPost: jest.fn(), + pathPing: jest.fn(), + })), + streaming: jest.fn(() => ({ + pathGet: jest.fn(), + pathReport: jest.fn(), + pathPost: jest.fn(), + pathPing: jest.fn(), + })), + }; + (makeRequestor as jest.Mock).mockReturnValue({}); + (createFDv1PollingSynchronizer as jest.Mock).mockReturnValue({ close: jest.fn() }); + const modeTable = { + ...MODE_TABLE, + streaming: { + ...MODE_TABLE.streaming, + fdv1Fallback: { endpoints: { pollingBaseUri: 'https://fallback-poll' } }, + }, + }; + const manager = createFDv2DataManagerBase( + makeBaseConfig({ + fdv1Endpoints, + modeTable, + foregroundMode: 'streaming', + }), + ); + await identifyManager(manager); + const dsConfig = capturedDataSourceConfigs[0]; + const fdv1Slot = dsConfig.synchronizerSlots[dsConfig.synchronizerSlots.length - 1]; + + // Create the FDv1 fallback synchronizer so that it builds its requestor. + fdv1Slot.factory.create(() => undefined); + + const fallbackEndpoints = (makeRequestor as jest.Mock).mock.calls[0][1]; + expect(fallbackEndpoints.polling).toBe('https://fallback-poll'); + + manager.close(); +}); diff --git a/packages/shared/sdk-client/src/api/LDOptions.ts b/packages/shared/sdk-client/src/api/LDOptions.ts index 596e314c10..4796a30f92 100644 --- a/packages/shared/sdk-client/src/api/LDOptions.ts +++ b/packages/shared/sdk-client/src/api/LDOptions.ts @@ -277,8 +277,8 @@ export interface LDOptions { * TestData or FileData data sources, nor will it be applied to any data source provided through the featureStore * config property. * - * Payload filtering is not supported with the FDv2 data system, so this key has no effect on requests made by - * FDv2 data sources. + * Payload filtering is not supported with the FDv2 data system. Data sources in that system, + * including the FDv1 fallback data source, do not send this key. */ payloadFilterKey?: string; diff --git a/packages/shared/sdk-client/src/configuration/Configuration.ts b/packages/shared/sdk-client/src/configuration/Configuration.ts index e314b3e7f8..3a9913d7ab 100644 --- a/packages/shared/sdk-client/src/configuration/Configuration.ts +++ b/packages/shared/sdk-client/src/configuration/Configuration.ts @@ -190,6 +190,12 @@ export default class ConfigurationImpl implements Configuration { } }); + const payloadFilterKey = this.dataSystem ? undefined : pristineOptions.payloadFilterKey; + if (this.dataSystem && pristineOptions.payloadFilterKey !== undefined) { + this.logger.warn( + '[FDv2DataManagerBase] Payload filtering is not supported with the FDv2 data system; the configured payload filter has no effect on FDv2 requests', + ); + } this.serviceEndpoints = new ServiceEndpoints( this.streamUri, this.baseUri, @@ -197,7 +203,7 @@ export default class ConfigurationImpl implements Configuration { internalOptions.analyticsEventPath, internalOptions.diagnosticEventPath, internalOptions.includeAuthorizationHeader, - pristineOptions.payloadFilterKey, + payloadFilterKey, ); this.useReport = pristineOptions.useReport ?? false; // useReport is an FDv1 option with no effect in FDv2, where usePost is the diff --git a/packages/shared/sdk-server/__tests__/LDClientImpl.payloadFilter.test.ts b/packages/shared/sdk-server/__tests__/LDClientImpl.payloadFilter.test.ts index a636415d67..84c091bc67 100644 --- a/packages/shared/sdk-server/__tests__/LDClientImpl.payloadFilter.test.ts +++ b/packages/shared/sdk-server/__tests__/LDClientImpl.payloadFilter.test.ts @@ -4,6 +4,24 @@ import { LDOptions } from '../src/api/options/LDOptions'; import LDClientImpl from '../src/LDClientImpl'; import { createBasicPlatform } from './createBasicPlatform'; +function makeEventSource() { + return { + onopen: jest.fn(), + onclose: jest.fn(), + onerror: jest.fn(), + onretrying: jest.fn(), + addEventListener: jest.fn(), + close: jest.fn(), + }; +} + +function requestUrls(platform: any): string[] { + return [ + ...platform.requests.fetch.mock.calls.map((c: any[]) => c[0] as string), + ...platform.requests.createEventSource.mock.calls.map((c: any[]) => c[0] as string), + ]; +} + describe('given a client using the FDv2 data system', () => { const callbacks = { onFailed: jest.fn(), @@ -55,8 +73,9 @@ describe('given a client using the FDv2 data system', () => { callbacks, ); + expect(logger.warn).toHaveBeenCalledTimes(1); expect(logger.warn).toHaveBeenCalledWith( - expect.stringContaining('Payload filtering is not supported with the FDv2 data system'), + 'Payload filtering is not supported with the FDv2 data system; the configured payload filter has no effect on FDv2 requests', ); }); @@ -67,4 +86,102 @@ describe('given a client using the FDv2 data system', () => { expect.stringContaining('Payload filtering is not supported'), ); }); + + it.each([ + ['the default host', undefined, 'https://sdk.launchdarkly.com/sdk/latest-all'], + [ + 'a custom base URI', + { baseUri: 'https://fallback.example.com' }, + 'https://fallback.example.com/sdk/latest-all', + ], + ])( + 'uses the unfiltered FDv1 fallback endpoint with %s', + async (_name, fdv1Fallback, expectedUrl) => { + platform.requests.fetch = jest.fn(async (url: string) => { + const fallback = url.includes('/sdk/poll'); + const headers = new Map(fallback ? [['x-ld-fd-fallback', 'true']] : []); + return { + status: fallback ? 500 : 200, + headers, + text: async () => (fallback ? '' : JSON.stringify({ flags: {}, segments: {} })), + }; + }); + client = new LDClientImpl( + 'sdk-key', + platform, + makeOptions({ + payloadFilterKey: 'microservice-1', + dataSystem: { + dataSource: { + dataSourceOptionsType: 'custom', + initializers: [{ type: 'polling' }], + synchronizers: [{ type: 'polling' }], + }, + fdv1Fallback, + }, + }), + callbacks, + ); + + // The FDv2 initializer response directs the SDK to the FDv1 fallback synchronizer. + await client.waitForInitialization({ timeout: 1 }); + + const urls = requestUrls(platform); + const fdv1Urls = urls.filter((u) => u.includes('/sdk/latest-all')); + expect(fdv1Urls.length).toBeGreaterThan(0); + fdv1Urls.forEach((u) => { + expect(u).toBe(expectedUrl); + }); + }, + ); +}); + +describe('given a client using the FDv1 data system', () => { + const callbacks = { + onFailed: jest.fn(), + onError: jest.fn(), + onReady: jest.fn(), + onUpdate: jest.fn(), + hasEventListeners: jest.fn(), + }; + let platform: any; + let client: LDClientImpl; + + beforeEach(() => { + platform = createBasicPlatform(); + platform.requests.fetch = jest.fn(async () => { + throw new Error('no network in test'); + }); + platform.requests.createEventSource = jest.fn(() => makeEventSource()); + }); + + afterEach(() => { + client?.close(); + jest.resetAllMocks(); + }); + + it.each([ + ['polling', false, '/sdk/latest-all'], + ['streaming', true, '/all'], + ])('sends the payload filter on %s requests', async (_name, stream, expectedPath) => { + client = new LDClientImpl( + 'sdk-key', + platform, + { + sendEvents: false, + diagnosticOptOut: true, + stream, + payloadFilterKey: 'microservice-1', + }, + callbacks, + ); + + // Wait briefly so that the data source makes its request. + await client.waitForInitialization({ timeout: 0.02 }).catch(() => {}); + + // The FDv1 request carries the filter. + const urls = requestUrls(platform).filter((u) => u.includes(expectedPath)); + expect(urls.length).toBeGreaterThan(0); + urls.forEach((u) => expect(u).toContain('filter=microservice-1')); + }); }); diff --git a/packages/shared/sdk-server/__tests__/options/Configuration.test.ts b/packages/shared/sdk-server/__tests__/options/Configuration.test.ts index f7a0375b08..af4d7d88c1 100644 --- a/packages/shared/sdk-server/__tests__/options/Configuration.test.ts +++ b/packages/shared/sdk-server/__tests__/options/Configuration.test.ts @@ -376,6 +376,34 @@ describe('when setting different options', () => { logger(config).expectMessages(logs); }); + it('omits the payload filter key and warns when the FDv2 data system is selected', () => { + const options = withLogger({ + payloadFilterKey: 'microservice-1', + dataSystem: {}, + }); + const config = new Configuration(options); + + expect(config.serviceEndpoints.payloadFilterKey).toBeUndefined(); + expect(config.payloadFilterKey).toBeUndefined(); + expect(logger(options).getCount(LogLevel.Warn)).toBe(1); + logger(options).expectMessages([ + { + level: LogLevel.Warn, + matches: + /^Payload filtering is not supported with the FDv2 data system; the configured payload filter has no effect on FDv2 requests$/, + }, + ]); + }); + + it('keeps the payload filter key without warning when the FDv1 data system is selected', () => { + const options = withLogger({ payloadFilterKey: 'microservice-1' }); + const config = new Configuration(options); + + expect(config.serviceEndpoints.payloadFilterKey).toBe('microservice-1'); + expect(config.payloadFilterKey).toBe('microservice-1'); + expect(logger(options).getCount()).toBe(0); + }); + it('discards unrecognized options with a warning', () => { // @ts-ignore const config = new Configuration(withLogger({ yes: 'no', cat: 'yes' })); diff --git a/packages/shared/sdk-server/src/api/options/LDOptions.ts b/packages/shared/sdk-server/src/api/options/LDOptions.ts index c1bd51f670..ff88325ed5 100644 --- a/packages/shared/sdk-server/src/api/options/LDOptions.ts +++ b/packages/shared/sdk-server/src/api/options/LDOptions.ts @@ -335,8 +335,8 @@ export interface LDOptions { * TestData or FileData data sources, nor will it be applied to any data source provided through the featureStore * config property. * - * Payload filtering is not supported with the FDv2 data system, so this key has no effect on requests made by - * FDv2 data sources. + * Payload filtering is not supported with the FDv2 data system. Data sources in that system, + * including the FDv1 fallback data source, do not send this key. */ payloadFilterKey?: string; diff --git a/packages/shared/sdk-server/src/options/Configuration.ts b/packages/shared/sdk-server/src/options/Configuration.ts index d35baa2228..09b6279701 100644 --- a/packages/shared/sdk-server/src/options/Configuration.ts +++ b/packages/shared/sdk-server/src/options/Configuration.ts @@ -528,6 +528,12 @@ export default class Configuration { }); } + const payloadFilterKey = this.dataSystem ? undefined : validatedOptions.payloadFilterKey; + if (this.dataSystem && validatedOptions.payloadFilterKey !== undefined) { + this.logger?.warn( + 'Payload filtering is not supported with the FDv2 data system; the configured payload filter has no effect on FDv2 requests', + ); + } this.serviceEndpoints = new ServiceEndpoints( validatedOptions.streamUri, validatedOptions.baseUri, @@ -535,7 +541,7 @@ export default class Configuration { internalOptions.analyticsEventPath, internalOptions.diagnosticEventPath, internalOptions.includeAuthorizationHeader, - validatedOptions.payloadFilterKey, + payloadFilterKey, ); this.eventsCapacity = validatedOptions.capacity; this.timeout = validatedOptions.timeout; @@ -557,7 +563,8 @@ export default class Configuration { this.tlsParams = validatedOptions.tlsParams; this.diagnosticOptOut = validatedOptions.diagnosticOptOut; this.wrapperName = validatedOptions.wrapperName; - this.payloadFilterKey = validatedOptions.payloadFilterKey; + // constructFDv2 in LDClientImpl warns again when this field is set, so it takes the stripped value + this.payloadFilterKey = payloadFilterKey; this.wrapperVersion = validatedOptions.wrapperVersion; this.tags = new ApplicationTags(validatedOptions); this.diagnosticRecordingInterval = validatedOptions.diagnosticRecordingInterval;