Skip to content

Commit 40cf85e

Browse files
steipetewahaha1223
andauthored
fix(tlon): cancel reconnect timers when monitoring stops
Cancel both Tlon SSE reconnect waits at stopReceiving(), the monitor-owned shutdown boundary, while preserving guarded HTTP, durable same-channel replay, and the original contributor's fix. Verified with authenticated loopback SSE, both real retry delays, normal reconnection, all 252 Tlon tests, extension type checks, lint, and focused owner regressions. Co-authored-by: wahaha1223 <[email protected]>
1 parent 39b9d11 commit 40cf85e

3 files changed

Lines changed: 298 additions & 8 deletions

File tree

Lines changed: 234 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,234 @@
1+
import { createServer, type Server, type ServerResponse } from "node:http";
2+
import type { AddressInfo } from "node:net";
3+
import type { LookupFn } from "openclaw/plugin-sdk/ssrf-runtime";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { UrbitSSEClient } from "./sse-client.js";
6+
7+
const proofCookie = "urbauth-~zod=synthetic-reconnect-proof";
8+
const lookupLoopback = (async () => [{ address: "127.0.0.1", family: 4 }]) as unknown as LookupFn;
9+
const runningServers: Server[] = [];
10+
11+
type UrbitChannelProof = {
12+
baseUrl: string;
13+
requests: string[];
14+
unauthorizedRequests: number;
15+
};
16+
17+
async function startUrbitChannelServer(options: { holdStream?: boolean } = {}) {
18+
const proof: UrbitChannelProof = {
19+
baseUrl: "",
20+
requests: [],
21+
unauthorizedRequests: 0,
22+
};
23+
const heldStreams = new Set<ServerResponse>();
24+
const server = createServer((request, response) => {
25+
if (!(request.headers.cookie ?? "").includes(proofCookie)) {
26+
proof.unauthorizedRequests += 1;
27+
response.writeHead(401).end();
28+
return;
29+
}
30+
proof.requests.push(`${request.method ?? "GET"} ${request.url ?? "/"}`);
31+
if (request.method === "GET") {
32+
response.writeHead(200, {
33+
"Cache-Control": "no-cache",
34+
"Content-Type": "text/event-stream",
35+
});
36+
if (options.holdStream) {
37+
heldStreams.add(response);
38+
response.once("close", () => heldStreams.delete(response));
39+
response.write(": connected\n\n");
40+
} else {
41+
response.end();
42+
}
43+
return;
44+
}
45+
response.writeHead(204).end();
46+
});
47+
await new Promise<void>((resolve, reject) => {
48+
server.once("error", reject);
49+
server.listen(0, "127.0.0.1", resolve);
50+
});
51+
runningServers.push(server);
52+
const address = server.address() as AddressInfo;
53+
proof.baseUrl = `http://127.0.0.1:${address.port}`;
54+
return proof;
55+
}
56+
57+
async function waitFor(predicate: () => boolean, timeoutMs = 2_000): Promise<void> {
58+
const deadline = Date.now() + timeoutMs;
59+
while (!predicate()) {
60+
if (Date.now() >= deadline) {
61+
throw new Error("Timed out waiting for the real Tlon SSE reconnect lifecycle");
62+
}
63+
await new Promise<void>((resolve) => {
64+
setTimeout(resolve, 5);
65+
});
66+
}
67+
}
68+
69+
async function expectPromptReconnectSettlement(reconnect: Promise<void>) {
70+
let deadline: ReturnType<typeof setTimeout> | undefined;
71+
try {
72+
const outcome = await Promise.race([
73+
reconnect.then(() => "settled" as const),
74+
new Promise<"timed out">((resolve) => {
75+
deadline = setTimeout(() => resolve("timed out"), 250);
76+
}),
77+
]);
78+
expect(outcome).toBe("settled");
79+
} finally {
80+
if (deadline !== undefined) {
81+
clearTimeout(deadline);
82+
}
83+
}
84+
}
85+
86+
afterEach(async () => {
87+
vi.restoreAllMocks();
88+
await Promise.all(
89+
runningServers.splice(0).map(
90+
(server) =>
91+
new Promise<void>((resolve) => {
92+
server.close(() => resolve());
93+
server.closeAllConnections();
94+
}),
95+
),
96+
);
97+
});
98+
99+
describe("UrbitSSEClient real reconnect shutdown lifecycle", () => {
100+
it("settles a real SSE reconnect when the monitor stops receiving", async () => {
101+
const proof = await startUrbitChannelServer();
102+
const logs: string[] = [];
103+
const onReconnect = vi.fn();
104+
const client = new UrbitSSEClient(proof.baseUrl, proofCookie, {
105+
ship: "zod",
106+
ssrfPolicy: { allowPrivateNetwork: true },
107+
lookupFn: lookupLoopback,
108+
reconnectDelay: 400,
109+
logger: { log: (message) => logs.push(message) },
110+
onReconnect,
111+
});
112+
const reconnectSpy = vi.spyOn(client, "attemptReconnect");
113+
114+
try {
115+
await client.connect();
116+
await waitFor(() => logs.some((message) => message.includes("in 400ms")));
117+
const reconnect = reconnectSpy.mock.results[0]?.value as Promise<void> | undefined;
118+
if (!reconnect) {
119+
throw new Error("The real SSE stream did not enter its reconnect backoff");
120+
}
121+
122+
const requestsBeforeStop = proof.requests.length;
123+
client.stopReceiving();
124+
await expectPromptReconnectSettlement(reconnect);
125+
126+
expect(onReconnect).not.toHaveBeenCalled();
127+
expect(proof.requests).toHaveLength(requestsBeforeStop);
128+
expect(proof.requests.some((request) => request.startsWith("GET /~/channel/"))).toBe(true);
129+
130+
const unauthorizedResponse = await fetch(`${proof.baseUrl}/unauthorized-control`);
131+
expect(unauthorizedResponse.status).toBe(401);
132+
expect(proof.unauthorizedRequests).toBe(1);
133+
} finally {
134+
await client.close();
135+
}
136+
});
137+
138+
it("settles the real ten-second retry cooldown when the monitor stops receiving", async () => {
139+
const proof = await startUrbitChannelServer({ holdStream: true });
140+
const logs: string[] = [];
141+
const onReconnect = vi.fn();
142+
const client = new UrbitSSEClient(proof.baseUrl, proofCookie, {
143+
ship: "zod",
144+
ssrfPolicy: { allowPrivateNetwork: true },
145+
lookupFn: lookupLoopback,
146+
maxReconnectAttempts: 1,
147+
reconnectDelay: 20,
148+
logger: { log: (message) => logs.push(message) },
149+
onReconnect,
150+
});
151+
152+
try {
153+
await client.connect();
154+
client.reconnectAttempts = client.maxReconnectAttempts;
155+
const reconnect = client.attemptReconnect();
156+
expect(logs.some((message) => message.includes("Waiting 10s"))).toBe(true);
157+
158+
const requestsBeforeStop = proof.requests.length;
159+
client.stopReceiving();
160+
await expectPromptReconnectSettlement(reconnect);
161+
162+
expect(onReconnect).not.toHaveBeenCalled();
163+
expect(proof.requests).toHaveLength(requestsBeforeStop);
164+
expect(logs.some((message) => message.includes("reset, resuming"))).toBe(false);
165+
} finally {
166+
await client.close();
167+
}
168+
});
169+
170+
it("settles a real pending reconnect when the public client closes", async () => {
171+
const proof = await startUrbitChannelServer();
172+
const logs: string[] = [];
173+
const onReconnect = vi.fn();
174+
const client = new UrbitSSEClient(proof.baseUrl, proofCookie, {
175+
ship: "zod",
176+
ssrfPolicy: { allowPrivateNetwork: true },
177+
lookupFn: lookupLoopback,
178+
reconnectDelay: 400,
179+
logger: { log: (message) => logs.push(message) },
180+
onReconnect,
181+
});
182+
const reconnectSpy = vi.spyOn(client, "attemptReconnect");
183+
184+
try {
185+
await client.connect();
186+
await waitFor(() => logs.some((message) => message.includes("in 400ms")));
187+
const reconnect = reconnectSpy.mock.results[0]?.value as Promise<void> | undefined;
188+
if (!reconnect) {
189+
throw new Error("The real SSE stream did not enter its reconnect backoff");
190+
}
191+
192+
await client.close();
193+
const requestsAfterClose = proof.requests.length;
194+
await expectPromptReconnectSettlement(reconnect);
195+
196+
expect(onReconnect).not.toHaveBeenCalled();
197+
expect(proof.requests).toHaveLength(requestsAfterClose);
198+
expect(proof.requests.some((request) => request.startsWith("DELETE /~/channel/"))).toBe(true);
199+
} finally {
200+
await client.close();
201+
}
202+
});
203+
204+
it("still reconnects an uninterrupted authenticated SSE stream", async () => {
205+
const proof = await startUrbitChannelServer();
206+
let reconnects = 0;
207+
const client = new UrbitSSEClient(proof.baseUrl, proofCookie, {
208+
ship: "zod",
209+
ssrfPolicy: { allowPrivateNetwork: true },
210+
lookupFn: lookupLoopback,
211+
reconnectDelay: 25,
212+
onReconnect: (reconnectingClient) => {
213+
reconnects += 1;
214+
reconnectingClient.autoReconnect = false;
215+
},
216+
});
217+
218+
try {
219+
await client.connect();
220+
await waitFor(() => reconnects === 1);
221+
await waitFor(
222+
() =>
223+
proof.requests.filter((request) => request.startsWith("GET /~/channel/")).length === 2,
224+
);
225+
expect(reconnects).toBe(1);
226+
expect(
227+
proof.requests.filter((request) => request.startsWith("GET /~/channel/")),
228+
).toHaveLength(2);
229+
expect(proof.unauthorizedRequests).toBe(0);
230+
} finally {
231+
await client.close();
232+
}
233+
});
234+
});
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { UrbitSSEClient } from "./sse-client.js";
3+
4+
afterEach(() => {
5+
vi.useRealTimers();
6+
vi.restoreAllMocks();
7+
});
8+
9+
describe("UrbitSSEClient owned reconnect timers", () => {
10+
it.each([
11+
{ name: "ordinary reconnect", exhausted: false, delayMs: 1_000 },
12+
{ name: "exhausted ten-second cooldown", exhausted: true, delayMs: 10_000 },
13+
])("clears the $name timer immediately when the monitor stops receiving", async (params) => {
14+
vi.useFakeTimers();
15+
const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
16+
const onReconnect = vi.fn();
17+
const logger = { log: vi.fn() };
18+
const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=synthetic", {
19+
maxReconnectAttempts: 1,
20+
reconnectDelay: 1_000,
21+
onReconnect,
22+
logger,
23+
});
24+
if (params.exhausted) {
25+
client.reconnectAttempts = client.maxReconnectAttempts;
26+
}
27+
28+
const reconnect = client.attemptReconnect();
29+
30+
expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), params.delayMs);
31+
expect(vi.getTimerCount()).toBe(1);
32+
client.stopReceiving();
33+
34+
await expect(reconnect).resolves.toBeUndefined();
35+
expect(vi.getTimerCount()).toBe(0);
36+
expect(onReconnect).not.toHaveBeenCalled();
37+
if (params.exhausted) {
38+
expect(logger.log).not.toHaveBeenCalledWith(
39+
expect.stringContaining("reset, resuming reconnection"),
40+
);
41+
}
42+
});
43+
});

