Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions packages/sdk/browser/__tests__/BrowserClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -69,7 +69,14 @@ function makePlatform() {
function makeConfig(overrides: Partial<any> = {}) {
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,
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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();
});
4 changes: 2 additions & 2 deletions packages/shared/sdk-client/src/api/LDOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,14 +190,20 @@ export default class ConfigurationImpl implements Configuration {
}
});

const payloadFilterKey = this.dataSystem ? undefined : pristineOptions.payloadFilterKey;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Shared manager relies on caller normalization

Built-in SDKs normalize endpoints here. Direct callers of createFDv2DataManagerBase still get a warning for filtered endpoints, but the manager forwards them unchanged.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

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,
this.eventsUri,
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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',
);
});

Expand All @@ -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']] : []);
Comment on lines +100 to +102

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 No regression check for FDv2 URLs

The fallback test accepts /sdk/poll requests even when they contain filter. No new assertion checks that FDv2 polling or streaming omits the parameter when payloadFilterKey is set.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

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'));
});
});
Loading
Loading