Skip to content

Commit ab5fcfc

Browse files
authored
feat(gateway): add channel-backed readiness probes (#38285)
* Changelog: add channel-backed readiness probe entry * Gateway: add channel-backed readiness probes * Docs: describe readiness probe behavior * Gateway: add readiness probe regression tests * Changelog: dedupe gateway probe entries * Docs: fix readiness startup grace description * Changelog: remove stale readiness entry * Gateway: cover readiness hardening * Gateway: harden readiness probes
1 parent b17baca commit ab5fcfc

13 files changed

Lines changed: 558 additions & 20 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ Docs: https://docs.openclaw.ai
207207
- WhatsApp media upload caps: make outbound media sends and auto-replies honor `channels.whatsapp.mediaMaxMb` with per-account overrides so inbound and outbound limits use the same channel config. Thanks @vincentkoc.
208208
- Windows/Plugin install: when OpenClaw runs on Windows via Bun and `npm-cli.js` is not colocated with the runtime binary, fall back to `npm.cmd`/`npx.cmd` through the existing `cmd.exe` wrapper so `openclaw plugins install` no longer fails with `spawn EINVAL`. (#38056) Thanks @0xlin2023.
209209
- Telegram/send retry classification: retry grammY `Network request ... failed after N attempts` envelopes in send flows without reclassifying plain `Network request ... failed!` wrappers as transient, restoring the intended retry path while keeping broad send-context message matching tight. (#38056) Thanks @0xlin2023.
210-
- Gateway/probe route precedence: keep `/health`, `/healthz`, `/ready`, and `/readyz` reachable when the Control UI is mounted at `/`, so root-mounted SPA fallbacks no longer swallow machine probe routes while plugin-owned routes on those paths still keep precedence. (#18446) Thanks @vibecodooor and @vincentkoc.
210+
- Gateway/probes: keep `/health`, `/healthz`, `/ready`, and `/readyz` reachable when the Control UI is mounted at `/`, preserve plugin-owned route precedence on those paths, and make `/ready` and `/readyz` report channel-backed readiness with startup grace plus `503` on disconnected managed channels, while `/health` and `/healthz` stay shallow liveness probes. (#18446) Thanks @vibecodooor, @mahsumaktas, and @vincentkoc.
211211

212212
## 2026.3.2
213213

‎docs/install/docker.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,10 @@ curl -fsS http://127.0.0.1:18789/readyz
476476

477477
Aliases: `/health` and `/ready`.
478478

479+
`/healthz` is a shallow liveness probe for "the gateway process is up".
480+
`/readyz` stays ready during startup grace, then becomes `503` only if required
481+
managed channels are still disconnected after grace or disconnect later.
482+
479483
The Docker image includes a built-in `HEALTHCHECK` that pings `/healthz` in the
480484
background. In plain terms: Docker keeps checking if OpenClaw is still
481485
responsive. If checks keep failing, Docker marks the container as `unhealthy`,

‎src/channels/plugins/types.core.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ export type ChannelAccountSnapshot = {
102102
linked?: boolean;
103103
running?: boolean;
104104
connected?: boolean;
105+
restartPending?: boolean;
105106
reconnectAttempts?: number;
106107
lastConnectedAt?: number | null;
107108
lastDisconnect?:

‎src/gateway/channel-health-monitor.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import type { ChannelId } from "../channels/plugins/types.js";
22
import { createSubsystemLogger } from "../logging/subsystem.js";
33
import {
4+
DEFAULT_CHANNEL_CONNECT_GRACE_MS,
5+
DEFAULT_CHANNEL_STALE_EVENT_THRESHOLD_MS,
46
evaluateChannelHealth,
57
resolveChannelRestartReason,
68
type ChannelHealthPolicy,
@@ -21,9 +23,6 @@ const ONE_HOUR_MS = 60 * 60_000;
2123
* This catches the half-dead WebSocket scenario where the connection appears
2224
* alive (health checks pass) but Slack silently stops delivering events.
2325
*/
24-
const DEFAULT_STALE_EVENT_THRESHOLD_MS = 30 * 60_000;
25-
const DEFAULT_CHANNEL_CONNECT_GRACE_MS = 120_000;
26-
2726
export type ChannelHealthTimingPolicy = {
2827
monitorStartupGraceMs: number;
2928
channelConnectGraceMs: number;
@@ -70,7 +69,7 @@ function resolveTimingPolicy(
7069
staleEventThresholdMs:
7170
deps.timing?.staleEventThresholdMs ??
7271
deps.staleEventThresholdMs ??
73-
DEFAULT_STALE_EVENT_THRESHOLD_MS,
72+
DEFAULT_CHANNEL_STALE_EVENT_THRESHOLD_MS,
7473
};
7574
}
7675

‎src/gateway/channel-health-policy.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ export type ChannelHealthSnapshot = {
33
connected?: boolean;
44
enabled?: boolean;
55
configured?: boolean;
6+
restartPending?: boolean;
67
busy?: boolean;
78
activeRuns?: number;
89
lastRunActivityAt?: number | null;
@@ -39,6 +40,10 @@ function isManagedAccount(snapshot: ChannelHealthSnapshot): boolean {
3940
}
4041

4142
const BUSY_ACTIVITY_STALE_THRESHOLD_MS = 25 * 60_000;
43+
// Keep these shared between the background health monitor and on-demand readiness
44+
// probes so both surfaces evaluate channel lifecycle windows consistently.
45+
export const DEFAULT_CHANNEL_STALE_EVENT_THRESHOLD_MS = 30 * 60_000;
46+
export const DEFAULT_CHANNEL_CONNECT_GRACE_MS = 120_000;
4247

4348
export function evaluateChannelHealth(
4449
snapshot: ChannelHealthSnapshot,

‎src/gateway/server-channels.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,7 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
180180
enabled: false,
181181
configured: true,
182182
running: false,
183+
restartPending: false,
183184
lastError: plugin.config.disabledReason?.(account, cfg) ?? "disabled",
184185
});
185186
return;
@@ -195,6 +196,7 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
195196
enabled: true,
196197
configured: false,
197198
running: false,
199+
restartPending: false,
198200
lastError: plugin.config.unconfiguredReason?.(account, cfg) ?? "not configured",
199201
});
200202
return;
@@ -215,6 +217,7 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
215217
enabled: true,
216218
configured: true,
217219
running: true,
220+
restartPending: false,
218221
lastStartAt: Date.now(),
219222
lastError: null,
220223
reconnectAttempts: preserveRestartAttempts ? (restartAttempts.get(rKey) ?? 0) : 0,
@@ -252,6 +255,11 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
252255
const attempt = (restartAttempts.get(rKey) ?? 0) + 1;
253256
restartAttempts.set(rKey, attempt);
254257
if (attempt > MAX_RESTART_ATTEMPTS) {
258+
setRuntime(channelId, id, {
259+
accountId: id,
260+
restartPending: false,
261+
reconnectAttempts: attempt,
262+
});
255263
log.error?.(`[${id}] giving up after ${MAX_RESTART_ATTEMPTS} restart attempts`);
256264
return;
257265
}
@@ -261,6 +269,7 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
261269
);
262270
setRuntime(channelId, id, {
263271
accountId: id,
272+
restartPending: true,
264273
reconnectAttempts: attempt,
265274
});
266275
try {
@@ -349,6 +358,7 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
349358
setRuntime(channelId, id, {
350359
accountId: id,
351360
running: false,
361+
restartPending: false,
352362
lastStopAt: Date.now(),
353363
});
354364
}),
@@ -377,6 +387,7 @@ export function createChannelManager(opts: ChannelManagerOptions): ChannelManage
377387
const next: ChannelAccountSnapshot = {
378388
accountId: resolvedId,
379389
running: false,
390+
restartPending: false,
380391
lastError: cleared ? "logged out" : current.lastError,
381392
};
382393
if (typeof current.connected === "boolean") {
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
import { describe, expect, it } from "vitest";
2+
import {
3+
AUTH_TOKEN,
4+
AUTH_NONE,
5+
createRequest,
6+
createResponse,
7+
dispatchRequest,
8+
withGatewayServer,
9+
} from "./server-http.test-harness.js";
10+
import type { ReadinessChecker } from "./server/readiness.js";
11+
12+
describe("gateway probe endpoints", () => {
13+
it("returns detailed readiness payload for local /ready requests", async () => {
14+
const getReadiness: ReadinessChecker = () => ({
15+
ready: true,
16+
failing: [],
17+
uptimeMs: 45_000,
18+
});
19+
20+
await withGatewayServer({
21+
prefix: "probe-ready",
22+
resolvedAuth: AUTH_NONE,
23+
overrides: { getReadiness },
24+
run: async (server) => {
25+
const req = createRequest({ path: "/ready" });
26+
const { res, getBody } = createResponse();
27+
await dispatchRequest(server, req, res);
28+
29+
expect(res.statusCode).toBe(200);
30+
expect(JSON.parse(getBody())).toEqual({ ready: true, failing: [], uptimeMs: 45_000 });
31+
},
32+
});
33+
});
34+
35+
it("returns only readiness state for unauthenticated remote /ready requests", async () => {
36+
const getReadiness: ReadinessChecker = () => ({
37+
ready: false,
38+
failing: ["discord", "telegram"],
39+
uptimeMs: 8_000,
40+
});
41+
42+
await withGatewayServer({
43+
prefix: "probe-not-ready",
44+
resolvedAuth: AUTH_NONE,
45+
overrides: { getReadiness },
46+
run: async (server) => {
47+
const req = createRequest({
48+
path: "/ready",
49+
remoteAddress: "10.0.0.8",
50+
host: "gateway.test",
51+
});
52+
const { res, getBody } = createResponse();
53+
await dispatchRequest(server, req, res);
54+
55+
expect(res.statusCode).toBe(503);
56+
expect(JSON.parse(getBody())).toEqual({ ready: false });
57+
},
58+
});
59+
});
60+
61+
it("returns detailed readiness payload for authenticated remote /ready requests", async () => {
62+
const getReadiness: ReadinessChecker = () => ({
63+
ready: false,
64+
failing: ["discord", "telegram"],
65+
uptimeMs: 8_000,
66+
});
67+
68+
await withGatewayServer({
69+
prefix: "probe-remote-authenticated",
70+
resolvedAuth: AUTH_TOKEN,
71+
overrides: { getReadiness },
72+
run: async (server) => {
73+
const req = createRequest({
74+
path: "/ready",
75+
remoteAddress: "10.0.0.8",
76+
host: "gateway.test",
77+
authorization: "Bearer test-token",
78+
});
79+
const { res, getBody } = createResponse();
80+
await dispatchRequest(server, req, res);
81+
82+
expect(res.statusCode).toBe(503);
83+
expect(JSON.parse(getBody())).toEqual({
84+
ready: false,
85+
failing: ["discord", "telegram"],
86+
uptimeMs: 8_000,
87+
});
88+
},
89+
});
90+
});
91+
92+
it("returns typed internal error payload when readiness evaluation throws", async () => {
93+
const getReadiness: ReadinessChecker = () => {
94+
throw new Error("boom");
95+
};
96+
97+
await withGatewayServer({
98+
prefix: "probe-throws",
99+
resolvedAuth: AUTH_NONE,
100+
overrides: { getReadiness },
101+
run: async (server) => {
102+
const req = createRequest({ path: "/ready" });
103+
const { res, getBody } = createResponse();
104+
await dispatchRequest(server, req, res);
105+
106+
expect(res.statusCode).toBe(503);
107+
expect(JSON.parse(getBody())).toEqual({ ready: false, failing: ["internal"], uptimeMs: 0 });
108+
},
109+
});
110+
});
111+
112+
it("keeps /healthz shallow even when readiness checker reports failing channels", async () => {
113+
const getReadiness: ReadinessChecker = () => ({
114+
ready: false,
115+
failing: ["discord"],
116+
uptimeMs: 999,
117+
});
118+
119+
await withGatewayServer({
120+
prefix: "probe-healthz-unaffected",
121+
resolvedAuth: AUTH_NONE,
122+
overrides: { getReadiness },
123+
run: async (server) => {
124+
const req = createRequest({ path: "/healthz" });
125+
const { res, getBody } = createResponse();
126+
await dispatchRequest(server, req, res);
127+
128+
expect(res.statusCode).toBe(200);
129+
expect(getBody()).toBe(JSON.stringify({ ok: true, status: "live" }));
130+
},
131+
});
132+
});
133+
134+
it("reflects readiness status on HEAD /readyz without a response body", async () => {
135+
const getReadiness: ReadinessChecker = () => ({
136+
ready: false,
137+
failing: ["discord"],
138+
uptimeMs: 5_000,
139+
});
140+
141+
await withGatewayServer({
142+
prefix: "probe-readyz-head",
143+
resolvedAuth: AUTH_NONE,
144+
overrides: { getReadiness },
145+
run: async (server) => {
146+
const req = createRequest({ path: "/readyz", method: "HEAD" });
147+
const { res, getBody } = createResponse();
148+
await dispatchRequest(server, req, res);
149+
150+
expect(res.statusCode).toBe(503);
151+
expect(getBody()).toBe("");
152+
},
153+
});
154+
});
155+
});

‎src/gateway/server-http.test-harness.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,15 @@ export function createRequest(params: {
2828
path: string;
2929
authorization?: string;
3030
method?: string;
31+
remoteAddress?: string;
32+
host?: string;
3133
}): IncomingMessage {
3234
return createGatewayRequest({
3335
path: params.path,
3436
authorization: params.authorization,
3537
method: params.method,
38+
remoteAddress: params.remoteAddress,
39+
host: params.host,
3640
});
3741
}
3842

@@ -127,6 +131,8 @@ export async function sendRequest(
127131
path: string;
128132
authorization?: string;
129133
method?: string;
134+
remoteAddress?: string;
135+
host?: string;
130136
},
131137
): Promise<ReturnType<typeof createResponse>> {
132138
const response = createResponse();

0 commit comments

Comments
 (0)