Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions packages/commands/src/commands/speech/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -531,9 +531,28 @@ export default defineCommand({
);
}

await downloadFile(audioUrl, destPath, {
quiet: settings.quiet || settings.output === "json",
});
try {
await downloadFile(audioUrl, destPath, {
quiet: settings.quiet || settings.output === "json",
});
} catch (error) {
const originalMessage = error instanceof Error ? error.message : String(error);
const exitCode = error instanceof BailianError ? error.exitCode : ExitCode.GENERAL;
const requestId = response.request_id?.trim();
// Keep the signed URL in hint only — telemetry records message / api.requestId, not hint.
throw new BailianError(
requestId ? `${originalMessage} request_id=${requestId}` : originalMessage,
exitCode,
ctx.localize({
"en-US": `Audio was generated successfully. Re-download from: ${audioUrl}; do not regenerate.`,
"zh-CN": `音频已生成成功。请从以下地址重新下载,勿重新生成:${audioUrl}`,
}),
{
cause: error,
...(requestId ? { api: { requestId } } : {}),
},
);
}

const result = {
...response,
Expand Down
68 changes: 68 additions & 0 deletions packages/commands/tests/e2e/speech-generate.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,74 @@ describe("e2e: speech generate dry-run / mock HTTP", () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});

test("download HTTP failure keeps request_id and audio URL", async () => {
let synthesizePosts = 0;
const server = createServer((incoming, outgoing) => {
const url = incoming.url ?? "";
if (url.startsWith("/api/v1/services/audio/tts/SpeechSynthesizer")) {
synthesizePosts += 1;
const address = server.address() as AddressInfo;
outgoing.writeHead(200, { "Content-Type": "application/json" });
outgoing.end(
JSON.stringify({
output: {
audio: {
url: `http://127.0.0.1:${address.port}/audio.wav`,
data: "",
id: "audio-1",
expires_at: "2099-01-01T00:00:00Z",
duration: 1.5,
},
},
usage: { characters: 10 },
request_id: "req-gen-dl-fail",
}),
);
return;
}
if (url.startsWith("/audio.wav")) {
outgoing.writeHead(403, { "Content-Type": "text/plain" });
outgoing.end("forbidden");
return;
}
outgoing.writeHead(404);
outgoing.end();
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address() as AddressInfo;
const outDir = makeE2eOutputDir("speech-generate-dl-fail");

try {
const failed = await runCommandInProcess(SPEECH_GENERATE_ROUTES, [
"speech",
"generate",
"--text-prompt",
"短播客",
"--base-url",
`http://127.0.0.1:${address.port}`,
"--api-key",
"sk-e2e",
"--out-dir",
outDir,
"--out-prefix",
"sample",
"--quiet",
]);
expect(failed.exitCode).not.toBe(0);
expect(synthesizePosts).toBe(1);
expect(failed.stderr).toMatch(/Download failed: HTTP 403/);
expect(failed.stderr).toMatch(/request_id=req-gen-dl-fail/);
// Signed URL stays in the hint (CLI recovery), not as message `url=` for telemetry.
expect(failed.stderr).toMatch(
new RegExp(`http://127\\.0\\.0\\.1:${address.port}/audio\\.wav`),
);
expect(failed.stderr).not.toMatch(/url=http:\/\//);
expect(failed.stderr).toMatch(/do not regenerate|勿重新生成/i);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
});

describe.skipIf(!isSpeechGenerateE2EReady())("e2e: speech generate (live)", () => {
Expand Down
179 changes: 54 additions & 125 deletions packages/runtime/src/utils/download.ts
Original file line number Diff line number Diff line change
@@ -1,165 +1,94 @@
import { httpTransport } from "bailian-cli-core";
import { BailianError, ExitCode, httpTransport } from "bailian-cli-core";
import { randomUUID } from "node:crypto";
import {
chmodSync,
copyFileSync,
createWriteStream,
existsSync,
lstatSync,
mkdirSync,
openSync,
realpathSync,
renameSync,
statSync,
unlinkSync,
} from "fs";
import { basename, dirname, join } from "path";
import { BailianError, ExitCode } from "bailian-cli-core";
import { dirname, join } from "path";
import { pipeline } from "node:stream/promises";
import { createProgressBar } from "../output/progress.ts";
import type { ReadableStreamReadResult } from "stream/web";

function errnoCode(error: unknown): string | undefined {
if (error !== null && typeof error === "object" && "code" in error) {
return (error as NodeJS.ErrnoException).code;
}
return undefined;
}

/**
* Publish temp over dest without unlinking dest first.
* Existing dest is moved aside and restored if publish fails.
*/
function publishDownloadedFile(
tempPath: string,
destPath: string,
preserveMode: number | undefined,
): void {
if (!existsSync(destPath)) {
renameSync(tempPath, destPath);
return;
}

const backupPath = join(
dirname(destPath),
`.${basename(destPath)}.${process.pid}.${Date.now()}.bak`,
);
renameSync(destPath, backupPath);

function resolveDownloadTarget(destPath: string): { path: string; mode?: number } {
let entry;
try {
try {
renameSync(tempPath, destPath);
} catch (renameError) {
const code = errnoCode(renameError);
// Windows cannot rename onto an existing name; EXDEV needs a copy.
// Never unlink dest first — backup already holds the previous bytes.
if (code === "EEXIST" || code === "EPERM" || code === "EXDEV") {
copyFileSync(tempPath, destPath);
try {
unlinkSync(tempPath);
} catch {
/* best effort */
}
} else {
throw renameError;
}
}

if (preserveMode !== undefined) {
chmodSync(destPath, preserveMode);
}
unlinkSync(backupPath);
entry = lstatSync(destPath);
} catch (error) {
try {
if (existsSync(destPath)) unlinkSync(destPath);
} catch {
/* best effort */
}
try {
renameSync(backupPath, destPath);
} catch {
/* best effort */
}
if ((error as NodeJS.ErrnoException).code === "ENOENT") return { path: destPath };
throw error;
}

// Keep the link itself intact. A dangling link must fail instead of guessing a target.
const targetPath = realpathSync.native(destPath);
const stats = entry.isSymbolicLink() ? statSync(targetPath) : entry;
if (!stats.isFile()) {
throw new BailianError(
`Download destination must be a regular file: ${targetPath}`,
ExitCode.USAGE,
);
}
return { path: targetPath, mode: stats.mode & 0o7777 };
}

export async function downloadFile(
url: string,
destPath: string,
opts?: { quiet?: boolean },
): Promise<{ size: number }> {
const target = resolveDownloadTarget(destPath);
const res = await httpTransport.fetch(url);

if (!res.ok) {
throw new BailianError(`Download failed: HTTP ${res.status}`, ExitCode.GENERAL);
}
const body = res.body;
if (!body) throw new BailianError("No response body", ExitCode.GENERAL);

const targetDir = dirname(target.path);
mkdirSync(targetDir, { recursive: true });
const tempPath = join(realpathSync.native(targetDir), `.download-${randomUUID()}.part`);
const descriptor = openSync(tempPath, "wx", target.mode);
const contentLength = Number(res.headers.get("content-length") || 0);
const reader = res.body?.getReader();
if (!reader) throw new BailianError("No response body", ExitCode.GENERAL);

mkdirSync(dirname(destPath), { recursive: true });

let preserveMode: number | undefined;
try {
preserveMode = statSync(destPath).mode & 0o7777;
} catch {
// Destination does not exist yet.
}

// Same-directory temp so rename stays on one filesystem; never truncate dest until publish.
const tempPath = join(
dirname(destPath),
`.${basename(destPath)}.${process.pid}.${Date.now()}.part`,
);
const writer = createWriteStream(tempPath);
const progress =
contentLength > 0 && !opts?.quiet ? createProgressBar(contentLength, "Downloading") : null;

let received = 0;
let completed = false;

try {
const writeError = new Promise<never>((_, reject) => {
writer.on("error", reject);
});

while (true) {
const { done, value } = (await Promise.race([
reader.read(),
writeError,
])) as ReadableStreamReadResult<Uint8Array>;
if (done) break;

const ok = writer.write(value);
if (!ok) await new Promise<void>((resolve) => writer.once("drain", () => resolve()));

received += value.byteLength;
progress?.update(received);
}
completed = true;
} finally {
reader.releaseLock();
progress?.finish();

await new Promise<void>((resolve, reject) => {
writer.on("finish", resolve);
writer.on("error", reject);
writer.end();
});

if (!completed) {
try {
unlinkSync(tempPath);
} catch {
/* best effort */
}
}
}

try {
publishDownloadedFile(tempPath, destPath, preserveMode);
await pipeline(
async function* ({ signal }: { signal?: AbortSignal } = {}) {
const reader = body.getReader();
const cancel = () => {
void reader.cancel(signal?.reason).catch(() => {});
};
signal?.addEventListener("abort", cancel, { once: true });
try {
for (;;) {
const { done, value } = await reader.read();
if (done) return;
received += value.byteLength;
progress?.update(received);
yield value;
}
} finally {
signal?.removeEventListener("abort", cancel);
reader.releaseLock();
}
},
createWriteStream(tempPath, { fd: descriptor }),
).finally(() => progress?.finish());
if (target.mode !== undefined) chmodSync(tempPath, target.mode);
renameSync(tempPath, target.path);
} catch (error) {
try {
unlinkSync(tempPath);
} catch {
/* best effort */
// Best-effort cleanup of the temporary file.
}
throw error;
}
Expand Down
Loading