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

196 lines • 7.89 kB
import { Readable } from 'node:stream'; import { MediaControlPlaneError } from '../errors.js'; import { resolveTenantToken } from './auth.js'; const trimSlash = (s) => s.replace(/\/+$/, ''); /** * The HTTP client of a media tenant: this app's service token on every call (a fresh one once after * a `401`), reads retried after a network error or a `5xx`, writes never retried, every failure a * {@link MediaControlPlaneError} (`503` when the control plane did not answer). */ export class MediaTenantClient { partition; #url; #token; #fetch; #timeoutMs; #uploadTimeoutMs; #retries; #resolved; constructor(options) { this.partition = options.partition; this.#url = options.url; this.#token = resolveTenantToken(options.token); this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init)); this.#timeoutMs = options.timeoutMs ?? 10_000; this.#uploadTimeoutMs = options.uploadTimeoutMs ?? 120_000; this.#retries = options.retries ?? 1; } /** The control plane's base URL (resolved through discovery when it is a function). */ async baseUrl() { if (typeof this.#url === 'string') return trimSlash(this.#url); if (this.#resolved) return this.#resolved; try { this.#resolved = trimSlash(await this.#url()); } catch (error) { throw new MediaControlPlaneError(`media control plane: its URL did not resolve (${error.message})`, 503); } return this.#resolved; } /** The last resolved base URL, without I/O. */ get url() { return typeof this.#url === 'string' ? trimSlash(this.#url) : this.#resolved; } /** After a connection error: look the URL up again (a function source only). */ async #rediscover() { if (typeof this.#url === 'string') return false; const refresh = this.#url.refresh; try { const fresh = trimSlash(refresh ? await refresh() : await this.#url()); const moved = fresh !== this.#resolved; this.#resolved = fresh; return moved; } catch { return false; } } /** * One call. Answers the response when it is a 2xx or a 304; anything else is thrown as a * {@link MediaControlPlaneError} carrying the control plane's status and code. */ async request(path, request = {}) { const method = request.method ?? 'GET'; const idempotent = method === 'GET' || method === 'HEAD'; const replayable = !(request.body instanceof Readable); let attempt = 0; let refreshedToken = false; let rediscovered = false; for (;;) { let response; try { response = await this.#send(path, request); } catch (error) { if (error instanceof MediaControlPlaneError) throw error; // Not reached: it may have moved (discovery), or be restarting. if (!rediscovered && replayable && (await this.#rediscover())) { rediscovered = true; continue; } if (idempotent && attempt < this.#retries) { attempt++; continue; } throw new MediaControlPlaneError(`media control plane did not answer ${method} ${path}: ${error.message}`, 503); } if (response.status === 401 && request.bearer === undefined && !refreshedToken && replayable && this.#token.reset) { await response.body?.cancel(); this.#token.reset(); refreshedToken = true; continue; } if (response.status >= 500 && idempotent && attempt < this.#retries) { await response.body?.cancel(); attempt++; continue; } if (response.ok || response.status === 304) return response; throw await failureOf(response, `${method} ${path}`); } } /** A JSON call. */ async json(path, request = {}) { const response = await this.request(path, { ...request, headers: { accept: 'application/json', ...request.headers }, }); return (await response.json()); } async #send(path, request) { const base = await this.baseUrl(); const url = new URL(`${base}/v1${path}`); for (const [key, value] of Object.entries(request.query ?? {})) { if (value !== undefined) url.searchParams.set(key, String(value)); } const bearer = request.bearer ?? (await this.#bearer()); const body = request.body; const init = { method: request.method ?? 'GET', headers: { authorization: `Bearer ${bearer}`, 'x-media-app': this.partition, ...request.headers, }, signal: AbortSignal.timeout(request.upload ? this.#uploadTimeoutMs : this.#timeoutMs), }; if (body instanceof Readable) { init.body = Readable.toWeb(body); init.duplex = 'half'; } else if (body !== undefined) { init.body = body; } return this.#fetch(url, init); } async #bearer() { try { return await this.#token.get(); } catch (error) { throw new MediaControlPlaneError(`media control plane: no token for ${this.partition} (${error.message})`, 503, 'E_MEDIA_CONTROL_PLANE_TOKEN'); } } } /** A failed answer as an error: the control plane's own code and message when it sent them. */ export async function failureOf(response, what) { const body = (await response.json().catch(() => null)); const message = typeof body?.message === 'string' ? body.message : `media control plane answered ${response.status} to ${what}`; return new MediaControlPlaneError(message, response.status, typeof body?.code === 'string' ? body.code : undefined); } /** A response body as a Node stream. */ export function nodeStreamOf(response) { if (!response.body) return Readable.from([]); return Readable.fromWeb(response.body); } /** The client a tenant config describes. */ export function tenantClientOf(config, options = {}) { const tenant = config.tenant; if (!tenant) throw new Error('media: not a tenant (no `tenant` in config/media.ts)'); const { url, partition, token } = tenant; // Filled in by the provider (`resolveMediaTenant`) when authkit-client supplies them. if (url === undefined || partition === undefined || token === undefined) { throw new Error('media: tenant.url, tenant.partition and tenant.token are required on a tenant'); } return clientOf({ ...tenant, url, partition, token }, options); } /** The client `accounts` describes (a standalone app's account files), or none. */ export function accountsClientOf(config, options = {}) { return config.accounts ? clientOf(config.accounts, options) : undefined; } function clientOf(source, options) { return new MediaTenantClient({ url: source.url, partition: source.partition, token: source.token, ...(source.timeoutMs !== undefined ? { timeoutMs: source.timeoutMs } : {}), ...(source.uploadTimeoutMs !== undefined ? { uploadTimeoutMs: source.uploadTimeoutMs } : {}), ...(source.retries !== undefined ? { retries: source.retries } : {}), ...(options.fetch ? { fetch: options.fetch } : {}), }); } //# sourceMappingURL=tenant_client.js.map