‎extensions/tlon/src/urbit/sse-client.ts‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
33
import { Readable } from "node:stream";
44
import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
55
import { readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
6+
import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
67
import type { LookupFn, SsrFPolicy } from "openclaw/plugin-sdk/ssrf-runtime";
78
import { ensureUrbitChannelOpen, pokeUrbitChannel, scryUrbitPath } from "./channel-ops.js";
89
import { getUrbitContext, normalizeUrbitCookie } from "./context.js";
@@ -89,6 +90,9 @@ export class UrbitSSEClient {
8990
private lastHeardEventId = -1;
9091
private lastAcknowledgedEventId = -1;
9192
private readonly ackThreshold = 20;
93+
// The monitor stops ingress before it closes the channel; cancel both retry
94+
// delays at that first shutdown edge so stale work cannot outlive its owner.
95+
private readonly reconnectAbortController = new AbortController();
9296

9397
constructor(url: string, cookie: string, options: UrbitSseOptions = {}) {
9498
const ctx = getUrbitContext(url, options.ship);
@@ -472,9 +476,9 @@ export class UrbitSSEClient {
472476
);
473477
// Wait 10 seconds before resetting and trying again
474478
const extendedBackoff = 10000; // 10 seconds
475-
await new Promise((resolve) => {
476-
setTimeout(resolve, extendedBackoff);
477-
});
479+
if (!(await this.waitForReconnectDelay(extendedBackoff)) || this.aborted) {
480+
return;
481+
}
478482
this.reconnectAttempts = 0; // Reset counter to continue trying
479483
this.logger.log?.("[SSE] Reconnection attempts reset, resuming reconnection...");
480484
}
@@ -489,11 +493,7 @@ export class UrbitSSEClient {
489493
`[SSE] Reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms...`,
490494
);
491495

492-
await new Promise((resolve) => {
493-
setTimeout(resolve, delay);
494-
});
495-
496-
if (this.aborted || !this.autoReconnect) {
496+
if (!(await this.waitForReconnectDelay(delay)) || this.aborted || !this.autoReconnect) {
497497
return;
498498
}
499499

@@ -528,6 +528,7 @@ export class UrbitSSEClient {
528528
stopReceiving(): void {
529529
this.aborted = true;
530530
this.isConnected = false;
531+
this.reconnectAbortController.abort();
531532
this.streamController?.abort();
532533
}
533534

@@ -586,6 +587,18 @@ export class UrbitSSEClient {
586587
}
587588
}
588589

590+
private async waitForReconnectDelay(delayMs: number): Promise<boolean> {
591+
try {
592+
await sleepWithAbort(delayMs, this.reconnectAbortController.signal);
593+
return true;
594+
} catch (error) {
595+
if (this.reconnectAbortController.signal.aborted) {
596+
return false;
597+
}
598+
throw error;
599+
}
600+
}
601+
589602
private async putChannelPayload(
590603
payload: unknown,
591604
params: { timeoutMs: number; auditContext: string },

0 commit comments

Comments
 (0)