gongxiangp2/lib/external-zip-stream.ts

89 lines
3.2 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
let activeArchives = 0
export class ExternalZipBusyError extends Error {}
export class ExternalZipTooLargeError extends Error {}
export class ExternalZipSourceError extends Error {}
type ZipEntry = { name: string; 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()
if (activeArchives >= MAX_ACTIVE_EXTERNAL_ZIPS) throw new ExternalZipBusyError()
const archive = archiver('zip', { zlib: { level: 5 } })
const download = createArchiveDownloadStream(archive)
const controller = new AbortController()
const signal = requestSignal ? AbortSignal.any([requestSignal, controller.signal]) : controller.signal
activeArchives++
let released = false
const release = () => {
if (released) return
released = true
activeArchives--
controller.abort()
requestSignal?.removeEventListener('abort', cancel)
}
const cancel = () => 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()
yield* file
} 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
}
}