Skip to content

Commit b611914

Browse files
authored
fix(gateway): isolate SDK event streams and preserve reconnect ownership (#116904)
* fix(gateway): isolate SDK event streams and fence reconnect ownership * test(gateway): normalize live WebSocket message payloads
1 parent 72adefb commit b611914

10 files changed

Lines changed: 421 additions & 43 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1631,7 +1631,7 @@ packages/normalization-core/src/stable-stringify.ts 1
16311631
packages/normalization-core/src/string-coerce.ts 1
16321632
packages/retry/src/index.ts 6
16331633
packages/sdk/src/client.ts 1
1634-
packages/sdk/src/event-hub.ts 4
1634+
packages/sdk/src/event-hub.ts 2
16351635
packages/sdk/src/transport.ts 3
16361636
packages/session-url-contract/src/parse.ts 1
16371637
packages/terminal-core/src/note.ts 1

‎packages/gateway-client/src/client.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,8 @@ export class GatewayClient {
431431
},
432432
notifyStoppedClose: true,
433433
onConnectError: (error) => this.notifyConnectError(error),
434+
onReconnectStopped: (error) =>
435+
this.notifyReconnectPaused({ code: 1008, reason: error.message, detailCode: null }),
434436
onParseError: (error) =>
435437
this.logDebug(`gateway client parse error: ${formatGatewayClientErrorForLog(error)}`),
436438
onEvent: (event) => this.opts.onEvent?.(event),

‎packages/gateway-client/src/protocol-client-contract.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ export type GatewayProtocolClientOptions<TPlan> = {
8484
notifyStoppedClose?: boolean;
8585
onConnectError?: (error: Error) => void;
8686
onSocketFactoryError?: (error: Error) => void;
87+
onReconnectStopped?: (error: Error) => void;
8788
onParseError?: (error: unknown) => void;
8889
onEvent?: (event: EventFrame) => void;
8990
onGap?: (info: { expected: number; received: number }) => void;

‎packages/gateway-client/src/protocol-client.socket-factory.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,69 @@ describe("GatewayProtocolClient socket factory recovery", () => {
248248
expect(vi.getTimerCount()).toBe(0);
249249
client.stop();
250250
});
251+
252+
it.each([true, false])(
253+
"contains a terminal asynchronous reconnect failure (rethrow: %s)",
254+
async (rethrow) => {
255+
vi.useFakeTimers();
256+
let socketAttempts = 0;
257+
let disconnect: ((code: number, reason: string) => void) | undefined;
258+
const onConnectError = vi.fn<(error: Error) => void>();
259+
const onCallbackError = vi.fn<(label: string, error: unknown) => void>();
260+
const onReconnectStopped = vi.fn<(error: Error) => void>();
261+
const client = new GatewayProtocolClient<Record<string, never>>({
262+
createSocket: (handlers) => {
263+
socketAttempts += 1;
264+
if (socketAttempts > 1) {
265+
throw new Error("loopback proxy policy rejected");
266+
}
267+
let open = true;
268+
disconnect = (code, reason) => {
269+
open = false;
270+
handlers.close(code, reason);
271+
};
272+
return {
273+
isOpen: () => open,
274+
send: vi.fn(),
275+
close: (code, reason) => disconnect?.(code ?? 1000, reason ?? ""),
276+
};
277+
},
278+
createRequestId: () => "request-1",
279+
buildConnectPlan: () => ({}),
280+
buildConnectParams: (plan) => plan,
281+
resolveClose: () => ({ retry: true, notify: true }),
282+
onConnectError,
283+
onCallbackError,
284+
onReconnectStopped,
285+
shouldRetrySocketFactoryError: () => rethrow,
286+
rethrowSocketFactoryError: () => rethrow,
287+
handshake: { mode: "require-challenge", timeoutMs: 100 },
288+
reconnect: { initialMs: 10, multiplier: 2, maxMs: 100 },
289+
});
290+
client.start();
291+
disconnect?.(1012, "service restart");
292+
293+
await vi.advanceTimersByTimeAsync(10);
294+
295+
expect(socketAttempts).toBe(2);
296+
expect(onConnectError).toHaveBeenCalledExactlyOnceWith(
297+
expect.objectContaining({ message: "loopback proxy policy rejected" }),
298+
);
299+
if (rethrow) {
300+
expect(onCallbackError).toHaveBeenCalledExactlyOnceWith(
301+
"reconnect",
302+
expect.objectContaining({ message: "loopback proxy policy rejected" }),
303+
);
304+
} else {
305+
expect(onCallbackError).not.toHaveBeenCalled();
306+
}
307+
expect(onReconnectStopped).toHaveBeenCalledExactlyOnceWith(
308+
expect.objectContaining({ message: "loopback proxy policy rejected" }),
309+
);
310+
expect(vi.getTimerCount()).toBe(0);
311+
client.stop();
312+
},
313+
);
251314
});
252315

