Skip to content

Commit 3b775b3

Browse files
authored
feat(browser): support shared custom HTTP clients (#2207)
1 parent f1c55cd commit 3b775b3

25 files changed

Lines changed: 305 additions & 30 deletions

File tree

‎packages/analytics-browser/src/browser-client-lite.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -435,7 +435,7 @@ export class AmplitudeBrowserLite extends AmplitudeCore implements BrowserClient
435435
this.q.push(this.setTransport.bind(this, transport));
436436
return;
437437
}
438-
this.config.transportProvider = createTransport(transport);
438+
this.config.transportProvider = createTransport(transport, this.config.httpClient);
439439
}
440440

441441
identify(identify: IIdentify, eventOptions?: EventOptions) {

‎packages/analytics-browser/src/browser-client.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -201,10 +201,14 @@ export class AmplitudeBrowser extends AmplitudeBrowserLite implements BrowserCli
201201
enableDiagnostics: boolean,
202202
diagnosticsSampleRate: number,
203203
): Promise<DiagnosticsClient> => {
204-
const diagnosticsClient = new DiagnosticsClient(options.apiKey, loggerProvider, serverZone, {
205-
enabled: enableDiagnostics,
206-
sampleRate: diagnosticsSampleRate,
207-
});
204+
const diagnosticsClient = new DiagnosticsClient(
205+
options.apiKey,
206+
loggerProvider,
207+
serverZone,
208+
{ enabled: enableDiagnostics, sampleRate: diagnosticsSampleRate },
209+
undefined,
210+
options.httpClient,
211+
);
208212
this.diagnosticsClient = diagnosticsClient;
209213
diagnosticsClient.setTag('library', `${LIBPREFIX}/${VERSION}`);
210214
diagnosticsClient.setTag('platform', BROWSER_PLATFORM);
@@ -220,11 +224,13 @@ export class AmplitudeBrowser extends AmplitudeBrowserLite implements BrowserCli
220224
loggerProvider: ILogger,
221225
serverZone: ServerZoneType,
222226
): Promise<IRemoteConfigClient> => {
227+
const httpClient = options.httpClient;
223228
const remoteConfigClient = new RemoteConfigClient(
224229
options.apiKey,
225230
loggerProvider,
226231
serverZone,
227232
/* istanbul ignore next */ options.remoteConfig?.serverUrl,
233+
httpClient ? (request) => httpClient.send(request) : undefined,
228234
);
229235

230236
// Fetch diagnostics config first to get sample rate

‎packages/analytics-browser/src/config.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
Plan,
1212
IdentityStorageType,
1313
TransportTypeOrOptions,
14+
HttpClient,
1415
MemoryStorage,
1516
UUID,
1617
CookieStorage,
@@ -111,8 +112,9 @@ export class BrowserConfig extends Config implements IBrowserConfig {
111112
public topLevelDomain?: string,
112113
public enableRequestBodyCompression: boolean = false,
113114
public customEnrichment?: boolean | CustomEnrichmentOptions,
115+
public httpClient?: HttpClient,
114116
) {
115-
super({ apiKey, instanceName, storageProvider, transportProvider: createTransport(transport) });
117+
super({ apiKey, instanceName, storageProvider, transportProvider: createTransport(transport, httpClient) });
116118
this._cookieStorage = cookieStorage;
117119
this.deviceId = deviceId;
118120
this.lastEventId = lastEventId;
@@ -420,6 +422,7 @@ export const useBrowserConfig = async (
420422
defaultCookieDomain,
421423
options.enableRequestBodyCompression,
422424
options.customEnrichment,
425+
options.httpClient,
423426
);
424427

425428
if (!(await browserConfig.storageProvider.isEnabled())) {
@@ -473,22 +476,22 @@ export const shouldFetchRemoteConfig = (options: BrowserOptions = {}): boolean =
473476
}
474477
};
475478

476-
export const createTransport = (transport?: TransportTypeOrOptions) => {
479+
export const createTransport = (transport?: TransportTypeOrOptions, httpClient?: HttpClient) => {
477480
const type = typeof transport === 'object' ? transport.type : transport;
478481
const headers = typeof transport === 'object' ? transport.headers : undefined;
479482
const enableKeepalive = typeof transport === 'object' ? transport.enableKeepalive : undefined;
480483
const referrerPolicy = typeof transport === 'object' ? transport.referrerPolicy : undefined;
481484

482-
if (type === 'xhr') {
485+
if (!httpClient && type === 'xhr') {
483486
return new XHRTransport(headers);
484487
}
485-
if (type === 'beacon') {
488+
if (!httpClient && type === 'beacon') {
486489
// SendBeacon does not support custom headers
487490
return new SendBeaconTransport();
488491
}
489492
// Keep a browser-local fetch transport for gzip support.
490493
// TODO: Merge back to core FetchTransport after React Native supports gzip.
491-
return new FetchTransport(headers, enableKeepalive, referrerPolicy);
494+
return new FetchTransport(headers, enableKeepalive, referrerPolicy, httpClient);
492495
};
493496

494497
export const getTopLevelDomain = async (url?: string, diagnosticsClient?: IDiagnosticsClient) => {

‎packages/analytics-browser/src/transports/fetch.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
Payload,
77
Response,
88
Transport,
9+
HttpClient,
910
} from '@amplitude/analytics-core';
1011

1112
// Conservative 1/4 of the shared 64 KiB keepalive budget. Why 16K: https://github.com/amplitude/Amplitude-TypeScript/pull/1781
@@ -19,7 +20,12 @@ export class FetchTransport extends BaseTransport implements Transport {
1920
private enableKeepalive: boolean;
2021
private referrerPolicy?: ReferrerPolicy;
2122

22-
constructor(customHeaders: Record<string, string> = {}, enableKeepalive?: boolean, referrerPolicy?: ReferrerPolicy) {
23+
constructor(
24+
customHeaders: Record<string, string> = {},
25+
enableKeepalive?: boolean,
26+
referrerPolicy?: ReferrerPolicy,
27+
private readonly httpClient?: HttpClient,
28+
) {
2329
super();
2430
this.customHeaders = customHeaders;
2531
// Enabled unless explicitly disabled.
@@ -31,7 +37,7 @@ export class FetchTransport extends BaseTransport implements Transport {
3137

3238
async send(serverUrl: string, payload: Payload, shouldCompressUploadBody = false): Promise<Response | null> {
3339
/* istanbul ignore if */
34-
if (typeof fetch === 'undefined') {
40+
if (!this.httpClient && typeof fetch === 'undefined') {
3541
throw new Error('FetchTransport is not supported');
3642
}
3743

@@ -72,7 +78,9 @@ export class FetchTransport extends BaseTransport implements Transport {
7278
options.referrerPolicy = this.referrerPolicy;
7379
}
7480

75-
const response = await fetch(serverUrl, options);
81+
const response = this.httpClient
82+
? await this.httpClient.send({ url: serverUrl, ...options })
83+
: await fetch(serverUrl, options);
7684
const responseText = await response.text();
7785
try {
7886
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument

‎packages/analytics-browser/src/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ export {
2929
IdentityStorageType,
3030
Storage,
3131
TransportType,
32+
HttpClient,
33+
HttpRequest,
3234
OfflineDisabled,
3335
Messenger,
3436
ElementInteractionsOptions,

‎packages/analytics-browser/test/browser-client.test.ts‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,37 @@ describe('browser-client', () => {
178178
expect(MockedRemoteConfigClient).not.toHaveBeenCalled();
179179
});
180180

181+
test('shares the HTTP client with remote config, diagnostics, and transport changes', async () => {
182+
const httpClient = {
183+
send: jest.fn().mockResolvedValue({ status: 200, ok: true, text: async () => '{"code":200}' }),
184+
};
185+
await client.init(apiKey, { httpClient, autocapture: false }).promise;
186+
const customFetch = MockedRemoteConfigClient.mock.calls[0][4] as core.RemoteConfigCustomFetch;
187+
const request: core.RemoteConfigFetchRequest = {
188+
url: 'https://example.com/config',
189+
method: 'GET',
190+
headers: {},
191+
signal: new AbortController().signal,
192+
};
193+
await customFetch(request);
194+
expect(httpClient.send).toHaveBeenLastCalledWith(request);
195+
await (client.config.diagnosticsClient as DiagnosticsClient).fetch({
196+
tags: {},
197+
histogram: {},
198+
counters: {},
199+
events: [],
200+
});
201+
expect(httpClient.send).toHaveBeenLastCalledWith(
202+
expect.objectContaining({
203+
url: expect.stringContaining('diagnostics.'),
204+
method: 'POST',
205+
}),
206+
);
207+
client.setTransport('beacon');
208+
await client.config.transportProvider.send('https://example.com/events', { api_key: apiKey, events: [] });
209+
expect(httpClient.send).toHaveBeenLastCalledWith(expect.objectContaining({ url: 'https://example.com/events' }));
210+
});
211+
181212
test('should pass remoteConfig.serverUrl to RemoteConfigClient when provided', async () => {
182213
const customServerUrl = 'https://my-proxy.com/remote-config';
183214

@@ -192,6 +223,7 @@ describe('browser-client', () => {
192223
expect.anything(), // loggerProvider
193224
'US', // default serverZone
194225
customServerUrl, // our custom URL
226+
undefined, // default config transport
195227
);
196228
});
197229

@@ -423,6 +455,8 @@ describe('browser-client', () => {
423455
enabled: expectedEnabled,
424456
sampleRate: expectedSampleRate,
425457
},
458+
undefined,
459+
undefined,
426460
);
427461

428462
// Verify that the diagnostics config was applied
@@ -2408,7 +2442,7 @@ describe('browser-client', () => {
24082442
createTransport.mockClear();
24092443
client.setTransport('xhr');
24102444

2411-
expect(createTransport).toHaveBeenCalledWith('xhr');
2445+
expect(createTransport).toHaveBeenCalledWith('xhr', undefined);
24122446
});
24132447

24142448
test('should keep custom endpoint compression setting when switching transport', async () => {
@@ -2422,7 +2456,7 @@ describe('browser-client', () => {
24222456
createTransport.mockClear();
24232457
client.setTransport('xhr');
24242458

2425-
expect(createTransport).toHaveBeenCalledWith('xhr');
2459+
expect(createTransport).toHaveBeenCalledWith('xhr', undefined);
24262460
});
24272461

24282462
test('should defer set transport', () => {

‎packages/analytics-browser/test/config.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,13 @@ import { AmplitudeBrowser } from '../src/browser-client';
2323
import { VERSION } from '../src/version';
2424

2525
describe('config', () => {
26+
test.each(['fetch', 'xhr', 'beacon'] as const)('custom HTTP client overrides %s transport', async (type) => {
27+
const httpClient = { send: jest.fn().mockResolvedValue({ status: 200, text: async () => '{"code":200}' }) };
28+
const transport = createTransport(type, httpClient);
29+
await transport.send('https://example.com/events', { api_key: 'key', events: [] });
30+
expect(httpClient.send).toHaveBeenCalledTimes(1);
31+
});
32+
2633
const someUUID: string = expect.stringMatching(uuidPattern) as string;
2734
const someCookieStorage: BrowserUtils.CookieStorage<UserSession> = expect.any(
2835
BrowserUtils.CookieStorage,

‎packages/analytics-browser/test/transport/fetch.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,60 @@ if (typeof global.TextEncoder === 'undefined') {
1111

1212
describe('fetch transport', () => {
1313
describe('send', () => {
14+
test('passes serialized requests to a stateful HTTP client and parses HTTP failures', async () => {
15+
const httpClient = {
16+
response: new Response('{"code":429}', { status: 429 }),
17+
send: jest.fn(function (this: { response: Response }, _request: analyticsCore.HttpRequest) {
18+
return Promise.resolve(this.response);
19+
}),
20+
};
21+
const fetchSpy = jest.spyOn(window, 'fetch');
22+
const transport = new FetchTransport({ Authorization: 'token' }, false, 'no-referrer', httpClient);
23+
const payload = { api_key: 'key', events: [] };
24+
25+
const response = await transport.send('https://example.com/events', payload);
26+
27+
expect(httpClient.send).toHaveBeenCalledWith({
28+
url: 'https://example.com/events',
29+
method: 'POST',
30+
headers: { Authorization: 'token', 'Content-Type': 'application/json', Accept: '*/*' },
31+
body: JSON.stringify(payload),
32+
keepalive: false,
33+
referrerPolicy: 'no-referrer',
34+
});
35+
expect(response?.statusCode).toBe(429);
36+
expect(fetchSpy).not.toHaveBeenCalled();
37+
});
38+
39+
test('passes compressed bytes to the custom client', async () => {
40+
const compressed = new ArrayBuffer(2);
41+
jest.spyOn(analyticsCore, 'isCompressionStreamAvailable').mockReturnValue(true);
42+
jest.spyOn(analyticsCore, 'compressToGzipArrayBuffer').mockResolvedValue(compressed);
43+
const httpClient = { send: jest.fn().mockResolvedValue(new Response('{"code":200}')) };
44+
const transport = new FetchTransport({}, undefined, undefined, httpClient);
45+
const payload = { api_key: 'key', events: [{ event_type: 'x'.repeat(MIN_GZIP_UPLOAD_BODY_SIZE_BYTES) }] };
46+
47+
await transport.send('https://example.com/events', payload, true);
48+
49+
expect(httpClient.send).toHaveBeenCalledWith(
50+
expect.objectContaining({
51+
body: compressed,
52+
headers: expect.objectContaining({ 'Content-Encoding': 'gzip' }),
53+
}),
54+
);
55+
});
56+
57+
test('propagates custom client network failures without bypassing the client', async () => {
58+
const error = new Error('offline');
59+
const httpClient = { send: jest.fn().mockRejectedValue(error) };
60+
const fetchSpy = jest.spyOn(window, 'fetch');
61+
const transport = new FetchTransport({}, undefined, undefined, httpClient);
62+
63+
await expect(transport.send('https://example.com/events', { api_key: 'key', events: [] })).rejects.toBe(error);
64+
expect(httpClient.send).toHaveBeenCalledTimes(1);
65+
expect(fetchSpy).not.toHaveBeenCalled();
66+
});
67+
1468
test.each([['{}'], [''], ['<']])('should resolve with response', async (body) => {
1569
const transport = new FetchTransport();
1670
const url = 'http://localhost:3000';

‎packages/analytics-core/src/diagnostics/diagnostics-client.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { HttpClient } from '../types/transport';
12
import { ILogger } from '../logger';
23
import { DiagnosticsStorage, IDiagnosticsStorage } from './diagnostics-storage';
34
import { ServerZoneType } from '../types/server-zone';
@@ -200,6 +201,7 @@ export class DiagnosticsClient implements IDiagnosticsClient {
200201
* not a public config option.
201202
*/
202203
storage?: IDiagnosticsStorage,
204+
private readonly httpClient?: HttpClient,
203205
) {
204206
this.apiKey = apiKey;
205207
this.logger = logger;
@@ -427,18 +429,21 @@ export class DiagnosticsClient implements IDiagnosticsClient {
427429
*/
428430
async fetch(payload: FlushPayload) {
429431
try {
430-
if (!getGlobalScope()) {
432+
if (!this.httpClient && !getGlobalScope()) {
431433
throw new Error('DiagnosticsClient: Fetch is not supported');
432434
}
433435

434-
const response = await fetch(this.serverUrl, {
436+
const options: RequestInit = {
435437
method: 'POST',
436438
headers: {
437439
'X-ApiKey': this.apiKey,
438440
'Content-Type': 'application/json',
439441
},
440442
body: JSON.stringify(payload),
441-
});
443+
};
444+
const response = this.httpClient
445+
? await this.httpClient.send({ url: this.serverUrl, ...options })
446+
: await fetch(this.serverUrl, options);
442447

443448
if (!response.ok) {
444449
this.logger.debug('DiagnosticsClient: Failed to send diagnostics data.');

‎packages/analytics-core/src/index.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,14 @@ export { IngestionMetadata } from './types/event/ingestion-metadata';
9090
export { ServerZoneType, ServerZone } from './types/server-zone';
9191
export { OfflineDisabled } from './types/offline';
9292
export { Plan } from './types/event/plan';
93-
export { TransportType, Transport, TransportOptions, TransportTypeOrOptions } from './types/transport';
93+
export {
94+
TransportType,
95+
Transport,
96+
TransportOptions,
97+
TransportTypeOrOptions,
98+
HttpClient,
99+
HttpRequest,
100+
} from './types/transport';
94101
export { Payload } from './types/payload';
95102
export { Response } from './types/response';
96103
export { UserSession } from './types/user-session';

0 commit comments

Comments
 (0)