fix: bulk download streaming reliability
This commit is contained in:
1 parent
d9d69ed861
commit
8dd1e10fea
1 file changed
+21
-44
@@ -7,7 +7,7 @@ import { albumGrantService } from "@/modules/albums/grants";
|
|||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-explicit-any
|
||||||
const archiver: any = require("archiver");
|
const archiver: any = require("archiver");
|
||||||
import * as crypto from "crypto";
|
import * as crypto from "crypto";
|
||||||
import { Readable } from "stream";
|
import { Readable, PassThrough } from "stream";
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
@@ -90,15 +90,9 @@ export async function POST(request: NextRequest) {
|
|||||||
return new Response("No valid assets found for download", { status: 404 });
|
return new Response("No valid assets found for download", { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create a streaming response with archiver
|
const passThrough = new PassThrough();
|
||||||
const archive = archiver('zip', { zlib: { level: 0 } }); // No compression, images are already compressed
|
const archive = archiver('zip', { zlib: { level: 0 } });
|
||||||
|
archive.pipe(passThrough);
|
||||||
// We must return a ReadableStream to Next.js
|
|
||||||
const transformStream = new TransformStream();
|
|
||||||
|
|
||||||
// Pipe archiver output to the writable side of the TransformStream
|
|
||||||
const writableNodeStream = new WritableStreamToNodeStream(transformStream.writable);
|
|
||||||
archive.pipe(writableNodeStream);
|
|
||||||
|
|
||||||
// Start appending files asynchronously
|
// Start appending files asynchronously
|
||||||
(async () => {
|
(async () => {
|
||||||
@@ -111,22 +105,24 @@ export async function POST(request: NextRequest) {
|
|||||||
try {
|
try {
|
||||||
const original = await immichClient.getOriginal(download.assetId);
|
const original = await immichClient.getOriginal(download.assetId);
|
||||||
|
|
||||||
// Track bytes read for accounting
|
await new Promise<void>((resolve, reject) => {
|
||||||
let transferredBytes = 0;
|
const nodeStream = Readable.fromWeb(original.body as any);
|
||||||
const trackingTransform = new TransformStream({
|
let transferredBytes = 0;
|
||||||
transform(chunk, controller) {
|
|
||||||
|
nodeStream.on('data', (chunk) => {
|
||||||
transferredBytes += chunk.length;
|
transferredBytes += chunk.length;
|
||||||
controller.enqueue(chunk);
|
});
|
||||||
},
|
|
||||||
async flush() {
|
nodeStream.on('end', () => {
|
||||||
await downloadDeliveryRepository.markCompleted(download.downloadId, transferredBytes);
|
downloadDeliveryRepository.markCompleted(download.downloadId, transferredBytes)
|
||||||
}
|
.then(() => resolve())
|
||||||
|
.catch(reject);
|
||||||
|
});
|
||||||
|
|
||||||
|
nodeStream.on('error', (err) => reject(err));
|
||||||
|
|
||||||
|
archive.append(nodeStream, { name: download.filename });
|
||||||
});
|
});
|
||||||
|
|
||||||
const trackedStream = original.body.pipeThrough(trackingTransform);
|
|
||||||
const nodeStream = Readable.fromWeb(trackedStream as any);
|
|
||||||
|
|
||||||
archive.append(nodeStream, { name: download.filename });
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to append original for asset", download.assetId, err);
|
console.error("Failed to append original for asset", download.assetId, err);
|
||||||
await downloadDeliveryRepository.failBeforeDelivery(download.downloadId, {
|
await downloadDeliveryRepository.failBeforeDelivery(download.downloadId, {
|
||||||
@@ -143,7 +139,7 @@ export async function POST(request: NextRequest) {
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
const date = new Date().toISOString().split('T')[0];
|
const date = new Date().toISOString().split('T')[0];
|
||||||
return new Response(transformStream.readable, {
|
return new Response(Readable.toWeb(passThrough) as any, {
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/zip",
|
"Content-Type": "application/zip",
|
||||||
"Content-Disposition": `attachment; filename="leuchtkasten-${date}.zip"`,
|
"Content-Disposition": `attachment; filename="leuchtkasten-${date}.zip"`,
|
||||||
@@ -155,22 +151,3 @@ export async function POST(request: NextRequest) {
|
|||||||
return new Response("Internal Server Error", { status: 500 });
|
return new Response("Internal Server Error", { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper to convert Web WritableStream to Node Writable Stream
|
|
||||||
import { Writable } from "stream";
|
|
||||||
class WritableStreamToNodeStream extends Writable {
|
|
||||||
private writer: WritableStreamDefaultWriter<any>;
|
|
||||||
|
|
||||||
constructor(writableStream: WritableStream) {
|
|
||||||
super();
|
|
||||||
this.writer = writableStream.getWriter();
|
|
||||||
}
|
|
||||||
|
|
||||||
_write(chunk: any, encoding: string, callback: (error?: Error | null) => void) {
|
|
||||||
this.writer.write(chunk).then(() => callback()).catch(callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
_final(callback: (error?: Error | null) => void) {
|
|
||||||
this.writer.close().then(() => callback()).catch(callback);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user