Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { TestHttpHandlers, TestHttpServer } from 'launchdarkly-js-test-helpers';

import { basicLogger, LDLogger } from '../src';
import LDClientNode from '../src/LDClientNode';

const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

const allData = { flags: {}, segments: {} };

describe('LDClientNode X-LaunchDarkly-Instance-Id header', () => {
let logger: LDLogger;
let closeable: { close: () => void }[];

beforeEach(() => {
closeable = [];
logger = basicLogger({ destination: () => {} });
});

afterEach(() => {
closeable.forEach((c) => c.close());
});

it('sends a v4 UUID X-LaunchDarkly-Instance-Id header on polling requests', async () => {
const server = await TestHttpServer.start();
server.forMethodAndPath('get', '/sdk/latest-all', TestHttpHandlers.respondJson(allData));

const client = new LDClientNode('sdk-key', {
baseUri: server.url,
stream: false,
sendEvents: false,
logger,
});

closeable.push(server, client);

await client.waitForInitialization({ timeout: 10 });
expect(client.initialized()).toBe(true);

const req = await server.nextRequest();
const headerValue = req.headers['x-launchdarkly-instance-id'];
expect(headerValue).toMatch(UUID_V4_RE);
});

it('uses a different UUID for different SDK instances', async () => {
const serverA = await TestHttpServer.start();
const serverB = await TestHttpServer.start();
serverA.forMethodAndPath('get', '/sdk/latest-all', TestHttpHandlers.respondJson(allData));
serverB.forMethodAndPath('get', '/sdk/latest-all', TestHttpHandlers.respondJson(allData));

const clientA = new LDClientNode('sdk-key-a', {
baseUri: serverA.url,
stream: false,
sendEvents: false,
logger,
});
const clientB = new LDClientNode('sdk-key-b', {
baseUri: serverB.url,
stream: false,
sendEvents: false,
logger,
});

closeable.push(serverA, serverB, clientA, clientB);

await clientA.waitForInitialization({ timeout: 10 });
await clientB.waitForInitialization({ timeout: 10 });

const reqA = await serverA.nextRequest();
const reqB = await serverB.nextRequest();

const headerA = reqA.headers['x-launchdarkly-instance-id'];
const headerB = reqB.headers['x-launchdarkly-instance-id'];

expect(headerA).toMatch(UUID_V4_RE);
expect(headerB).toMatch(UUID_V4_RE);
expect(headerA).not.toEqual(headerB);
});
});
1 change: 1 addition & 0 deletions packages/sdk/server-node/contract-tests/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ app.get('/', (req: Request, res: Response) => {
'optional-event-gzip',
'flag-change-listeners',
'fdv1-fallback',
'instance-id',
],
});
});
Expand Down
10 changes: 9 additions & 1 deletion packages/sdk/server-node/src/LDClientNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,16 @@ class LDClientNode extends LDClientImpl implements LDClient {
const baseOptions = { ...options, logger };
delete baseOptions.plugins;

const platform = new NodePlatform({ ...options, logger });
// Per SCMP-server-connection-minutes-polling, generate one v4 GUID per SDK
// instance and pass it through `internalOptions` so LDClientImpl can attach it as the
// `X-LaunchDarkly-Instance-Id` default header. Generation happens here (not in
// LDClientImpl) so edge SDKs that share LDClientImpl do not advertise instance-id.
const instanceId = platform.crypto.randomUUID();

super(
sdkKey,
new NodePlatform({ ...options, logger }),
platform,
baseOptions,
{
onError: (err: Error) => {
Expand Down Expand Up @@ -81,6 +88,7 @@ class LDClientNode extends LDClientImpl implements LDClient {
{
getImplementationHooks: (environmentMetadata: LDPluginEnvironmentMetadata) =>
internal.safeGetHooks(logger, environmentMetadata, plugins),
instanceId,
},
);

Expand Down
24 changes: 24 additions & 0 deletions packages/shared/common/src/utils/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,30 @@ describe('defaultHeaders', () => {
'x-launchdarkly-tags': 'application-id/test-application application-version/test-version',
});
});

it('does not include the instance-id header by default', () => {
const h = defaultHeaders('my-sdk-key', makeInfo());
expect(h['x-launchdarkly-instance-id']).toBeUndefined();
});

it('sets the X-LaunchDarkly-Instance-Id header when an instance id is supplied', () => {
const h = defaultHeaders(
'my-sdk-key',
makeInfo(),
undefined,
true,
'user-agent',
'd3135edb-6531-4874-8a38-f0c9e556e836',
);
expect(h).toMatchObject({
'x-launchdarkly-instance-id': 'd3135edb-6531-4874-8a38-f0c9e556e836',
});
});

it('omits the X-LaunchDarkly-Instance-Id header when an empty instance id is supplied', () => {
const h = defaultHeaders('my-sdk-key', makeInfo(), undefined, true, 'user-agent', '');
expect(h['x-launchdarkly-instance-id']).toBeUndefined();
});
});

