Skip to content

feat(1 3223): add client identification headers #235

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jan 8, 2025
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "unleash-proxy-client",
"version": "3.6.1",
"description": "A browser client that can be used together with the unleash-proxy.",
"description": "A browser client that can be used together with Unleash Edge or the Unleash Frontend API.",
"type": "module",
"main": "./build/index.cjs",
"types": "./build/cjs/index.d.ts",
Expand Down
42 changes: 42 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { FetchMock } from 'jest-fetch-mock';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const packageJSON = require('../package.json');
import 'jest-localstorage-mock';
import * as data from './test/testdata.json';
import IStorageProvider from './storage-provider';
Expand Down Expand Up @@ -1356,6 +1358,46 @@ test('Should pass custom headers', async () => {
});
});

test('Should add `x-unleash` headers', async () => {
fetchMock.mockResponses(
[JSON.stringify(data), { status: 200 }],
[JSON.stringify(data), { status: 200 }]
);
const appName = 'unleash-client-test';
const config: IConfig = {
url: 'http://localhost/test',
clientKey: 'some123key',
appName,
};
const client = new UnleashClient(config);
await client.start();

const featureRequest = getTypeSafeRequest(fetchMock, 0);

client.isEnabled('count-metrics');
jest.advanceTimersByTime(2001);

const metricsRequest = getTypeSafeRequest(fetchMock, 1);

const uuidFormat =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

const expectedHeaders = {
'x-unleash-sdk': `unleash-js@${packageJSON.version}`,
'x-unleash-connection-id': expect.stringMatching(uuidFormat),
'x-unleash-appname': appName,
};

const getConnectionId = (request: any) =>
request.headers['x-unleash-connection-id'];

expect(featureRequest.headers).toMatchObject(expectedHeaders);
expect(metricsRequest.headers).toMatchObject(expectedHeaders);
expect(getConnectionId(featureRequest)).toEqual(
getConnectionId(metricsRequest)
);
});

