Skip to content

Commit e0cd3b8

Browse files
committed
fix(line): bound inbound media response bodies
1 parent 81d4436 commit e0cd3b8

4 files changed

Lines changed: 148 additions & 45 deletions

File tree

‎extensions/line/src/bot-handlers.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1363,6 +1363,49 @@ describe("handleLineWebhookEvents", () => {
13631363
expect(processMessage).not.toHaveBeenCalled();
13641364
});
13651365

1366+
it("does not materialize or dispatch media after ingress cancellation", async () => {
1367+
const cancellation = new Error("LINE webhook spool stopped");
1368+
const abort = new AbortController();
1369+
const processMessage = vi.fn();
1370+
downloadLineMediaMock.mockImplementationOnce(
1371+
async (
1372+
_messageId: string,
1373+
_token: string,
1374+
_maxBytes: number,
1375+
options?: { signal?: AbortSignal },
1376+
) => {
1377+
options?.signal?.throwIfAborted();
1378+
throw new Error("download did not receive ingress cancellation");
1379+
},
1380+
);
1381+
const event = createTestMessageEvent({
1382+
message: {
1383+
id: "image-cancelled-1",
1384+
type: "image",
1385+
contentProvider: { type: "line" },
1386+
quoteToken: "q-image-cancelled",
1387+
},
1388+
source: { type: "user", userId: "user-image-cancelled" },
1389+
webhookEventId: "evt-image-cancelled",
1390+
});
1391+
const context = {
1392+
...createLineWebhookTestContext({ processMessage, dmPolicy: "open" }),
1393+
turnAdoptionLifecycle: {
1394+
admission: "exclusive" as const,
1395+
abortSignal: abort.signal,
1396+
onAdopted: vi.fn(),
1397+
onDeferred: vi.fn(),
1398+
onAbandoned: vi.fn(),
1399+
},
1400+
};
1401+
abort.abort(cancellation);
1402+
1403+
await expect(handleLineWebhookEvents([event], context)).rejects.toBe(cancellation);
1404+
1405+
expect(buildLineMessageContextMock).not.toHaveBeenCalled();
1406+
expect(processMessage).not.toHaveBeenCalled();
1407+
});
1408+
13661409
it("allows non-text group messages through when requireMention is set (cannot detect mention)", async () => {
13671410
// Image message -- LINE only carries mention metadata on text messages.
13681411
const event = createTestMessageEvent({

‎extensions/line/src/bot-handlers.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -423,20 +423,25 @@ async function handleMessageEvent(event: MessageEvent, context: LineHandlerConte
423423
let mediaUnavailable = false;
424424

425425
if (isDownloadableLineMessageType(message.type)) {
426+
const abortSignal = context.turnAdoptionLifecycle?.abortSignal;
426427
try {
427428
const originalFilename =
428429
message.type === "file" ? normalizeOptionalString(message.fileName) : undefined;
429430
const media = await downloadLineMedia(
430431
message.id,
431432
account.channelAccessToken,
432433
mediaMaxBytes,
433-
{ originalFilename },
434+
{ originalFilename, ...(abortSignal ? { signal: abortSignal } : {}) },
434435
);
436+
abortSignal?.throwIfAborted();
435437
allMedia.push({
436438
path: media.path,
437439
contentType: media.contentType,
438440
});
439441
} catch (err) {
442+
if (abortSignal?.aborted) {
443+
throw abortSignal.reason;
444+
}
440445
if (isRetryableLineInboundMediaError(err)) {
441446
// Preparation-phase failure before turn adoption: reject so the durable
442447
// ingress drain retries the whole event once LINE finishes preparing the

‎extensions/line/src/download.test.ts‎

Lines changed: 44 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ describe("downloadLineMedia", () => {
313313

314314
vi.useFakeTimers();
315315
const pending = downloadLineMedia("mid-hung", "token");
316-
const rejection = expect(pending).rejects.toThrow(/did not become ready within 15 seconds/i);
316+
const rejection = expect(pending).rejects.toThrow(/did not download within 15 seconds/i);
317317
await vi.advanceTimersByTimeAsync(15_000);
318318
await rejection;
319319

@@ -383,23 +383,57 @@ describe("downloadLineMedia", () => {
383383
expect(isRetryableLineInboundMediaError(err)).toBe(true);
384384
});
385385

386-
it("raises a retryable MediaFetchError when the readiness deadline aborts", async () => {
387-
fetchMock.mockImplementation(
388-
async (_input: RequestInfo | URL, init?: RequestInit): Promise<Response> =>
389-
await new Promise<Response>((_resolve, reject) => {
390-
init?.signal?.addEventListener("abort", () => reject(new Error("fetch aborted")), {
391-
once: true,
392-
});
393-
}),
386+
it("uses one deadline across headers and body, then permits an identical retry", async () => {
387+
let stalledBody: ReadableStreamDefaultController<Uint8Array> | undefined;
388+
let stalledResponse: Response | undefined;
389+
let requestSignal: AbortSignal | undefined;
390+
fetchMock.mockImplementationOnce(
391+
async (_input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
392+
requestSignal = init?.signal ?? undefined;
393+
stalledResponse = new Response(
394+
new ReadableStream<Uint8Array>({
395+
start(controller) {
396+
stalledBody = controller;
397+
controller.enqueue(Buffer.from("partial"));
398+
init?.signal?.addEventListener("abort", () => controller.error(init.signal?.reason), {
399+
once: true,
400+
});
401+
},
402+
}),
403+
{ status: 200 },
404+
);
405+
return stalledResponse;
406+
},
394407
);
395408

396409
vi.useFakeTimers();
397-
const pending = downloadLineMedia("mid-hung", "token").catch((e: unknown) => e);
410+
let settledAtDeadline = false;
411+
const pending = downloadLineMedia("mid-body-stall", "token")
412+
.catch((error: unknown) => error)
413+
.finally(() => {
414+
settledAtDeadline = true;
415+
});
416+
await vi.waitFor(() => expect(saveMediaStreamMock).toHaveBeenCalledTimes(1));
398417
await vi.advanceTimersByTimeAsync(15_000);
418+
await Promise.resolve();
419+
const observedAtDeadline = settledAtDeadline;
420+
if (!settledAtDeadline) {
421+
stalledBody?.error(new Error("pre-fix test cleanup"));
422+
}
399423
const err = expectMediaFetchError(await pending);
400424

425+
expect(observedAtDeadline).toBe(true);
401426
expect(err.code).toBe("fetch_failed");
427+
expect(err).toBe(requestSignal?.reason);
428+
expect(requestSignal?.aborted).toBe(true);
429+
expect(stalledResponse?.body?.locked).toBe(false);
402430
expect(isRetryableLineInboundMediaError(err)).toBe(true);
431+
432+
const healthy = Buffer.from("healthy retry");
433+
fetchMock.mockResolvedValueOnce(responseWithChunks(200, [healthy]));
434+
await expect(downloadLineMedia("mid-body-stall", "token")).resolves.toMatchObject({
435+
size: healthy.length,
436+
});
403437
});
404438

405439
it("raises a non-retryable MediaFetchError for a permanent HTTP error", async () => {

‎extensions/line/src/download.ts‎

Lines changed: 55 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ interface DownloadResult {
1616
const CONTENT_READY_MAX_ATTEMPTS = 6;
1717
const CONTENT_READY_BASE_DELAY_MS = 500;
1818
const CONTENT_READY_MAX_DELAY_MS = 4000;
19-
const CONTENT_READY_TIMEOUT_MS = 15_000;
19+
const CONTENT_DOWNLOAD_TIMEOUT_MS = 15_000;
2020
const LINE_CONTENT_BASE_URL = "https://api-data.line.me/v2/bot/message";
2121

2222
class RetryableLineMediaFetchError extends MediaFetchError {
@@ -37,6 +37,8 @@ function lineContentUrl(messageId: string): string {
3737
async function* lineResponseBodyChunks(
3838
response: Response,
3939
messageId: string,
40+
signal: AbortSignal,
41+
onComplete: () => void,
4042
): AsyncIterable<Uint8Array> {
4143
const body = response.body;
4244
if (!body) {
@@ -52,13 +54,17 @@ async function* lineResponseBodyChunks(
5254
try {
5355
chunk = await reader.read();
5456
} catch (err) {
57+
if (signal.aborted) {
58+
throw signal.reason;
59+
}
5560
throw new RetryableLineMediaFetchError(
5661
`LINE media response stream failed for message ${messageId}`,
5762
{ cause: err },
5863
);
5964
}
6065
if (chunk.done) {
6166
completed = true;
67+
onComplete();
6268
return;
6369
}
6470
if (chunk.value.byteLength > 0) {
@@ -67,7 +73,7 @@ async function* lineResponseBodyChunks(
6773
}
6874
} finally {
6975
if (!completed) {
70-
await reader.cancel().catch(() => undefined);
76+
await reader.cancel(signal.aborted ? signal.reason : undefined).catch(() => undefined);
7177
}
7278
try {
7379
reader.releaseLock();
@@ -78,16 +84,14 @@ async function* lineResponseBodyChunks(
7884
async function fetchLineContentWhenReady(
7985
messageId: string,
8086
channelAccessToken: string,
87+
signal: AbortSignal,
8188
): Promise<Response> {
82-
const controller = new AbortController();
83-
const deadline = setTimeout(() => controller.abort(), CONTENT_READY_TIMEOUT_MS);
84-
deadline.unref();
8589
try {
8690
for (let attempt = 0; attempt < CONTENT_READY_MAX_ATTEMPTS; attempt++) {
8791
const response = await fetchWithRuntimeDispatcherOrMockedGlobal(lineContentUrl(messageId), {
8892
headers: { Authorization: `Bearer ${channelAccessToken}` },
8993
redirect: "error",
90-
signal: controller.signal,
94+
signal,
9195
});
9296
if (response.status === 200) {
9397
if (!response.body) {
@@ -107,24 +111,19 @@ async function fetchLineContentWhenReady(
107111
);
108112
}
109113
if (attempt < CONTENT_READY_MAX_ATTEMPTS - 1) {
110-
await delay(contentBackoffDelayMs(attempt), undefined, { signal: controller.signal });
114+
await delay(contentBackoffDelayMs(attempt), undefined, { signal });
111115
}
112116
}
113117
} catch (err) {
114-
if (controller.signal.aborted) {
115-
throw new RetryableLineMediaFetchError(
116-
`LINE media for message ${messageId} did not become ready within ${CONTENT_READY_TIMEOUT_MS / 1000} seconds`,
117-
{ cause: err },
118-
);
118+
if (signal.aborted) {
119+
throw signal.reason;
119120
}
120121
if (err instanceof MediaFetchError) {
121122
throw err;
122123
}
123124
throw new RetryableLineMediaFetchError(`LINE media download failed for message ${messageId}`, {
124125
cause: err,
125126
});
126-
} finally {
127-
clearTimeout(deadline);
128127
}
129128

130129
throw new MediaFetchError(
@@ -160,27 +159,49 @@ export async function downloadLineMedia(
160159
messageId: string,
161160
channelAccessToken: string,
162161
maxBytes = 10 * 1024 * 1024,
163-
options?: { originalFilename?: string },
162+
options?: { originalFilename?: string; signal?: AbortSignal },
164163
): Promise<DownloadResult> {
165-
const response = await fetchLineContentWhenReady(messageId, channelAccessToken);
166-
let saved: Awaited<ReturnType<typeof saveMediaStream>>;
167-
try {
168-
saved = await saveMediaStream(
169-
lineResponseBodyChunks(response, messageId),
170-
response.headers.get("content-type") ?? undefined,
171-
"inbound",
172-
maxBytes,
173-
options?.originalFilename,
164+
options?.signal?.throwIfAborted();
165+
const deadlineAbort = new AbortController();
166+
const signal = options?.signal
167+
? AbortSignal.any([options.signal, deadlineAbort.signal])
168+
: deadlineAbort.signal;
169+
// Header resolution does not finish the request; only EOF retires this deadline.
170+
const deadline = setTimeout(() => {
171+
deadlineAbort.abort(
172+
new RetryableLineMediaFetchError(
173+
`LINE media for message ${messageId} did not download within ${CONTENT_DOWNLOAD_TIMEOUT_MS / 1000} seconds`,
174+
),
174175
);
175-
} catch (err) {
176-
await response.body?.cancel().catch(() => undefined);
177-
throw err;
178-
}
179-
logVerbose(`line: persisted media ${messageId} to ${saved.path} (${saved.size} bytes)`);
176+
}, CONTENT_DOWNLOAD_TIMEOUT_MS);
177+
deadline.unref();
178+
try {
179+
const response = await fetchLineContentWhenReady(messageId, channelAccessToken, signal);
180+
let saved: Awaited<ReturnType<typeof saveMediaStream>>;
181+
try {
182+
saved = await saveMediaStream(
183+
lineResponseBodyChunks(response, messageId, signal, () => clearTimeout(deadline)),
184+
response.headers.get("content-type") ?? undefined,
185+
"inbound",
186+
maxBytes,
187+
options?.originalFilename,
188+
);
189+
} catch (err) {
190+
await response.body?.cancel(signal.aborted ? signal.reason : err).catch(() => undefined);
191+
if (signal.aborted) {
192+
throw signal.reason;
193+
}
194+
throw err;
195+
}
196+
options?.signal?.throwIfAborted();
197+
logVerbose(`line: persisted media ${messageId} to ${saved.path} (${saved.size} bytes)`);
180198

181-
return {
182-
path: saved.path,
183-
contentType: saved.contentType,
184-
size: saved.size,
185-
};
199+
return {
200+
path: saved.path,
201+
contentType: saved.contentType,
202+
size: saved.size,
203+
};
204+
} finally {
205+
clearTimeout(deadline);
206+
}
186207
}

0 commit comments

Comments
 (0)