253316
describe("GatewayClient socket factory recovery", () => {

‎packages/gateway-client/src/protocol-client.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,9 @@ export class GatewayProtocolClient<TPlan> {
205205
this.opts.onSocketFactoryError?.(normalized);
206206
this.opts.onConnectError?.(normalized);
207207
if (this.opts.rethrowSocketFactoryError?.(normalized)) {
208+
if (this.generation > 0 && !this.stopped && !this.socket && !this.reconnectSignal) {
209+
this.opts.onReconnectStopped?.(normalized);
210+
}
208211
throw normalized;
209212
}
210213
// Callbacks can stop or restart synchronously; never schedule over their replacement socket.
@@ -215,6 +218,8 @@ export class GatewayProtocolClient<TPlan> {
215218
!this.reconnectSignal
216219
) {
217220
this.scheduleReconnect();
221+
} else if (this.generation > 0 && !this.stopped && !this.socket && !this.reconnectSignal) {
222+
this.opts.onReconnectStopped?.(normalized);
218223
}
219224
return;
220225
}
@@ -499,7 +504,8 @@ export class GatewayProtocolClient<TPlan> {
499504
return;
500505
}
501506
this.reconnectSignal = null;
502-
this.connect();
507+
// Explicit start retains synchronous policy errors; background retries cannot reject orphaned.
508+
this.invoke("reconnect", () => this.connect());
503509
},
504510
() => {
505511
if (this.reconnectSignal === retry.signal) {

‎packages/sdk/src/event-hub.test.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { describe, expect, it } from "vitest";
2+
import { EventHub } from "./event-hub.js";
3+
4+
describe("EventHub subscriber ownership", () => {
5+
it("isolates a failing filter from healthy event streams", async () => {
6+
const hub = new EventHub<string>();
7+
const failedStream = hub.stream(() => {
8+
throw new Error("subscriber filter failed");
9+
});
10+
const failed = failedStream[Symbol.asyncIterator]();
11+
const healthy = hub.stream()[Symbol.asyncIterator]();
12+
const failedRead = failed.next();
13+
const healthyRead = healthy.next();
14+
15+
expect(() => hub.publish("first")).not.toThrow();
16+
await expect(failedRead).rejects.toThrow("subscriber filter failed");
17+
await expect(healthyRead).resolves.toEqual({ done: false, value: "first" });
18+
19+
const nextHealthyRead = healthy.next();
20+
hub.publish("second");
21+
await expect(nextHealthyRead).resolves.toEqual({ done: false, value: "second" });
22+
});
23+
24+
it("settles concurrent reads in event order", async () => {
25+
const hub = new EventHub<string>();
26+
const iterator = hub.stream()[Symbol.asyncIterator]();
27+
const first = iterator.next();
28+
const second = iterator.next();
29+
30+
hub.publish("first");
31+
hub.publish("second");
32+
33+
await expect(Promise.all([first, second])).resolves.toEqual([
34+
{ done: false, value: "first" },
35+
{ done: false, value: "second" },
36+
]);
37+
});
38+
39+
it("reserves a published event for the reader it wakes", async () => {
40+
const hub = new EventHub<string>();
41+
const iterator = hub.stream()[Symbol.asyncIterator]();
42+
const first = iterator.next();
43+
44+
hub.publish("first");
45+
const second = iterator.next();
46+
hub.publish("second");
47+
48+
await expect(Promise.all([first, second])).resolves.toEqual([
49+
{ done: false, value: "first" },
50+
{ done: false, value: "second" },
51+
]);
52+
});
53+
54+
it("settles every pending read when its iterator closes", async () => {
55+
const hub = new EventHub<string>();
56+
const iterator = hub.stream()[Symbol.asyncIterator]();
57+
const first = iterator.next();
58+
const second = iterator.next();
59+
60+
await expect(iterator.return?.()).resolves.toEqual({ done: true, value: undefined });
61+
await expect(Promise.all([first, second])).resolves.toEqual([
62+
{ done: true, value: undefined },
63+
{ done: true, value: undefined },
64+
]);
65+
});
66+
67+
it("rejects every pending read when the hub closes with an error", async () => {
68+
const hub = new EventHub<string>();
69+
const iterator = hub.stream()[Symbol.asyncIterator]();
70+
const first = iterator.next();
71+
const second = iterator.next();
72+
73+
hub.close(new Error("gateway event stream closed"));
74+
75+
await expect(first).rejects.toThrow("gateway event stream closed");
76+
await expect(second).rejects.toThrow("gateway event stream closed");
77+
});
78+
79+
it("does not yield buffered events after its iterator closes", async () => {
80+
const hub = new EventHub<string>();
81+
const iterator = hub.stream()[Symbol.asyncIterator]();
82+
hub.publish("stale");
83+
84+
await iterator.return?.();
85+
86+
await expect(iterator.next()).resolves.toEqual({ done: true, value: undefined });
87+
});
88+
});

‎packages/sdk/src/event-hub.ts‎

Lines changed: 59 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -68,20 +68,24 @@ export class EventHub<T> {
6868
[Symbol.asyncIterator]: (): AsyncIterator<T> => {
6969
const queue: T[] = options.replay ? this.snapshot(filter) : [];
7070
let stopped = false;
71-
let wake: (() => void) | null = null;
72-
const wakePending = () => {
73-
const pending = wake;
74-
if (!pending) {
75-
return;
76-
}
77-
wake = null;
78-
this.waiters.delete(pending);
79-
pending();
71+
let streamError: unknown;
72+
let hasStreamError = false;
73+
type PendingRead = {
74+
resolve: (result: IteratorResult<T>) => void;
75+
reject: (error: unknown) => void;
76+
wake: () => void;
8077
};
81-
const listener = (event: T) => {
82-
if (!filter || filter(event)) {
83-
queue.push(event);
84-
wakePending();
78+
const pendingReads: PendingRead[] = [];
79+
const finishPendingReads = () => {
80+
for (const pending of pendingReads.splice(0)) {
81+
this.waiters.delete(pending.wake);
82+
if (hasStreamError) {
83+
pending.reject(streamError);
84+
} else if (this.hasCloseError) {
85+
pending.reject(this.closeError);
86+
} else {
87+
pending.resolve({ done: true, value: undefined });
88+
}
8589
}
8690
};
8791
const cleanup = () => {
@@ -90,44 +94,66 @@ export class EventHub<T> {
9094
}
9195
stopped = true;
9296
this.listeners.delete(listener);
93-
wakePending();
97+
finishPendingReads();
98+
};
99+
const listener = (event: T) => {
100+
let matches: boolean;
101+
try {
102+
matches = !filter || filter(event);
103+
} catch (error) {
104+
streamError = error;
105+
hasStreamError = true;
106+
cleanup();
107+
return;
108+
}
109+
if (!matches) {
110+
return;
111+
}
112+
const pending = pendingReads.shift();
113+
if (pending) {
114+
this.waiters.delete(pending.wake);
115+
pending.resolve({ done: false, value: event });
116+
return;
117+
}
118+
queue.push(event);
94119
};
95120

96121
this.listeners.add(listener);
97122

98123
return {
99124
next: async (): Promise<IteratorResult<T>> => {
100-
while (true) {
101-
if (stopped) {
102-
break;
103-
}
104-
if (queue.length > 0) {
105-
return { done: false, value: queue.shift() as T };
125+
if (stopped) {
126+
if (hasStreamError) {
127+
throw streamError;
106128
}
107-
if (this.closed) {
108-
break;
129+
if (this.hasCloseError) {
130+
throw this.closeError;
109131
}
110-
await new Promise<void>((resolve) => {
111-
const wakeCurrent = () => {
112-
if (wake === wakeCurrent) {
113-
wake = null;
114-
}
115-
this.waiters.delete(wakeCurrent);
116-
resolve();
132+
return { done: true, value: undefined };
133+
}
134+
if (queue.length > 0) {
135+
return { done: false, value: queue.shift() as T };
136+
}
137+
if (!this.closed) {
138+
return await new Promise<IteratorResult<T>>((resolve, reject) => {
139+
const pending: PendingRead = {
140+
resolve,
141+
reject,
142+
wake: () => cleanup(),
117143
};
118-
wake = wakeCurrent;
119-
this.waiters.add(wakeCurrent);
144+
pendingReads.push(pending);
145+
this.waiters.add(pending.wake);
120146
});
121147
}
122148
cleanup();
123149
if (this.hasCloseError) {
124150
throw this.closeError;
125151
}
126-
return { done: true, value: undefined as never };
152+
return { done: true, value: undefined };
127153
},
128154
return: async (): Promise<IteratorResult<T>> => {
129155
cleanup();
130-
return { done: true, value: undefined as never };
156+
return { done: true, value: undefined };
131157
},
132158
};
133159
},

0 commit comments

Comments
 (0)