Skip to content

Commit e7777b8

Browse files
committed
refactor: share channel probe runner
1 parent 877ae06 commit e7777b8

9 files changed

Lines changed: 441 additions & 422 deletions

File tree

‎extensions/discord/src/probe.ts‎

Lines changed: 61 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { BaseProbeResult } from "openclaw/plugin-sdk/channel-contract";
33
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
44
import { resolveFetch } from "openclaw/plugin-sdk/fetch-runtime";
55
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
6-
import { fetchWithTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
6+
import { fetchWithTimeout, runChannelProbe } from "openclaw/plugin-sdk/text-utility-runtime";
77
import { DiscordApiError, fetchDiscord } from "./api.js";
88
import { normalizeDiscordToken } from "./token.js";
99

@@ -140,72 +140,67 @@ export async function probeDiscord(
140140
timeoutMs: number,
141141
opts?: { fetcher?: typeof fetch; includeApplication?: boolean },
142142
): Promise<DiscordProbe> {
143-
const started = Date.now();
144-
const fetcher = opts?.fetcher ?? fetch;
145-
const includeApplication = opts?.includeApplication === true;
146-
const normalized = normalizeDiscordToken(token, "channels.discord.token");
147-
const result: DiscordProbe = {
148-
ok: false,
149-
status: null,
150-
error: null,
151-
elapsedMs: 0,
152-
};
153-
if (!normalized) {
154-
return {
155-
...result,
156-
error: "missing token",
157-
elapsedMs: Date.now() - started,
158-
};
159-
}
160-
let res: Response | undefined;
161-
try {
162-
const getMeUrl = `${DISCORD_API_BASE}/users/@me`;
163-
const getMeDeadlineMs = Date.now() + timeoutMs;
164-
res = await fetchWithTimeout(
165-
getMeUrl,
166-
{ headers: { Authorization: `Bot ${normalized}` } },
167-
timeoutMs,
168-
getResolvedFetch(fetcher),
169-
);
170-
if (!res.ok) {
171-
result.status = res.status;
172-
result.error = `getMe failed (${res.status})`;
173-
return { ...result, elapsedMs: Date.now() - started };
174-
}
175-
const json = await readDiscordProbeGetMeJson(res, timeoutMs, getMeDeadlineMs);
176-
result.ok = true;
177-
result.bot = {
178-
id: json.id ?? null,
179-
username: json.username ?? null,
180-
};
181-
if (includeApplication) {
182-
// Application metadata is optional. Keep its deadline inside the outer status budget so a
183-
// stalled secondary response cannot discard the already-resolved bot identity.
184-
const elapsedMs = Math.max(0, Date.now() - started);
185-
const completionReserveMs = Math.min(
186-
DISCORD_PROBE_COMPLETION_RESERVE_MAX_MS,
187-
Math.max(1, Math.floor(timeoutMs / 10)),
188-
);
189-
const applicationTimeoutMs = Math.floor(timeoutMs - elapsedMs - completionReserveMs);
190-
if (applicationTimeoutMs > 0) {
191-
result.application =
192-
(await fetchDiscordApplicationSummary(normalized, applicationTimeoutMs, fetcher)) ??
193-
undefined;
143+
return await runChannelProbe(
144+
undefined,
145+
async ({ startedAt }) => {
146+
const fetcher = opts?.fetcher ?? fetch;
147+
const includeApplication = opts?.includeApplication === true;
148+
const normalized = normalizeDiscordToken(token, "channels.discord.token");
149+
const result: Omit<DiscordProbe, "elapsedMs"> = {
150+
ok: false,
151+
status: null,
152+
error: null,
153+
};
154+
if (!normalized) {
155+
return { ...result, error: "missing token" };
194156
}
195-
}
196-
return { ...result, elapsedMs: Date.now() - started };
197-
} catch (err) {
198-
return {
199-
...result,
200-
status: err instanceof Response ? err.status : result.status,
201-
error: formatErrorMessage(err),
202-
elapsedMs: Date.now() - started,
203-
};
204-
} finally {
205-
if (res?.bodyUsed !== true) {
206-
await res?.body?.cancel().catch(() => undefined);
207-
}
208-
}
157+
let res: Response | undefined;
158+
try {
159+
const getMeUrl = `${DISCORD_API_BASE}/users/@me`;
160+
const getMeDeadlineMs = Date.now() + timeoutMs;
161+
res = await fetchWithTimeout(
162+
getMeUrl,
163+
{ headers: { Authorization: `Bot ${normalized}` } },
164+
timeoutMs,
165+
getResolvedFetch(fetcher),
166+
);
167+
if (!res.ok) {
168+
return { ...result, status: res.status, error: `getMe failed (${res.status})` };
169+
}
170+
const json = await readDiscordProbeGetMeJson(res, timeoutMs, getMeDeadlineMs);
171+
result.ok = true;
172+
result.bot = {
173+
id: json.id ?? null,
174+
username: json.username ?? null,
175+
};
176+
if (includeApplication) {
177+
// Application metadata is optional. Keep its deadline inside the outer status budget so a
178+
// stalled secondary response cannot discard the already-resolved bot identity.
179+
const elapsedMs = Math.max(0, Date.now() - startedAt);
180+
const completionReserveMs = Math.min(
181+
DISCORD_PROBE_COMPLETION_RESERVE_MAX_MS,
182+
Math.max(1, Math.floor(timeoutMs / 10)),
183+
);
184+
const applicationTimeoutMs = Math.floor(timeoutMs - elapsedMs - completionReserveMs);
185+
if (applicationTimeoutMs > 0) {
186+
result.application =
187+
(await fetchDiscordApplicationSummary(normalized, applicationTimeoutMs, fetcher)) ??
188+
undefined;
189+
}
190+
}
191+
return result;
192+
} finally {
193+
if (res?.bodyUsed !== true) {
194+
await res?.body?.cancel().catch(() => undefined);
195+
}
196+
}
197+
},
198+
(error) => ({
199+
ok: false,
200+
status: error instanceof Response ? error.status : null,
201+
error: formatErrorMessage(error),
202+
}),
203+
);
209204
}
210205

211206
/**

‎extensions/matrix/src/matrix/probe.ts‎

Lines changed: 43 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
33
import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
44
import type { PinnedDispatcherPolicy } from "openclaw/plugin-sdk/ssrf-dispatcher";
55
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
6+
import { runChannelProbe } from "openclaw/plugin-sdk/text-utility-runtime";
67
import type { SsrFPolicy } from "../runtime-api.js";
78
import type { BaseProbeResult } from "../runtime-api.js";
89
import { isBunRuntime } from "./client/runtime.js";
@@ -30,65 +31,47 @@ export async function probeMatrix(params: {
3031
ssrfPolicy?: SsrFPolicy;
3132
dispatcherPolicy?: PinnedDispatcherPolicy;
3233
}): Promise<MatrixProbe> {
33-
const started = Date.now();
34-
const result: MatrixProbe = {
35-
ok: false,
36-
status: null,
37-
error: null,
38-
elapsedMs: 0,
39-
};
40-
if (isBunRuntime()) {
41-
return {
42-
...result,
43-
error: "Matrix probe requires Node (bun runtime not supported)",
44-
elapsedMs: Date.now() - started,
45-
};
46-
}
47-
if (!params.homeserver?.trim()) {
48-
return {
49-
...result,
50-
error: "missing homeserver",
51-
elapsedMs: Date.now() - started,
52-
};
53-
}
54-
if (!params.accessToken?.trim()) {
55-
return {
56-
...result,
57-
error: "missing access token",
58-
elapsedMs: Date.now() - started,
59-
};
60-
}
61-
try {
62-
const { createMatrixClient } = await loadMatrixProbeRuntimeDeps();
63-
const inputUserId = normalizeOptionalString(params.userId);
64-
const client = await createMatrixClient({
65-
homeserver: params.homeserver,
66-
userId: inputUserId,
67-
accessToken: params.accessToken,
68-
deviceId: params.deviceId,
69-
persistStorage: false,
70-
localTimeoutMs: params.timeoutMs,
71-
accountId: params.accountId,
72-
allowPrivateNetwork: params.allowPrivateNetwork,
73-
ssrfPolicy: params.ssrfPolicy,
74-
dispatcherPolicy: params.dispatcherPolicy,
75-
});
76-
// The client wrapper resolves user ID via whoami when needed.
77-
const userId = await client.getUserId();
78-
result.ok = true;
79-
result.userId = userId ?? null;
80-
81-
result.elapsedMs = Date.now() - started;
82-
return result;
83-
} catch (err) {
84-
return {
85-
...result,
34+
return await runChannelProbe(
35+
undefined,
36+
async () => {
37+
const result: Omit<MatrixProbe, "elapsedMs"> = {
38+
ok: false,
39+
status: null,
40+
error: null,
41+
};
42+
if (isBunRuntime()) {
43+
return { ...result, error: "Matrix probe requires Node (bun runtime not supported)" };
44+
}
45+
if (!params.homeserver?.trim()) {
46+
return { ...result, error: "missing homeserver" };
47+
}
48+
if (!params.accessToken?.trim()) {
49+
return { ...result, error: "missing access token" };
50+
}
51+
const { createMatrixClient } = await loadMatrixProbeRuntimeDeps();
52+
const inputUserId = normalizeOptionalString(params.userId);
53+
const client = await createMatrixClient({
54+
homeserver: params.homeserver,
55+
userId: inputUserId,
56+
accessToken: params.accessToken,
57+
deviceId: params.deviceId,
58+
persistStorage: false,
59+
localTimeoutMs: params.timeoutMs,
60+
accountId: params.accountId,
61+
allowPrivateNetwork: params.allowPrivateNetwork,
62+
ssrfPolicy: params.ssrfPolicy,
63+
dispatcherPolicy: params.dispatcherPolicy,
64+
});
65+
// The client wrapper resolves user ID via whoami when needed.
66+
return { ...result, ok: true, userId: (await client.getUserId()) ?? null };
67+
},
68+
(error) => ({
69+
ok: false,
8670
status:
87-
typeof err === "object" && err && "statusCode" in err
88-
? Number((err as { statusCode?: number }).statusCode)
89-
: result.status,
90-
error: formatErrorMessage(err),
91-
elapsedMs: Date.now() - started,
92-
};
93-
}
71+
typeof error === "object" && error && "statusCode" in error
72+
? Number((error as { statusCode?: number }).statusCode)
73+
: null,
74+
error: formatErrorMessage(error),
75+
}),
76+
);
9477
}

‎extensions/mattermost/src/mattermost/probe.ts‎

Lines changed: 42 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
ssrfPolicyFromPrivateNetworkOptIn,
88
type LookupFn,
99
} from "openclaw/plugin-sdk/ssrf-runtime";
10+
import { runChannelProbe } from "openclaw/plugin-sdk/text-utility-runtime";
1011
import { normalizeMattermostBaseUrl, readMattermostError, type MattermostUser } from "./client.js";
1112
import type { BaseProbeResult } from "./runtime-api.js";
1213

@@ -34,49 +35,51 @@ export async function probeMattermost(
3435
return { ok: false, error: "baseUrl missing" };
3536
}
3637
const url = `${normalized}/api/v4/users/me`;
37-
const start = Date.now();
38-
// Guard-owned timeoutMs covers DNS/proxy preflight; init.signal alone does not.
39-
const resolvedTimeoutMs = timeoutMs > 0 ? resolveTimerTimeoutMs(timeoutMs, 2500) : undefined;
40-
try {
41-
const { response: res, release } = await fetchWithSsrFGuard({
42-
url,
43-
init: {
44-
headers: { Authorization: `Bearer ${botToken}` },
45-
},
46-
auditContext: "mattermost-probe",
47-
policy: ssrfPolicyFromPrivateNetworkOptIn(allowPrivateNetwork),
48-
...(resolvedTimeoutMs !== undefined ? { timeoutMs: resolvedTimeoutMs } : {}),
49-
...(deps?.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
50-
...(deps?.lookupFn ? { lookupFn: deps.lookupFn } : {}),
51-
});
52-
try {
53-
const elapsedMs = Date.now() - start;
54-
if (!res.ok) {
55-
const detail = await readMattermostError(res);
38+
return await runChannelProbe(
39+
undefined,
40+
async ({ elapsedMs }) => {
41+
// Guard-owned timeoutMs covers DNS/proxy preflight; init.signal alone does not.
42+
const resolvedTimeoutMs = timeoutMs > 0 ? resolveTimerTimeoutMs(timeoutMs, 2500) : undefined;
43+
const { response: res, release } = await fetchWithSsrFGuard({
44+
url,
45+
init: {
46+
headers: { Authorization: `Bearer ${botToken}` },
47+
},
48+
auditContext: "mattermost-probe",
49+
policy: ssrfPolicyFromPrivateNetworkOptIn(allowPrivateNetwork),
50+
...(resolvedTimeoutMs !== undefined ? { timeoutMs: resolvedTimeoutMs } : {}),
51+
...(deps?.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
52+
...(deps?.lookupFn ? { lookupFn: deps.lookupFn } : {}),
53+
});
54+
const requestElapsedMs = elapsedMs();
55+
try {
56+
if (!res.ok) {
57+
const detail = await readMattermostError(res);
58+
return {
59+
ok: false,
60+
status: res.status,
61+
error: detail || res.statusText,
62+
elapsedMs: requestElapsedMs,
63+
};
64+
}
65+
const bot = await readProviderJsonResponse<MattermostUser>(
66+
res,
67+
"Mattermost probe /users/me",
68+
);
5669
return {
57-
ok: false,
70+
ok: true,
5871
status: res.status,
59-
error: detail || res.statusText,
60-
elapsedMs,
72+
elapsedMs: requestElapsedMs,
73+
bot,
6174
};
75+
} finally {
76+
await release();
6277
}
63-
const bot = await readProviderJsonResponse<MattermostUser>(res, "Mattermost probe /users/me");
64-
return {
65-
ok: true,
66-
status: res.status,
67-
elapsedMs,
68-
bot,
69-
};
70-
} finally {
71-
await release();
72-
}
73-
} catch (err) {
74-
const message = formatErrorMessage(err);
75-
return {
78+
},
79+
(error) => ({
7680
ok: false,
7781
status: null,
78-
error: message,
79-
elapsedMs: Date.now() - start,
80-
};
81-
}
82+
error: formatErrorMessage(error),
83+
}),
84+
);
8285
}

0 commit comments

Comments
 (0)