From b72d589d8aa0c739aa1c59166f682f9b584d5783 Mon Sep 17 00:00:00 2001 From: Brian Bischoff Date: Mon, 2 Nov 2026 16:19:42 +0000 Subject: [PATCH 1/3] feat: support strict notification subprotocol authentication --- README.md | 8 ++ src/common/notification-client.ts | 46 +++++++--- test/fixtures/notification-strict.ts | 90 +++++++++++++++++++ test/tests/common/notification-strict.test.ts | 16 ++++ 4 files changed, 150 insertions(+), 10 deletions(-) create mode 100644 test/fixtures/notification-strict.ts create mode 100644 test/tests/common/notification-strict.test.ts diff --git a/README.md b/README.md index c6eac4e..11f37a7 100644 --- a/README.md +++ b/README.md @@ -1089,6 +1089,14 @@ client.disconnect() #### Configuration Options +- **allowQueryFallback**: Defaults to `true` for compatibility with older servers. Set `false` + to keep API keys and bearer tokens in WebSocket subprotocols and never retry them + as URL query parameters. Requires a server that negotiates `flowcore-api-key` or + `flowcore-bearer` (hosted tenant API 2.18.1 or later). A failed or unnegotiated + handshake reports a fixed error through the observer and sends no subscription. + This option does not sanitize caller-supplied endpoint URLs or all logging paths. + Wrappers such as data pumps must explicitly forward the option; updating the SDK + alone does not enable it. - **reconnectInterval**: Time in milliseconds between reconnection attempts (default: 1000) - **maxReconnects**: Maximum number of reconnection attempts (optional) - **maxEvents**: Maximum number of events to receive before auto-disconnecting (optional) diff --git a/src/common/notification-client.ts b/src/common/notification-client.ts index 305c535..d85b208 100644 --- a/src/common/notification-client.ts +++ b/src/common/notification-client.ts @@ -52,6 +52,8 @@ type NotificationEventData = { * Configuration options for the NotificationClient */ export type NotificationClientOptions = { + /** Default true for legacy servers. False requires subprotocol auth and never retries credentials in a URL. */ + allowQueryFallback?: boolean reconnectInterval: number maxReconnects?: number maxEvents?: number @@ -70,14 +72,10 @@ interface NotificationClientAuthOptionsApiKey { apiKeyId?: string } -type NotificationClientAuthOptions = - | NotificationClientAuthOptionsBearer - | NotificationClientAuthOptionsApiKey +type NotificationClientAuthOptions = NotificationClientAuthOptionsBearer | NotificationClientAuthOptionsApiKey /** The resolved credential, after an OIDC token has been fetched. */ -type NotificationCredential = - | { kind: "bearer"; token: string } - | { kind: "apiKey"; apiKey: string; apiKeyId?: string } +type NotificationCredential = { kind: "bearer"; token: string } | { kind: "apiKey"; apiKey: string; apiKeyId?: string } /** * Client for handling WebSocket connections to the Flowcore notification system. @@ -104,6 +102,7 @@ export class NotificationClient { private authTransport: "subprotocol" | "query" = "subprotocol" /** True once a handshake has settled, so the fallback is probed at most once. */ private transportSettled = false + private handshakeAccepted = false /** * Creates a new NotificationClient instance @@ -155,6 +154,7 @@ export class NotificationClient { } this._isConnecting = true + this.handshakeAccepted = false let flowcoreClient: FlowcoreClient | null = null const urlParams = new URLSearchParams() @@ -218,6 +218,11 @@ export class NotificationClient { ) as unknown as WebSocket this.webSocket.onopen = () => { + if (this.options.allowQueryFallback === false && this.webSocket.protocol !== credentialProtocols[0]) { + this.rejectStrictHandshake() + return + } + this.handshakeAccepted = true this._isOpen = true this._isConnecting = false // This transport works; never probe the other one again. @@ -253,6 +258,11 @@ export class NotificationClient { this.webSocket.onclose = (event) => { this._isOpen = false + if (this.options.allowQueryFallback === false && !this.handshakeAccepted) { + this._isConnecting = false + this.observer.error(new Error("Notification WebSocket handshake failed")) + return + } this.logger.debug(`Connection closed: Code [${event.code}], Reason: ${event.reason}`) if (this.shouldFallBackToQueryTransport()) { this.fallBackToQueryTransport() @@ -269,7 +279,17 @@ export class NotificationClient { this.webSocket.onerror = (error) => this.handleWebSocketError(error) } + private rejectStrictHandshake() { + this._isConnecting = false + this.observer.error(new Error("Notification WebSocket handshake failed")) + this.webSocket.close() + } + private handleWebSocketError(error: Event) { + if (this.options.allowQueryFallback === false && !this.handshakeAccepted) { + this.rejectStrictHandshake() + return + } // A server without subprotocol support refuses the handshake, which // surfaces here BEFORE `onopen`. That is a probe result, not a fault, so // it must not terminate the observable — `onclose` performs the retry. @@ -294,9 +314,10 @@ export class NotificationClient { * everyone with log access — for a long-lived `fc_` key that is a full * tenant compromise sitting in a log index. */ - private buildCredentialHandshake( - credential: NotificationCredential, - ): { query: URLSearchParams; protocols: string[] } { + private buildCredentialHandshake(credential: NotificationCredential): { + query: URLSearchParams + protocols: string[] + } { const query = new URLSearchParams() const protocols: string[] = [] @@ -330,7 +351,12 @@ export class NotificationClient { * failure is a real failure and goes through normal reconnect handling. */ private shouldFallBackToQueryTransport(): boolean { - return this.authTransport === "subprotocol" && !this.transportSettled && !this._isOpen + return ( + this.options.allowQueryFallback !== false && + this.authTransport === "subprotocol" && + !this.transportSettled && + !this._isOpen + ) } /** diff --git a/test/fixtures/notification-strict.ts b/test/fixtures/notification-strict.ts new file mode 100644 index 0000000..8cfd3e5 --- /dev/null +++ b/test/fixtures/notification-strict.ts @@ -0,0 +1,90 @@ +import assert from "node:assert/strict" +import { Subject } from "rxjs" + +const sockets: Socket[] = [] +class Socket { + protocol = "" + onopen?: () => void + onerror?: (event: Event) => void + onclose?: (event: { code: number; reason: string }) => void + sent: string[] = [] + constructor( + readonly url: string, + readonly protocols: string[], + ) { + sockets.push(this) + } + send(value: string) { + this.sent.push(value) + } + close() {} +} +globalThis.WebSocket = Socket as unknown as typeof WebSocket +globalThis.fetch = (async () => + Response.json([ + { + id: "core", + tenantId: "tenant", + tenant: "synthetic", + name: "synthetic", + description: "", + accessControl: "private", + deleteProtection: false, + isDeleting: false, + isFlowcoreManaged: false, + }, + ])) as unknown as typeof fetch +const { NotificationClient } = await import("../../src/common/notification-client.ts") +const logger = { debug() {}, info() {}, warn() {}, error() {} } +for (const bearer of [false, true]) { + for (const outcome of ["error", "close", "missing-protocol", "success"]) { + sockets.length = 0 + const observer = new Subject() + let failure: Error | undefined + observer.subscribe({ + error: (error) => { + failure = error + }, + }) + const client = new NotificationClient( + observer as never, + bearer + ? { oidcClient: { getToken: async () => ({ accessToken: "synthetic-token" }) } } + : { apiKey: "synthetic-key", apiKeyId: "synthetic-id" }, + { tenant: "synthetic", dataCore: "synthetic" }, + { allowQueryFallback: false, reconnectInterval: 1, logger }, + ) + await client.connect() + const socket = sockets[0] + assert.equal(new URL(socket.url).search, "") + assert.equal(socket.protocols[0], bearer ? "flowcore-bearer" : "flowcore-api-key") + if (outcome === "error") socket.onerror?.(new Event("error")) + if (outcome === "close") socket.onclose?.({ code: 1006, reason: "synthetic" }) + if (outcome === "missing-protocol") socket.onopen?.() + if (outcome === "success") { + socket.protocol = socket.protocols[0] + socket.onopen?.() + } else socket.onclose?.({ code: 1006, reason: "synthetic" }) + await Bun.sleep(10) + assert.equal(sockets.length, 1) + assert.equal(socket.sent.length, outcome === "success" ? 1 : 0) + assert.equal(failure?.message, outcome === "success" ? undefined : "Notification WebSocket handshake failed") + assert.equal(client.isConnecting, false) + client.disconnect() + } +} +sockets.length = 0 +const legacy = new NotificationClient( + new Subject(), + { apiKey: "synthetic-key", apiKeyId: "synthetic-id" }, + { tenant: "synthetic", dataCore: "synthetic" }, + { logger }, +) +await legacy.connect() +sockets[0].onerror?.(new Event("error")) +sockets[0].onclose?.({ code: 1006, reason: "" }) +await Bun.sleep(10) +assert.equal(sockets.length, 2) +assert.equal(new URL(sockets[1].url).searchParams.get("api_key"), "synthetic-key") +legacy.disconnect() +console.log("strict notification transport passed") diff --git a/test/tests/common/notification-strict.test.ts b/test/tests/common/notification-strict.test.ts new file mode 100644 index 0000000..042a06f --- /dev/null +++ b/test/tests/common/notification-strict.test.ts @@ -0,0 +1,16 @@ +import { expect, test } from "bun:test" + +test("strict notification transport rejects failed handshakes without URL fallback", async () => { + const child = Bun.spawn([process.execPath, "test/fixtures/notification-strict.ts"], { + cwd: `${import.meta.dir}/../../..`, + stdout: "pipe", + stderr: "pipe", + }) + const [code, stdout, stderr] = await Promise.all([ + child.exited, + new Response(child.stdout).text(), + new Response(child.stderr).text(), + ]) + expect({ code, stderr }).toEqual({ code: 0, stderr: "" }) + expect(stdout).toContain("strict notification transport passed") +}) From 0df057f3b9ee8df79783cc4d053c0e8f64ef8dfa Mon Sep 17 00:00:00 2001 From: Brian Bischoff Date: Mon, 2 Nov 2026 16:25:08 +0000 Subject: [PATCH 2/3] fix: cancel notifier setup and resume reconnect attempts --- README.md | 7 + src/common/notification-client.ts | 239 +++++++++++++++------------ test/fixtures/notification-strict.ts | 75 +++++++++ 3 files changed, 216 insertions(+), 105 deletions(-) diff --git a/README.md b/README.md index 11f37a7..6446c4f 100644 --- a/README.md +++ b/README.md @@ -1102,6 +1102,13 @@ client.disconnect() - **maxEvents**: Maximum number of events to receive before auto-disconnecting (optional) - **logger**: Custom logger implementation (optional) +`disconnect()` cancels scheduled reconnects and invalidates pending authentication +or metadata setup so it cannot open a socket or send a subscription afterward. +Already-running HTTP/token requests are not aborted. A later explicit `connect()` +starts a new generation; disconnect completes the supplied observer as before. +Automatic reconnect after an accepted socket closes abnormally now releases the +connection guard before attempting the replacement handshake. + #### Subscription Specification You can narrow down your notification subscription by specifying: diff --git a/src/common/notification-client.ts b/src/common/notification-client.ts index d85b208..a54febd 100644 --- a/src/common/notification-client.ts +++ b/src/common/notification-client.ts @@ -103,6 +103,8 @@ export class NotificationClient { /** True once a handshake has settled, so the fallback is probed at most once. */ private transportSettled = false private handshakeAccepted = false + private generation = 0 + private reconnectTimer?: ReturnType /** * Creates a new NotificationClient instance @@ -153,133 +155,149 @@ export class NotificationClient { return } + const generation = ++this.generation this._isConnecting = true this.handshakeAccepted = false - - let flowcoreClient: FlowcoreClient | null = null - const urlParams = new URLSearchParams() - - let credential: NotificationCredential - if ("oidcClient" in this.authOptions) { - const oidcClient = this.authOptions.oidcClient - flowcoreClient = new FlowcoreClient({ - getBearerToken: async () => (await oidcClient.getToken()).accessToken, - }) - credential = { kind: "bearer", token: (await oidcClient.getToken()).accessToken } - } else { - flowcoreClient = new FlowcoreClient({ - apiKey: this.authOptions.apiKey, - ...(this.authOptions.apiKeyId ? { apiKeyId: this.authOptions.apiKeyId } : {}), - }) - credential = { - kind: "apiKey", - apiKey: this.authOptions.apiKey, - ...(this.authOptions.apiKeyId ? { apiKeyId: this.authOptions.apiKeyId } : {}), + try { + let flowcoreClient: FlowcoreClient | null = null + const urlParams = new URLSearchParams() + + let credential: NotificationCredential + if ("oidcClient" in this.authOptions) { + const oidcClient = this.authOptions.oidcClient + flowcoreClient = new FlowcoreClient({ + getBearerToken: async () => (await oidcClient.getToken()).accessToken, + }) + credential = { kind: "bearer", token: (await oidcClient.getToken()).accessToken } + } else { + flowcoreClient = new FlowcoreClient({ + apiKey: this.authOptions.apiKey, + ...(this.authOptions.apiKeyId ? { apiKeyId: this.authOptions.apiKeyId } : {}), + }) + credential = { + kind: "apiKey", + apiKey: this.authOptions.apiKey, + ...(this.authOptions.apiKeyId ? { apiKeyId: this.authOptions.apiKeyId } : {}), + } } - } - - const handshake = this.buildCredentialHandshake(credential) - for (const [key, value] of handshake.query) { - urlParams.set(key, value) - } - const credentialProtocols = handshake.protocols - const dataCore = await flowcoreClient.execute( - new DataCoreFetchCommand({ - tenant: this.subscriptionSpec.tenant, - dataCore: this.subscriptionSpec.dataCore, - }), - ) + if (generation !== this.generation) return + const handshake = this.buildCredentialHandshake(credential) + for (const [key, value] of handshake.query) { + urlParams.set(key, value) + } + const credentialProtocols = handshake.protocols - let flowType: FlowType | undefined - let eventType: EventType | undefined - if (this.subscriptionSpec.flowType) { - flowType = await flowcoreClient.execute( - new FlowTypeFetchCommand({ - dataCoreId: dataCore.id, - flowType: this.subscriptionSpec.flowType, + const dataCore = await flowcoreClient.execute( + new DataCoreFetchCommand({ + tenant: this.subscriptionSpec.tenant, + dataCore: this.subscriptionSpec.dataCore, }), ) - if (this.subscriptionSpec.eventType) { - eventType = await flowcoreClient.execute( - new EventTypeFetchCommand({ - flowTypeId: flowType?.id, - eventType: this.subscriptionSpec.eventType, + if (generation !== this.generation) return + let flowType: FlowType | undefined + let eventType: EventType | undefined + if (this.subscriptionSpec.flowType) { + flowType = await flowcoreClient.execute( + new FlowTypeFetchCommand({ + dataCoreId: dataCore.id, + flowType: this.subscriptionSpec.flowType, }), ) - } - } - - const query = urlParams.toString() - this.webSocket = new WebSocketConstructor( - query ? `${this.url}?${query}` : this.url, - credentialProtocols.length > 0 ? credentialProtocols : undefined, - ) as unknown as WebSocket - this.webSocket.onopen = () => { - if (this.options.allowQueryFallback === false && this.webSocket.protocol !== credentialProtocols[0]) { - this.rejectStrictHandshake() - return + if (generation !== this.generation) return + if (this.subscriptionSpec.eventType) { + eventType = await flowcoreClient.execute( + new EventTypeFetchCommand({ + flowTypeId: flowType?.id, + eventType: this.subscriptionSpec.eventType, + }), + ) + } } - this.handshakeAccepted = true - this._isOpen = true - this._isConnecting = false - // This transport works; never probe the other one again. - this.transportSettled = true - this.logger.debug("WebSocket connection opened.") - this.reconnectInterval = this.options.reconnectInterval - this.reconnectAttempts = 0 - this.webSocket.send( - JSON.stringify({ - tenant: this.subscriptionSpec.tenant, - dataCoreId: dataCore.id, - flowTypeId: flowType?.id, - eventTypeId: eventType?.id, - }), - ) - } - this.webSocket.onmessage = (event) => { - let parsedData: string - if (event.data instanceof ArrayBuffer) { - parsedData = new TextDecoder().decode(event.data) - } else if (Buffer.isBuffer(event.data)) { - parsedData = (event.data as BufferType).toString() - } else if (Array.isArray(event.data)) { - // Handle Buffer arrays by concatenating them - parsedData = Buffer.concat(event.data as Uint8Array[]).toString() - } else { - parsedData = event.data as string + if (generation !== this.generation) return + const query = urlParams.toString() + this.webSocket = new WebSocketConstructor( + query ? `${this.url}?${query}` : this.url, + credentialProtocols.length > 0 ? credentialProtocols : undefined, + ) as unknown as WebSocket + + this.webSocket.onopen = () => { + if (generation !== this.generation) return + if (this.options.allowQueryFallback === false && this.webSocket.protocol !== credentialProtocols[0]) { + this.rejectStrictHandshake() + return + } + this.handshakeAccepted = true + this._isOpen = true + this._isConnecting = false + // This transport works; never probe the other one again. + this.transportSettled = true + this.logger.debug("WebSocket connection opened.") + this.reconnectInterval = this.options.reconnectInterval + this.reconnectAttempts = 0 + this.webSocket.send( + JSON.stringify({ + tenant: this.subscriptionSpec.tenant, + dataCoreId: dataCore.id, + flowTypeId: flowType?.id, + eventTypeId: eventType?.id, + }), + ) } - this.handleMessage(parsedData) - } + this.webSocket.onmessage = (event) => { + if (generation !== this.generation) return + let parsedData: string + if (event.data instanceof ArrayBuffer) { + parsedData = new TextDecoder().decode(event.data) + } else if (Buffer.isBuffer(event.data)) { + parsedData = (event.data as BufferType).toString() + } else if (Array.isArray(event.data)) { + // Handle Buffer arrays by concatenating them + parsedData = Buffer.concat(event.data as Uint8Array[]).toString() + } else { + parsedData = event.data as string + } - this.webSocket.onclose = (event) => { - this._isOpen = false - if (this.options.allowQueryFallback === false && !this.handshakeAccepted) { - this._isConnecting = false - this.observer.error(new Error("Notification WebSocket handshake failed")) - return + this.handleMessage(parsedData) } - this.logger.debug(`Connection closed: Code [${event.code}], Reason: ${event.reason}`) - if (this.shouldFallBackToQueryTransport()) { - this.fallBackToQueryTransport() - return + + this.webSocket.onclose = (event) => { + if (generation !== this.generation) return + this._isOpen = false + if (this.options.allowQueryFallback === false && !this.handshakeAccepted) { + this.rejectStrictHandshake() + return + } + this.logger.debug(`Connection closed: Code [${event.code}], Reason: ${event.reason}`) + if (this.shouldFallBackToQueryTransport()) { + this.fallBackToQueryTransport() + return + } + if (![1000].includes(event.code)) { + this.attemptReconnect() + return + } + this._isConnecting = false + this.observer.complete() } - if (![1000].includes(event.code)) { - this.attemptReconnect() - return + + this.webSocket.onerror = (error) => { + if (generation === this.generation) this.handleWebSocketError(error) } + } catch (error) { + if (generation !== this.generation) return this._isConnecting = false - this.observer.complete() + throw error } - - this.webSocket.onerror = (error) => this.handleWebSocketError(error) } private rejectStrictHandshake() { + ++this.generation + this._isOpen = false this._isConnecting = false this.observer.error(new Error("Notification WebSocket handshake failed")) this.webSocket.close() @@ -466,8 +484,13 @@ export class NotificationClient { this.options.maxReconnects ? `/${this.options.maxReconnects}` : "" } in ${this.reconnectInterval} ms...`, ) - setTimeout(() => { - this.connect() + const generation = this.generation + if (this.reconnectTimer) clearTimeout(this.reconnectTimer) + this.reconnectTimer = setTimeout(() => { + this.reconnectTimer = undefined + if (generation !== this.generation) return + this._isConnecting = false + void this.connect().catch(() => this.observer.error(new Error("Notification connection setup failed"))) }, this.reconnectInterval) this.reconnectInterval = Math.min(MAX_RECONNECT_INTERVAL, this.reconnectInterval * 2) @@ -477,9 +500,15 @@ export class NotificationClient { * Closes the WebSocket connection */ disconnect() { + ++this.generation + if (this.reconnectTimer) clearTimeout(this.reconnectTimer) + this.reconnectTimer = undefined + this._isConnecting = false + this._isOpen = false if (this.webSocket) { this.webSocket.close(1000, "Disconnected by user") } + this.observer.complete() } /** diff --git a/test/fixtures/notification-strict.ts b/test/fixtures/notification-strict.ts index 8cfd3e5..42ccf62 100644 --- a/test/fixtures/notification-strict.ts +++ b/test/fixtures/notification-strict.ts @@ -87,4 +87,79 @@ await Bun.sleep(10) assert.equal(sockets.length, 2) assert.equal(new URL(sockets[1].url).searchParams.get("api_key"), "synthetic-key") legacy.disconnect() +// Reconnect must create a replacement socket and revalidate its negotiated scheme. +for (const accepted of [true, false]) { + sockets.length = 0 + const observer = new Subject() + let failure: Error | undefined + observer.subscribe({ + error: (error) => { + failure = error + }, + }) + const client = new NotificationClient( + observer as never, + { apiKey: "synthetic-key", apiKeyId: "synthetic-id" }, + { tenant: "synthetic", dataCore: "synthetic" }, + { allowQueryFallback: false, reconnectInterval: 1, logger }, + ) + await client.connect() + sockets[0].protocol = "flowcore-api-key" + sockets[0].onopen?.() + sockets[0].onclose?.({ code: 1006, reason: "" }) + for (let i = 0; i < 100 && sockets.length < 2; i++) await Bun.sleep(1) + assert.equal(sockets.length, 2) + assert.equal(new URL(sockets[1].url).search, "") + sockets[1].protocol = accepted ? "flowcore-api-key" : "" + sockets[1].onopen?.() + assert.equal(sockets[1].sent.length, accepted ? 1 : 0) + assert.equal(Boolean(failure), !accepted) + client.disconnect() +} +// Disconnect cancels deferred metadata setup and any later socket callbacks. +const originalFetch = globalThis.fetch +for (const stage of ["metadata", "socket", "backoff"]) { + sockets.length = 0 + let release!: () => void + let entered!: () => void + const started = new Promise((resolve) => { + entered = resolve + }) + const gate = new Promise((resolve) => { + release = resolve + }) + globalThis.fetch = (async (...args: Parameters) => { + entered() + if (stage === "metadata") await gate + return originalFetch(...args) + }) as unknown as typeof fetch + const observer = new Subject() + const client = new NotificationClient( + observer as never, + { apiKey: "synthetic-key", apiKeyId: "synthetic-id" }, + { tenant: "synthetic", dataCore: "synthetic" }, + { allowQueryFallback: false, reconnectInterval: 5, logger }, + ) + const connecting = client.connect() + await started + if (stage !== "metadata") await connecting + if (stage === "backoff") { + sockets[0].protocol = "flowcore-api-key" + sockets[0].onopen?.() + sockets[0].onclose?.({ code: 1006, reason: "" }) + } + client.disconnect() + release() + await connecting + if (stage === "socket") { + sockets[0].protocol = "flowcore-api-key" + sockets[0].onopen?.() + } + await Bun.sleep(20) + assert.equal(sockets.length, stage === "metadata" ? 0 : 1) + assert.equal(sockets[0]?.sent.length ?? 0, stage === "backoff" ? 1 : 0) + assert.equal(client.isOpen, false) + assert.equal(client.isConnecting, false) + globalThis.fetch = originalFetch +} console.log("strict notification transport passed") From 4007cd6cd08a84a61df7eaf8a2d6e8add4ec88b9 Mon Sep 17 00:00:00 2001 From: Brian Bischoff Date: Mon, 2 Nov 2026 16:30:22 +0000 Subject: [PATCH 3/3] fix: stop reconnect after terminal notification errors --- README.md | 4 +++- src/common/notification-client.ts | 6 ++++++ test/fixtures/notification-strict.ts | 31 ++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6446c4f..bc2c0b1 100644 --- a/README.md +++ b/README.md @@ -1107,7 +1107,9 @@ or metadata setup so it cannot open a socket or send a subscription afterward. Already-running HTTP/token requests are not aborted. A later explicit `connect()` starts a new generation; disconnect completes the supplied observer as before. Automatic reconnect after an accepted socket closes abnormally now releases the -connection guard before attempting the replacement handshake. +connection guard before attempting the replacement handshake. Socket errors remain +terminal observer errors; their subsequent close events cannot reconnect into a +stopped observer. Close-only abnormal disconnects remain reconnectable. #### Subscription Specification diff --git a/src/common/notification-client.ts b/src/common/notification-client.ts index a54febd..582434c 100644 --- a/src/common/notification-client.ts +++ b/src/common/notification-client.ts @@ -318,6 +318,12 @@ export class NotificationClient { } // ErrorEvent stringification can include the request URL and its query. this.logger.error("WebSocket encountered an error.") + // Error terminates the Subject; invalidate this socket before close can retry. + ++this.generation + if (this.reconnectTimer) clearTimeout(this.reconnectTimer) + this.reconnectTimer = undefined + this._isOpen = false + this._isConnecting = false this.observer.error(error) this.webSocket.close() } diff --git a/test/fixtures/notification-strict.ts b/test/fixtures/notification-strict.ts index 42ccf62..9f73582 100644 --- a/test/fixtures/notification-strict.ts +++ b/test/fixtures/notification-strict.ts @@ -162,4 +162,35 @@ for (const stage of ["metadata", "socket", "backoff"]) { assert.equal(client.isConnecting, false) globalThis.fetch = originalFetch } +// A terminal socket error must not reconnect into an already-stopped Subject. +for (const allowQueryFallback of [false, true]) { + sockets.length = 0 + const observer = new Subject() + let errors = 0 + observer.subscribe({ + error: () => { + errors++ + }, + }) + const client = new NotificationClient( + observer as never, + { apiKey: "synthetic-key", apiKeyId: "synthetic-id" }, + { tenant: "synthetic", dataCore: "synthetic" }, + { allowQueryFallback, reconnectInterval: 1, logger }, + ) + await client.connect() + const socket = sockets[0] + socket.protocol = "flowcore-api-key" + socket.onopen?.() + socket.onerror?.(new Event("error")) + socket.onclose?.({ code: 1006, reason: "" }) + await Bun.sleep(20) + assert.equal(errors, 1) + assert.equal(observer.isStopped, true) + assert.equal(sockets.length, 1) + assert.equal(socket.sent.length, 1) + assert.equal(client.isOpen, false) + assert.equal(client.isConnecting, false) + client.disconnect() +} console.log("strict notification transport passed")