Skip to content

Commit c46cc1e

Browse files
authored
refactor(channels): unify inbound replay protection (#109117)
* refactor(channels): unify inbound replay-guard orchestration on shared factory * fix(plugin-sdk): bind replay-guard settlement to claim handles * fix(plugin-sdk): claim-handle settlement (rest) * fix(discord): align skipped queue cleanup * style(feishu): simplify bot menu claim settlement * refactor(plugin-sdk): extract replay dedupe contracts
1 parent eb107c1 commit c46cc1e

54 files changed

Lines changed: 1560 additions & 1466 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
a1d46522f78815ebda945360e6814772eb0b563350c4f0ee9cf2f414ad9dc948 plugin-sdk-api-baseline.json
2-
2dc9fd508e3875a00113171b8dabe738554c049c0083f5d05a4f1f82cc5320da plugin-sdk-api-baseline.jsonl
1+
e59682fe6e11b4bd6e47d585105b75f417ccc774e7085569336fffd478200be2 plugin-sdk-api-baseline.json
2+
4db490b8a21d1b4ce20f3e4d2f053b034d3ae039c79b2dbba995d13a5c4b0150 plugin-sdk-api-baseline.jsonl
Lines changed: 10 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,20 @@
11
// Discord plugin module implements inbound dedupe behavior.
2-
import { createClaimableDedupe, type ClaimableDedupe } from "openclaw/plugin-sdk/persistent-dedupe";
2+
import { createChannelReplayGuard } from "openclaw/plugin-sdk/persistent-dedupe";
33
import type { DiscordMessageEvent } from "./listeners.js";
44
import { resolveDiscordMessageChannelId } from "./message-utils.js";
55

66
const RECENT_DISCORD_MESSAGE_TTL_MS = 5 * 60_000;
77
const RECENT_DISCORD_MESSAGE_MAX = 5000;
88

9-
export function createDiscordInboundReplayGuard(): ClaimableDedupe {
10-
return createClaimableDedupe({
11-
ttlMs: RECENT_DISCORD_MESSAGE_TTL_MS,
12-
memoryMaxSize: RECENT_DISCORD_MESSAGE_MAX,
9+
type DiscordInboundReplayKeys = string | readonly (string | null | undefined)[] | null | undefined;
10+
11+
export function createDiscordInboundReplayGuard() {
12+
return createChannelReplayGuard<DiscordInboundReplayKeys>({
13+
dedupe: {
14+
ttlMs: RECENT_DISCORD_MESSAGE_TTL_MS,
15+
memoryMaxSize: RECENT_DISCORD_MESSAGE_MAX,
16+
},
17+
buildReplayKey: (keys) => keys,
1318
});
1419
}
1520

@@ -37,44 +42,3 @@ export function buildDiscordInboundReplayKey(params: {
3742
}
3843
return `${params.accountId}:${channelId}:${messageId}`;
3944
}
40-
41-
export async function claimDiscordInboundReplay(params: {
42-
replayKey?: string | null;
43-
replayGuard: ClaimableDedupe;
44-
}): Promise<boolean> {
45-
const replayKey = params.replayKey?.trim();
46-
if (!replayKey) {
47-
return true;
48-
}
49-
const claim = await params.replayGuard.claim(replayKey);
50-
return claim.kind === "claimed";
51-
}
52-
53-
export async function commitDiscordInboundReplay(params: {
54-
replayKeys?: readonly (string | null | undefined)[];
55-
replayGuard: ClaimableDedupe;
56-
}): Promise<void> {
57-
const replayKeys = normalizeDiscordInboundReplayKeys(params.replayKeys);
58-
await Promise.all(replayKeys.map((replayKey) => params.replayGuard.commit(replayKey)));
59-
}
60-
61-
export function releaseDiscordInboundReplay(params: {
62-
replayKeys?: readonly (string | null | undefined)[];
63-
replayGuard: ClaimableDedupe;
64-
error?: unknown;
65-
}): void {
66-
const replayKeys = normalizeDiscordInboundReplayKeys(params.replayKeys);
67-
replayKeys.forEach((replayKey) => params.replayGuard.release(replayKey, { error: params.error }));
68-
}
69-
70-
function normalizeDiscordInboundReplayKeys(
71-
replayKeys?: readonly (string | null | undefined)[],
72-
): string[] {
73-
return [
74-
...new Set(
75-
(replayKeys ?? [])
76-
.map((replayKey) => replayKey?.trim())
77-
.filter((replayKey): replayKey is string => Boolean(replayKey)),
78-
),
79-
];
80-
}

‎extensions/discord/src/monitor/inbound-job.test.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Discord tests cover inbound job plugin behavior.
2-
import { describe, expect, it } from "vitest";
2+
import { describe, expect, it, vi } from "vitest";
33
import { Message } from "../internal/discord.js";
44
import { createPartialDiscordChannelWithThrowingGetters } from "../test-support/partial-channel.js";
55
import { buildDiscordInboundJob, materializeDiscordInboundJob } from "./inbound-job.js";
@@ -143,7 +143,12 @@ describe("buildDiscordInboundJob", () => {
143143

144144
it("re-materializes the process context with an overridden abort signal", async () => {
145145
const ctx = await createBaseDiscordMessageContext();
146-
const job = buildDiscordInboundJob(ctx, { replayKeys: ["default:ch-1:m-1"] });
146+
const replayClaim = {
147+
keys: ["default:ch-1:m-1"] as const,
148+
commit: vi.fn(async () => true),
149+
release: vi.fn(),
150+
};
151+
const job = buildDiscordInboundJob(ctx, { replayClaims: [replayClaim] });
147152
const overrideAbortController = new AbortController();
148153

149154
const rematerialized = materializeDiscordInboundJob(job, overrideAbortController.signal);
@@ -154,7 +159,7 @@ describe("buildDiscordInboundJob", () => {
154159
expect(rematerialized.abortSignal).toBe(overrideAbortController.signal);
155160
expect(rematerialized.message).toEqual(job.payload.message);
156161
expect(rematerialized.data).toEqual(job.payload.data);
157-
expect(job.replayKeys).toEqual(["default:ch-1:m-1"]);
162+
expect(job.replayClaims).toEqual([replayClaim]);
158163
});
159164

160165
it("preserves Discord message getters across queued jobs", async () => {

‎extensions/discord/src/monitor/inbound-job.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Discord plugin module implements inbound job behavior.
2+
import type { ChannelReplayClaimHandle } from "openclaw/plugin-sdk/persistent-dedupe";
23
import {
34
resolveDiscordChannelIdSafe,
45
resolveDiscordChannelInfoSafe,
@@ -23,7 +24,7 @@ export type DiscordInboundJob = {
2324
queueKey: string;
2425
payload: DiscordInboundJobPayload;
2526
runtime: DiscordInboundJobRuntime;
26-
replayKeys?: string[];
27+
replayClaims?: readonly ChannelReplayClaimHandle[];
2728
};
2829

2930
function resolveDiscordInboundJobQueueKey(ctx: DiscordMessagePreflightContext): string {
@@ -42,7 +43,7 @@ function resolveDiscordInboundJobQueueKey(ctx: DiscordMessagePreflightContext):
4243

4344
export function buildDiscordInboundJob(
4445
ctx: DiscordMessagePreflightContext,
45-
options?: { replayKeys?: readonly string[] },
46+
options?: { replayClaims?: readonly ChannelReplayClaimHandle[] },
4647
): DiscordInboundJob {
4748
const {
4849
runtime,
@@ -77,7 +78,7 @@ export function buildDiscordInboundJob(
7778
threadBindings,
7879
discordRestFetch,
7980
},
80-
replayKeys: options?.replayKeys ? [...options.replayKeys] : undefined,
81+
replayClaims: options?.replayClaims,
8182
};
8283
}
8384

‎extensions/discord/src/monitor/message-handler.ts‎

Lines changed: 19 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,14 @@ import {
44
shouldDebounceTextInbound,
55
} from "openclaw/plugin-sdk/channel-inbound";
66
import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
7+
import type { ChannelReplayClaimHandle } from "openclaw/plugin-sdk/persistent-dedupe";
78
import { danger } from "openclaw/plugin-sdk/runtime-env";
89
import { resolveOpenProviderRuntimeGroupPolicy } from "openclaw/plugin-sdk/runtime-group-policy";
910
import type { Client } from "../internal/discord.js";
1011
import {
1112
buildDiscordInboundReplayKey,
12-
claimDiscordInboundReplay,
13-
commitDiscordInboundReplay,
1413
createDiscordInboundReplayGuard,
1514
DiscordRetryableInboundError,
16-
releaseDiscordInboundReplay,
1715
} from "./inbound-dedupe.js";
1816
import { buildDiscordInboundJob } from "./inbound-job.js";
1917
import type { DiscordMessageEvent, DiscordMessageHandler } from "./listeners.js";
@@ -76,15 +74,14 @@ export function createDiscordMessageHandler(
7674
runtime: params.runtime,
7775
setStatus: params.setStatus,
7876
abortSignal: params.abortSignal,
79-
replayGuard,
8077
testing: params.testing,
8178
});
8279

8380
const { debouncer } = createChannelInboundDebouncer<{
8481
data: DiscordMessageEvent;
8582
client: Client;
8683
abortSignal?: AbortSignal;
87-
replayKey?: string;
84+
replayClaim?: ChannelReplayClaimHandle;
8885
}>({
8986
cfg: params.cfg,
9087
channel: "discord",
@@ -122,14 +119,14 @@ export function createDiscordMessageHandler(
122119
if (!last) {
123120
return;
124121
}
125-
const replayKeys = entries.map((entry) => entry.replayKey).filter(isNonEmptyString);
122+
const replayClaims = entries
123+
.map((entry) => entry.replayClaim)
124+
.filter((claim): claim is ChannelReplayClaimHandle => claim !== undefined);
126125
const abortSignal = last.abortSignal;
127126
if (abortSignal?.aborted) {
128-
releaseDiscordInboundReplay({
129-
replayKeys,
130-
error: abortSignal.reason,
131-
replayGuard,
132-
});
127+
for (const claim of replayClaims) {
128+
claim.release({ error: abortSignal.reason });
129+
}
133130
return;
134131
}
135132
try {
@@ -146,11 +143,11 @@ export function createDiscordMessageHandler(
146143
client: last.client,
147144
});
148145
if (!ctx) {
149-
await commitDiscordInboundReplay({ replayKeys, replayGuard });
146+
await Promise.all(replayClaims.map((claim) => claim.commit()));
150147
return;
151148
}
152149
applyImplicitReplyBatchGate(ctx, params.replyToMode, false);
153-
messageRunQueue.enqueue(buildDiscordInboundJob(ctx, { replayKeys }));
150+
messageRunQueue.enqueue(buildDiscordInboundJob(ctx, { replayClaims }));
154151
return;
155152
}
156153
const combinedBaseText = entries
@@ -195,7 +192,7 @@ export function createDiscordMessageHandler(
195192
client: last.client,
196193
});
197194
if (!ctx) {
198-
await commitDiscordInboundReplay({ replayKeys, replayGuard });
195+
await Promise.all(replayClaims.map((claim) => claim.commit()));
199196
return;
200197
}
201198
applyImplicitReplyBatchGate(ctx, params.replyToMode, true);
@@ -212,12 +209,14 @@ export function createDiscordMessageHandler(
212209
ctxBatch.MessageSidLast = ids[ids.length - 1];
213210
}
214211
}
215-
messageRunQueue.enqueue(buildDiscordInboundJob(ctx, { replayKeys }));
212+
messageRunQueue.enqueue(buildDiscordInboundJob(ctx, { replayClaims }));
216213
} catch (error) {
217214
if (error instanceof DiscordRetryableInboundError) {
218-
releaseDiscordInboundReplay({ replayKeys, error, replayGuard });
215+
for (const claim of replayClaims) {
216+
claim.release({ error });
217+
}
219218
} else {
220-
await commitDiscordInboundReplay({ replayKeys, replayGuard });
219+
await Promise.all(replayClaims.map((claim) => claim.commit()));
221220
}
222221
throw error;
223222
}
@@ -245,20 +244,16 @@ export function createDiscordMessageHandler(
245244
accountId: params.accountId,
246245
data,
247246
});
248-
if (
249-
!(await claimDiscordInboundReplay({
250-
replayKey,
251-
replayGuard,
252-
}))
253-
) {
247+
const replayClaim = await replayGuard.claim(replayKey);
248+
if (replayClaim.kind !== "claimed" && replayClaim.kind !== "invalid") {
254249
return;
255250
}
256251

257252
await debouncer.enqueue({
258253
data,
259254
client,
260255
abortSignal: options?.abortSignal,
261-
replayKey: replayKey ?? undefined,
256+
...(replayClaim.kind === "claimed" ? { replayClaim: replayClaim.handle } : {}),
262257
});
263258
} catch (err) {
264259
params.runtime.error(danger(`handler failed: ${String(err)}`));

‎extensions/discord/src/monitor/message-run-queue.ts‎

Lines changed: 15 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,8 @@
11
// Discord plugin module implements message run queue behavior.
22
import { createChannelRunQueue } from "openclaw/plugin-sdk/channel-outbound";
33
import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
4-
import type { ClaimableDedupe } from "openclaw/plugin-sdk/persistent-dedupe";
54
import { danger } from "openclaw/plugin-sdk/runtime-env";
6-
import {
7-
commitDiscordInboundReplay,
8-
createDiscordInboundReplayGuard,
9-
DiscordRetryableInboundError,
10-
releaseDiscordInboundReplay,
11-
} from "./inbound-dedupe.js";
5+
import { DiscordRetryableInboundError } from "./inbound-dedupe.js";
126
import { materializeDiscordInboundJob, type DiscordInboundJob } from "./inbound-job.js";
137
import type { RuntimeEnv } from "./message-handler.preflight.types.js";
148
import type { DiscordMonitorStatusSink } from "./status.js";
@@ -19,7 +13,6 @@ type DiscordMessageRunQueueParams = {
1913
runtime: RuntimeEnv;
2014
setStatus?: DiscordMonitorStatusSink;
2115
abortSignal?: AbortSignal;
22-
replayGuard?: ClaimableDedupe;
2316
testing?: DiscordMessageRunQueueTestingHooks;
2417
};
2518

@@ -41,7 +34,6 @@ const loadMessageProcessRuntime = createLazyRuntimeModule(
4134
async function processDiscordQueuedMessage(params: {
4235
job: DiscordInboundJob;
4336
lifecycleSignal?: AbortSignal;
44-
replayGuard: ClaimableDedupe;
4537
testing?: DiscordMessageRunQueueTestingHooks;
4638
}) {
4739
const processDiscordMessageImpl =
@@ -53,42 +45,32 @@ async function processDiscordQueuedMessage(params: {
5345
: (params.job.runtime.abortSignal ?? params.lifecycleSignal);
5446
try {
5547
await processDiscordMessageImpl(materializeDiscordInboundJob(params.job, abortSignal));
56-
await commitDiscordInboundReplay({
57-
replayKeys: params.job.replayKeys,
58-
replayGuard: params.replayGuard,
59-
});
48+
await Promise.all(params.job.replayClaims?.map((claim) => claim.commit()) ?? []);
6049
} catch (error) {
6150
if (error instanceof DiscordRetryableInboundError) {
62-
releaseDiscordInboundReplay({
63-
replayKeys: params.job.replayKeys,
64-
error,
65-
replayGuard: params.replayGuard,
66-
});
51+
for (const claim of params.job.replayClaims ?? []) {
52+
claim.release({ error });
53+
}
6754
} else {
68-
await commitDiscordInboundReplay({
69-
replayKeys: params.job.replayKeys,
70-
replayGuard: params.replayGuard,
71-
});
55+
await Promise.all(params.job.replayClaims?.map((claim) => claim.commit()) ?? []);
7256
}
7357
throw error;
7458
}
7559
}
7660

77-
function cleanupSkippedDiscordQueuedMessage(params: {
78-
job: DiscordInboundJob;
79-
replayGuard: ClaimableDedupe;
80-
}) {
81-
releaseDiscordInboundReplay({
82-
replayKeys: params.job.replayKeys,
83-
error: new DiscordRetryableInboundError("discord queued run skipped before processing"),
84-
replayGuard: params.replayGuard,
85-
});
61+
function cleanupSkippedDiscordQueuedMessage(params: { job: DiscordInboundJob }) {
62+
// Typing feedback is created inside processing after admission, so skipped
63+
// jobs only carry replay claims that need reopening for a later retry.
64+
for (const claim of params.job.replayClaims ?? []) {
65+
claim.release({
66+
error: new DiscordRetryableInboundError("discord queued run skipped before processing"),
67+
});
68+
}
8669
}
8770

8871
export function createDiscordMessageRunQueue(
8972
params: DiscordMessageRunQueueParams,
9073
): DiscordMessageRunQueue {
91-
const replayGuard = params.replayGuard ?? createDiscordInboundReplayGuard();
9274
const skippedCleanup = new Set<SkippedQueuedMessageCleanup>();
9375
const runQueue = createChannelRunQueue({
9476
setStatus: params.setStatus,
@@ -122,7 +104,7 @@ export function createDiscordMessageRunQueue(
122104
return {
123105
enqueue(job) {
124106
const cleanupSkipped = () => {
125-
cleanupSkippedDiscordQueuedMessage({ job, replayGuard });
107+
cleanupSkippedDiscordQueuedMessage({ job });
126108
};
127109
if (!lifecycleActive) {
128110
cleanupSkipped();
@@ -136,7 +118,6 @@ export function createDiscordMessageRunQueue(
136118
await processDiscordQueuedMessage({
137119
job,
138120
lifecycleSignal,
139-
replayGuard,
140121
testing: params.testing,
141122
});
142123
});

0 commit comments

Comments
 (0)