From b771be1e0711a403e7191851e33a4e13c6b36be4 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Wed, 16 Sep 2026 16:26:07 -0400 Subject: [PATCH 1/5] feat: Use Electron's net module as the default HTTP transport --- .../platform/ElectronRequests.test.ts | 191 +++++++++++++++++- .../electron/src/platform/ElectronRequests.ts | 81 ++++++-- .../electron/src/platform/ElectronResponse.ts | 59 +++--- 3 files changed, 285 insertions(+), 46 deletions(-) diff --git a/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts b/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts index e04792e0db..e8d32408b4 100644 --- a/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts +++ b/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts @@ -1,6 +1,127 @@ import * as http from 'http'; import * as zlib from 'zlib'; +// electron.net isn't available outside a real Electron main process, so this fakes just +// enough of the ClientRequest API to drive the local test server below over Node's real +// http module. Verified against real Electron 42.6.0: Chromium's net module transparently +// decompresses a compressed body while `IncomingMessage.headers` still reports the origin's +// original `content-encoding` -- this fake reproduces exactly that (see the scrutinize +// report for the real-Electron verification), rather than handing back a raw, never +// -transcoded Node response the way a naive passthrough would. +jest.mock('electron', () => { + // eslint-disable-next-line global-require + const { EventEmitter } = require('events'); + // eslint-disable-next-line global-require + const nodeHttp = require('http'); + // eslint-disable-next-line global-require + const nodeZlib = require('zlib'); + + class ChromiumLikeResponse extends EventEmitter { + headers: http.IncomingHttpHeaders; + + statusCode: number; + + constructor(headers: http.IncomingHttpHeaders, statusCode: number) { + super(); + this.headers = headers; + this.statusCode = statusCode; + } + } + + class FakeClientRequest extends EventEmitter { + headers: Record = {}; + + chunks: Buffer[] = []; + + realRequest?: http.ClientRequest; + + ended: boolean = false; + + constructor( + private options: { + method?: string; + url: string; + redirect?: string; + credentials?: string; + cache?: string; + }, + ) { + super(); + } + + setHeader(name: string, value: string) { + this.headers[name] = value; + } + + write(chunk: string | Buffer) { + this.chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + } + + end() { + if (this.ended) { + return; + } + this.ended = true; + const body = Buffer.concat(this.chunks); + this.realRequest = nodeHttp.request( + this.options.url, + { method: this.options.method, headers: this.headers }, + (res: http.IncomingMessage) => { + // 'response' fires as soon as headers arrive, same as real net.request -- the + // status/headers are available immediately, independent of whether the body ever + // completes (this matters for the /reset scenario below). + const fakeRes = new ChromiumLikeResponse(res.headers, res.statusCode!); + this.emit('response', fakeRes); + + const raw: Buffer[] = []; + res.on('data', (chunk: Buffer) => raw.push(chunk)); + res.on('aborted', () => fakeRes.emit('aborted')); + res.on('error', (err: Error) => fakeRes.emit('error', err)); + res.on('end', () => { + // Chromium decompresses transparently; the caller never sees compressed bytes, + // even though res.headers still reports the origin's content-encoding. + const decoded = + res.headers['content-encoding'] === 'gzip' + ? nodeZlib.gunzipSync(Buffer.concat(raw)) + : Buffer.concat(raw); + if (decoded.length) { + fakeRes.emit('data', decoded); + } + fakeRes.emit('end'); + }); + }, + ); + this.realRequest!.on('error', (err: Error) => this.emit('error', err)); + if (body.length) { + this.realRequest!.write(body); + } + this.realRequest!.end(); + } + + abort() { + this.realRequest?.destroy(); + this.emit('abort'); + this.emit('close'); + } + } + + return { + app: { + isReady: jest.fn(() => true), + whenReady: jest.fn(() => Promise.resolve()), + }, + net: { + request: jest.fn( + (options: { method?: string; url: string }) => new FakeClientRequest(options), + ), + }, + }; +}); + +// eslint-disable-next-line import/first +import { app as mockedElectronApp, net as mockedElectronNet } from 'electron'; + +// eslint-disable-next-line import/first import ElectronRequests from '../../src/platform/ElectronRequests'; const PORT = '3333'; @@ -52,6 +173,12 @@ beforeEach(() => { } else if ((req.url?.indexOf('404') || -1) >= 0) { res.statusCode = 404; res.end(); + } else if ((req.url?.indexOf('slow') || -1) >= 0) { + setTimeout(() => { + if (!res.destroyed) { + res.end(TEXT_RESPONSE); + } + }, 200).unref(); } else if ((req.url?.indexOf('reset') || -1) >= 0) { res.statusCode = 200; res.flushHeaders(); @@ -77,7 +204,7 @@ afterEach( }), ); -describe('given a default instance of NodeRequests', () => { +describe('given a default instance of ElectronRequests', () => { const requests = new ElectronRequests(); it('can make a basic get request', async () => { const res = await requests.fetch(`http://localhost:${PORT}`); @@ -179,9 +306,31 @@ describe('given a default instance of NodeRequests', () => { expect(serverResult.method).toEqual('GET'); expect(serverResult.body).toEqual(''); }); + + it('rejects with a timeout error and aborts the underlying request', async () => { + await expect(requests.fetch(`http://localhost:${PORT}/slow`, { timeout: 20 })).rejects.toThrow( + 'Request timed out', + ); + }); + + it('does not time out when the response arrives before the deadline', async () => { + const res = await requests.fetch(`http://localhost:${PORT}`, { timeout: 5000 }); + expect(res.status).toEqual(200); + }); + + it('does not follow redirects, omits ambient session credentials, and bypasses the shared cache', async () => { + await requests.fetch(`http://localhost:${PORT}`); + expect(mockedElectronNet.request).toHaveBeenCalledWith( + expect.objectContaining({ + redirect: 'error', + credentials: 'omit', + cache: 'no-store', + }), + ); + }); }); -describe('given an instance of NodeRequests with enableEventCompression turned on', () => { +describe('given an instance of ElectronRequests with enableEventCompression turned on', () => { const requests = new ElectronRequests(true); it('can make a basic post with compressBodyIfPossible enabled', async () => { await requests.fetch(`http://localhost:${PORT}`, { @@ -207,3 +356,41 @@ describe('given an instance of NodeRequests with enableEventCompression turned o expect(serverResult.body).toEqual('BODY TEXT'); }); }); + +describe('given the app is not ready yet', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + afterEach(() => { + (mockedElectronApp.isReady as jest.Mock).mockReturnValue(true); + }); + + it('waits for whenReady() before issuing the request, then proceeds', async () => { + (mockedElectronApp.isReady as jest.Mock).mockReturnValue(false); + let readyResolve: () => void = () => {}; + (mockedElectronApp.whenReady as jest.Mock).mockReturnValue( + new Promise((res) => { + readyResolve = res; + }), + ); + + const requests = new ElectronRequests(); + const fetchPromise = requests.fetch(`http://localhost:${PORT}`); + + expect(mockedElectronNet.request).not.toHaveBeenCalled(); + + readyResolve(); + const res = await fetchPromise; + + expect(res.status).toEqual(200); + expect(mockedElectronNet.request).toHaveBeenCalled(); + }); + + it('does not call whenReady() when the app is already ready', async () => { + const requests = new ElectronRequests(); + await requests.fetch(`http://localhost:${PORT}`); + + expect(mockedElectronApp.whenReady).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/sdk/electron/src/platform/ElectronRequests.ts b/packages/sdk/electron/src/platform/ElectronRequests.ts index 18a3fd7712..64fe23b154 100644 --- a/packages/sdk/electron/src/platform/ElectronRequests.ts +++ b/packages/sdk/electron/src/platform/ElectronRequests.ts @@ -1,6 +1,8 @@ -import * as http from 'http'; -import * as https from 'https'; +import { app , net } from 'electron'; +import type { ClientRequest, IncomingMessage } from 'electron'; // No types for the event source. +// TODO: once we merge in the shared @launchdarkly/eventsource, we will replace +// this dependency. Expect some deviations between streaming and polling until then. // @ts-ignore import { EventSource as LDEventSource } from 'launchdarkly-eventsource'; import { promisify } from 'util'; @@ -19,9 +21,19 @@ export default class ElectronRequests implements platform.Requests { this._enableBodyCompression = !!enableEventCompression; } + /** + * Uses Electron's `net` module (Chromium's networking stack) for polling, analytics, + * and diagnostic requests. The `net` module is only usable once Electron's `ready` event + * has fired; this method transparently waits for that milestone (which Electron reaches + * on its own, independent of application code) rather than requiring callers to + * sequence their own calls around it. + * + * https://www.electronjs.org/docs/latest/api/net + */ async fetch(url: string, options: platform.Options = {}): Promise { - const isSecure = url.startsWith('https://'); - const impl = isSecure ? https : http; + if (!app.isReady()) { + await app.whenReady(); + } const headers = { ...options.headers }; let bodyData: string | Buffer | undefined = options.body; @@ -45,24 +57,65 @@ export default class ElectronRequests implements platform.Requests { } return new Promise((resolve, reject) => { - const req = impl.request( + const req: ClientRequest = net.request({ + method: options.method, url, - { - timeout: options.timeout, - headers, - method: options.method, - }, - (res) => resolve(new ElectronResponse(res)), - ); + // Node's http/https never followed redirects, sent ambient session credentials, or + // served requests from a shared cache; net.request() defaults to all three (`redirect: + // 'follow'`, session-ambient auth, `cache: 'default'`). Preserve the prior behavior: + // surface any redirect as an error instead of silently following it with credentials + // attached, don't attach ambient session auth, and don't let polling/analytics/ + // diagnostic responses be served from or written into the app's shared HTTP cache. + redirect: 'error', + credentials: 'omit', + cache: 'no-store', + }); - if (bodyData) { - req.write(bodyData); + Object.entries(headers).forEach(([name, value]) => { + if (value !== undefined) { + req.setHeader(name, value); + } + }); + + // The net module has no built-in request timeout, unlike Node's http/https, + // so we abort the request ourselves and surface it the same way. + let timedOut = false; + let timeoutHandle: ReturnType | undefined; + if (options.timeout && options.timeout > 0) { + timeoutHandle = setTimeout(() => { + timedOut = true; + req.abort(); + }, options.timeout); } + const clearRequestTimeout = () => { + if (timeoutHandle) { + clearTimeout(timeoutHandle); + } + }; + + req.on('response', (res: IncomingMessage) => { + clearRequestTimeout(); + resolve(new ElectronResponse(res)); + }); + + // abort() only emits 'abort' (and then 'close'), not 'error', so a + // self-triggered timeout must be surfaced here rather than in 'error'. + req.on('abort', () => { + clearRequestTimeout(); + if (timedOut) { + reject(new Error('Request timed out')); + } + }); req.on('error', (err) => { + clearRequestTimeout(); reject(err); }); + if (bodyData) { + req.write(bodyData); + } + req.end(); }); } diff --git a/packages/sdk/electron/src/platform/ElectronResponse.ts b/packages/sdk/electron/src/platform/ElectronResponse.ts index d348d06157..5f96f3b4f0 100644 --- a/packages/sdk/electron/src/platform/ElectronResponse.ts +++ b/packages/sdk/electron/src/platform/ElectronResponse.ts @@ -1,23 +1,13 @@ -import * as http from 'http'; -import { pipeline, Writable } from 'stream'; -import * as zlib from 'zlib'; +import type { IncomingMessage } from 'electron'; import { platform } from '@launchdarkly/js-client-sdk-common'; import HeaderWrapper from './HeaderWrapper'; export default class ElectronResponse implements platform.Response { - incomingMessage: http.IncomingMessage; + incomingMessage: IncomingMessage; - chunks: any[] = []; - - memoryStream: Writable = new Writable({ - decodeStrings: true, - write: (chunk, _enc, next) => { - this.chunks.push(chunk); - next(); - }, - }); + chunks: Buffer[] = []; promise: Promise; @@ -28,32 +18,41 @@ export default class ElectronResponse implements platform.Response { listened: boolean = false; rejection?: Error; - constructor(res: http.IncomingMessage) { + // Electron's net module response object implements the Readable-stream 'data'/'end' + // events. Its TypeScript declarations aren't a `stream.Readable`, so it isn't type-compatible + // with `stream.pipeline()` the way `http.IncomingMessage` is -- collect chunks manually instead. + constructor(res: IncomingMessage) { this.headers = new HeaderWrapper(res.headers); - // Status code is optionally typed, but will always be present for this - // use case. - this.status = res.statusCode || 0; + this.status = res.statusCode; this.incomingMessage = res; this.promise = new Promise((resolve, reject) => { - // Called on error or completion of the pipeline. - const pipelineCallback = (err: any) => { + let settled = false; + + // Called on error, abort, or completion of the response. Idempotent: only the first + // call has any effect, since a body already resolved from 'end' should not be retroactively + // poisoned by a late 'error'/'aborted' that fires after the transaction is otherwise done. + const finish = (err?: unknown) => { + if (settled) { + return; + } + settled = true; if (err) { - this.rejection = err; + this.rejection = err instanceof Error ? err : new Error(String(err)); if (this.listened) { - reject(err); + reject(this.rejection); + return; } } - return resolve(Buffer.concat(this.chunks).toString()); + resolve(Buffer.concat(this.chunks).toString()); }; - switch (res.headers['content-encoding']) { - case 'gzip': - pipeline(res, zlib.createGunzip(), this.memoryStream, pipelineCallback); - break; - default: - pipeline(res, this.memoryStream, pipelineCallback); - break; - } + + res.on('data', (chunk: Buffer) => { + this.chunks.push(chunk); + }); + res.on('error', finish); + res.on('aborted', () => finish(new Error('Response aborted'))); + res.on('end', () => finish()); }); } From 2ee7924442f1565500b5ae4a699fee1d1398dc77 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Wed, 16 Sep 2026 17:06:14 -0400 Subject: [PATCH 2/5] fix: Fix formatting introduced by stack rebase --- .../electron/src/platform/ElectronRequests.ts | 20 ++++++++++--------- .../electron/src/platform/ElectronResponse.ts | 6 ------ 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/packages/sdk/electron/src/platform/ElectronRequests.ts b/packages/sdk/electron/src/platform/ElectronRequests.ts index 64fe23b154..fc6ca12070 100644 --- a/packages/sdk/electron/src/platform/ElectronRequests.ts +++ b/packages/sdk/electron/src/platform/ElectronRequests.ts @@ -1,4 +1,4 @@ -import { app , net } from 'electron'; +import { app, net } from 'electron'; import type { ClientRequest, IncomingMessage } from 'electron'; // No types for the event source. // TODO: once we merge in the shared @launchdarkly/eventsource, we will replace @@ -24,9 +24,7 @@ export default class ElectronRequests implements platform.Requests { /** * Uses Electron's `net` module (Chromium's networking stack) for polling, analytics, * and diagnostic requests. The `net` module is only usable once Electron's `ready` event - * has fired; this method transparently waits for that milestone (which Electron reaches - * on its own, independent of application code) rather than requiring callers to - * sequence their own calls around it. + * has fired. * * https://www.electronjs.org/docs/latest/api/net */ @@ -60,14 +58,18 @@ export default class ElectronRequests implements platform.Requests { const req: ClientRequest = net.request({ method: options.method, url, - // Node's http/https never followed redirects, sent ambient session credentials, or - // served requests from a shared cache; net.request() defaults to all three (`redirect: - // 'follow'`, session-ambient auth, `cache: 'default'`). Preserve the prior behavior: + // These options are set to be compatible with Node's http/https never + // (which was used in the previous version implementation). + // surface any redirect as an error instead of silently following it with credentials - // attached, don't attach ambient session auth, and don't let polling/analytics/ - // diagnostic responses be served from or written into the app's shared HTTP cache. + // attached. redirect: 'error', + + // don't attach ambient session auth. credentials: 'omit', + + // don't let polling/analytics/diagnostic responses be served from or written into + // the app's shared HTTP cache. cache: 'no-store', }); diff --git a/packages/sdk/electron/src/platform/ElectronResponse.ts b/packages/sdk/electron/src/platform/ElectronResponse.ts index 5f96f3b4f0..bfc1cbc1df 100644 --- a/packages/sdk/electron/src/platform/ElectronResponse.ts +++ b/packages/sdk/electron/src/platform/ElectronResponse.ts @@ -18,9 +18,6 @@ export default class ElectronResponse implements platform.Response { listened: boolean = false; rejection?: Error; - // Electron's net module response object implements the Readable-stream 'data'/'end' - // events. Its TypeScript declarations aren't a `stream.Readable`, so it isn't type-compatible - // with `stream.pipeline()` the way `http.IncomingMessage` is -- collect chunks manually instead. constructor(res: IncomingMessage) { this.headers = new HeaderWrapper(res.headers); this.status = res.statusCode; @@ -29,9 +26,6 @@ export default class ElectronResponse implements platform.Response { this.promise = new Promise((resolve, reject) => { let settled = false; - // Called on error, abort, or completion of the response. Idempotent: only the first - // call has any effect, since a body already resolved from 'end' should not be retroactively - // poisoned by a late 'error'/'aborted' that fires after the transaction is otherwise done. const finish = (err?: unknown) => { if (settled) { return; From c8d526fad009703dbc6aa5897d0493918fef2ade Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Wed, 28 Oct 2026 15:19:03 -0400 Subject: [PATCH 3/5] docs: Restore explanatory comments lost in an earlier rebase --- .../electron/src/platform/ElectronRequests.ts | 18 ++++++++---------- .../electron/src/platform/ElectronResponse.ts | 6 ++++++ 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/packages/sdk/electron/src/platform/ElectronRequests.ts b/packages/sdk/electron/src/platform/ElectronRequests.ts index fc6ca12070..70e6e70488 100644 --- a/packages/sdk/electron/src/platform/ElectronRequests.ts +++ b/packages/sdk/electron/src/platform/ElectronRequests.ts @@ -24,7 +24,9 @@ export default class ElectronRequests implements platform.Requests { /** * Uses Electron's `net` module (Chromium's networking stack) for polling, analytics, * and diagnostic requests. The `net` module is only usable once Electron's `ready` event - * has fired. + * has fired; this method transparently waits for that milestone (which Electron reaches + * on its own, independent of application code) rather than requiring callers to + * sequence their own calls around it. * * https://www.electronjs.org/docs/latest/api/net */ @@ -58,18 +60,14 @@ export default class ElectronRequests implements platform.Requests { const req: ClientRequest = net.request({ method: options.method, url, - // These options are set to be compatible with Node's http/https never - // (which was used in the previous version implementation). - + // Node's http/https never followed redirects, sent ambient session credentials, or + // served requests from a shared cache; net.request() defaults to all three (`redirect: + // 'follow'`, session-ambient auth, `cache: 'default'`). Preserve the prior behavior: // surface any redirect as an error instead of silently following it with credentials - // attached. + // attached, don't attach ambient session auth, and don't let polling/analytics/ + // diagnostic responses be served from or written into the app's shared HTTP cache. redirect: 'error', - - // don't attach ambient session auth. credentials: 'omit', - - // don't let polling/analytics/diagnostic responses be served from or written into - // the app's shared HTTP cache. cache: 'no-store', }); diff --git a/packages/sdk/electron/src/platform/ElectronResponse.ts b/packages/sdk/electron/src/platform/ElectronResponse.ts index bfc1cbc1df..5f96f3b4f0 100644 --- a/packages/sdk/electron/src/platform/ElectronResponse.ts +++ b/packages/sdk/electron/src/platform/ElectronResponse.ts @@ -18,6 +18,9 @@ export default class ElectronResponse implements platform.Response { listened: boolean = false; rejection?: Error; + // Electron's net module response object implements the Readable-stream 'data'/'end' + // events. Its TypeScript declarations aren't a `stream.Readable`, so it isn't type-compatible + // with `stream.pipeline()` the way `http.IncomingMessage` is -- collect chunks manually instead. constructor(res: IncomingMessage) { this.headers = new HeaderWrapper(res.headers); this.status = res.statusCode; @@ -26,6 +29,9 @@ export default class ElectronResponse implements platform.Response { this.promise = new Promise((resolve, reject) => { let settled = false; + // Called on error, abort, or completion of the response. Idempotent: only the first + // call has any effect, since a body already resolved from 'end' should not be retroactively + // poisoned by a late 'error'/'aborted' that fires after the transaction is otherwise done. const finish = (err?: unknown) => { if (settled) { return; From d677b5aa1cf3707e055c28fcef0315099769d8f2 Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Wed, 28 Oct 2026 17:08:55 -0400 Subject: [PATCH 4/5] feat: update to use electron's net.fetch --- .../ElectronClient.mainProcess.test.ts | 108 ++++--- .../platform/ElectronRequests.test.ts | 285 ++++++++++-------- .../__tests__/platform/HeaderWrapper.test.ts | 53 ---- packages/sdk/electron/package.json | 4 +- .../electron/src/platform/ElectronRequests.ts | 127 ++++---- .../electron/src/platform/ElectronResponse.ts | 75 ----- .../electron/src/platform/HeaderWrapper.ts | 58 ---- 7 files changed, 297 insertions(+), 413 deletions(-) delete mode 100644 packages/sdk/electron/__tests__/platform/HeaderWrapper.test.ts delete mode 100644 packages/sdk/electron/src/platform/ElectronResponse.ts delete mode 100644 packages/sdk/electron/src/platform/HeaderWrapper.ts diff --git a/packages/sdk/electron/__tests__/ElectronClient.mainProcess.test.ts b/packages/sdk/electron/__tests__/ElectronClient.mainProcess.test.ts index 5b6216173e..8b63769387 100644 --- a/packages/sdk/electron/__tests__/ElectronClient.mainProcess.test.ts +++ b/packages/sdk/electron/__tests__/ElectronClient.mainProcess.test.ts @@ -97,11 +97,23 @@ jest.mock('../src/platform/ElectronPlatform', () => ({ const clientSideId = 'client-side-id'; const DEFAULT_INITIAL_CONTEXT = { kind: 'user' as const, key: 'test-user' }; +// A client that stays open keeps its poll and flush timers, and jest cannot exit. +const openClients: { close(): Promise }[] = []; + +function closeAfterTest }>(client: T): T { + openClients.push(client); + return client; +} + beforeEach(() => { jest.clearAllMocks(); handlers.clear(); }); +afterEach(async () => { + await Promise.all(openClients.splice(0).map((client) => client.close())); +}); + describe('given an initialized ElectronClient with enableIPC: false', () => { const logger: LDLogger = { debug: jest.fn(), @@ -121,6 +133,10 @@ describe('given an initialized ElectronClient with enableIPC: false', () => { await client.start(); }); + afterAll(async () => { + await client.close(); + }); + it('does not register any IPC channels so ipcMain.on and ipcMain.handle are never called', () => { expect(mockOn).not.toHaveBeenCalled(); expect(mockHandle).not.toHaveBeenCalled(); @@ -195,12 +211,14 @@ describe('given an initialized ElectronClient with enableIPC: false and bootstra }; it('evaluates flags from bootstrap when called directly on the client', async () => { - const client = new ElectronClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { - initialConnectionMode: 'offline', - enableIPC: false, - logger, - diagnosticOptOut: true, - }); + const client = closeAfterTest( + new ElectronClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { + initialConnectionMode: 'offline', + enableIPC: false, + logger, + diagnosticOptOut: true, + }), + ); await client.start({ bootstrap: goodBootstrapData }); expect(client.variation('killswitch', false)).toBe(true); @@ -223,12 +241,14 @@ describe('enableIPC: false and close()', () => { }; it('does not register channels so close() does not remove any handlers', async () => { - const client = new ElectronClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { - initialConnectionMode: 'offline', - enableIPC: false, - logger, - diagnosticOptOut: true, - }); + const client = closeAfterTest( + new ElectronClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { + initialConnectionMode: 'offline', + enableIPC: false, + logger, + diagnosticOptOut: true, + }), + ); await client.start(); expect(mockOn).not.toHaveBeenCalled(); @@ -267,13 +287,15 @@ describe('given an initialized ElectronClient with enableIPC: false and polling' }, }); - const client = createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { - initialConnectionMode: 'polling', - enableIPC: false, - logger, - diagnosticOptOut: true, - sendEvents: false, - }); + const client = closeAfterTest( + createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { + initialConnectionMode: 'polling', + enableIPC: false, + logger, + diagnosticOptOut: true, + sendEvents: false, + }), + ); await client.start(); expect(client.boolVariation('on-off-flag', false)).toBe(true); @@ -319,13 +341,15 @@ describe('maxCachedContexts', () => { storage, }); - const client = createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { - initialConnectionMode: 'polling', - enableIPC: false, - diagnosticOptOut: true, - sendEvents: false, - maxCachedContexts: 1, - }); + const client = closeAfterTest( + createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { + initialConnectionMode: 'polling', + enableIPC: false, + diagnosticOptOut: true, + sendEvents: false, + maxCachedContexts: 1, + }), + ); await client.start(); // After start, context A's flags are cached. @@ -364,13 +388,15 @@ describe('maxCachedContexts', () => { storage, }); - const client = createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { - initialConnectionMode: 'polling', - enableIPC: false, - diagnosticOptOut: true, - sendEvents: false, - maxCachedContexts: 0, - }); + const client = closeAfterTest( + createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { + initialConnectionMode: 'polling', + enableIPC: false, + diagnosticOptOut: true, + sendEvents: false, + maxCachedContexts: 0, + }), + ); await client.start(); // Flags should still evaluate correctly from the network response @@ -412,13 +438,15 @@ describe('given an initialized ElectronClient with enableIPC: false and streamin }, }); - const client = createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { - initialConnectionMode: 'streaming', - enableIPC: false, - logger, - diagnosticOptOut: true, - sendEvents: false, - }); + const client = closeAfterTest( + createClient(clientSideId, DEFAULT_INITIAL_CONTEXT, { + initialConnectionMode: 'streaming', + enableIPC: false, + logger, + diagnosticOptOut: true, + sendEvents: false, + }), + ); await client.start(); expect(client.boolVariation('on-off-flag', false)).toBe(true); diff --git a/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts b/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts index e8d32408b4..9a9ea625fc 100644 --- a/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts +++ b/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts @@ -1,122 +1,18 @@ import * as http from 'http'; import * as zlib from 'zlib'; -// electron.net isn't available outside a real Electron main process, so this fakes just -// enough of the ClientRequest API to drive the local test server below over Node's real -// http module. Verified against real Electron 42.6.0: Chromium's net module transparently -// decompresses a compressed body while `IncomingMessage.headers` still reports the origin's -// original `content-encoding` -- this fake reproduces exactly that (see the scrutinize -// report for the real-Electron verification), rather than handing back a raw, never -// -transcoded Node response the way a naive passthrough would. -jest.mock('electron', () => { - // eslint-disable-next-line global-require - const { EventEmitter } = require('events'); - // eslint-disable-next-line global-require - const nodeHttp = require('http'); - // eslint-disable-next-line global-require - const nodeZlib = require('zlib'); - - class ChromiumLikeResponse extends EventEmitter { - headers: http.IncomingHttpHeaders; - - statusCode: number; - - constructor(headers: http.IncomingHttpHeaders, statusCode: number) { - super(); - this.headers = headers; - this.statusCode = statusCode; - } - } - - class FakeClientRequest extends EventEmitter { - headers: Record = {}; - - chunks: Buffer[] = []; - - realRequest?: http.ClientRequest; - - ended: boolean = false; - - constructor( - private options: { - method?: string; - url: string; - redirect?: string; - credentials?: string; - cache?: string; - }, - ) { - super(); - } - - setHeader(name: string, value: string) { - this.headers[name] = value; - } - - write(chunk: string | Buffer) { - this.chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); - } - - end() { - if (this.ended) { - return; - } - this.ended = true; - const body = Buffer.concat(this.chunks); - this.realRequest = nodeHttp.request( - this.options.url, - { method: this.options.method, headers: this.headers }, - (res: http.IncomingMessage) => { - // 'response' fires as soon as headers arrive, same as real net.request -- the - // status/headers are available immediately, independent of whether the body ever - // completes (this matters for the /reset scenario below). - const fakeRes = new ChromiumLikeResponse(res.headers, res.statusCode!); - this.emit('response', fakeRes); - - const raw: Buffer[] = []; - res.on('data', (chunk: Buffer) => raw.push(chunk)); - res.on('aborted', () => fakeRes.emit('aborted')); - res.on('error', (err: Error) => fakeRes.emit('error', err)); - res.on('end', () => { - // Chromium decompresses transparently; the caller never sees compressed bytes, - // even though res.headers still reports the origin's content-encoding. - const decoded = - res.headers['content-encoding'] === 'gzip' - ? nodeZlib.gunzipSync(Buffer.concat(raw)) - : Buffer.concat(raw); - if (decoded.length) { - fakeRes.emit('data', decoded); - } - fakeRes.emit('end'); - }); - }, - ); - this.realRequest!.on('error', (err: Error) => this.emit('error', err)); - if (body.length) { - this.realRequest!.write(body); - } - this.realRequest!.end(); - } - - abort() { - this.realRequest?.destroy(); - this.emit('abort'); - this.emit('close'); - } - } - - return { - app: { - isReady: jest.fn(() => true), - whenReady: jest.fn(() => Promise.resolve()), - }, - net: { - request: jest.fn( - (options: { method?: string; url: string }) => new FakeClientRequest(options), - ), - }, - }; -}); +// electron.net isn't available outside a real Electron main process. net.fetch is a standard +// fetch over Chromium's stack, so Node's own fetch stands in for it. Both decode a compressed +// body and keep the origin's content-encoding header. +jest.mock('electron', () => ({ + app: { + isReady: jest.fn(() => true), + whenReady: jest.fn(() => Promise.resolve()), + }, + net: { + fetch: jest.fn((url: string, init: RequestInit) => globalThis.fetch(url, init)), + }, +})); // eslint-disable-next-line import/first import { app as mockedElectronApp, net as mockedElectronNet } from 'electron'; @@ -320,7 +216,8 @@ describe('given a default instance of ElectronRequests', () => { it('does not follow redirects, omits ambient session credentials, and bypasses the shared cache', async () => { await requests.fetch(`http://localhost:${PORT}`); - expect(mockedElectronNet.request).toHaveBeenCalledWith( + expect(mockedElectronNet.fetch).toHaveBeenLastCalledWith( + `http://localhost:${PORT}`, expect.objectContaining({ redirect: 'error', credentials: 'omit', @@ -330,6 +227,156 @@ describe('given a default instance of ElectronRequests', () => { }); }); +describe('given a streaming server', () => { + // A long-lived server on its own port. Restarting a server per test leaves undici's pooled + // connections pointing at the old one, which resets the next streaming request. + const STREAM_PORT = 3334; + const SSE_CHUNK = 'event: put\ndata: {"hello":"world"}\n\n'; + const requests = new ElectronRequests(); + let streamServer: http.Server; + let streamRequest: Promise; + let streamResolve: (value: TestRequestData) => void; + + beforeAll(async () => { + streamServer = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (chunk: Buffer) => chunks.push(chunk)); + req.on('end', () => { + if (req.url === '/redirect') { + res.writeHead(307, { Location: '/stream' }); + res.end(); + return; + } + streamResolve({ + method: req.method, + body: Buffer.concat(chunks).toString(), + headers: req.headers, + }); + // Holds the connection open after the first event, like an SSE stream. + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + res.write(SSE_CHUNK); + }); + }); + await new Promise((res) => { + streamServer.listen(STREAM_PORT, res); + }); + }); + + beforeEach(() => { + streamRequest = new Promise((res) => { + streamResolve = res; + }); + }); + + afterAll( + async () => + new Promise((resolveClose) => { + streamServer.close(resolveClose); + streamServer.closeAllConnections(); + }), + ); + + it('delivers body chunks before the stream ends', async () => { + const res = await requests.fetch(`http://localhost:${STREAM_PORT}/stream`, { + streaming: true, + }); + expect(res.status).toEqual(200); + expect(res.headers.get('content-type')).toEqual('text/event-stream'); + + const reader = res.body!.getReader(); + const first = await reader.read(); + expect(first.done).toBe(false); + expect(Buffer.from(first.value!).toString()).toEqual(SSE_CHUNK); + await reader.cancel?.(); + }); + + it('uses net.fetch with the method, headers, body, and signal', async () => { + const controller = new AbortController(); + const res = await requests.fetch(`http://localhost:${STREAM_PORT}/stream`, { + method: 'REPORT', + headers: { 'Sample-Header': 'Some header value' }, + body: '{"key":"user"}', + signal: controller.signal, + timeout: 1, + streaming: true, + }); + expect(mockedElectronNet.fetch).toHaveBeenLastCalledWith( + `http://localhost:${STREAM_PORT}/stream`, + { + method: 'REPORT', + headers: { 'Sample-Header': 'Some header value' }, + body: '{"key":"user"}', + signal: controller.signal, + redirect: 'follow', + credentials: 'omit', + cache: 'no-store', + }, + ); + const serverResult = await streamRequest; + expect(serverResult.method).toEqual('REPORT'); + expect(serverResult.body).toEqual('{"key":"user"}'); + expect(serverResult.headers['sample-header']).toEqual('Some header value'); + expect(serverResult.headers['accept-encoding']).not.toEqual('gzip'); + controller.abort(); + await expect(res.body!.getReader().read()).rejects.toThrow('This operation was aborted'); + }); + + it('follows a redirect', async () => { + const res = await requests.fetch(`http://localhost:${STREAM_PORT}/redirect`, { + streaming: true, + }); + expect(res.status).toEqual(200); + const reader = res.body!.getReader(); + const first = await reader.read(); + expect(Buffer.from(first.value!).toString()).toEqual(SSE_CHUNK); + await reader.cancel?.(); + }); + + it('waits for whenReady() before issuing the request', async () => { + (mockedElectronNet.fetch as jest.Mock).mockClear(); + (mockedElectronApp.isReady as jest.Mock).mockReturnValueOnce(false); + let readyResolve: () => void = () => {}; + (mockedElectronApp.whenReady as jest.Mock).mockReturnValueOnce( + new Promise((res) => { + readyResolve = res; + }), + ); + + const fetchPromise = requests.fetch(`http://localhost:${STREAM_PORT}/stream`, { + streaming: true, + }); + await Promise.resolve(); + expect(mockedElectronNet.fetch).not.toHaveBeenCalled(); + + readyResolve(); + const res = await fetchPromise; + expect(res.status).toEqual(200); + await res.body!.cancel?.(); + }); + + it('delivers server-sent events through createEventSource', async () => { + const es = requests.createEventSource(`http://localhost:${STREAM_PORT}/stream`, { + headers: { authorization: 'sdk-key' }, + errorFilter: () => true, + initialRetryDelayMillis: 1000, + readTimeoutMillis: 0, + retryResetIntervalMillis: 60000, + }); + try { + const data = await new Promise((resolveEvent) => { + es.addEventListener('put', (event) => resolveEvent(event?.data)); + }); + expect(JSON.parse(data)).toEqual({ hello: 'world' }); + expect(mockedElectronNet.fetch).toHaveBeenCalled(); + const serverResult = await streamRequest; + expect(serverResult.headers.authorization).toEqual('sdk-key'); + expect(serverResult.headers.accept).toEqual('text/event-stream'); + } finally { + es.close(); + } + }); +}); + describe('given an instance of ElectronRequests with enableEventCompression turned on', () => { const requests = new ElectronRequests(true); it('can make a basic post with compressBodyIfPossible enabled', async () => { @@ -378,13 +425,13 @@ describe('given the app is not ready yet', () => { const requests = new ElectronRequests(); const fetchPromise = requests.fetch(`http://localhost:${PORT}`); - expect(mockedElectronNet.request).not.toHaveBeenCalled(); + expect(mockedElectronNet.fetch).not.toHaveBeenCalled(); readyResolve(); const res = await fetchPromise; expect(res.status).toEqual(200); - expect(mockedElectronNet.request).toHaveBeenCalled(); + expect(mockedElectronNet.fetch).toHaveBeenCalled(); }); it('does not call whenReady() when the app is already ready', async () => { diff --git a/packages/sdk/electron/__tests__/platform/HeaderWrapper.test.ts b/packages/sdk/electron/__tests__/platform/HeaderWrapper.test.ts deleted file mode 100644 index d2c89ae6b9..0000000000 --- a/packages/sdk/electron/__tests__/platform/HeaderWrapper.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import * as http from 'http'; - -import HeaderWrapper from '../../src/platform/HeaderWrapper'; - -describe('given header values', () => { - const headers: http.IncomingHttpHeaders = { - accept: 'anything', - 'some-header': 'some-value', - 'some-array': ['a', 'b'], - }; - const wrapper = new HeaderWrapper(headers); - - it('can get a single value header', () => { - expect(wrapper.get('accept')).toEqual('anything'); - }); - - it('can get an array value header', () => { - expect(wrapper.get('some-array')).toEqual('a, b'); - }); - - it('can get the entries', () => { - const flat: Array<[string, string]> = []; - for (const entry of wrapper.entries()) { - flat.push(entry); - } - expect(flat).toEqual([ - ['accept', 'anything'], - ['some-header', 'some-value'], - ['some-array', 'a, b'], - ]); - }); - - it('can check if a value is present', () => { - expect(wrapper.has('accept')).toBeTruthy(); - expect(wrapper.has('potato')).toBeFalsy(); - }); - - it('can key the keys', () => { - const keys: string[] = []; - for (const key of wrapper.keys()) { - keys.push(key); - } - expect(keys).toEqual(['accept', 'some-header', 'some-array']); - }); - - it('can key the values', () => { - const values: string[] = []; - for (const value of wrapper.values()) { - values.push(value); - } - expect(values).toEqual(['anything', 'some-value', 'a, b']); - }); -}); diff --git a/packages/sdk/electron/package.json b/packages/sdk/electron/package.json index dd0770ba03..7deefb30f3 100644 --- a/packages/sdk/electron/package.json +++ b/packages/sdk/electron/package.json @@ -65,8 +65,8 @@ "electron": ">=34.5.6" }, "dependencies": { - "@launchdarkly/js-client-sdk-common": "workspace:^", - "launchdarkly-eventsource": "2.3.0" + "@launchdarkly/eventsource": "0.2.2", + "@launchdarkly/js-client-sdk-common": "workspace:^" }, "devDependencies": { "@types/jest": "^29.4.0", diff --git a/packages/sdk/electron/src/platform/ElectronRequests.ts b/packages/sdk/electron/src/platform/ElectronRequests.ts index 70e6e70488..8be30fcade 100644 --- a/packages/sdk/electron/src/platform/ElectronRequests.ts +++ b/packages/sdk/electron/src/platform/ElectronRequests.ts @@ -1,17 +1,10 @@ import { app, net } from 'electron'; -import type { ClientRequest, IncomingMessage } from 'electron'; -// No types for the event source. -// TODO: once we merge in the shared @launchdarkly/eventsource, we will replace -// this dependency. Expect some deviations between streaming and polling until then. -// @ts-ignore -import { EventSource as LDEventSource } from 'launchdarkly-eventsource'; import { promisify } from 'util'; import * as zlib from 'zlib'; +import { createEventSource } from '@launchdarkly/eventsource'; import { EventSourceCapabilities, platform } from '@launchdarkly/js-client-sdk-common'; -import ElectronResponse from './ElectronResponse'; - const gzip = promisify(zlib.gzip); export default class ElectronRequests implements platform.Requests { @@ -22,9 +15,9 @@ export default class ElectronRequests implements platform.Requests { } /** - * Uses Electron's `net` module (Chromium's networking stack) for polling, analytics, - * and diagnostic requests. The `net` module is only usable once Electron's `ready` event - * has fired; this method transparently waits for that milestone (which Electron reaches + * Uses Electron's `net` module (Chromium's networking stack) for streaming, polling, + * analytics, and diagnostic requests. The `net` module is only usable once Electron's `ready` + * event has fired; this method transparently waits for that milestone (which Electron reaches * on its own, independent of application code) rather than requiring callers to * sequence their own calls around it. * @@ -35,11 +28,15 @@ export default class ElectronRequests implements platform.Requests { await app.whenReady(); } + if (options.streaming) { + return this._streamingFetch(url, options); + } + const headers = { ...options.headers }; - let bodyData: string | Buffer | undefined = options.body; + let bodyData: string | Uint8Array | undefined = options.body; // For get requests we are going to automatically support compressed responses. - // Note this does not affect SSE as the event source is not using this fetch implementation. + // Streaming requests return above, so this does not affect SSE. if (options.method?.toLowerCase() === 'get') { headers['accept-encoding'] = 'gzip'; } @@ -53,15 +50,31 @@ export default class ElectronRequests implements platform.Requests { options.body ) { headers['content-encoding'] = 'gzip'; - bodyData = await gzip(Buffer.from(options.body, 'utf8')); + // net.fetch accepts only views backed by an ArrayBuffer. A zlib Buffer can sit on a shared + // pool, so copy it into its own buffer. + bodyData = new Uint8Array(await gzip(Buffer.from(options.body, 'utf8'))); } - return new Promise((resolve, reject) => { - const req: ClientRequest = net.request({ + // net.fetch has no built-in request timeout, unlike Node's http/https, so we abort the + // request ourselves and surface it the same way. The timer stops when the headers arrive. + const controller = new AbortController(); + let timedOut = false; + let timeoutHandle: ReturnType | undefined; + if (options.timeout && options.timeout > 0) { + timeoutHandle = setTimeout(() => { + timedOut = true; + controller.abort(); + }, options.timeout); + } + + try { + return await net.fetch(url, { method: options.method, - url, + headers, + body: bodyData, + signal: controller.signal, // Node's http/https never followed redirects, sent ambient session credentials, or - // served requests from a shared cache; net.request() defaults to all three (`redirect: + // served requests from a shared cache; net.fetch() defaults to all three (`redirect: // 'follow'`, session-ambient auth, `cache: 'default'`). Preserve the prior behavior: // surface any redirect as an error instead of silently following it with credentials // attached, don't attach ambient session auth, and don't let polling/analytics/ @@ -70,53 +83,35 @@ export default class ElectronRequests implements platform.Requests { credentials: 'omit', cache: 'no-store', }); - - Object.entries(headers).forEach(([name, value]) => { - if (value !== undefined) { - req.setHeader(name, value); - } - }); - - // The net module has no built-in request timeout, unlike Node's http/https, - // so we abort the request ourselves and surface it the same way. - let timedOut = false; - let timeoutHandle: ReturnType | undefined; - if (options.timeout && options.timeout > 0) { - timeoutHandle = setTimeout(() => { - timedOut = true; - req.abort(); - }, options.timeout); - } - const clearRequestTimeout = () => { - if (timeoutHandle) { - clearTimeout(timeoutHandle); - } - }; - - req.on('response', (res: IncomingMessage) => { - clearRequestTimeout(); - resolve(new ElectronResponse(res)); - }); - - // abort() only emits 'abort' (and then 'close'), not 'error', so a - // self-triggered timeout must be surfaced here rather than in 'error'. - req.on('abort', () => { - clearRequestTimeout(); - if (timedOut) { - reject(new Error('Request timed out')); - } - }); - - req.on('error', (err) => { - clearRequestTimeout(); - reject(err); - }); - - if (bodyData) { - req.write(bodyData); + } catch (err) { + if (timedOut) { + throw new Error('Request timed out'); } + throw err; + } finally { + clearTimeout(timeoutHandle); + } + } - req.end(); + /** + * The transport for a streaming request. `net.fetch` returns a standard response whose body + * streams, and it rejects a pending read when the signal aborts. It applies no timeout; the + * caller owns the read timeout. Chromium negotiates and decodes content encoding by itself. + * + * Unlike `fetch`, this follows redirects. `net.fetch` cannot hand a redirect back to the + * caller (`redirect: 'manual'` cancels the request), and the stream must survive a + * redirect. Chromium keeps the request headers, the Authorization header included, on each + * hop. + */ + private _streamingFetch(url: string, options: platform.Options): Promise { + return net.fetch(url, { + method: options.method, + headers: options.headers, + body: options.body, + signal: options.signal, + redirect: 'follow', + credentials: 'omit', + cache: 'no-store', }); } @@ -124,12 +119,12 @@ export default class ElectronRequests implements platform.Requests { url: string, eventSourceInitDict: platform.EventSourceInitDict, ): platform.EventSource { - const expandedOptions = { + return createEventSource(url, { ...eventSourceInitDict, maxBackoffMillis: 30 * 1000, jitterRatio: 0.5, - }; - return new LDEventSource(url, expandedOptions); + fetch: (fetchUrl, init) => this.fetch(fetchUrl, { ...init, streaming: true }), + }); } getEventSourceCapabilities(): EventSourceCapabilities { diff --git a/packages/sdk/electron/src/platform/ElectronResponse.ts b/packages/sdk/electron/src/platform/ElectronResponse.ts deleted file mode 100644 index 5f96f3b4f0..0000000000 --- a/packages/sdk/electron/src/platform/ElectronResponse.ts +++ /dev/null @@ -1,75 +0,0 @@ -import type { IncomingMessage } from 'electron'; - -import { platform } from '@launchdarkly/js-client-sdk-common'; - -import HeaderWrapper from './HeaderWrapper'; - -export default class ElectronResponse implements platform.Response { - incomingMessage: IncomingMessage; - - chunks: Buffer[] = []; - - promise: Promise; - - headers: platform.Headers; - - status: number; - - listened: boolean = false; - rejection?: Error; - - // Electron's net module response object implements the Readable-stream 'data'/'end' - // events. Its TypeScript declarations aren't a `stream.Readable`, so it isn't type-compatible - // with `stream.pipeline()` the way `http.IncomingMessage` is -- collect chunks manually instead. - constructor(res: IncomingMessage) { - this.headers = new HeaderWrapper(res.headers); - this.status = res.statusCode; - this.incomingMessage = res; - - this.promise = new Promise((resolve, reject) => { - let settled = false; - - // Called on error, abort, or completion of the response. Idempotent: only the first - // call has any effect, since a body already resolved from 'end' should not be retroactively - // poisoned by a late 'error'/'aborted' that fires after the transaction is otherwise done. - const finish = (err?: unknown) => { - if (settled) { - return; - } - settled = true; - if (err) { - this.rejection = err instanceof Error ? err : new Error(String(err)); - if (this.listened) { - reject(this.rejection); - return; - } - } - resolve(Buffer.concat(this.chunks).toString()); - }; - - res.on('data', (chunk: Buffer) => { - this.chunks.push(chunk); - }); - res.on('error', finish); - res.on('aborted', () => finish(new Error('Response aborted'))); - res.on('end', () => finish()); - }); - } - - private async _wrappedWait(): Promise { - this.listened = true; - if (this.rejection) { - throw this.rejection; - } - return this.promise; - } - - text(): Promise { - return this._wrappedWait(); - } - - async json(): Promise { - const stringValue = await this._wrappedWait(); - return JSON.parse(stringValue); - } -} diff --git a/packages/sdk/electron/src/platform/HeaderWrapper.ts b/packages/sdk/electron/src/platform/HeaderWrapper.ts deleted file mode 100644 index 9c447c2a8f..0000000000 --- a/packages/sdk/electron/src/platform/HeaderWrapper.ts +++ /dev/null @@ -1,58 +0,0 @@ -import * as http from 'http'; - -import { platform } from '@launchdarkly/js-client-sdk-common'; - -/** - * Wraps the headers to match those used by fetch APIs. - * @internal - */ -export default class HeaderWrapper implements platform.Headers { - private _headers: http.IncomingHttpHeaders; - - constructor(headers: http.IncomingHttpHeaders) { - this._headers = headers; - } - - private _headerVal(name: string) { - const val = this._headers[name]; - if (val === undefined || val === null) { - return null; - } - if (Array.isArray(val)) { - return val.join(', '); - } - return val; - } - - get(name: string): string | null { - return this._headerVal(name); - } - - keys(): Iterable { - return Object.keys(this._headers); - } - - // We want to use generators here for the simplicity of maintaining - // this interface. Also they aren't expected to be high frequency usage. - *values(): Iterable { - for (const key of this.keys()) { - const val = this.get(key); - if (val !== null) { - yield val; - } - } - } - - *entries(): Iterable<[string, string]> { - for (const key of this.keys()) { - const val = this.get(key); - if (val !== null) { - yield [key, val]; - } - } - } - - has(name: string): boolean { - return Object.prototype.hasOwnProperty.call(this._headers, name); - } -} From 2d15645aadf23b82be3948e986aca7ee35b6d2ce Mon Sep 17 00:00:00 2001 From: Steven Zhang Date: Fri, 20 Nov 2026 11:42:11 -0500 Subject: [PATCH 5/5] fix: stop streaming requests from asking for compressed responses --- .../platform/ElectronRequests.test.ts | 4 +-- packages/sdk/electron/package.json | 2 +- .../electron/src/platform/ElectronRequests.ts | 34 ++++++++----------- 3 files changed, 18 insertions(+), 22 deletions(-) diff --git a/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts b/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts index 9a9ea625fc..d3eaa733a3 100644 --- a/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts +++ b/packages/sdk/electron/__tests__/platform/ElectronRequests.test.ts @@ -304,7 +304,7 @@ describe('given a streaming server', () => { `http://localhost:${STREAM_PORT}/stream`, { method: 'REPORT', - headers: { 'Sample-Header': 'Some header value' }, + headers: { 'Sample-Header': 'Some header value', 'accept-encoding': 'identity' }, body: '{"key":"user"}', signal: controller.signal, redirect: 'follow', @@ -316,7 +316,7 @@ describe('given a streaming server', () => { expect(serverResult.method).toEqual('REPORT'); expect(serverResult.body).toEqual('{"key":"user"}'); expect(serverResult.headers['sample-header']).toEqual('Some header value'); - expect(serverResult.headers['accept-encoding']).not.toEqual('gzip'); + expect(serverResult.headers['accept-encoding']).toEqual('identity'); controller.abort(); await expect(res.body!.getReader().read()).rejects.toThrow('This operation was aborted'); }); diff --git a/packages/sdk/electron/package.json b/packages/sdk/electron/package.json index 7deefb30f3..aa23b6898d 100644 --- a/packages/sdk/electron/package.json +++ b/packages/sdk/electron/package.json @@ -65,7 +65,7 @@ "electron": ">=34.5.6" }, "dependencies": { - "@launchdarkly/eventsource": "0.2.2", + "@launchdarkly/eventsource": "0.2.5", "@launchdarkly/js-client-sdk-common": "workspace:^" }, "devDependencies": { diff --git a/packages/sdk/electron/src/platform/ElectronRequests.ts b/packages/sdk/electron/src/platform/ElectronRequests.ts index 8be30fcade..82b7156f89 100644 --- a/packages/sdk/electron/src/platform/ElectronRequests.ts +++ b/packages/sdk/electron/src/platform/ElectronRequests.ts @@ -17,9 +17,7 @@ export default class ElectronRequests implements platform.Requests { /** * Uses Electron's `net` module (Chromium's networking stack) for streaming, polling, * analytics, and diagnostic requests. The `net` module is only usable once Electron's `ready` - * event has fired; this method transparently waits for that milestone (which Electron reaches - * on its own, independent of application code) rather than requiring callers to - * sequence their own calls around it. + * event has fired. This method waits for that event, so callers do not have to. * * https://www.electronjs.org/docs/latest/api/net */ @@ -36,7 +34,6 @@ export default class ElectronRequests implements platform.Requests { let bodyData: string | Uint8Array | undefined = options.body; // For get requests we are going to automatically support compressed responses. - // Streaming requests return above, so this does not affect SSE. if (options.method?.toLowerCase() === 'get') { headers['accept-encoding'] = 'gzip'; } @@ -50,13 +47,13 @@ export default class ElectronRequests implements platform.Requests { options.body ) { headers['content-encoding'] = 'gzip'; - // net.fetch accepts only views backed by an ArrayBuffer. A zlib Buffer can sit on a shared - // pool, so copy it into its own buffer. + // The net.fetch body type accepts only a view backed by an ArrayBuffer. A Buffer has + // the wider ArrayBufferLike type, so copy it into a plain Uint8Array. bodyData = new Uint8Array(await gzip(Buffer.from(options.body, 'utf8'))); } - // net.fetch has no built-in request timeout, unlike Node's http/https, so we abort the - // request ourselves and surface it the same way. The timer stops when the headers arrive. + // net.fetch applies no timeout. This timer limits only the wait for the response + // headers. It stops when the headers arrive, so it does not limit the body read. const controller = new AbortController(); let timedOut = false; let timeoutHandle: ReturnType | undefined; @@ -73,12 +70,9 @@ export default class ElectronRequests implements platform.Requests { headers, body: bodyData, signal: controller.signal, - // Node's http/https never followed redirects, sent ambient session credentials, or - // served requests from a shared cache; net.fetch() defaults to all three (`redirect: - // 'follow'`, session-ambient auth, `cache: 'default'`). Preserve the prior behavior: - // surface any redirect as an error instead of silently following it with credentials - // attached, don't attach ambient session auth, and don't let polling/analytics/ - // diagnostic responses be served from or written into the app's shared HTTP cache. + // A redirect fails the request, so the SDK key never follows it to another host. + // Ambient session credentials stay off. Responses never come from, or go into, + // the app's shared HTTP cache. redirect: 'error', credentials: 'omit', cache: 'no-store', @@ -94,19 +88,21 @@ export default class ElectronRequests implements platform.Requests { } /** - * The transport for a streaming request. `net.fetch` returns a standard response whose body + * Sends a streaming request. `net.fetch` returns a standard response whose body * streams, and it rejects a pending read when the signal aborts. It applies no timeout; the - * caller owns the read timeout. Chromium negotiates and decodes content encoding by itself. + * caller owns the read timeout. It asks for an uncompressed body, so that a proxy + * does not hold events back in a compression buffer. * * Unlike `fetch`, this follows redirects. `net.fetch` cannot hand a redirect back to the * caller (`redirect: 'manual'` cancels the request), and the stream must survive a - * redirect. Chromium keeps the request headers, the Authorization header included, on each - * hop. + * redirect. Chromium follows 301, 302, 303, 307 and 308, up to 20 hops. It keeps the + * request headers on each hop, the Authorization header included, also to another + * origin. A 303 changes the method to GET and drops the body. */ private _streamingFetch(url: string, options: platform.Options): Promise { return net.fetch(url, { method: options.method, - headers: options.headers, + headers: { ...options.headers, 'accept-encoding': 'identity' }, body: options.body, signal: options.signal, redirect: 'follow',