Skip to content

Commit 6194cfd

Browse files
authored
fix(sms): retry transient MMS failures before durable adoption (#118994)
* fix(sms): retry transient MMS downloads before durable adoption * test(sms): align durable ingress harness with typed runtime contracts
1 parent a492eb9 commit 6194cfd

3 files changed

Lines changed: 364 additions & 40 deletions

File tree

‎extensions/sms/src/ingress-spool.test.ts‎

Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
// Sms tests cover durable Twilio webhook admission and replay.
2+
import { createHmac } from "node:crypto";
23
import { mkdtemp, realpath, rm } from "node:fs/promises";
4+
import { createServer } from "node:http";
35
import os from "node:os";
46
import path from "node:path";
7+
import { saveRemoteMedia } from "openclaw/plugin-sdk/media-runtime";
58
import { createChannelIngressQueueForTests } from "openclaw/plugin-sdk/plugin-state-test-runtime";
69
import { afterEach, describe, expect, it, vi } from "vitest";
710
import type { SmsChannelRuntime } from "./inbound.js";
811
import { createSmsIngressSpool } from "./ingress-spool.js";
912
import type { ResolvedSmsAccount } from "./types.js";
13+
import { createSmsWebhookHandler } from "./webhook.js";
1014

1115
type SmsIngressPayload = {
1216
version: 1;
@@ -64,6 +68,22 @@ async function drainSpool(spool: SmsIngressSpool): Promise<void> {
6468
await spool.waitForIdle();
6569
}
6670

71+
async function listenSmsTestServer(server: ReturnType<typeof createServer>): Promise<string> {
72+
await new Promise<void>((resolve) => {
73+
server.listen(0, "127.0.0.1", resolve);
74+
});
75+
disposers.push(async () => {
76+
await new Promise<void>((resolve) => {
77+
server.close(() => resolve());
78+
});
79+
});
80+
const address = server.address();
81+
if (!address || typeof address === "string") {
82+
throw new Error("expected a loopback HTTP server address");
83+
}
84+
return `http://127.0.0.1:${address.port}`;
85+
}
86+
6787
afterEach(async () => {
6888
for (const dispose of disposers.splice(0).toReversed()) {
6989
await dispose();
@@ -74,6 +94,173 @@ afterEach(async () => {
7494
});
7595

7696
describe("createSmsIngressSpool", () => {
97+
it("retries acknowledged MMS provider outages before adopting later same-sender messages", async () => {
98+
const stateDir = await createStateDir();
99+
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
100+
disposers.push(() => {
101+
vi.unstubAllEnvs();
102+
});
103+
const mediaBytes = Buffer.from(
104+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/a0cAAAAASUVORK5CYII=",
105+
"base64",
106+
);
107+
let mediaRequests = 0;
108+
let authenticatedMediaRequests = 0;
109+
const mediaOrigin = await listenSmsTestServer(
110+
createServer((req, res) => {
111+
mediaRequests += 1;
112+
if (req.headers.authorization?.startsWith("Basic ")) {
113+
authenticatedMediaRequests += 1;
114+
}
115+
if (mediaRequests === 1) {
116+
res.statusCode = 429;
117+
res.end("Twilio rate limited");
118+
return;
119+
}
120+
res.setHeader("content-type", "image/png");
121+
res.end(mediaBytes);
122+
}),
123+
);
124+
const sender = "+15551234567";
125+
const messageSid = `MM${"a".repeat(32)}`;
126+
const testAccount = {
127+
...account,
128+
accountSid: `AC${"c".repeat(32)}`,
129+
dmPolicy: "allowlist" as const,
130+
allowFrom: [sender],
131+
};
132+
const deliveries: Array<{ id: string; body: string; attachments: number }> = [];
133+
const channelRuntime = {
134+
commands: {
135+
shouldComputeCommandAuthorized: () => false,
136+
isControlCommandMessage: () => false,
137+
},
138+
pairing: { readAllowFromStore: async () => [] },
139+
routing: {
140+
resolveAgentRoute: () => ({
141+
agentId: "main",
142+
accountId: account.accountId,
143+
sessionKey: `agent:main:sms:direct:${sender}`,
144+
}),
145+
},
146+
media: {
147+
saveRemoteMedia: async (options: Parameters<typeof saveRemoteMedia>[0]) =>
148+
await saveRemoteMedia({
149+
...options,
150+
fetchImpl: async (_url, init) =>
151+
await fetch(`${mediaOrigin}/twilio-media`, {
152+
headers: init?.headers,
153+
signal: init?.signal,
154+
}),
155+
}),
156+
},
157+
inbound: {
158+
buildContext: (input: Parameters<SmsChannelRuntime["inbound"]["buildContext"]>[0]) => {
159+
deliveries.push({
160+
id: String(input.extra?.MessageSid),
161+
body: input.message.bodyForAgent ?? input.message.rawBody,
162+
attachments: input.media?.length ?? 0,
163+
});
164+
return {};
165+
},
166+
run: async (input: Parameters<SmsChannelRuntime["inbound"]["run"]>[0]) => {
167+
const turnInput = await input.adapter.ingest(input.raw);
168+
if (!turnInput) {
169+
throw new Error("expected normalized SMS turn");
170+
}
171+
await input.adapter.resolveTurn(
172+
turnInput,
173+
{ kind: "message", canStartAgentTurn: true },
174+
{},
175+
);
176+
await input.turnAdoptionLifecycle?.onAdopted();
177+
},
178+
},
179+
reply: {},
180+
session: {},
181+
} as unknown as SmsChannelRuntime;
182+
const queue = createQueue(stateDir);
183+
const spool = createSmsIngressSpool({
184+
cfg: {},
185+
account: testAccount,
186+
channelRuntime,
187+
queue,
188+
log: { warn: () => undefined },
189+
});
190+
disposers.push(spool.stop);
191+
const webhookHandler = createSmsWebhookHandler({
192+
cfg: {},
193+
account: testAccount,
194+
ingress: spool,
195+
});
196+
const webhookOrigin = await listenSmsTestServer(
197+
createServer((req, res) => {
198+
void webhookHandler(req, res).catch((error: unknown) => {
199+
res.statusCode = 500;
200+
res.end(error instanceof Error ? error.message : String(error));
201+
});
202+
}),
203+
);
204+
testAccount.publicWebhookUrl = `${webhookOrigin}/webhooks/sms`;
205+
spool.start();
206+
207+
async function postSignedCallback(callback: Record<string, string>) {
208+
const signatureData =
209+
testAccount.publicWebhookUrl +
210+
Object.keys(callback)
211+
.toSorted()
212+
.map((key) => `${key}${callback[key] ?? ""}`)
213+
.join("");
214+
const signature = createHmac("sha1", testAccount.authToken)
215+
.update(signatureData)
216+
.digest("base64");
217+
return await fetch(testAccount.publicWebhookUrl, {
218+
method: "POST",
219+
headers: { "x-twilio-signature": signature },
220+
body: new URLSearchParams(callback),
221+
});
222+
}
223+
224+
const mediaCallback = {
225+
...form(messageSid),
226+
AccountSid: testAccount.accountSid,
227+
Body: "keep this attachment",
228+
NumMedia: "1",
229+
MediaUrl0: `https://api.twilio.com/2010-04-01/Accounts/${testAccount.accountSid}/Messages/${messageSid}/Media/ME${"b".repeat(32)}`,
230+
MediaContentType0: "image/png",
231+
};
232+
const firstResponse = await postSignedCallback(mediaCallback);
233+
expect(firstResponse.status).toBe(200);
234+
expect(firstResponse.headers.get("x-openclaw-delivery-accepted")).toBe("durable");
235+
await vi.waitFor(async () => {
236+
expect(mediaRequests).toBe(1);
237+
expect(await queue.listPending()).toEqual([
238+
expect.objectContaining({ id: messageSid, lastError: expect.stringContaining("HTTP 429") }),
239+
]);
240+
});
241+
expect(deliveries).toEqual([]);
242+
243+
const secondSid = `SM${"d".repeat(32)}`;
244+
const secondResponse = await postSignedCallback({
245+
...form(secondSid),
246+
AccountSid: testAccount.accountSid,
247+
Body: "the later message",
248+
});
249+
expect(secondResponse.status).toBe(200);
250+
await vi.waitFor(() => expect(deliveries).toHaveLength(2), { timeout: 5_000 });
251+
expect(deliveries).toEqual([
252+
{ id: messageSid, body: "keep this attachment", attachments: 1 },
253+
{ id: secondSid, body: "the later message", attachments: 0 },
254+
]);
255+
expect(mediaRequests).toBe(2);
256+
expect(authenticatedMediaRequests).toBe(2);
257+
expect(await spool.enqueue(mediaCallback)).toMatchObject({
258+
kind: "completed",
259+
duplicate: true,
260+
});
261+
expect(await queue.listPending()).toEqual([]);
262+
});
263+
77264
it("recovers an uncompleted message with a fresh drain instance", async () => {
78265
const stateDir = await createStateDir();
79266
const first = createSmsIngressSpool({

0 commit comments

Comments
 (0)