mirror of
https://github.com/Tencent/BrowserSkill.git
synced 2026-09-10 13:01:23 +08:00
fix(extension): harden websocket reconnect lifecycle (#82)
Co-authored-by: NianJiuZst <3235467914@qq.com>
This commit is contained in:
1 parent
1371c92721
commit
f98c0606a1
6 files changed
+233
-24
No files matched your search
@@ -198,6 +198,25 @@ describe("performHandshake", () => {
|
||||
result: { server: "browser-skill-daemon", protocol_version: "1.0" },
|
||||
});
|
||||
});
|
||||
|
||||
it("stops waiting immediately when the connection generation is aborted", async () => {
|
||||
const { transport } = deferredFakeTransport();
|
||||
const controller = new AbortController();
|
||||
const pending = performHandshake(
|
||||
transport,
|
||||
{
|
||||
instanceId: "x",
|
||||
browser: { name: "chrome", version: "131" },
|
||||
label: "",
|
||||
rpcId: "hs-abort",
|
||||
},
|
||||
{ signal: controller.signal, timeoutMs: 60_000 },
|
||||
);
|
||||
|
||||
controller.abort();
|
||||
|
||||
await expect(pending).rejects.toMatchObject({ name: "AbortError" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectBrowserMeta", () => {
|
||||
|
||||
@@ -49,6 +49,10 @@ class FakeSocket {
|
||||
this.emit("close", { code, reason: "server-gone" });
|
||||
}
|
||||
|
||||
emitClose(code = 1006): void {
|
||||
this.emit("close", { code, reason: "delayed-close" });
|
||||
}
|
||||
|
||||
private emit(type: string, ev: unknown): void {
|
||||
for (const l of this.listeners[type] ?? []) {
|
||||
// biome-ignore lint/suspicious/noExplicitAny: minimal fake mirrors WebSocket Event shape
|
||||
@@ -202,6 +206,34 @@ describe("WSTransport", () => {
|
||||
expect(FakeSocket.instances.length).toBe(beforeCount + 1);
|
||||
});
|
||||
|
||||
it("cancels pending backoff and ignores delayed events from a replaced socket", async () => {
|
||||
const t = new WSTransport({
|
||||
url: "ws://127.0.0.1:52800",
|
||||
webSocketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||
});
|
||||
const initial = t.connect();
|
||||
const first = lastSocket();
|
||||
first.open();
|
||||
await initial;
|
||||
|
||||
first.serverClose();
|
||||
const reconnect = t.connect();
|
||||
expect(FakeSocket.instances).toHaveLength(2);
|
||||
const second = lastSocket();
|
||||
second.open();
|
||||
await reconnect;
|
||||
|
||||
// A real browser can deliver the old close callback after the replacement
|
||||
// socket is already open. It must not clear or disconnect the new socket.
|
||||
first.emitClose();
|
||||
t.send({ id: "current", method: "system.ping" });
|
||||
expect(second.sent).toEqual([JSON.stringify({ id: "current", method: "system.ping" })]);
|
||||
expect(t.state).toBe("connected");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
expect(FakeSocket.instances).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("ignores malformed inbound messages (non-JSON) without throwing", async () => {
|
||||
const handler = vi.fn();
|
||||
const t = new WSTransport({
|
||||
|
||||
@@ -57,7 +57,7 @@ function ridToString(): string {
|
||||
export function performHandshake(
|
||||
transport: Transport,
|
||||
input: HandshakeInput,
|
||||
options: { timeoutMs?: number } = {},
|
||||
options: { timeoutMs?: number; signal?: AbortSignal } = {},
|
||||
): Promise<HandshakeOutcome> {
|
||||
const id = input.rpcId ?? ridToString();
|
||||
const params: HandshakeParams = {
|
||||
@@ -75,6 +75,12 @@ export function performHandshake(
|
||||
const timeoutMs = options.timeoutMs ?? 10_000;
|
||||
|
||||
return new Promise<HandshakeOutcome>((resolve, reject) => {
|
||||
const onAbort = () => {
|
||||
cleanup();
|
||||
const err = new Error("[handshake] aborted because the connection changed");
|
||||
err.name = "AbortError";
|
||||
reject(err);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error("[handshake] timed out waiting for daemon response"));
|
||||
@@ -97,8 +103,15 @@ export function performHandshake(
|
||||
function cleanup() {
|
||||
clearTimeout(timer);
|
||||
sub.dispose();
|
||||
options.signal?.removeEventListener("abort", onAbort);
|
||||
}
|
||||
|
||||
if (options.signal?.aborted) {
|
||||
onAbort();
|
||||
return;
|
||||
}
|
||||
options.signal?.addEventListener("abort", onAbort, { once: true });
|
||||
|
||||
try {
|
||||
transport.send(req);
|
||||
} catch (err) {
|
||||
|
||||
@@ -50,6 +50,7 @@ export class WSTransport implements Transport {
|
||||
private explicitlyClosed = false;
|
||||
private reconnectAttempt = 0;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private socketGeneration = 0;
|
||||
private connectingPromise: Promise<void> | null = null;
|
||||
private resolveConnect: ((value: void) => void) | null = null;
|
||||
private rejectConnect: ((reason: Error) => void) | null = null;
|
||||
@@ -69,16 +70,26 @@ export class WSTransport implements Transport {
|
||||
}
|
||||
|
||||
connect(): Promise<void> {
|
||||
if (this.connectingPromise) return this.connectingPromise;
|
||||
if (this.currentState === "connected") return Promise.resolve();
|
||||
|
||||
this.explicitlyClosed = false;
|
||||
this.openSocket();
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
|
||||
if (this.connectingPromise) {
|
||||
// A previous physical attempt closed before reaching OPEN. Keep the
|
||||
// original caller's promise, but start the next socket generation.
|
||||
if (!this.socket) this.openSocket();
|
||||
return this.connectingPromise;
|
||||
}
|
||||
|
||||
this.connectingPromise = new Promise<void>((resolve, reject) => {
|
||||
this.resolveConnect = resolve;
|
||||
this.rejectConnect = reject;
|
||||
});
|
||||
this.openSocket();
|
||||
return this.connectingPromise;
|
||||
}
|
||||
|
||||
@@ -88,9 +99,12 @@ export class WSTransport implements Transport {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
if (this.socket) {
|
||||
const socket = this.socket;
|
||||
this.socket = null;
|
||||
this.socketGeneration += 1;
|
||||
if (socket) {
|
||||
try {
|
||||
this.socket.close();
|
||||
socket.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
@@ -135,10 +149,12 @@ export class WSTransport implements Transport {
|
||||
|
||||
private openSocket(): void {
|
||||
this.setState("connecting");
|
||||
const generation = ++this.socketGeneration;
|
||||
const socket = this.factory(this.url);
|
||||
this.socket = socket;
|
||||
|
||||
socket.addEventListener("open", () => {
|
||||
if (!this.isCurrentSocket(socket, generation)) return;
|
||||
this.reconnectAttempt = 0;
|
||||
this.setState("connected");
|
||||
const resolve = this.resolveConnect;
|
||||
@@ -149,11 +165,12 @@ export class WSTransport implements Transport {
|
||||
});
|
||||
|
||||
socket.addEventListener("message", (ev: MessageEvent) => {
|
||||
if (!this.isCurrentSocket(socket, generation)) return;
|
||||
this.handleInbound((ev as unknown as MessageLikeEvent).data);
|
||||
});
|
||||
|
||||
socket.addEventListener("close", (ev: Event) => {
|
||||
this.handleClose(ev as unknown as CloseLikeEvent);
|
||||
this.handleClose(socket, generation, ev as unknown as CloseLikeEvent);
|
||||
});
|
||||
|
||||
socket.addEventListener("error", () => {
|
||||
@@ -179,7 +196,8 @@ export class WSTransport implements Transport {
|
||||
}
|
||||
}
|
||||
|
||||
private handleClose(_ev: CloseLikeEvent): void {
|
||||
private handleClose(socket: WebSocket, generation: number, _ev: CloseLikeEvent): void {
|
||||
if (!this.isCurrentSocket(socket, generation)) return;
|
||||
this.socket = null;
|
||||
if (this.explicitlyClosed) {
|
||||
this.setState("disconnected");
|
||||
@@ -196,10 +214,16 @@ export class WSTransport implements Transport {
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
if (this.explicitlyClosed) return;
|
||||
this.openSocket();
|
||||
void this.connect().catch((err) => {
|
||||
console.debug("[WSTransport] reconnect attempt failed", err);
|
||||
});
|
||||
}, delay);
|
||||
}
|
||||
|
||||
private isCurrentSocket(socket: WebSocket, generation: number): boolean {
|
||||
return this.socket === socket && this.socketGeneration === generation;
|
||||
}
|
||||
|
||||
private setState(next: ConnectionState): void {
|
||||
if (this.currentState === next) return;
|
||||
this.currentState = next;
|
||||
|
||||
Reference in new issue
Block a user