@adonis-agora/media
Version:
Media-library for AdonisJS — owner collections (MIME whitelist, single-file replace, ordering), image conversions (eager/lazy), pluggable content transformers (HLS video via mediabunny, metadata probe, image blur-up placeholder), and column attachments, a
204 lines • 8.91 kB
JavaScript
import { randomUUID } from 'node:crypto';
import { Readable } from 'node:stream';
import { publishMedia } from './diagnostics.js';
import { UploadNotSupportedError, UploadOffsetConflictError, UploadSessionExpiredError, UploadSessionNotFoundError, } from './errors.js';
import { isMultipartCapable } from './multipart.js';
/**
* Framework-agnostic resumable-upload engine — the storage core the TUS HTTP handler drives. Bytes
* flow through the backend in chunks; each chunk is written immediately as a part on the target disk
* (native S3 multipart when available, else a buffered part object), so a dropped connection resumes
* from `offset` without re-sending. {@link complete} assembles the parts into the final object.
*
* This never imports AdonisJS; the provider exposes it over TUS routes and {@link MediaManager}
* surfaces it as `media.resumable`.
*/
export class ResumableUploadManager {
storage;
sessions;
tmpPrefix;
ttlSeconds;
newId;
now;
emitDiagnostics;
constructor(options) {
this.storage = options.storage;
this.sessions = options.sessions;
this.tmpPrefix = options.tmpPrefix ?? '.uploads';
this.ttlSeconds = options.sessionTtlSeconds;
this.newId = options.idGenerator ?? (() => randomUUID());
this.now = options.clock ?? (() => new Date());
this.emitDiagnostics = options.emitDiagnostics ?? true;
}
partKey(session, part) {
return `${this.tmpPrefix}/${session.id}/${part}`;
}
/** Begin a resumable upload session and reserve any native multipart upload the disk supports. */
async createUpload(input) {
const disk = this.storage.disk(input.disk);
const multipart = isMultipartCapable(disk)
? {
multipartUploadId: (await disk.createMultipartUpload(input.key, input.contentType ? { contentType: input.contentType } : undefined)).uploadId,
}
: {};
const createdAt = this.now();
const session = await this.sessions.create({
id: this.newId(),
disk: input.disk,
key: input.key,
contentType: input.contentType,
size: input.size,
offset: 0,
parts: 0,
createdAt,
...(this.ttlSeconds !== undefined
? { expiresAt: new Date(createdAt.getTime() + this.ttlSeconds * 1000) }
: {}),
...(input.metadata !== undefined ? { metadata: input.metadata } : {}),
...multipart,
});
this.emit('upload.start', {
id: session.id,
disk: session.disk,
key: session.key,
mode: 'proxy',
size: session.size,
contentType: session.contentType,
});
return session;
}
/** Append a chunk at `offset` (must equal the session's current offset). Returns the new offset. */
async writeChunk(id, offset, chunk) {
const session = await this.require(id);
if (offset !== session.offset) {
throw new UploadOffsetConflictError(session.offset, offset);
}
const disk = this.storage.disk(session.disk);
if (session.multipartUploadId && isMultipartCapable(disk)) {
if (typeof this.sessions.addPart !== 'function') {
throw new UploadNotSupportedError(session.disk, 'resumable multipart part recording');
}
const part = await disk.uploadPart(session.key, session.multipartUploadId, session.parts + 1, chunk);
await this.sessions.addPart(id, part);
}
else {
await disk.put(this.partKey(session, session.parts), chunk);
}
session.parts += 1;
session.offset += chunk.byteLength;
await this.sessions.update(session);
this.emit('upload.progress', {
id: session.id,
offset: session.offset,
parts: session.parts,
size: session.size,
});
return { offset: session.offset };
}
/**
* Current offset, declared size, declared content type, and expiry for a session (drives the TUS
* `HEAD` response). `contentType` is what the client DECLARED at creation (TUS `Upload-Metadata`'s
* `filetype`) — nothing here proves it; the TUS handler checks it against the real bytes.
*/
async status(id) {
const session = await this.require(id);
return {
offset: session.offset,
size: session.size,
contentType: session.contentType,
expiresAt: session.expiresAt,
};
}
/** Assemble all parts into the final object, clean up, and return the final key/disk/size. */
async complete(id) {
const session = await this.require(id);
const disk = this.storage.disk(session.disk);
if (session.multipartUploadId && isMultipartCapable(disk)) {
const parts = [...((await this.sessions.listParts?.(id)) ?? [])].sort((a, b) => a.partNumber - b.partNumber);
await disk.completeMultipartUpload(session.key, session.multipartUploadId, parts);
}
else {
const writeOptions = session.contentType ? { contentType: session.contentType } : {};
if (typeof disk.putStream === 'function') {
await disk.putStream(session.key, Readable.from(this.streamParts(disk, session), { highWaterMark: 1 }), {
...writeOptions,
contentLength: session.offset,
});
}
else {
const chunks = [];
for (let part = 0; part < session.parts; part += 1) {
chunks.push(await disk.getBytes(this.partKey(session, part)));
}
await disk.put(session.key, Buffer.concat(chunks), writeOptions);
}
}
await this.cleanup(session);
await this.sessions.delete(id);
const size = session.size ?? session.offset;
this.emit('upload.complete', { id: session.id, disk: session.disk, key: session.key });
return { key: session.key, disk: session.disk, size };
}
/** Discard an in-flight session, freeing its native multipart upload or buffered parts. */
async abort(id) {
const session = await this.sessions.get(id);
if (!session)
return;
const disk = this.storage.disk(session.disk);
if (session.multipartUploadId && isMultipartCapable(disk)) {
await disk.abortMultipartUpload(session.key, session.multipartUploadId);
}
await this.cleanup(session);
await this.sessions.delete(id);
this.emit('upload.abort', { id: session.id, disk: session.disk, key: session.key });
}
/** All recorded parts for a session (multipart-capable disks). */
async listParts(id) {
await this.require(id);
return (await this.sessions.listParts?.(id)) ?? [];
}
/** In-progress sessions, optionally filtered. Empty when the store cannot enumerate. */
async list(filter) {
return (await this.sessions.list?.(filter)) ?? [];
}
emit(event, payload) {
if (this.emitDiagnostics)
publishMedia(event, payload);
}
/** Yields the buffered parts in order, opening each one only once the previous is drained. */
async *streamParts(disk, session) {
for (let part = 0; part < session.parts; part += 1) {
for await (const chunk of await disk.getStream(this.partKey(session, part))) {
yield chunk;
}
}
}
async cleanup(session) {
if (session.multipartUploadId)
return;
const disk = this.storage.disk(session.disk);
for (let part = 0; part < session.parts; part += 1) {
await disk.delete(this.partKey(session, part)).catch(() => { });
}
}
/**
* Load a session, treating an expired one as gone: its native/buffered parts are cleaned up, the
* record is deleted, and an {@link UploadSessionExpiredError} is thrown (the TUS handler maps this
* to `410 Gone`).
*/
async require(id) {
const session = await this.sessions.get(id);
if (!session)
throw new UploadSessionNotFoundError(id);
if (session.expiresAt && session.expiresAt.getTime() <= this.now().getTime()) {
const disk = this.storage.disk(session.disk);
if (session.multipartUploadId && isMultipartCapable(disk)) {
await disk.abortMultipartUpload(session.key, session.multipartUploadId).catch(() => { });
}
await this.cleanup(session);
await this.sessions.delete(id);
throw new UploadSessionExpiredError(id);
}
return session;
}
}
//# sourceMappingURL=resumable_upload.js.map