Skip to content

Commit

Permalink
feat: Allow using custom user-agent name. (#580)
Browse files Browse the repository at this point in the history
Allow for SDK implementations to control the name of the header their
SDK name and version are put in.

Browser SDKs need to use `x-launchdarkly-user-agent` all other platforms
can use `user-agent`.

In a browser the `user-agent` is a forbidden header and can only contain
the browser's user agent.
  • Loading branch information
kinyoklion authored Sep 13, 2024
1 parent 887548a commit ed5a206
Show file tree
Hide file tree
Showing 20 changed files with 99 additions and 91 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,12 @@ describe('given an event processor', () => {
}),
);
contextDeduplicator = new ContextDeduplicator();
eventProcessor = new EventProcessor(eventProcessorConfig, clientContext, contextDeduplicator);
eventProcessor = new EventProcessor(
eventProcessorConfig,
clientContext,
{},
contextDeduplicator,
);
});

afterEach(() => {
Expand Down Expand Up @@ -788,6 +793,7 @@ describe('given an event processor', () => {
eventProcessor = new EventProcessor(
eventProcessorConfig,
clientContextWithDebug,
{},
contextDeduplicator,
);

Expand Down
4 changes: 3 additions & 1 deletion packages/shared/common/src/internal/events/EventProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import LDEventProcessor from '../../api/subsystem/LDEventProcessor';
import AttributeReference from '../../AttributeReference';
import ContextFilter from '../../ContextFilter';
import { ClientContext } from '../../options';
import { LDHeaders } from '../../utils';
import { DiagnosticsManager } from '../diagnostics';
import EventSender from './EventSender';
import EventSummarizer, { SummarizedFlagsEvent } from './EventSummarizer';
Expand Down Expand Up @@ -106,13 +107,14 @@ export default class EventProcessor implements LDEventProcessor {
constructor(
private readonly config: EventProcessorOptions,
clientContext: ClientContext,
baseHeaders: LDHeaders,
private readonly contextDeduplicator?: LDContextDeduplicator,
private readonly diagnosticsManager?: DiagnosticsManager,
start: boolean = true,
) {
this.capacity = config.eventsCapacity;
this.logger = clientContext.basicConfiguration.logger;
this.eventSender = new EventSender(clientContext);
this.eventSender = new EventSender(clientContext, baseHeaders);

this.contextFilter = new ContextFilter(
config.allAttributesPrivate,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,12 @@ describe('given an event sender', () => {

eventSender = new EventSender(
new ClientContext('sdk-key', basicConfig, { ...mockPlatform, info }),
{
authorization: 'sdk-key',
'user-agent': 'TestUserAgent/2.0.2',
'x-launchdarkly-tags': 'application-id/testApplication1 application-version/1.0.0',
'x-launchdarkly-wrapper': 'Rapper/1.2.3',
},
);

eventSenderResult = await eventSender.sendEventData(
Expand Down
12 changes: 5 additions & 7 deletions packages/shared/common/src/internal/events/EventSender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
LDUnexpectedResponseError,
} from '../../errors';
import { ClientContext, getEventsUri } from '../../options';
import { defaultHeaders, httpErrorMessage, sleep } from '../../utils';
import { httpErrorMessage, LDHeaders, sleep } from '../../utils';

export default class EventSender implements LDEventSender {
private crypto: Crypto;
Expand All @@ -22,16 +22,14 @@ export default class EventSender implements LDEventSender {
private eventsUri: string;
private requests: Requests;

constructor(clientContext: ClientContext) {
constructor(clientContext: ClientContext, baseHeaders: LDHeaders) {
const { basicConfiguration, platform } = clientContext;
const {
sdkKey,
serviceEndpoints: { analyticsEventPath, diagnosticEventPath, includeAuthorizationHeader },
tags,
serviceEndpoints: { analyticsEventPath, diagnosticEventPath },
} = basicConfiguration;
const { crypto, info, requests } = platform;
const { crypto, requests } = platform;

this.defaultHeaders = defaultHeaders(sdkKey, info, tags, includeAuthorizationHeader);
this.defaultHeaders = { ...baseHeaders };
this.eventsUri = getEventsUri(basicConfiguration.serviceEndpoints, analyticsEventPath, []);
this.diagnosticEventsUri = getEventsUri(
basicConfiguration.serviceEndpoints,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type LDInternalOptions = {
analyticsEventPath?: string;
diagnosticEventPath?: string;
includeAuthorizationHeader?: boolean;
userAgentHeaderName?: 'user-agent' | 'x-launchdarkly-user-agent';

/**
* In seconds. Log a warning if identifyTimeout is greater than this value.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,18 @@ describe('given a stream processor with mock event source', () => {

diagnosticsManager = new DiagnosticsManager(sdkKey, basicPlatform, {});
streamingProcessor = new StreamingProcessor(
sdkKey,
{
basicConfiguration: getBasicConfiguration(logger),
platform: basicPlatform,
},
'/all',
[],
listeners,
{
authorization: 'my-sdk-key',
'user-agent': 'TestUserAgent/2.0.2',
'x-launchdarkly-wrapper': 'Rapper/1.2.3',
},
diagnosticsManager,
mockErrorHandler,
);
Expand Down Expand Up @@ -137,14 +141,18 @@ describe('given a stream processor with mock event source', () => {

it('sets streamInitialReconnectDelay correctly', () => {
streamingProcessor = new StreamingProcessor(
sdkKey,
{
basicConfiguration: getBasicConfiguration(logger),
platform: basicPlatform,
},
'/all',
[],
listeners,
{
authorization: 'my-sdk-key',
'user-agent': 'TestUserAgent/2.0.2',
'x-launchdarkly-wrapper': 'Rapper/1.2.3',
},
diagnosticsManager,
mockErrorHandler,
22,
Expand Down
10 changes: 5 additions & 5 deletions packages/shared/common/src/internal/stream/StreamingProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { LDStreamProcessor } from '../../api/subsystem';
import { LDStreamingError } from '../../errors';
import { ClientContext } from '../../options';
import { getStreamingUri } from '../../options/ServiceEndpoints';
import { defaultHeaders, httpErrorMessage, shouldRetry } from '../../utils';
import { httpErrorMessage, LDHeaders, shouldRetry } from '../../utils';
import { DiagnosticsManager } from '../diagnostics';
import { StreamingErrorHandler } from './types';

Expand All @@ -35,20 +35,20 @@ class StreamingProcessor implements LDStreamProcessor {
private connectionAttemptStartTime?: number;

constructor(
sdkKey: string,
clientContext: ClientContext,
streamUriPath: string,
parameters: { key: string; value: string }[],
private readonly listeners: Map<EventName, ProcessStreamResponse>,
baseHeaders: LDHeaders,
private readonly diagnosticsManager?: DiagnosticsManager,
private readonly errorHandler?: StreamingErrorHandler,
private readonly streamInitialReconnectDelay = 1,
) {
const { basicConfiguration, platform } = clientContext;
const { logger, tags } = basicConfiguration;
const { info, requests } = platform;
const { logger } = basicConfiguration;
const { requests } = platform;

this.headers = defaultHeaders(sdkKey, info, tags);
this.headers = { ...baseHeaders };
this.logger = logger;
this.requests = requests;
this.streamUri = getStreamingUri(
Expand Down
6 changes: 4 additions & 2 deletions packages/shared/common/src/utils/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { ApplicationTags } from '../options';

export type LDHeaders = {
authorization?: string;
'user-agent': string;
'user-agent'?: string;
'x-launchdarkly-user-agent'?: string;
'x-launchdarkly-wrapper'?: string;
'x-launchdarkly-tags'?: string;
};
Expand All @@ -14,11 +15,12 @@ export function defaultHeaders(
info: Info,
tags?: ApplicationTags,
includeAuthorizationHeader: boolean = true,
userAgentHeaderName: 'user-agent' | 'x-launchdarkly-user-agent' = 'user-agent',
): LDHeaders {
const { userAgentBase, version, wrapperName, wrapperVersion } = info.sdkData();

const headers: LDHeaders = {
'user-agent': `${userAgentBase ?? 'NodeJSClient'}/${version}`,
[userAgentHeaderName]: `${userAgentBase ?? 'NodeJSClient'}/${version}`,
};

// edge sdks sets this to false because they use the clientSideID
Expand Down
3 changes: 2 additions & 1 deletion packages/shared/mocks/src/streamingProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type {
ClientContext,
EventName,
internal,
LDHeaders,
LDStreamingError,
ProcessStreamResponse,
} from '@common';
Expand All @@ -22,11 +23,11 @@ export const setupMockStreamingProcessor = (

MockStreamingProcessor.mockImplementation(
(
sdkKey: string,
clientContext: ClientContext,
streamUriPath: string,
parameters: { key: string; value: string }[],
listeners: Map<EventName, ProcessStreamResponse>,
baseHeaders: LDHeaders,
diagnosticsManager: internal.DiagnosticsManager,
errorHandler: internal.StreamingErrorHandler,
_streamInitialReconnectDelay: number,
Expand Down
4 changes: 2 additions & 2 deletions packages/shared/sdk-client/__tests__/LDClientImpl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,11 @@ describe('sdk-client object', () => {
'dev-test-flag': false,
});
expect(MockStreamingProcessor).toHaveBeenCalledWith(
expect.anything(),
expect.anything(),
'/stream/path',
expect.anything(),
expect.anything(),
expect.anything(),
undefined,
expect.anything(),
);
Expand All @@ -129,11 +129,11 @@ describe('sdk-client object', () => {
await ldc.identify(carContext);

expect(MockStreamingProcessor).toHaveBeenCalledWith(
expect.anything(),
expect.anything(),
'/stream/path',
[{ key: 'withReasons', value: 'true' }],
expect.anything(),
expect.anything(),
undefined,
expect.anything(),
);
Expand Down
Loading

0 comments on commit ed5a206

Please sign in to comment.