108 lines
4.0 KiB
TypeScript
108 lines
4.0 KiB
TypeScript
import { nodeReadableToWebStream } from '@/lib/node-readable-stream'
|
|
import archiver from 'archiver'
|
|
import { Readable } from 'node:stream'
|
|
import { createArchiveDownloadStream } from '@/lib/archive-download-stream'
|
|
|
|
export const MAX_ACTIVE_EXTERNAL_ZIPS = 4
|
|
export const MAX_EXTERNAL_ZIP_ENTRIES = 1000
|
|
export const MAX_EXTERNAL_ZIP_BYTES = 2 * 1024 * 1024 * 1024
|
|
let activeArchives = 0
|
|
|
|
export class ExternalZipBusyError extends Error {}
|
|
export class ExternalZipTooLargeError extends Error {}
|
|
export class ExternalZipSourceError extends Error {}
|
|
|
|
type ZipEntry = { name: string; size?: number; open: (signal: AbortSignal) => Promise<Readable> }
|
|
|
|
export async function streamExternalZip(entries: ZipEntry[], requestSignal?: AbortSignal, prime = false) {
|
|
if (entries.length > MAX_EXTERNAL_ZIP_ENTRIES) throw new ExternalZipTooLargeError()
|
|
let declaredBytes = 0
|
|
for (const entry of entries) {
|
|
if (typeof entry.size === 'number' && Number.isFinite(entry.size) && entry.size > 0) {
|
|
declaredBytes += entry.size
|
|
if (declaredBytes > MAX_EXTERNAL_ZIP_BYTES) throw new ExternalZipTooLargeError()
|
|
}
|
|
}
|
|
if (activeArchives >= MAX_ACTIVE_EXTERNAL_ZIPS) throw new ExternalZipBusyError()
|
|
const archive = archiver('zip', { zlib: { level: 5 }, highWaterMark: 64 * 1024 })
|
|
const download = createArchiveDownloadStream(archive)
|
|
const controller = new AbortController()
|
|
const signal = requestSignal ? AbortSignal.any([requestSignal, controller.signal]) : controller.signal
|
|
activeArchives++
|
|
let released = false
|
|
let streamedBytes = 0
|
|
const release = () => {
|
|
if (released) return
|
|
released = true
|
|
activeArchives--
|
|
controller.abort()
|
|
requestSignal?.removeEventListener('abort', cancel)
|
|
}
|
|
const cancel = () => {
|
|
controller.abort()
|
|
download.abort()
|
|
}
|
|
archive.once('end', release)
|
|
archive.once('close', release)
|
|
requestSignal?.addEventListener('abort', cancel, { once: true })
|
|
const stream = nodeReadableToWebStream(archive, { onCancel: cancel })
|
|
const remaining = entries[Symbol.iterator]()
|
|
let initial: { entry: ZipEntry; file: Readable } | undefined
|
|
const appendNext = () => {
|
|
if (signal.aborted || archive.destroyed) return
|
|
const first = initial
|
|
initial = undefined
|
|
const next = first ? { done: false as const, value: first.entry } : remaining.next()
|
|
if (next.done) {
|
|
void archive.finalize().catch(error => archive.destroy(error))
|
|
return
|
|
}
|
|
const entry = next.value
|
|
const source = Readable.from((async function* () {
|
|
signal.throwIfAborted()
|
|
const file = first?.file ?? await entry.open(signal)
|
|
try {
|
|
signal.throwIfAborted()
|
|
for await (const chunk of file) {
|
|
signal.throwIfAborted()
|
|
streamedBytes += Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(String(chunk))
|
|
if (streamedBytes > MAX_EXTERNAL_ZIP_BYTES) {
|
|
throw new ExternalZipTooLargeError()
|
|
}
|
|
yield chunk
|
|
}
|
|
} finally {
|
|
file.destroy()
|
|
}
|
|
})(), { objectMode: false, highWaterMark: 64 * 1024 })
|
|
// Archiver starts buffering appended streams immediately. Append the next entry only after completion.
|
|
archive.append(download.trackSource(source), { name: entry.name, date: new Date('1980-01-01T00:00:00Z') })
|
|
}
|
|
archive.on('entry', appendNext)
|
|
archive.on('warning', error => archive.destroy(error))
|
|
archive.once('error', cancel)
|
|
try {
|
|
signal.throwIfAborted()
|
|
if (prime) {
|
|
const first = remaining.next()
|
|
if (!first.done) {
|
|
try {
|
|
const file = await first.value.open(signal)
|
|
if (signal.aborted) file.destroy()
|
|
signal.throwIfAborted()
|
|
initial = { entry: first.value, file: download.trackSource(file) }
|
|
} catch (error) {
|
|
signal.throwIfAborted()
|
|
throw new ExternalZipSourceError('ZIP 资源不可用', { cause: error })
|
|
}
|
|
}
|
|
}
|
|
appendNext()
|
|
return stream
|
|
} catch (error) {
|
|
cancel()
|
|
release()
|
|
throw error
|
|
}
|
|
}
|