Handle intentional WS closes and heartbeat freshness
- Ignore intentional close events during transport disposal - Track heartbeat freshness from pong traffic and reset on reconnect - Propagate request lifecycle hooks through the RPC client
This commit is contained in:
1 parent
3ee6fbba2c
commit
1e929ad74f
7 files changed
+388
-47
No files matched your search
@@ -242,10 +242,15 @@ describe("WsTransport (web instrumentation)", () => {
|
||||
socket.close(1012, "service restart");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onClose).toHaveBeenCalledWith({
|
||||
code: 1012,
|
||||
reason: "service restart",
|
||||
});
|
||||
expect(onClose).toHaveBeenCalledWith(
|
||||
{
|
||||
code: 1012,
|
||||
reason: "service restart",
|
||||
},
|
||||
{
|
||||
intentional: false,
|
||||
},
|
||||
);
|
||||
expect(getWsConnectionStatus()).toMatchObject({
|
||||
attemptCount: 2,
|
||||
closeReason: "service restart",
|
||||
|
||||
@@ -31,8 +31,11 @@ function createWsRpcProtocolLayer(
|
||||
clearAllTrackedRpcRequests();
|
||||
recordWsConnectionErrored(message);
|
||||
},
|
||||
onClose: (details) => {
|
||||
onClose: (details, context) => {
|
||||
clearAllTrackedRpcRequests();
|
||||
if (context.intentional) {
|
||||
return;
|
||||
}
|
||||
recordWsConnectionClosed(details);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -43,12 +43,13 @@ describe("createWsRpcClient", () => {
|
||||
reconnect: vi.fn(async () => {
|
||||
order.push("reconnect");
|
||||
}),
|
||||
isHeartbeatFresh: vi.fn(() => true),
|
||||
request: vi.fn(),
|
||||
requestStream: vi.fn(),
|
||||
subscribe: vi.fn(() => () => undefined),
|
||||
} satisfies Pick<
|
||||
WsTransport,
|
||||
"dispose" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
"dispose" | "isHeartbeatFresh" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
>;
|
||||
|
||||
const client = createWsRpcClient(transport as unknown as WsTransport, {
|
||||
@@ -61,6 +62,26 @@ describe("createWsRpcClient", () => {
|
||||
expect(order).toEqual(["beforeReconnect", "reconnect"]);
|
||||
});
|
||||
|
||||
it("delegates heartbeat freshness to the transport", () => {
|
||||
const isHeartbeatFresh = vi.fn(() => true);
|
||||
const transport = {
|
||||
dispose: vi.fn(async () => undefined),
|
||||
reconnect: vi.fn(async () => undefined),
|
||||
isHeartbeatFresh,
|
||||
request: vi.fn(),
|
||||
requestStream: vi.fn(),
|
||||
subscribe: vi.fn(() => () => undefined),
|
||||
} satisfies Pick<
|
||||
WsTransport,
|
||||
"dispose" | "isHeartbeatFresh" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
>;
|
||||
|
||||
const client = createWsRpcClient(transport as unknown as WsTransport);
|
||||
|
||||
expect(client.isHeartbeatFresh()).toBe(true);
|
||||
expect(isHeartbeatFresh).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("reduces vcs status stream events into flat status snapshots", () => {
|
||||
const subscribe = vi.fn(<TValue>(_connect: unknown, listener: (value: TValue) => void) => {
|
||||
for (const event of [
|
||||
@@ -89,12 +110,13 @@ describe("createWsRpcClient", () => {
|
||||
const transport = {
|
||||
dispose: vi.fn(async () => undefined),
|
||||
reconnect: vi.fn(async () => undefined),
|
||||
isHeartbeatFresh: vi.fn(() => true),
|
||||
request: vi.fn(),
|
||||
requestStream: vi.fn(),
|
||||
subscribe,
|
||||
} satisfies Pick<
|
||||
WsTransport,
|
||||
"dispose" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
"dispose" | "isHeartbeatFresh" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
>;
|
||||
|
||||
const client = createWsRpcClient(transport as unknown as WsTransport);
|
||||
@@ -134,12 +156,13 @@ describe("createWsRpcClient", () => {
|
||||
const transport = {
|
||||
dispose: vi.fn(async () => undefined),
|
||||
reconnect: vi.fn(async () => undefined),
|
||||
isHeartbeatFresh: vi.fn(() => true),
|
||||
request: vi.fn(),
|
||||
requestStream: vi.fn(),
|
||||
subscribe,
|
||||
} satisfies Pick<
|
||||
WsTransport,
|
||||
"dispose" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
"dispose" | "isHeartbeatFresh" | "reconnect" | "request" | "requestStream" | "subscribe"
|
||||
>;
|
||||
|
||||
const client = createWsRpcClient(transport as unknown as WsTransport);
|
||||
|
||||
@@ -125,7 +125,9 @@ export interface WsRpcClient {
|
||||
};
|
||||
readonly server: {
|
||||
readonly getConfig: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetConfig>;
|
||||
readonly refreshProviders: RpcUnaryNoArgMethod<typeof WS_METHODS.serverRefreshProviders>;
|
||||
readonly refreshProviders: (
|
||||
input?: RpcInput<typeof WS_METHODS.serverRefreshProviders>,
|
||||
) => ReturnType<RpcUnaryMethod<typeof WS_METHODS.serverRefreshProviders>>;
|
||||
readonly discoverSourceControl: RpcUnaryNoArgMethod<
|
||||
typeof WS_METHODS.serverDiscoverSourceControl
|
||||
>;
|
||||
@@ -171,7 +173,7 @@ export function createWsRpcClient(
|
||||
): WsRpcClient {
|
||||
return {
|
||||
dispose: () => transport.dispose(),
|
||||
isHeartbeatFresh: () => false,
|
||||
isHeartbeatFresh: () => transport.isHeartbeatFresh(),
|
||||
reconnect: async () => {
|
||||
options?.beforeReconnect?.();
|
||||
await transport.reconnect();
|
||||
@@ -278,8 +280,8 @@ export function createWsRpcClient(
|
||||
},
|
||||
server: {
|
||||
getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})),
|
||||
refreshProviders: () =>
|
||||
transport.request((client) => client[WS_METHODS.serverRefreshProviders]({})),
|
||||
refreshProviders: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.serverRefreshProviders](input ?? {})),
|
||||
discoverSourceControl: () =>
|
||||
transport.request((client) => client[WS_METHODS.serverDiscoverSourceControl]({})),
|
||||
updateProvider: (input) =>
|
||||
|
||||
@@ -15,10 +15,34 @@ import {
|
||||
export interface WsProtocolLifecycleHandlers {
|
||||
readonly getConnectionLabel?: () => string | null;
|
||||
readonly getVersionMismatchHint?: () => string | null;
|
||||
readonly isCloseIntentional?: () => boolean;
|
||||
readonly isActive?: () => boolean;
|
||||
readonly onAttempt?: (socketUrl: string) => void;
|
||||
readonly onOpen?: () => void;
|
||||
readonly onHeartbeatPing?: () => void;
|
||||
readonly onHeartbeatPong?: () => void;
|
||||
readonly onHeartbeatTimeout?: () => void;
|
||||
readonly onRequestStart?: (info: {
|
||||
readonly id: string;
|
||||
readonly tag: string;
|
||||
readonly stream: boolean;
|
||||
}) => void;
|
||||
readonly onRequestChunk?: (info: {
|
||||
readonly id: string;
|
||||
readonly tag: string;
|
||||
readonly chunkCount: number;
|
||||
}) => void;
|
||||
readonly onRequestExit?: (info: {
|
||||
readonly id: string;
|
||||
readonly tag: string;
|
||||
readonly stream: boolean;
|
||||
}) => void;
|
||||
readonly onRequestInterrupt?: (info: { readonly id: string; readonly tag?: string }) => void;
|
||||
readonly onError?: (message: string) => void;
|
||||
readonly onClose?: (details: { readonly code: number; readonly reason: string }) => void;
|
||||
readonly onClose?: (
|
||||
details: { readonly code: number; readonly reason: string },
|
||||
context: { readonly intentional: boolean },
|
||||
) => void;
|
||||
}
|
||||
|
||||
export interface WsRpcProtocolRequestTelemetry {
|
||||
@@ -63,48 +87,107 @@ function resolveWsRpcSocketUrl(rawUrl: string): string {
|
||||
return resolved.toString();
|
||||
}
|
||||
|
||||
function defaultLifecycleHandlers(): Required<WsProtocolLifecycleHandlers> {
|
||||
type ResolvedLifecycleHandlers = Required<
|
||||
Pick<
|
||||
WsProtocolLifecycleHandlers,
|
||||
| "getConnectionLabel"
|
||||
| "getVersionMismatchHint"
|
||||
| "isCloseIntentional"
|
||||
| "isActive"
|
||||
| "onAttempt"
|
||||
| "onOpen"
|
||||
| "onHeartbeatPing"
|
||||
| "onHeartbeatPong"
|
||||
| "onHeartbeatTimeout"
|
||||
| "onError"
|
||||
| "onClose"
|
||||
>
|
||||
>;
|
||||
|
||||
function defaultLifecycleHandlers(): ResolvedLifecycleHandlers {
|
||||
return {
|
||||
onAttempt: () => undefined,
|
||||
onOpen: () => undefined,
|
||||
onHeartbeatPing: () => undefined,
|
||||
onHeartbeatPong: () => undefined,
|
||||
onHeartbeatTimeout: () => undefined,
|
||||
onError: () => undefined,
|
||||
onClose: () => undefined,
|
||||
getConnectionLabel: () => null,
|
||||
getVersionMismatchHint: () => null,
|
||||
isCloseIntentional: () => false,
|
||||
isActive: () => true,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveLifecycleHandlers(
|
||||
handlers: WsProtocolLifecycleHandlers | undefined,
|
||||
telemetryLifecycle: WsProtocolLifecycleHandlers | undefined,
|
||||
): Required<WsProtocolLifecycleHandlers> {
|
||||
if (telemetryLifecycle === undefined) {
|
||||
return {
|
||||
...defaultLifecycleHandlers(),
|
||||
...handlers,
|
||||
};
|
||||
}
|
||||
): ResolvedLifecycleHandlers {
|
||||
const defaults = defaultLifecycleHandlers();
|
||||
const isActive = handlers?.isActive ?? telemetryLifecycle?.isActive ?? defaults.isActive;
|
||||
const isCloseIntentional =
|
||||
handlers?.isCloseIntentional ??
|
||||
telemetryLifecycle?.isCloseIntentional ??
|
||||
defaults.isCloseIntentional;
|
||||
|
||||
return {
|
||||
getConnectionLabel: () =>
|
||||
handlers?.getConnectionLabel?.() ?? telemetryLifecycle.getConnectionLabel?.() ?? null,
|
||||
handlers?.getConnectionLabel?.() ?? telemetryLifecycle?.getConnectionLabel?.() ?? null,
|
||||
getVersionMismatchHint: () =>
|
||||
handlers?.getVersionMismatchHint?.() ?? telemetryLifecycle.getVersionMismatchHint?.() ?? null,
|
||||
handlers?.getVersionMismatchHint?.() ??
|
||||
telemetryLifecycle?.getVersionMismatchHint?.() ??
|
||||
null,
|
||||
isActive,
|
||||
isCloseIntentional,
|
||||
onAttempt: (socketUrl) => {
|
||||
telemetryLifecycle.onAttempt?.(socketUrl);
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onAttempt?.(socketUrl);
|
||||
handlers?.onAttempt?.(socketUrl);
|
||||
},
|
||||
onOpen: () => {
|
||||
telemetryLifecycle.onOpen?.();
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onOpen?.();
|
||||
handlers?.onOpen?.();
|
||||
},
|
||||
onHeartbeatPing: () => {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onHeartbeatPing?.();
|
||||
handlers?.onHeartbeatPing?.();
|
||||
},
|
||||
onHeartbeatPong: () => {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onHeartbeatPong?.();
|
||||
handlers?.onHeartbeatPong?.();
|
||||
},
|
||||
onHeartbeatTimeout: () => {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onHeartbeatTimeout?.();
|
||||
handlers?.onHeartbeatTimeout?.();
|
||||
},
|
||||
onError: (message) => {
|
||||
telemetryLifecycle.onError?.(message);
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onError?.(message);
|
||||
handlers?.onError?.(message);
|
||||
},
|
||||
onClose: (details) => {
|
||||
telemetryLifecycle.onClose?.(details);
|
||||
handlers?.onClose?.(details);
|
||||
onClose: (details, context) => {
|
||||
if (!isActive()) {
|
||||
return;
|
||||
}
|
||||
telemetryLifecycle?.onClose?.(details, context);
|
||||
handlers?.onClose?.(details, context);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -158,10 +241,15 @@ export function createWsRpcProtocolLayer(
|
||||
socket.addEventListener(
|
||||
"close",
|
||||
(event) => {
|
||||
lifecycle.onClose({
|
||||
code: event.code,
|
||||
reason: event.reason,
|
||||
});
|
||||
lifecycle.onClose(
|
||||
{
|
||||
code: event.code,
|
||||
reason: event.reason,
|
||||
},
|
||||
{
|
||||
intentional: lifecycle.isCloseIntentional(),
|
||||
},
|
||||
);
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
@@ -210,6 +298,77 @@ export function createWsRpcProtocolLayer(
|
||||
retryTransientErrors: true,
|
||||
}),
|
||||
);
|
||||
const requestHooksLayer = Layer.succeed(
|
||||
RpcClient.RequestHooks,
|
||||
RpcClient.RequestHooks.of({
|
||||
onRequestStart: (info) =>
|
||||
Effect.sync(() => {
|
||||
if (!lifecycle.isActive()) {
|
||||
return;
|
||||
}
|
||||
handlers?.onRequestStart?.({
|
||||
id: String(info.id),
|
||||
tag: info.tag,
|
||||
stream: info.stream,
|
||||
});
|
||||
}),
|
||||
onRequestChunk: (info) =>
|
||||
Effect.sync(() => {
|
||||
if (!lifecycle.isActive()) {
|
||||
return;
|
||||
}
|
||||
handlers?.onRequestChunk?.({
|
||||
id: String(info.id),
|
||||
tag: info.tag,
|
||||
chunkCount: info.chunkCount,
|
||||
});
|
||||
}),
|
||||
onRequestExit: (info) =>
|
||||
Effect.sync(() => {
|
||||
if (!lifecycle.isActive()) {
|
||||
return;
|
||||
}
|
||||
handlers?.onRequestExit?.({
|
||||
id: String(info.id),
|
||||
tag: info.tag,
|
||||
stream: info.stream,
|
||||
});
|
||||
}),
|
||||
onRequestInterrupt: (info) =>
|
||||
Effect.sync(() => {
|
||||
if (!lifecycle.isActive()) {
|
||||
return;
|
||||
}
|
||||
handlers?.onRequestInterrupt?.({
|
||||
id: String(info.id),
|
||||
...(info.tag === undefined ? {} : { tag: info.tag }),
|
||||
});
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const connectionHooksLayer = Layer.succeed(
|
||||
RpcClient.ConnectionHooks,
|
||||
RpcClient.ConnectionHooks.of({
|
||||
onConnect: Effect.void,
|
||||
onDisconnect: Effect.void,
|
||||
onPing: Effect.sync(() => {
|
||||
lifecycle.onHeartbeatPing();
|
||||
}),
|
||||
onPong: Effect.sync(() => {
|
||||
lifecycle.onHeartbeatPong();
|
||||
}),
|
||||
onPingTimeout: Effect.sync(() => {
|
||||
requestTelemetry?.onClearTrackedRequests?.();
|
||||
lifecycle.onHeartbeatTimeout();
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
return protocolLayer.pipe(Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson)));
|
||||
return Layer.mergeAll(
|
||||
protocolLayer.pipe(
|
||||
Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson, connectionHooksLayer)),
|
||||
),
|
||||
requestHooksLayer,
|
||||
connectionHooksLayer,
|
||||
);
|
||||
}
|
||||
@@ -202,15 +202,111 @@ describe("WsTransport", () => {
|
||||
socket.close(1012, "service restart");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onClose).toHaveBeenCalledWith({
|
||||
code: 1012,
|
||||
reason: "service restart",
|
||||
});
|
||||
expect(onClose).toHaveBeenCalledWith(
|
||||
{
|
||||
code: 1012,
|
||||
reason: "service restart",
|
||||
},
|
||||
{
|
||||
intentional: false,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("tracks heartbeat freshness from websocket pongs", async () => {
|
||||
const nowSpy = vi.spyOn(performance, "now").mockReturnValue(1_000);
|
||||
const onHeartbeatPong = vi.fn();
|
||||
const transport = createTransport("ws://localhost:3020", { onHeartbeatPong });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
expect(transport.isHeartbeatFresh()).toBe(false);
|
||||
|
||||
const socket = getSocket();
|
||||
socket.open();
|
||||
socket.serverMessage(JSON.stringify({ _tag: "Pong" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onHeartbeatPong).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
expect(transport.isHeartbeatFresh()).toBe(true);
|
||||
expect(transport.isHeartbeatFresh(500)).toBe(true);
|
||||
|
||||
nowSpy.mockReturnValue(1_501);
|
||||
expect(transport.isHeartbeatFresh(500)).toBe(false);
|
||||
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("clears heartbeat freshness when reconnecting", async () => {
|
||||
vi.spyOn(performance, "now").mockReturnValue(1_000);
|
||||
const onHeartbeatPong = vi.fn();
|
||||
const transport = createTransport("ws://localhost:3020", { onHeartbeatPong });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const firstSocket = getSocket();
|
||||
firstSocket.open();
|
||||
firstSocket.serverMessage(JSON.stringify({ _tag: "Pong" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onHeartbeatPong).toHaveBeenCalledOnce();
|
||||
});
|
||||
expect(transport.isHeartbeatFresh()).toBe(true);
|
||||
|
||||
await transport.reconnect();
|
||||
|
||||
expect(transport.isHeartbeatFresh()).toBe(false);
|
||||
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("does not report an intentional dispose as a close", async () => {
|
||||
const onClose = vi.fn();
|
||||
const transport = createTransport("ws://localhost:3020", { onClose });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
getSocket().open();
|
||||
await transport.dispose();
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores stale socket lifecycle events after reconnect starts a new session", async () => {
|
||||
const onClose = vi.fn();
|
||||
const transport = createTransport("ws://localhost:3020", { onClose });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
const firstSocket = getSocket();
|
||||
firstSocket.open();
|
||||
|
||||
await transport.reconnect();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(sockets).toHaveLength(2);
|
||||
});
|
||||
|
||||
firstSocket.close(1006, "stale close");
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
|
||||
await transport.dispose();
|
||||
});
|
||||
|
||||
it("reconnects the websocket session without disposing the transport", async () => {
|
||||
const transport = createTransport("ws://localhost:3020");
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ export interface WsTransportOptions {
|
||||
interface SubscribeOptions {
|
||||
readonly retryDelay?: Duration.Input;
|
||||
readonly onResubscribe?: () => void;
|
||||
readonly tag?: string;
|
||||
}
|
||||
|
||||
const DEFAULT_SUBSCRIPTION_RETRY_DELAY = Duration.millis(250);
|
||||
@@ -66,6 +67,13 @@ export class WsTransport {
|
||||
private readonly options: WsTransportOptions | undefined;
|
||||
private disposed = false;
|
||||
private hasReportedTransportDisconnect = false;
|
||||
private intentionalCloseDepth = 0;
|
||||
private nextSessionId = 0;
|
||||
private activeSessionId = 0;
|
||||
private lastHeartbeatPongAt: number | null = null;
|
||||
private readonly streamRequestStartListeners = new Set<
|
||||
(info: { readonly tag: string }) => void
|
||||
>();
|
||||
private reconnectChain: Promise<void> = Promise.resolve();
|
||||
private session: TransportSession;
|
||||
|
||||
@@ -130,6 +138,22 @@ export class WsTransport {
|
||||
Duration.fromInputUnsafe(options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY),
|
||||
);
|
||||
let cancelCurrentStream: () => void = NOOP;
|
||||
const onStreamRequestStart = (info: { readonly tag: string }) => {
|
||||
if (
|
||||
!hasReceivedValue ||
|
||||
!active ||
|
||||
(options?.tag !== undefined && info.tag !== options.tag)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
options?.onResubscribe?.();
|
||||
} catch {
|
||||
// Ignore reconnect hook failures so the stream can recover.
|
||||
}
|
||||
};
|
||||
this.streamRequestStartListeners.add(onStreamRequestStart);
|
||||
|
||||
void (async () => {
|
||||
for (;;) {
|
||||
@@ -139,14 +163,6 @@ export class WsTransport {
|
||||
|
||||
const session = this.session;
|
||||
try {
|
||||
if (hasReceivedValue) {
|
||||
try {
|
||||
options?.onResubscribe?.();
|
||||
} catch {
|
||||
// Ignore reconnect hook failures so the stream can recover.
|
||||
}
|
||||
}
|
||||
|
||||
const runningStream = this.runStreamOnSession(
|
||||
session,
|
||||
connect,
|
||||
@@ -190,6 +206,7 @@ export class WsTransport {
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
this.streamRequestStartListeners.delete(onStreamRequestStart);
|
||||
cancelCurrentStream();
|
||||
};
|
||||
}
|
||||
@@ -210,6 +227,7 @@ export class WsTransport {
|
||||
// Ignore hook failures so reconnect can proceed.
|
||||
}
|
||||
|
||||
this.lastHeartbeatPongAt = null;
|
||||
const previousSession = this.session;
|
||||
this.session = this.createSession();
|
||||
await this.closeSession(previousSession);
|
||||
@@ -219,6 +237,12 @@ export class WsTransport {
|
||||
await reconnectOperation;
|
||||
}
|
||||
|
||||
isHeartbeatFresh(maxAgeMs = 15_000): boolean {
|
||||
return (
|
||||
this.lastHeartbeatPongAt !== null && performance.now() - this.lastHeartbeatPongAt <= maxAgeMs
|
||||
);
|
||||
}
|
||||
|
||||
async dispose() {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
@@ -229,14 +253,43 @@ export class WsTransport {
|
||||
}
|
||||
|
||||
private closeSession(session: TransportSession) {
|
||||
this.intentionalCloseDepth += 1;
|
||||
return session.runtime.runPromise(Scope.close(session.clientScope, Exit.void)).finally(() => {
|
||||
this.intentionalCloseDepth = Math.max(0, this.intentionalCloseDepth - 1);
|
||||
session.runtime.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
private createSession(): TransportSession {
|
||||
const protocolFactory = this.options?.createProtocolLayer ?? createWsRpcProtocolLayer;
|
||||
const protocolLayer = protocolFactory(this.url, this.lifecycleHandlers);
|
||||
const sessionId = this.nextSessionId + 1;
|
||||
this.nextSessionId = sessionId;
|
||||
this.activeSessionId = sessionId;
|
||||
const lifecycleHandlers = this.lifecycleHandlers;
|
||||
const protocolLayer = protocolFactory(this.url, {
|
||||
...lifecycleHandlers,
|
||||
isActive: () =>
|
||||
!this.disposed &&
|
||||
this.activeSessionId === sessionId &&
|
||||
(lifecycleHandlers?.isActive?.() ?? true),
|
||||
isCloseIntentional: () =>
|
||||
this.disposed ||
|
||||
this.intentionalCloseDepth > 0 ||
|
||||
lifecycleHandlers?.isCloseIntentional?.() === true,
|
||||
onHeartbeatPong: () => {
|
||||
this.lastHeartbeatPongAt = performance.now();
|
||||
lifecycleHandlers?.onHeartbeatPong?.();
|
||||
},
|
||||
onRequestStart: (info) => {
|
||||
lifecycleHandlers?.onRequestStart?.(info);
|
||||
if (!info.stream) {
|
||||
return;
|
||||
}
|
||||
for (const listener of this.streamRequestStartListeners) {
|
||||
listener({ tag: info.tag });
|
||||
}
|
||||
},
|
||||
});
|
||||
const rootLayer = this.options?.tracingLayer
|
||||
? Layer.mergeAll(protocolLayer, this.options.tracingLayer)
|
||||
: protocolLayer;
|
||||
|
||||
Reference in new issue
Block a user