Skip to content

Commit 8090cb1

Browse files
fix(discord): honor abortSignal during gateway READY retry backoff (#108561)
* fix(discord): honor abortSignal during gateway READY retry backoff * fix(discord): avoid __testing alias to satisfy Knip production scan * test(discord): make READY abort proof deterministic Co-authored-by: wangmiao0668000666 <[email protected]> * fix(retry): support unref abort sleeps Co-authored-by: wangmiao0668000666 <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 27065a6 commit 8090cb1

5 files changed

Lines changed: 85 additions & 6 deletions

File tree

‎extensions/discord/src/monitor/provider.lifecycle.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,52 @@ describe("runDiscordGatewayLifecycle", () => {
741741
});
742742
});
743743

744+
describe("waitForGatewayReady", () => {
745+
let waitForGatewayReady: (typeof import("../../test-api.js"))["discordGatewayLifecycleTesting"]["waitForGatewayReady"];
746+
747+
beforeAll(async () => {
748+
waitForGatewayReady = (await import("../../test-api.js")).discordGatewayLifecycleTesting
749+
.waitForGatewayReady;
750+
});
751+
752+
it("returns promptly when abortSignal fires during the READY retry backoff", async () => {
753+
vi.useFakeTimers();
754+
try {
755+
const controller = new AbortController();
756+
const gateway = {
757+
isConnected: false,
758+
connect: vi.fn(),
759+
disconnect: vi.fn(),
760+
ws: null,
761+
};
762+
const runtime: RuntimeEnv = {
763+
log: () => {},
764+
error: () => {},
765+
exit: () => {},
766+
};
767+
768+
const readyPromise = waitForGatewayReady({
769+
gateway,
770+
abortSignal: controller.signal,
771+
readyTimeoutMs: 200,
772+
runtime,
773+
});
774+
775+
await vi.advanceTimersByTimeAsync(250);
776+
expect(gateway.connect).toHaveBeenCalledTimes(1);
777+
controller.abort();
778+
779+
await expect(readyPromise).resolves.toBeUndefined();
780+
expect(vi.getTimerCount()).toBe(0);
781+
await vi.advanceTimersByTimeAsync(2_000);
782+
expect(gateway.connect).toHaveBeenCalledTimes(1);
783+
expect(gateway.disconnect).toHaveBeenCalledTimes(1);
784+
} finally {
785+
vi.useRealTimers();
786+
}
787+
});
788+
});
789+
744790
function toLintErrorObject(value: unknown, fallbackMessage: string): Error {
745791
if (value instanceof Error) {
746792
return value;

‎extensions/discord/src/monitor/provider.lifecycle.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import {
44
createTransportActivityStatusPatch,
55
} from "openclaw/plugin-sdk/gateway-runtime";
66
import { asDateTimestampMs, parseStrictPositiveInteger } from "openclaw/plugin-sdk/number-runtime";
7-
import { danger } from "openclaw/plugin-sdk/runtime-env";
7+
import { danger, sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
88
import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime-env";
99
import { formatErrorMessage } from "openclaw/plugin-sdk/ssrf-runtime";
1010
import { attachDiscordGatewayLogging } from "../gateway-logging.js";
@@ -399,10 +399,14 @@ async function waitForGatewayReady(params: {
399399
if (params.abortSignal?.aborted) {
400400
return;
401401
}
402-
await new Promise<void>((resolve) => {
403-
const timeout = setTimeout(resolve, DISCORD_GATEWAY_READY_RETRY_BACKOFF_MS);
404-
timeout.unref?.();
405-
});
402+
try {
403+
await sleepWithAbort(DISCORD_GATEWAY_READY_RETRY_BACKOFF_MS, params.abortSignal, {
404+
ref: false,
405+
});
406+
} catch {
407+
// Abort is normal lifecycle shutdown; do not enter another reconnect attempt.
408+
return;
409+
}
406410
}
407411
}
408412

@@ -581,3 +585,7 @@ export async function runDiscordGatewayLifecycle(params: {
581585
params.threadBindings.stop();
582586
}
583587
}
588+
589+
// Test-only surface. Re-exported from the plugin root `test-api.ts` entry so Knip's
590+
// production scan sees the consumer; tests import `testing` from `test-api.js`.
591+
export const testing = { waitForGatewayReady };

‎extensions/discord/test-api.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Discord API module exposes the plugin public contract.
22
export { discordPlugin } from "./src/channel.js";
33
export { buildFinalizedDiscordDirectInboundContext } from "./src/monitor/inbound-context.test-helpers.js";
4+
export { testing as discordGatewayLifecycleTesting } from "./src/monitor/provider.lifecycle.js";
45
export { testing as discordThreadBindingTesting } from "./src/monitor/thread-bindings.manager.js";
56
export { discordOutbound } from "./src/outbound-adapter.js";

‎packages/retry/src/index.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,22 @@ describe("RetrySupervisor", () => {
5959
vi.useRealTimers();
6060
}
6161
});
62+
63+
it("can unref the scheduled timer", async () => {
64+
const controller = new AbortController();
65+
const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
66+
try {
67+
const sleeper = sleepWithAbort(60_000, controller.signal, { ref: false });
68+
const timer = setTimeoutSpy.mock.results.at(-1)?.value as NodeJS.Timeout | undefined;
69+
70+
expect(timer?.hasRef()).toBe(false);
71+
controller.abort();
72+
await expect(sleeper).rejects.toMatchObject({ message: "aborted" });
73+
} finally {
74+
controller.abort();
75+
setTimeoutSpy.mockRestore();
76+
}
77+
});
6278
});
6379

6480
describe("retryAsync", () => {

‎packages/retry/src/index.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,11 @@ export function computeBackoffSchedule(scheduleMs: readonly number[], attempt: n
1818
return attempt <= 0 ? 0 : (scheduleMs[index] ?? 0);
1919
}
2020

21-
export async function sleepWithAbort(ms: number, abortSignal?: AbortSignal): Promise<void> {
21+
export async function sleepWithAbort(
22+
ms: number,
23+
abortSignal?: AbortSignal,
24+
options: { ref?: boolean } = {},
25+
): Promise<void> {
2226
if (!Number.isFinite(ms) || ms <= 0) {
2327
return;
2428
}
@@ -50,6 +54,10 @@ export async function sleepWithAbort(ms: number, abortSignal?: AbortSignal): Pro
5054
timer = null;
5155
resolve();
5256
}, delayMs);
57+
// Retry loops can stay abortable without keeping an otherwise idle process alive.
58+
if (options.ref === false) {
59+
timer.unref?.();
60+
}
5361
if (abortSignal?.aborted) {
5462
onAbort();
5563
}

0 commit comments

Comments
 (0)