Skip to content

Commit 2134cd6

Browse files
committed
fix(video-generation): release failed DashScope downloads
1 parent 4ac19a4 commit 2134cd6

2 files changed

Lines changed: 65 additions & 72 deletions

File tree

‎src/video-generation/dashscope-compatible.test.ts‎

Lines changed: 40 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
// DashScope-compatible download regressions: body idle after headers.
2-
import { once } from "node:events";
3-
import http from "node:http";
4-
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { describe, expect, it, vi } from "vitest";
53
import { downloadDashscopeGeneratedVideos } from "./dashscope-compatible.js";
64

75
function neverChunkingVideoResponse(): Response {
@@ -100,56 +98,46 @@ describe("downloadDashscopeGeneratedVideos", () => {
10098
// Exhausted deadline is checked before fetch — no network I/O is initiated.
10199
expect(fetchFn).not.toHaveBeenCalled();
102100
});
103-
});
104-
105-
describe("downloadDashscopeGeneratedVideos loopback HTTP", () => {
106-
let server: http.Server | undefined;
107101

108-
afterEach(async () => {
109-
if (!server) {
110-
return;
102+
it("releases the guarded fetch when the remaining-budget resolver throws", async () => {
103+
vi.useFakeTimers();
104+
try {
105+
let requestSignal: AbortSignal | undefined;
106+
const cancelBody = vi.fn();
107+
const timeoutMs = vi
108+
.fn<() => number>()
109+
.mockReturnValueOnce(100)
110+
.mockImplementationOnce(() => {
111+
throw new Error("remaining-budget resolver failed");
112+
});
113+
const fetchFn = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
114+
requestSignal = init?.signal ?? undefined;
115+
return new Response(new ReadableStream({ cancel: cancelBody }), {
116+
status: 200,
117+
headers: { "content-type": "video/mp4" },
118+
});
119+
});
120+
121+
await expect(
122+
downloadDashscopeGeneratedVideos({
123+
providerLabel: "Alibaba Wan",
124+
urls: ["https://example.com/out.mp4"],
125+
timeoutMs,
126+
fetchFn: fetchFn as typeof fetch,
127+
maxBytes: 10 * 1024 * 1024,
128+
}),
129+
).rejects.toThrow("remaining-budget resolver failed");
130+
131+
expect(timeoutMs).toHaveBeenCalledTimes(2);
132+
expect(cancelBody).toHaveBeenCalledOnce();
133+
expect(cancelBody.mock.calls[0]?.[0]).toMatchObject({
134+
message: "remaining-budget resolver failed",
135+
});
136+
expect(requestSignal?.aborted).toBe(false);
137+
await vi.advanceTimersByTimeAsync(100);
138+
expect(requestSignal?.aborted).toBe(false);
139+
} finally {
140+
vi.useRealTimers();
111141
}
112-
server.closeAllConnections?.();
113-
server.close();
114-
await once(server, "close").catch(() => undefined);
115-
server = undefined;
116-
});
117-
118-
it("bounds a stalled loopback HTTP body with a real server", async () => {
119-
server = http.createServer((_req, res) => {
120-
res.writeHead(200, { "content-type": "video/mp4" });
121-
// Write one chunk so fetch resolves (Node fetch hangs until first body byte).
122-
// Then never write more — simulates stalled CDN.
123-
res.write("first-chunk");
124-
});
125-
server.on("clientError", (_err, socket) => socket.destroy());
126-
server.listen(0, "127.0.0.1");
127-
await once(server, "listening");
128-
const address = server.address();
129-
if (!address || typeof address === "string") {
130-
throw new Error("expected loopback server address");
131-
}
132-
const port = address.port;
133-
134-
const timeoutMs = 200;
135-
const startedAt = Date.now();
136-
137-
// Accept either error because the fetch-level AbortSignal timeout and
138-
// the post-header chunk-idle timeout race; both are bounded within the
139-
// configured budget.
140-
await expect(
141-
downloadDashscopeGeneratedVideos({
142-
providerLabel: "Alibaba Wan",
143-
urls: [`http://127.0.0.1:${port}/out.mp4`],
144-
timeoutMs,
145-
fetchFn: fetch,
146-
allowPrivateNetwork: true,
147-
maxBytes: 10 * 1024 * 1024,
148-
}),
149-
).rejects.toThrow();
150-
151-
const elapsedMs = Date.now() - startedAt;
152-
// Bounded proof: the download rejects within 5s, not an indefinite hang.
153-
expect(elapsedMs).toBeLessThan(5_000);
154142
});
155143
});

‎src/video-generation/dashscope-compatible.ts‎

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -344,23 +344,25 @@ export async function runDashscopeVideoGenerationTask(params: {
344344
}
345345

346346
function resolveDashscopeVideoDownloadTimeoutMs(
347+
providerLabel: string,
347348
timeoutMs: ProviderOperationTimeoutMs | undefined,
348349
defaultTimeoutMs: number | undefined,
349350
): number {
350351
const resolved = typeof timeoutMs === "function" ? timeoutMs() : timeoutMs;
351-
if (typeof resolved === "number" && Number.isFinite(resolved)) {
352-
// Preserve exhausted budgets (0 or negative) so a function-valued remaining
353-
// deadline that the header fetch consumed fails closed instead of getting
354-
// reset to the full default timeout.
355-
return Math.max(0, Math.floor(resolved));
352+
const downloadTimeoutMs =
353+
typeof resolved === "number" && Number.isFinite(resolved)
354+
? Math.max(0, Math.floor(resolved))
355+
: (defaultTimeoutMs ?? DEFAULT_VIDEO_GENERATION_TIMEOUT_MS);
356+
if (downloadTimeoutMs <= 0) {
357+
throw new Error(
358+
`${providerLabel} generated video download stalled: remaining budget exhausted`,
359+
);
356360
}
357-
return defaultTimeoutMs ?? DEFAULT_VIDEO_GENERATION_TIMEOUT_MS;
361+
return downloadTimeoutMs;
358362
}
359363

360364
// Downloads task result URLs into generated video assets. The byte limit comes
361365
// from OpenClaw media config so provider URLs cannot overfill memory.
362-
// chunkTimeoutMs is required after headers: fetchWithTimeoutGuarded clears its
363-
// abort once the response arrives, so a dripping CDN body would hang forever.
364366
export async function downloadDashscopeGeneratedVideos(params: {
365367
providerLabel: string;
366368
urls: string[];
@@ -378,16 +380,10 @@ export async function downloadDashscopeGeneratedVideos(params: {
378380
stage: "download",
379381
operation: async () => {
380382
const downloadTimeoutMs = resolveDashscopeVideoDownloadTimeoutMs(
383+
params.providerLabel,
381384
params.timeoutMs,
382385
params.defaultTimeoutMs,
383386
);
384-
// Reject a non-positive remaining budget before starting fetch so an
385-
// already-exhausted operation does not initiate network I/O.
386-
if (downloadTimeoutMs <= 0) {
387-
throw new Error(
388-
`${params.providerLabel} generated video download stalled: remaining budget exhausted`,
389-
);
390-
}
391387
const guarded = await fetchWithTimeoutGuarded(
392388
url,
393389
{ method: "GET" },
@@ -410,14 +406,23 @@ export async function downloadDashscopeGeneratedVideos(params: {
410406
}
411407
},
412408
});
413-
// Resolve after headers so a function timeout still sees remaining budget.
414-
const downloadTimeoutMs = resolveDashscopeVideoDownloadTimeoutMs(
415-
params.timeoutMs,
416-
params.defaultTimeoutMs,
417-
);
418409
let buffer: Buffer;
419410
let mimeType: string;
420411
try {
412+
// Re-resolve after headers so the body uses the remaining operation budget.
413+
let downloadTimeoutMs: number;
414+
try {
415+
downloadTimeoutMs = resolveDashscopeVideoDownloadTimeoutMs(
416+
params.providerLabel,
417+
params.timeoutMs,
418+
params.defaultTimeoutMs,
419+
);
420+
} catch (error) {
421+
// The body reader normally owns cancellation. If deadline resolution
422+
// fails first, cancel here before release clears the guarded abort.
423+
await result.response.body?.cancel(error).catch(() => undefined);
424+
throw error;
425+
}
421426
buffer = await readResponseWithLimit(result.response, params.maxBytes, {
422427
chunkTimeoutMs: downloadTimeoutMs,
423428
onOverflow: ({ maxBytes }) =>

0 commit comments

Comments
 (0)