UNPKG

@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

375 lines • 18.2 kB
import { currentTenantId, currentTenantScope, TENANCY_OFF, } from './agora/tenancy.js'; import { AttachmentManager } from './attachment.js'; import { DirectUploadManager } from './direct_upload.js'; import { DirectUploadsNotConfiguredError, MediaTenantUnsupportedError, ResumableUploadsNotConfiguredError, } from './errors.js'; import { MediaAccess } from './media_access.js'; import { MediaLibrary } from './media_library.js'; import { ResumableUploadManager } from './resumable_upload.js'; import { StorageManager } from './storage_manager.js'; import { tenantScopedSessionStore } from './tenant_scoped_store.js'; import { FakeImageProcessor } from './testing/fake_image_processor.js'; import { InMemoryMediaStore } from './testing/in_memory_media_store.js'; import { InMemoryUploadSessionStore } from './testing/in_memory_upload_session_store.js'; import { lazyInMemoryDiskResolver, MediaFake, } from './testing/media_fake.js'; import { partitionStore } from './topology/partition_store.js'; import { UploadManager, } from './upload_manager.js'; /** * The singleton bound into the AdonisJS container as `MediaManager`. Composes the two layers over a * shared {@link StorageManager}: {@link MediaLibrary} (owner collections + conversions) and * {@link AttachmentManager} (column attachments). * * ```ts * const media = await app.container.make(MediaManager) * await media.library.attach({ ownerType: 'Post', ownerId: '1', collection: 'gallery', ... }) * const att = await media.attachments.createFromFile({ fileName, mimeType, contents }) * ``` */ export class MediaManager { #storage; #library; #access; #attachments; #store; #uploads; /** Resumable (TUS) upload coordinator — present only when a session store is configured. */ #resumable; /** Session-backed direct upload coordinator — present only when a session store is configured. */ #direct; /** Kept so {@link fake} can build an in-memory twin with the same collections and settings. */ #options; /** The in-memory twin every accessor defers to while {@link fake} is active. */ #fake; /** {@link controlPlaneLibrary}'s libraries, by partition (`''`: the whole store). */ #partitionLibraries = new Map(); constructor(options) { this.#options = options; this.#store = options.store; this.#storage = new StorageManager({ default: options.defaultDisk, resolve: options.resolve }); const libraryOptions = this.#libraryOptions(options.store, options.tenancy); this.#library = options.library ? options.library(libraryOptions) : new MediaLibrary(libraryOptions); this.#access = new MediaAccess({ library: this.#library, ...(options.accessIdentity !== undefined ? { identity: options.accessIdentity } : {}), }); this.#attachments = new AttachmentManager({ storage: this.#storage, ...(options.imageProcessor !== undefined ? { imageProcessor: options.imageProcessor } : {}), ...(options.attachmentKeyPrefix !== undefined ? { keyPrefix: options.attachmentKeyPrefix } : {}), ...(options.emitDiagnostics !== undefined ? { emitDiagnostics: options.emitDiagnostics } : {}), }); this.#uploads = new UploadManager({ storage: this.#storage, ...(options.uploadMode !== undefined ? { mode: options.uploadMode } : {}), ...(options.uploadPartSize !== undefined ? { partSize: options.uploadPartSize } : {}), ...(options.uploadPresignTtlSeconds !== undefined ? { presignTtlSeconds: options.uploadPresignTtlSeconds } : {}), ...(options.emitDiagnostics !== undefined ? { emitDiagnostics: options.emitDiagnostics } : {}), }); // With tenancy on, upload sessions are stamped with the active tenant and another tenant's // session reads as missing (it cannot be resumed, completed or aborted from there). const tenancy = options.tenancy; const sessionsOf = (store) => tenancy?.enabled ? tenantScopedSessionStore(store, { scope: () => currentTenantScope(tenancy), stamp: () => currentTenantId(tenancy), }) : store; if (options.uploadSessions !== undefined) { this.#resumable = new ResumableUploadManager({ storage: this.#storage, sessions: sessionsOf(options.uploadSessions), ...(options.resumableTmpPrefix !== undefined ? { tmpPrefix: options.resumableTmpPrefix } : {}), ...(options.resumableSessionTtlSeconds !== undefined ? { sessionTtlSeconds: options.resumableSessionTtlSeconds } : {}), ...(options.emitDiagnostics !== undefined ? { emitDiagnostics: options.emitDiagnostics } : {}), }); } if (options.directUploadSessions !== undefined) { this.#direct = new DirectUploadManager({ storage: this.#storage, sessions: sessionsOf(options.directUploadSessions), // The manager reads the whitelist from the same registry attach uses, so the initiate // gate and the attach-time barrier cannot drift. collections: this.#library.collections, ...(options.directPartSize !== undefined ? { partSize: options.directPartSize } : {}), ...(options.directPresignTtlSeconds !== undefined ? { presignTtlSeconds: options.directPresignTtlSeconds } : {}), ...(options.directSessionTtlSeconds !== undefined ? { sessionTtlSeconds: options.directSessionTtlSeconds } : {}), ...(options.emitDiagnostics !== undefined ? { emitDiagnostics: options.emitDiagnostics } : {}), }); } } /** What a {@link MediaLibrary} over `store` is built from: this manager's settings. */ #libraryOptions(store, tenancy) { const options = this.#options; return { storage: this.#storage, store, ...(options.collections !== undefined ? { collections: options.collections } : {}), ...(options.imageProcessor !== undefined ? { imageProcessor: options.imageProcessor } : {}), ...(options.emitDiagnostics !== undefined ? { emitDiagnostics: options.emitDiagnostics } : {}), ...(options.deliveryMode !== undefined ? { deliveryMode: options.deliveryMode } : {}), ...(options.deliverySignedTtlSeconds !== undefined ? { deliverySignedTtlSeconds: options.deliverySignedTtlSeconds } : {}), ...(options.deliveryImages !== undefined ? { deliveryImages: options.deliveryImages } : {}), ...(options.deliverySigning !== undefined ? { deliverySigning: options.deliverySigning } : {}), ...(options.deliveryPath !== undefined ? { deliveryPath: options.deliveryPath } : {}), ...(options.deliveryStreamPath !== undefined ? { deliveryStreamPath: options.deliveryStreamPath } : {}), ...(tenancy !== undefined ? { tenancy } : {}), }; } /** * The library a media control plane runs a tenant app's requests on: this manager's disks, * collections, processor and delivery settings, over the store seen through `partition` (only * that app's records), with organization tenancy off. Without `partition`, the whole store * (account files, shared by every app). One instance per partition, so lazy conversions of the * same record are generated once. */ controlPlaneLibrary(partition) { const key = partition ?? ''; let library = this.#partitionLibraries.get(key); if (!library) { const store = partition === undefined ? this.#store : partitionStore(this.#store, partition); // Organization tenancy stays off here on purpose: a partition is an app, not an // organization, and the guard store is what scopes it. Tenant rows carry no tenant. library = new MediaLibrary(this.#libraryOptions(store, undefined)); this.#partitionLibraries.set(key, library); } return library; } /** Storage façade the layers resolve disks through. */ get storage() { return this.#fake ? this.#fake.manager.storage : this.#storage; } /** Owner collections + conversions. While {@link fake} is active, the recording in-memory twin. */ get library() { return this.#fake ? this.#fake.handle.library : this.#library; } /** Authorization for media: the delivery route, authorized `image()`, `authorize()`/`can()`. */ get access() { return this.#fake ? this.#fake.access : this.#access; } /** Column attachments. */ get attachments() { return this.#fake ? this.#fake.manager.attachments : this.#attachments; } /** * The configured persistence SPI. Exposed for management/console reads (e.g. the cross-owner * {@link MediaStore.list}); day-to-day writes go through {@link MediaManager.library}. */ get store() { return this.#fake ? this.#fake.manager.store : this.#store; } /** Organizations as tenants, as resolved from `config/media.ts` and `config/context.ts`. */ get tenancy() { return this.#options.tenancy ?? TENANCY_OFF; } /** Where this app's media runs: `standalone`, `control-plane` (the Hub) or `tenant`. */ get topology() { return this.#options.topology ?? 'standalone'; } /** * A person's own files on the media control plane, shared by every app (an avatar): read with * this app's token, written and removed with the person's own access token. On a media tenant, or * a standalone app with `accounts` in `config/media.ts`. */ get accounts() { // Not faked: `media.fake()` covers `media.library`; account files still go to the control plane. if (!this.#options.accounts) { throw new MediaTenantUnsupportedError('media.accounts (outside a tenant, and no `accounts` in config/media.ts)'); } return this.#options.accounts; } /** Direct-S3 upload coordinator (proxy + direct multipart modes). */ get uploads() { return this.#fake ? this.#fake.manager.uploads : this.#uploads; } /** * Swap the whole manager onto in-memory doubles — the `drive.fake()` / `mail.fake()` of this * package. Because the swap happens INSIDE the manager, code that already holds it (the * `@adonis-agora/media/services/main` singleton, captured once at boot) sees the fake too. * * The twin runs the real {@link MediaLibrary} with this manager's collections and delivery * settings over an `InMemoryMediaStore`, in-memory disks for every disk name and a * `FakeImageProcessor`, so attach/list/deliver/signedUrl/delete keep their real semantics. Every * `media.library` call is recorded on the returned {@link MediaFake}, which can also stub a method. * * Calling it again replaces the previous fake with a fresh one. Undo with {@link restore}. * * ```ts * const fake = media.fake() * // ... exercise the app ... * fake.assertCalled('delete', (id) => id === record.id) * media.restore() * ``` */ fake(options = {}) { this.restore(); const { resolve, disks } = lazyInMemoryDiskResolver(this.#options.defaultDisk, options.visibility); const store = options.store ?? new InMemoryMediaStore(); const { library: _remote, accounts: _accounts, ...local } = this.#options; const manager = new MediaManager({ ...local, resolve, store, imageProcessor: options.imageProcessor ?? new FakeImageProcessor(), ...(this.#options.uploadSessions !== undefined ? { uploadSessions: new InMemoryUploadSessionStore() } : {}), ...(this.#options.directUploadSessions !== undefined ? { directUploadSessions: new InMemoryUploadSessionStore() } : {}), }); const handle = new MediaFake({ library: manager.library, store, resolve, disks, onRestore: () => { if (this.#fake?.handle === handle) this.restore(); }, }); // Access goes through the RECORDING library, so `media.access.image/serve` calls are recorded // and honour stubs, like a direct `media.library` call. const access = new MediaAccess({ library: handle.library, ...(this.#options.accessIdentity !== undefined ? { identity: this.#options.accessIdentity } : {}), }); this.#fake = { manager, handle, access }; return handle; } /** Undo {@link fake}: the real store, disks and library are back. A no-op when not faked. */ restore() { this.#fake = undefined; } /** * The resumable (TUS) upload coordinator. Throws {@link ResumableUploadsNotConfiguredError} unless * a session store was configured via `uploads.resumable` in `config/media.ts`. */ get resumable() { if (this.#fake) return this.#fake.manager.resumable; if (this.topology === 'tenant') throw new MediaTenantUnsupportedError('media.resumable'); if (!this.#resumable) throw new ResumableUploadsNotConfiguredError(); return this.#resumable; } /** * Finish a resumable (TUS) upload and register the assembled object as a media record, in one * step and without ever reading the uploaded bytes back: `resumable.complete()` returns the final * `{ key, disk, size }`, which {@link MediaLibrary.attachExisting} adopts as-is. * * This lives here because the two layers meet only at the manager — {@link ResumableUploadManager} * knows nothing of the library. It is opt-in: {@link resumable}'s `complete()` stays the raw * primitive for uploads that should NOT become library assets. * * ```ts * await media.completeUploadToLibrary(sessionId, { * ownerType: 'Post', ownerId: post.id, collection: 'gallery', * fileName: 'scan.pdf', mimeType: 'application/pdf', * }) * ``` */ async completeUploadToLibrary(sessionId, input) { const { key, disk, size } = await this.resumable.complete(sessionId); return this.library.attachExisting({ ...input, key, disk, size }); } /** * The session-backed direct upload coordinator. Throws {@link DirectUploadsNotConfiguredError} * unless a session store was configured via `uploads.direct` in `config/media.ts`. */ get direct() { if (this.#fake) return this.#fake.manager.direct; if (this.topology === 'tenant') throw new MediaTenantUnsupportedError('media.direct'); if (!this.#direct) throw new DirectUploadsNotConfiguredError(); return this.#direct; } /** Whether session-backed direct uploads are configured (a session store is present). */ get hasDirect() { return this.#fake ? this.#fake.manager.hasDirect : this.#direct !== undefined; } /** * Finish a session-backed direct upload and register the assembled object as a media record, in * one step — the direct-mode twin of {@link completeUploadToLibrary}, meeting the two layers at * the manager the same way. `attachExisting` adopts the object zero-copy and re-validates the * collection's whitelist against the REAL bytes (a short head read), so a client that lied about * `contentType` at initiate is caught here, exactly like every other upload path. * * ```ts * await media.completeDirectUploadToLibrary(sessionId, { * ownerType: 'Lesson', ownerId: lesson.id, collection: 'video', * fileName: 'original.mp4', mimeType: 'video/mp4', * }, partsFromClient) * ``` */ async completeDirectUploadToLibrary(sessionId, input, parts = []) { const { key, disk, size } = await this.direct.complete(sessionId, parts); return this.library.attachExisting({ ...input, key, disk, size }); } /** * The registered collection configs — the single source of truth for `acceptsMimeTypes`. Exposed * so the upload edge (`TusUploadHandler`) can enforce the very same whitelist the library will * enforce at attach time, without the app restating it. */ get collections() { return this.library.collections; } /** Whether resumable (TUS) uploads are configured (a session store is present). */ get hasResumable() { return this.#fake ? this.#fake.manager.hasResumable : this.#resumable !== undefined; } /** Resolve a raw disk by name (escape hatch to the underlying Drive disk). */ disk(name) { return this.storage.disk(name); } /** Begin a direct-S3 multipart upload — returns presigned part URLs for the client. */ initiateDirectUpload(input) { return this.uploads.initiateDirect(input); } /** Assemble the client-uploaded parts into the final object. */ completeDirectUpload(input) { return this.uploads.completeDirect(input); } /** Abort an in-flight direct-S3 multipart upload. */ abortDirectUpload(input) { return this.uploads.abortDirect(input); } /** Proxy upload: stream bytes through the app to the disk (works on any disk). */ proxyUpload(input) { return this.uploads.proxyUpload(input); } } //# sourceMappingURL=media_manager.js.map