test('Should emit impression events on getVariant calls when impressionData is true', (done) => {
const bootstrap = [
{
Expand Down
11 changes: 11 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { TinyEmitter } from 'tiny-emitter';
import { v4 as uuidv4 } from 'uuid';
import Metrics from './metrics';
import type IStorageProvider from './storage-provider';
import InMemoryStorageProvider from './storage-provider-inmemory';
Expand All @@ -10,6 +11,9 @@ import {
urlWithContextAsQuery,
} from './util';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const packageJSON = require('../package.json');

const DEFINED_FIELDS = [
'userId',
'sessionId',
Expand Down Expand Up @@ -169,6 +173,7 @@ export class UnleashClient extends TinyEmitter {
private lastError: any;
private experimental: IExperimentalConfig;
private lastRefreshTimestamp: number;
private connectionId: string;

constructor({
storageProvider,
Expand Down Expand Up @@ -261,6 +266,8 @@ export class UnleashClient extends TinyEmitter {
bootstrap && bootstrap.length > 0 ? bootstrap : undefined;
this.bootstrapOverride = bootstrapOverride;

this.connectionId = uuidv4();

this.metrics = new Metrics({
onError: this.emit.bind(this, EVENTS.ERROR),
onSent: this.emit.bind(this, EVENTS.SENT),
Expand All @@ -273,6 +280,7 @@ export class UnleashClient extends TinyEmitter {
headerName,
customHeaders,
metricsIntervalInitial,
connectionId: this.connectionId,
});
}

Expand Down Expand Up @@ -468,6 +476,9 @@ export class UnleashClient extends TinyEmitter {
const headers = {
[this.headerName]: this.clientKey,
Accept: 'application/json',
'x-unleash-sdk': `unleash-js@${packageJSON.version}`,
'x-unleash-connection-id': this.connectionId,
'x-unleash-appname': this.context.appName,
};
if (isPOST) {
headers['Content-Type'] = 'application/json';
Expand Down
9 changes: 9 additions & 0 deletions src/metrics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ test('should be disabled by flag disableMetrics', async () => {
fetch: fetchMock,
headerName: 'Authorization',
metricsIntervalInitial: 0,
connectionId: '123',
});

metrics.count('foo', true);
Expand All @@ -42,6 +43,7 @@ test('should send metrics', async () => {
fetch: fetchMock,
headerName: 'Authorization',
metricsIntervalInitial: 0,
connectionId: '123',
});

metrics.count('foo', true);
Expand Down Expand Up @@ -79,6 +81,7 @@ test('should send metrics with custom auth header', async () => {
fetch: fetchMock,
headerName: 'NotAuthorization',
metricsIntervalInitial: 0,
connectionId: '123',
});

metrics.count('foo', true);
Expand All @@ -103,6 +106,7 @@ test('Should send initial metrics after 2 seconds', () => {
fetch: fetchMock,
headerName: 'Authorization',
metricsIntervalInitial: 2,
connectionId: '123',
});

metrics.start();
Expand All @@ -127,6 +131,7 @@ test('Should send initial metrics after 20 seconds, when metricsIntervalInitial
fetch: fetchMock,
headerName: 'Authorization',
metricsIntervalInitial: 20,
connectionId: '123',
});

metrics.start();
Expand All @@ -151,6 +156,7 @@ test('Should send metrics for initial and after metrics interval', () => {
fetch: fetchMock,
headerName: 'Authorization',
metricsIntervalInitial: 2,
connectionId: '123',
});

metrics.start();
Expand Down Expand Up @@ -178,6 +184,7 @@ test('Should not send initial metrics if disabled', () => {
fetch: fetchMock,
headerName: 'Authorization',
metricsIntervalInitial: 0,
connectionId: '123',
});

metrics.start();
Expand All @@ -202,6 +209,7 @@ test('should send metrics based on timer interval', async () => {
fetch: fetchMock,
headerName: 'Authorization',
metricsIntervalInitial: 2,
connectionId: '123',
});

metrics.start();
Expand Down Expand Up @@ -242,6 +250,7 @@ describe('Custom headers for metrics', () => {
fetch: fetchMock,
headerName: 'Authorization',
customHeaders,
connectionId: '123',
metricsIntervalInitial: 2,
});

Expand Down
9 changes: 9 additions & 0 deletions src/metrics.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Simplified version of: https://github.com/Unleash/unleash-client-node/blob/main/src/metrics.ts

import { notNullOrUndefined } from './util';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const packageJSON = require('../package.json');

export interface MetricsOptions {
onError: OnError;
Expand All @@ -14,6 +16,7 @@ export interface MetricsOptions {
headerName: string;
customHeaders?: Record<string, string>;
metricsIntervalInitial: number;
connectionId: string;
}

interface VariantBucket {
Expand Down Expand Up @@ -53,6 +56,7 @@ export default class Metrics {
private headerName: string;
private customHeaders: Record<string, string>;
private metricsIntervalInitial: number;
private connectionId: string;

constructor({
onError,
Expand All @@ -66,6 +70,7 @@ export default class Metrics {
headerName,
customHeaders = {},
metricsIntervalInitial,
connectionId,
}: MetricsOptions) {
this.onError = onError;
this.onSent = onSent || doNothing;
Expand All @@ -79,6 +84,7 @@ export default class Metrics {
this.fetch = fetch;
this.headerName = headerName;
this.customHeaders = customHeaders;
this.connectionId = connectionId;
}

public start() {
Expand Down Expand Up @@ -121,6 +127,9 @@ export default class Metrics {
[this.headerName]: this.clientKey,
Accept: 'application/json',
'Content-Type': 'application/json',
'x-unleash-sdk': `unleash-js@${packageJSON.version}`,
'x-unleash-connection-id': this.connectionId,
'x-unleash-appname': this.appName,
};

Object.entries(this.customHeaders)
Expand Down
Loading