|
| 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 | +}); |
0 commit comments