describe('httpErrorMessage', () => {
Expand Down
11 changes: 11 additions & 0 deletions packages/shared/common/src/utils/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type LDHeaders = {
'x-launchdarkly-user-agent'?: string;
'x-launchdarkly-wrapper'?: string;
'x-launchdarkly-tags'?: string;
'x-launchdarkly-instance-id'?: string;
};

export function defaultHeaders(
Expand All @@ -16,6 +17,7 @@ export function defaultHeaders(
tags?: ApplicationTags,
includeAuthorizationHeader: boolean = true,
userAgentHeaderName: 'user-agent' | 'x-launchdarkly-user-agent' = 'user-agent',
instanceId?: string,
): LDHeaders {
const { userAgentBase, version, wrapperName, wrapperVersion } = info.sdkData();

Expand All @@ -39,6 +41,15 @@ export function defaultHeaders(
headers['x-launchdarkly-tags'] = tags.value;
}

// Per SCMP-server-connection-minutes-polling (spec section 1.1), server SDKs include a
// per-instance v4 GUID on every polling request. The caller (a server SDK) is responsible
// for generating the GUID once per SDK instance and passing it here, so that it rides on
// every outbound request via this shared default-headers map. Client/edge SDKs do not pass
// this value, so the header is omitted for them.
if (instanceId) {
headers['x-launchdarkly-instance-id'] = instanceId;
}

return headers;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { LDClientImpl } from '../src';
import { createBasicPlatform } from './createBasicPlatform';
import TestLogger from './Logger';
import makeCallbacks from './makeCallbacks';

// When `internalOptions.instanceId` is supplied, the SDK must attach
// `X-LaunchDarkly-Instance-Id` to every outbound request using that value. When it is
// omitted, the header must not be attached. The platform SDK that owns instance-id
// generation (e.g. the Node server SDK) is responsible for producing the GUID and
// passing it through `internalOptions`.
describe('LDClientImpl instance-id header', () => {
const fixedUuid = 'd3135edb-6531-4874-8a38-f0c9e556e836';

it('attaches the X-LaunchDarkly-Instance-Id header when internalOptions.instanceId is set', async () => {
const platform = createBasicPlatform();
platform.requests.fetch.mockImplementation(() =>
Promise.resolve({ status: 200, headers: new Headers() }),
);

const client = new LDClientImpl(
'sdk-key-instance-id-1',
platform,
{ logger: new TestLogger(), stream: false },
makeCallbacks(false),
{ instanceId: fixedUuid },
);

client.identify({ key: 'user' });
client.variation('dev-test-flag', { key: 'user' }, false);
await client.flush();

expect(platform.requests.fetch).toHaveBeenCalledWith(
'https://events.launchdarkly.com/bulk',
expect.objectContaining({
headers: expect.objectContaining({
'x-launchdarkly-instance-id': fixedUuid,
}),
}),
);

client.close();
});

it('omits the X-LaunchDarkly-Instance-Id header when no instanceId is supplied', async () => {
const platform = createBasicPlatform();
platform.requests.fetch.mockImplementation(() =>
Promise.resolve({ status: 200, headers: new Headers() }),
);

const client = new LDClientImpl(
'sdk-key-instance-id-2',
platform,
{ logger: new TestLogger(), stream: false },
makeCallbacks(false),
);

client.identify({ key: 'user' });
client.variation('dev-test-flag', { key: 'user' }, false);
await client.flush();

expect(platform.requests.fetch).toHaveBeenCalledWith(
'https://events.launchdarkly.com/bulk',
expect.objectContaining({
headers: expect.not.objectContaining({
'x-launchdarkly-instance-id': expect.anything(),
}),
}),
);

client.close();
});
});
31 changes: 28 additions & 3 deletions packages/shared/sdk-server/src/LDClientImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ function constructFDv1(
initSuccess: () => void,
dataSourceErrorHandler: (e: any) => void,
hooks: Hook[],
instanceId: string | undefined,
): {
config: Configuration;
logger: LDLogger | undefined;
Expand All @@ -137,7 +138,14 @@ function constructFDv1(
throw new Error('You must configure the client with an SDK key');
}
const { logger } = config;
const baseHeaders = defaultHeaders(sdkKey, platform.info, config.tags);
const baseHeaders = defaultHeaders(
sdkKey,
platform.info,
config.tags,
true,
'user-agent',
instanceId,
);
Comment thread
cursor[bot] marked this conversation as resolved.

const clientContext = new ClientContext(sdkKey, config, platform);
const featureStore = config.featureStoreFactory(clientContext);
Expand Down Expand Up @@ -245,6 +253,7 @@ function constructFDv2(
callbacks: LDClientCallbacks,
initSuccess: () => void,
hooks: Hook[],
instanceId: string | undefined,
): {
config: Configuration;
logger: LDLogger | undefined;
Expand All @@ -268,7 +277,14 @@ function constructFDv2(
}

const { logger } = config;
const baseHeaders = defaultHeaders(sdkKey, platform.info, config.tags);
const baseHeaders = defaultHeaders(
sdkKey,
platform.info,
config.tags,
true,
'user-agent',
instanceId,
);

const clientContext = new ClientContext(sdkKey, config, platform);
const dataSystem = config.dataSystem!; // dataSystem must be defined to get into this construct function
Expand Down Expand Up @@ -604,6 +620,7 @@ export default class LDClientImpl implements LDClient {
() => this._initSuccess(),
(e) => this._dataSourceErrorHandler(e),
hooks,
internalOptions?.instanceId,
));

this.bigSegmentStatusProviderInternal = this._bigSegmentsManager
Expand Down Expand Up @@ -633,7 +650,15 @@ export default class LDClientImpl implements LDClient {
onError: this._onError,
onFailed: this._onFailed,
onReady: this._onReady,
} = constructFDv2(_sdkKey, _platform, config, callbacks, () => this._initSuccess(), hooks));
} = constructFDv2(
_sdkKey,
_platform,
config,
callbacks,
() => this._initSuccess(),
hooks,
internalOptions?.instanceId,
));
this._featureStore = transactionalStore;
this.bigSegmentStatusProviderInternal = this._bigSegmentsManager
.statusProvider as BigSegmentStoreStatusProvider;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,12 @@ import { Hook } from '../integrations';

export interface ServerInternalOptions extends internal.LDInternalOptions {
getImplementationHooks?: (environmentMetadata: LDPluginEnvironmentMetadata) => Hook[];

/**
* Per-SDK-instance identifier sent as the `X-LaunchDarkly-Instance-Id` header on every
* outbound request. The SDK that owns instance-id generation (e.g. the Node server SDK)
* supplies this; SDKs that do not advertise instance-id support (edge SDKs) leave it
* undefined and the header is omitted.
*/
instanceId?: string;
}
Loading