Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: bound processing transfers and download Drive revisions directly

Richie McIlroyed800661b9a3
diff --git a/apps/media-server/src/__tests__/lib/media-transfer.test.ts b/apps/media-server/src/__tests__/lib/media-transfer.test.ts
new file mode 100644
index 000000000..8ac2a27c7
--- /dev/null
+++ b/apps/media-server/src/__tests__/lib/media-transfer.test.ts
@@ -0,0 +1,244 @@
+import { afterEach, describe, expect, spyOn, test } from "bun:test";
+import { createHash, randomUUID } from "node:crypto";
+import { link, mkdtemp, readFile, rm, stat } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ cleanupMediaTransferCache,
+ downloadDriveRevision,
+ getMediaDownloadTarget,
+ type MediaDownloadTarget,
+ MediaTransferBudgetError,
+ materializeMedia,
+ releaseMaterializedMedia,
+ withMediaTransfers,
+} from "../../lib/media-transfer";
+
+const roots: string[] = [];
+const originalFetch = globalThis.fetch;
+const originalSecret = process.env.MEDIA_SERVER_WEBHOOK_SECRET;
+afterEach(async () => {
+ globalThis.fetch = originalFetch;
+ if (originalSecret === undefined)
+ delete process.env.MEDIA_SERVER_WEBHOOK_SECRET;
+ else process.env.MEDIA_SERVER_WEBHOOK_SECRET = originalSecret;
+ await cleanupMediaTransferCache();
+ for (const root of roots.splice(0))
+ await rm(root, { recursive: true, force: true });
+});
+async function destination() {
+ const root = await mkdtemp(join(tmpdir(), "media-transfer-test-"));
+ roots.push(root);
+ return join(root, "recording.mp4");
+}
+const content = Buffer.from("a real transfer with an interrupted stream");
+function target(): MediaDownloadTarget {
+ return {
+ version: 1,
+ url: "https://www.googleapis.com/drive/v3/files/file/revisions/revision?alt=media",
+ authorization: "Bearer private",
+ objectIdentity: '"identity"',
+ size: content.length,
+ sha256: createHash("sha256").update(content).digest("hex"),
+ };
+}
+function fetcher(
+ run: (
+ input: string | URL | Request,
+ init?: RequestInit,
+ ) => Response | Promise<Response>,
+): typeof fetch {
+ return Object.assign(run, { preconnect: fetch.preconnect }) as typeof fetch;
+}
+describe("bounded revision downloads", () => {
+ test("resumes an interrupted pinned revision without rereading completed bytes", async () => {
+ const path = await destination();
+ let calls = 0;
+ let received = 0;
+ const network = fetcher((_input, init) => {
+ calls++;
+ if (calls === 1) {
+ let pull = 0;
+ return new Response(
+ new ReadableStream({
+ pull(controller) {
+ if (pull++ === 0) controller.enqueue(content.subarray(0, 12));
+ else controller.error(new Error("network disconnected"));
+ },
+ }),
+ { headers: { "Content-Length": String(content.length) } },
+ );
+ }
+ expect(new Headers(init?.headers).get("range")).toBe("bytes=12-");
+ return new Response(content.subarray(12), {
+ status: 206,
+ headers: {
+ "Content-Length": String(content.length - 12),
+ "Content-Range": `bytes 12-${content.length - 1}/${content.length}`,
+ },
+ });
+ });
+ await downloadDriveRevision(target(), path, {
+ fetcher: network,
+ onBytes: (bytes) => {
+ received += bytes;
+ },
+ });
+ expect(await readFile(path)).toEqual(content);
+ expect(received).toBe(content.length);
+ expect(calls).toBe(2);
+ });
+ test("rejects corruption and removes the incomplete file", async () => {
+ const path = await destination();
+ await expect(
+ downloadDriveRevision(target(), path, {
+ fetcher: fetcher(
+ () =>
+ new Response(Buffer.alloc(content.length), {
+ headers: { "Content-Length": String(content.length) },
+ }),
+ ),
+ }),
+ ).rejects.toThrow("checksum");
+ expect(await stat(path).catch(() => null)).toBeNull();
+ });
+ test("does not retry after the byte budget is exhausted", async () => {
+ let calls = 0;
+ await expect(
+ downloadDriveRevision(target(), await destination(), {
+ fetcher: fetcher(() => {
+ calls++;
+ return new Response(content, {
+ headers: { "Content-Length": String(content.length) },
+ });
+ }),
+ onBytes: () => {
+ throw new MediaTransferBudgetError();
+ },
+ }),
+ ).rejects.toBeInstanceOf(MediaTransferBudgetError);
+ expect(calls).toBe(1);
+ });
+ test("does not forward worker credentials to an arbitrary host", async () => {
+ await expect(
+ getMediaDownloadTarget("https://attacker.example/api/storage/object"),
+ ).rejects.toThrow("Untrusted");
+ });
+ test("bounds a repeatedly truncated source to three requests", async () => {
+ let calls = 0;
+ await expect(
+ downloadDriveRevision(target(), await destination(), {
+ fetcher: fetcher(() => {
+ calls++;
+ return new Response(
+ new ReadableStream({
+ start(controller) {
+ controller.close();
+ },
+ }),
+ { headers: { "Content-Length": String(content.length) } },
+ );
+ }),
+ }),
+ ).rejects.toThrow("checksum or size");
+ expect(calls).toBe(3);
+ });
+});
+
+describe("parallel transfer admission and cache reuse", () => {
+ function network() {
+ process.env.MEDIA_SERVER_WEBHOOK_SECRET = "worker-secret";
+ let downloads = 0;
+ globalThis.fetch = fetcher((input) => {
+ if (String(input).startsWith("https://cap.so/"))
+ return Response.json(target());
+ downloads++;
+ return new Response(content, {
+ headers: { "Content-Length": String(content.length) },
+ });
+ });
+ return () => downloads;
+ }
+ const url = () => `https://cap.so/api/storage/object?key=${randomUUID()}`;
+
+ test("reuses a verified file across retries without another media download", async () => {
+ const downloads = network();
+ const input = url();
+ await withMediaTransfers(content.length, async () => {
+ const first = await materializeMedia(input);
+ const second = await materializeMedia(input);
+ expect(first?.path).toBe(second?.path);
+ });
+ await withMediaTransfers(1, async () => {
+ expect(await materializeMedia(input)).toBeDefined();
+ });
+ expect(downloads()).toBe(1);
+ });
+
+ test("releases one cache retention after concurrent reads in the same job", async () => {
+ const downloads = network();
+ const input = url();
+ await withMediaTransfers(content.length, () => materializeMedia(input));
+ await withMediaTransfers(content.length, async () => {
+ const reads = await Promise.all(
+ Array.from({ length: 10 }, () => materializeMedia(input)),
+ );
+ expect(new Set(reads.map((read) => read?.path)).size).toBe(1);
+ });
+ const now = Date.now();
+ const clock = spyOn(Date, "now").mockReturnValue(now + 31 * 60_000);
+ try {
+ await withMediaTransfers(content.length, () => materializeMedia(input));
+ } finally {
+ clock.mockRestore();
+ }
+ expect(downloads()).toBe(2);
+ });
+
+ test("retains a worker input after its cache pathname is removed", async () => {
+ network();
+ await withMediaTransfers(content.length, async () => {
+ const local = await materializeMedia(url());
+ expect(local).toBeDefined();
+ if (!local) throw new Error("Input was not materialized");
+ const path = await destination();
+ await link(local.path, path);
+ await releaseMaterializedMedia(local.path);
+ await cleanupMediaTransferCache();
+ expect(await readFile(path)).toEqual(content);
+ });
+ });
+
+ test("does not let simultaneous files overbook the remaining byte budget", async () => {
+ const downloads = network();
+ await withMediaTransfers(content.length, async () => {
+ const results = await Promise.allSettled([
+ materializeMedia(url()),
+ materializeMedia(url()),
+ ]);
+ expect(
+ results.filter((result) => result.status === "fulfilled"),
+ ).toHaveLength(1);
+ const failed = results.find((result) => result.status === "rejected");
+ expect(
+ failed?.status === "rejected" &&
+ failed.reason instanceof MediaTransferBudgetError,
+ ).toBe(true);
+ });
+ expect(downloads()).toBe(1);
+ });
+
+ test("does not follow a descriptor redirect with worker credentials", async () => {
+ process.env.MEDIA_SERVER_WEBHOOK_SECRET = "worker-secret";
+ let calls = 0;
+ globalThis.fetch = fetcher((_input, init) => {
+ calls++;
+ expect(init?.redirect).toBe("manual");
+ return Response.redirect("https://attacker.example/", 307);
+ });
+ await expect(getMediaDownloadTarget(url())).rejects.toThrow(
+ "authorization failed",
+ );
+ expect(calls).toBe(1);
+ });
+});
diff --git a/apps/media-server/src/index.ts b/apps/media-server/src/index.ts
index 68942e2d6..7a5b2151d 100644
--- a/apps/media-server/src/index.ts
+++ b/apps/media-server/src/index.ts
@@ -1,6 +1,7 @@
import app from "./app";
import { abortAllJobs } from "./lib/job-manager";
import { cancelAllMediaOperations } from "./lib/media-operations";
+import { cleanupMediaTransferCache } from "./lib/media-transfer";
const port = Number(process.env.PORT) || 3456;
@@ -17,6 +18,7 @@ const shutdown = async () => {
console.log(`[media-server] Aborted ${abortedJobs} active jobs`);
}
await cancelAllMediaOperations();
+ await cleanupMediaTransferCache();
process.exit(0);
};
diff --git a/apps/media-server/src/lib/job-manager.ts b/apps/media-server/src/lib/job-manager.ts
index 30472fc26..88232e137 100644
--- a/apps/media-server/src/lib/job-manager.ts
+++ b/apps/media-server/src/lib/job-manager.ts
@@ -24,7 +24,8 @@ export type RecordingErrorCode =
| "source-missing"
| "source-changed"
| "output-invalid"
- | "processing-unavailable";
+ | "processing-unavailable"
+ | "processing-budget-exhausted";
export interface RecordingVerificationRequest {
version: 1;
@@ -324,10 +325,17 @@ export function hasCriticalMemoryPressure(): boolean {
return getSystemResources().memoryPressure >= MEMORY_REJECT_THRESHOLD;
}
-export function canAcceptNewVideoProcess(): boolean {
+export function canAcceptNewVideoProcess(
+ priority: "interactive" | "recovery" = "interactive",
+): boolean {
const active = getActiveVideoProcessCount();
const resources = getSystemResources();
- return active < resources.effectiveMax;
+ return (
+ active <
+ (priority === "recovery" && resources.effectiveMax > 1
+ ? Math.max(1, Math.floor(resources.effectiveMax / 2))
+ : resources.effectiveMax)
+ );
}
export function generateJobId(): string {
diff --git a/apps/media-server/src/lib/media-probe.ts b/apps/media-server/src/lib/media-probe.ts
index 75ae229b0..ef6ee8ace 100644
--- a/apps/media-server/src/lib/media-probe.ts
+++ b/apps/media-server/src/lib/media-probe.ts
@@ -11,6 +11,7 @@ import {
getActiveProbeOperationCount,
withMediaOperation,
} from "./media-operations";
+import { materializeMedia } from "./media-transfer";
const PROBE_TIMEOUT_MS = 30_000;
const probeFetch: typeof fetch = globalThis.fetch.bind(globalThis);
@@ -119,6 +120,8 @@ async function probeMedia(path: string): Promise<VideoMetadata> {
}
export async function probeVideo(videoUrl: string): Promise<VideoMetadata> {
+ const local = await materializeMedia(videoUrl);
+ if (local) return probeVideoFile(local.path);
if (!canAcceptNewProbeOperation()) {
throw new Error("Server is busy, please try again later");
}
diff --git a/apps/media-server/src/lib/media-transfer.ts b/apps/media-server/src/lib/media-transfer.ts
new file mode 100644
index 000000000..b63e19790
--- /dev/null
+++ b/apps/media-server/src/lib/media-transfer.ts
@@ -0,0 +1,423 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+import { createHash } from "node:crypto";
+import { mkdir, open, readdir, rm, stat } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { z } from "zod";
+
+const targetSchema = z.object({
+ version: z.literal(1),
+ url: z.string().url(),
+ authorization: z.string().regex(/^Bearer [^\r\n]+$/),
+ objectIdentity: z.string().min(1).max(1024),
+ size: z.number().int().positive().safe(),
+ sha256: z.string().regex(/^[a-f0-9]{64}$/),
+});
+export type MediaDownloadTarget = z.infer<typeof targetSchema>;
+export class MediaTransferBudgetError extends Error {
+ constructor() {
+ super("Recording transfer budget exhausted");
+ this.name = "MediaTransferBudgetError";
+ }
+}
+
+type CachedFile = { path: string; size: number; users: number; usedAt: number };
+type TransferContext = {
+ limit: number;
+ bytes: number;
+ reserved: number;
+ cacheHits: number;
+ files: Map<string, CachedFile>;
+ controller: AbortController;
+ pending: Map<string, Promise<{ path: string; target: MediaDownloadTarget }>>;
+};
+const transfers = new AsyncLocalStorage<TransferContext>();
+const cache = new Map<string, CachedFile>();
+const cacheBase = join(tmpdir(), "cap-media-download-cache");
+const cacheRoot = join(cacheBase, String(process.pid));
+const CACHE_BYTES = 2 * 1024 ** 3;
+const CACHE_TTL_MS = 30 * 60_000;
+let cacheBytes = 0;
+let lastPruneAt = 0;
+
+async function initializeCache() {
+ await mkdir(cacheRoot, { recursive: true, mode: 0o700 });
+ for (const entry of await readdir(cacheBase, { withFileTypes: true })) {
+ if (
+ !entry.isDirectory() ||
+ !/^\d+$/.test(entry.name) ||
+ entry.name === String(process.pid)
+ )
+ continue;
+ try {
+ process.kill(Number(entry.name), 0);
+ } catch (error) {
+ if (
+ typeof error === "object" &&
+ error !== null &&
+ "code" in error &&
+ error.code === "ESRCH"
+ )
+ await rm(join(cacheBase, entry.name), { recursive: true, force: true });
+ }
+ }
+}
+let cacheReady: Promise<void> | undefined;
+const pruneTimer = setInterval(() => {
+ void pruneCache().catch(() => {});
+}, 60_000);
+pruneTimer.unref?.();
+export async function cleanupMediaTransferCache() {
+ await rm(cacheRoot, { recursive: true, force: true }).catch(() => {});
+ cache.clear();
+ cacheBytes = 0;
+ cacheReady = undefined;
+}
+
+export function isInternalMediaUrl(input: string): boolean {
+ try {
+ const url = new URL(input);
+ const origins = new Set(["https://cap.so", "https://www.cap.so"]);
+ if (process.env.MEDIA_SERVER_WEB_ORIGIN)
+ origins.add(new URL(process.env.MEDIA_SERVER_WEB_ORIGIN).origin);
+ return (
+ origins.has(url.origin) &&
+ url.pathname === "/api/storage/object" &&
+ !url.username &&
+ !url.password
+ );
+ } catch {
+ return false;
+ }
+}
+
+async function pruneCache() {
+ if (cacheBytes <= CACHE_BYTES && Date.now() - lastPruneAt < 60_000) return;
+ lastPruneAt = Date.now();
+ for (const [key, entry] of [...cache].sort(
+ (a, b) => a[1].usedAt - b[1].usedAt,
+ )) {
+ if (
+ entry.users ||
+ (cacheBytes <= CACHE_BYTES && Date.now() - entry.usedAt < CACHE_TTL_MS)
+ )
+ continue;
+ if (cache.get(key) !== entry) continue;
+ cache.delete(key);
+ cacheBytes -= entry.size;
+ await rm(entry.path, { force: true }).catch(() => {});
+ }
+}
+
+export async function withMediaTransfers<T>(
+ limit: number,
+ run: () => Promise<T>,
+): Promise<T> {
+ if (!Number.isSafeInteger(limit) || limit <= 0)
+ throw new Error("Invalid recording transfer budget");
+ const context: TransferContext = {
+ limit,
+ bytes: 0,
+ reserved: 0,
+ cacheHits: 0,
+ files: new Map(),
+ controller: new AbortController(),
+ pending: new Map(),
+ };
+ const timeout = setTimeout(
+ () => context.controller.abort(new Error("Recording transfer timed out")),
+ Math.min(
+ 3 * 60 * 60_000,
+ 15 * 60_000 + Math.ceil(limit / (2 * 1024 ** 2)) * 1000,
+ ),
+ );
+ timeout.unref?.();
+ return transfers.run(context, async () => {
+ try {
+ return await run();
+ } finally {
+ clearTimeout(timeout);
+ context.controller.abort();
+ for (const [key, entry] of context.files) {
+ entry.users--;
+ if (cache.get(key) !== entry && !entry.users)
+ await rm(entry.path, { force: true }).catch(() => {});
+ }
+ await pruneCache();
+ console.info("[media-transfer] Completed", {
+ downloadedBytes: context.bytes,
+ cacheHits: context.cacheHits,
+ budgetBytes: limit,
+ });
+ }
+ });
+}
+
+export async function getMediaDownloadTarget(
+ input: string,
+ signal?: AbortSignal,
+ expectedIdentity?: string,
+): Promise<MediaDownloadTarget> {
+ if (!isInternalMediaUrl(input))
+ throw new Error("Untrusted media authorization origin");
+ const secret = process.env.MEDIA_SERVER_WEBHOOK_SECRET;
+ if (!secret) throw new Error("Media authorization is unavailable");
+ const response = await fetch(input, {
+ headers: {
+ "x-cap-internal-download": "1",
+ "x-media-server-secret": secret,
+ ...(expectedIdentity ? { "if-match": expectedIdentity } : {}),
+ },
+ signal,
+ redirect: "manual",
+ });
+ if (
+ !response.ok ||
+ !response.headers.get("content-type")?.includes("application/json")
+ ) {
+ await response.body?.cancel();
+ throw new Error(`Media download authorization failed (${response.status})`);
+ }
+ const target = targetSchema.parse(await response.json());
+ const url = new URL(target.url);
+ if (
+ url.origin !== "https://www.googleapis.com" ||
+ !/^\/drive\/v3\/files\/[^/]+\/revisions\/[^/]+$/.test(url.pathname) ||
+ url.search !== "?alt=media" ||
+ url.username ||
+ url.password ||
+ url.hash
+ ) {
+ throw new Error("Untrusted Drive revision URL");
+ }
+ if (expectedIdentity && target.objectIdentity !== expectedIdentity)
+ throw new Error("Recording object changed");
+ return target;
+}
+
+export async function downloadDriveRevision(
+ target: MediaDownloadTarget,
+ path: string,
+ options: {
+ signal?: AbortSignal;
+ onBytes?: (bytes: number) => void;
+ fetcher?: typeof fetch;
+ } = {},
+): Promise<number> {
+ const fetcher = options.fetcher ?? fetch;
+ const writer = await open(path, "wx", 0o600);
+ const hash = createHash("sha256");
+ let bytes = 0;
+ try {
+ for (let attempt = 0; attempt < 3 && bytes < target.size; attempt++) {
+ options.signal?.throwIfAborted();
+ const start = bytes;
+ const response = await fetcher(target.url, {
+ headers: {
+ Authorization: target.authorization,
+ "Accept-Encoding": "identity",
+ ...(start ? { Range: `bytes=${start}-` } : {}),
+ },
+ signal: options.signal,
+ redirect: "error",
+ });
+ const valid = start
+ ? response.status === 206 &&
+ response.headers.get("content-range") ===
+ `bytes ${start}-${target.size - 1}/${target.size}`
+ : response.status === 200;
+ if (
+ !valid ||
+ Number(response.headers.get("content-length")) !==
+ target.size - start ||
+ !response.body
+ ) {
+ await response.body?.cancel();
+ throw new Error(
+ `Drive revision response is invalid (${response.status})`,
+ );
+ }
+ const reader = response.body.getReader();
+ try {
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ options.onBytes?.(value.byteLength);
+ if (bytes + value.byteLength > target.size)
+ throw new Error("Drive revision exceeds its committed size");
+ let offset = 0;
+ while (offset < value.byteLength) {
+ const result = await writer
+ .write(value, offset, value.byteLength - offset, bytes + offset)
+ .catch((cause: unknown) => {
+ throw new Error("Recording download could not be written", {
+ cause,
+ });
+ });
+ if (result.bytesWritten === 0)
+ throw new Error("Recording download could not be written");
+ offset += result.bytesWritten;
+ }
+ hash.update(value);
+ bytes += value.byteLength;
+ }
+ } catch (error) {
+ if (
+ options.signal?.aborted ||
+ error instanceof MediaTransferBudgetError ||
+ bytes === target.size ||
+ attempt === 2 ||
+ (error instanceof Error &&
+ /committed size|could not be written/.test(error.message))
+ )
+ throw error;
+ } finally {
+ await reader.cancel().catch(() => {});
+ reader.releaseLock();
+ }
+ if (bytes < target.size && attempt < 2)
+ await Bun.sleep(250 * 2 ** attempt);
+ }
+ if (bytes !== target.size || hash.digest("hex") !== target.sha256)
+ throw new Error("Drive revision checksum or size mismatch");
+ return bytes;
+ } catch (error) {
+ await rm(path, { force: true });
+ throw error;
+ } finally {
+ await writer.close();
+ }
+}
+
+export async function materializeMedia(
+ input: string,
+ signal?: AbortSignal,
+ expectedIdentity?: string,
+): Promise<{ path: string; target: MediaDownloadTarget } | undefined> {
+ const context = transfers.getStore();
+ if (!context || !isInternalMediaUrl(input)) return undefined;
+ const combinedSignal = signal
+ ? AbortSignal.any([signal, context.controller.signal])
+ : context.controller.signal;
+ const target = await getMediaDownloadTarget(
+ input,
+ combinedSignal,
+ expectedIdentity,
+ );
+ const key = createHash("sha256")
+ .update(
+ JSON.stringify([
+ new URL(input).origin,
+ new URL(input).searchParams.get("key"),
+ target.objectIdentity,
+ target.sha256,
+ ]),
+ )
+ .digest("hex");
+ await pruneCache();
+ const pending = context.pending.get(key);
+ if (pending) return pending;
+ const download = async () => {
+ const existing = context.files.get(key) ?? cache.get(key);
+ if (existing) {
+ const retained = context.files.has(key);
+ if (!retained) existing.users++;
+ if (
+ (await stat(existing.path).catch(() => undefined))?.size === target.size
+ ) {
+ if (!retained) context.files.set(key, existing);
+ existing.usedAt = Date.now();
+ context.cacheHits++;
+ return { path: existing.path, target };
+ }
+ if (!retained) existing.users--;
+ }
+
+ if (context.bytes + context.reserved + target.size > context.limit)
+ throw new MediaTransferBudgetError();
+ let reservationRemaining = target.size;
+ context.reserved += reservationRemaining;
+ try {
+ cacheReady ??= initializeCache();
+ await cacheReady;
+ const path = join(cacheRoot, `${key}-${crypto.randomUUID()}.mp4`);
+ await downloadDriveRevision(target, path, {
+ signal: combinedSignal,
+ onBytes: (bytes) => {
+ context.bytes += bytes;
+ const spent = Math.min(reservationRemaining, bytes);
+ reservationRemaining -= spent;
+ context.reserved -= spent;
+ if (context.bytes > context.limit) {
+ context.controller.abort();
+ throw new MediaTransferBudgetError();
+ }
+ },
+ });
+ const entry = { path, size: target.size, users: 1, usedAt: Date.now() };
+ context.files.set(key, entry);
+ const previous = cache.get(key);
+ if (!previous) {
+ cache.set(key, entry);
+ cacheBytes += target.size;
+ } else {
+ entry.usedAt = 0;
+ }
+ return { path, target };
+ } finally {
+ context.reserved -= reservationRemaining;
+ }
+ };
+ const operation = download();
+ context.pending.set(key, operation);
+ try {
+ return await operation;
+ } finally {
+ context.pending.delete(key);
+ }
+}
+
+export async function releaseMaterializedMedia(path: string) {
+ const context = transfers.getStore();
+ if (!context) return;
+ for (const [key, entry] of context.files) {
+ if (entry.path !== path) continue;
+ context.files.delete(key);
+ entry.users--;
+ if (cache.get(key) !== entry && !entry.users)
+ await rm(entry.path, { force: true }).catch(() => {});
+ break;
+ }
+ await pruneCache();
+}
+
+export async function fetchMedia(
+ input: string,
+ init: RequestInit = {},
+): Promise<Response> {
+ const headers = new Headers(init.headers);
+ const local = await materializeMedia(
+ input,
+ init.signal ?? undefined,
+ headers.get("if-match") ?? undefined,
+ );
+ if (!local) return fetch(input, init);
+ const range = headers.get("range");
+ const match = range?.match(/^bytes=(\d+)-(\d*)$/);
+ const start = match ? Number(match[1]) : 0;
+ const end = match?.[2]
+ ? Math.min(Number(match[2]), local.target.size - 1)
+ : local.target.size - 1;
+ if (range && (!match || start > end || start >= local.target.size))
+ return new Response(null, { status: 416 });
+ return new Response(Bun.file(local.path).slice(start, end + 1), {
+ status: range ? 206 : 200,
+ headers: {
+ ETag: local.target.objectIdentity,
+ "Content-Length": String(end - start + 1),
+ ...(range
+ ? { "Content-Range": `bytes ${start}-${end}/${local.target.size}` }
+ : {}),
+ },
+ });
+}
diff --git a/apps/media-server/src/lib/media-video.ts b/apps/media-server/src/lib/media-video.ts
index 232fac2f2..022fb3fae 100644
--- a/apps/media-server/src/lib/media-video.ts
+++ b/apps/media-server/src/lib/media-video.ts
@@ -12,6 +12,7 @@ import {
withTimeout,
} from "./media-common";
import { probeVideoFile } from "./media-probe";
+import { fetchMedia, materializeMedia } from "./media-transfer";
import {
RecordingTimingError,
readRecordingVideoTiming,
@@ -1229,6 +1230,9 @@ export async function downloadVideoToTemp(
return await downloadStreamingVideoToTemp(videoUrl, abortSignal);
}
+ const local = await materializeMedia(videoUrl, abortSignal);
+ if (local) return { path: local.path, cleanup: async () => {} };
+
const tempFile = await createTempFile(
normalizeVideoInputExtension(inputExtension),
);
@@ -1239,7 +1243,7 @@ export async function downloadVideoToTemp(
? AbortSignal.any([abortSignal, timeoutSignal])
: timeoutSignal;
- const response = await fetch(videoUrl, {
+ const response = await fetchMedia(videoUrl, {
signal: combinedSignal,
});
diff --git a/apps/media-server/src/lib/recording-verification.ts b/apps/media-server/src/lib/recording-verification.ts
index 530c9d0ad..6d0a0a1c1 100644
--- a/apps/media-server/src/lib/recording-verification.ts
+++ b/apps/media-server/src/lib/recording-verification.ts
@@ -5,6 +5,7 @@ import { lstat } from "node:fs/promises";
import { isAbsolute } from "node:path";
import { Readable } from "node:stream";
import { PROCESS_TIMEOUT_MS } from "./media-common";
+import { fetchMedia, materializeMedia } from "./media-transfer";
import {
RecordingTimingError,
type RecordingVideoTiming,
@@ -987,7 +988,7 @@ async function readRemoteIdentity(
if (expectedObjectIdentity) headers["If-Match"] = expectedObjectIdentity;
let response: Response;
try {
- response = await fetch(input, { headers, signal: abortSignal });
+ response = await fetchMedia(input, { headers, signal: abortSignal });
} catch {
throw new RecordingVerificationError(
"Recording object identity could not be read",
@@ -1040,7 +1041,7 @@ async function hashRemoteRecording(
): Promise<string> {
let response: Response;
try {
- response = await fetch(input, {
+ response = await fetchMedia(input, {
headers: {
"If-Match": objectIdentity,
"X-Cap-Recording-Verification": "1",
@@ -1160,10 +1161,11 @@ export async function verifyRemoteRecording(
true,
);
}
+ const local = await materializeMedia(input, signal, before.objectIdentity);
const evidence = await decodeRecording(
- input,
+ local?.path ?? input,
{ ...options, abortSignal: signal, timeoutMs: remainingMs },
- before.objectIdentity,
+ local ? undefined : before.objectIdentity,
);
const remoteSha256 =
options.expectedSha256 || options.hashContent
diff --git a/apps/media-server/src/routes/video.ts b/apps/media-server/src/routes/video.ts
index b41a58878..1f1a00547 100644
--- a/apps/media-server/src/routes/video.ts
+++ b/apps/media-server/src/routes/video.ts
@@ -1,4 +1,5 @@
import { createHash, randomUUID } from "node:crypto";
+import { link } from "node:fs/promises";
import { file } from "bun";
import { Hono } from "hono";
import { z } from "zod";
@@ -36,6 +37,13 @@ import {
probeVideo,
probeVideoFile,
} from "../lib/media-probe";
+import {
+ fetchMedia,
+ MediaTransferBudgetError,
+ materializeMedia,
+ releaseMaterializedMedia,
+ withMediaTransfers,
+} from "../lib/media-transfer";
import type {
ResilientInputFlags,
StorageUploadTarget,
@@ -699,13 +707,15 @@ video.post("/process", async (c) => {
const jobId = generateJobId();
const job = createJob(jobId, videoId, userId, webhookUrl, webhookSecret);
- processVideoAsync(
- job.jobId,
- videoUrl,
- outputPresignedUrl,
- thumbnailPresignedUrl,
- previewGifPresignedUrl,
- result.data,
+ withMediaTransfers(32 * 1024 ** 3, () =>
+ processVideoAsync(
+ job.jobId,
+ videoUrl,
+ outputPresignedUrl,
+ thumbnailPresignedUrl,
+ previewGifPresignedUrl,
+ result.data,
+ ),
).catch((err) => {
console.error(
`[video/process] Async processing error for job ${jobId}:`,
@@ -776,13 +786,15 @@ video.post("/edit", async (c) => {
const jobId = generateJobId();
const job = createJob(jobId, videoId, userId, webhookUrl, webhookSecret);
- editVideoAsync(
- job.jobId,
- sourceUrl,
- outputPresignedUrl,
- thumbnailPresignedUrl,
- previewGifPresignedUrl,
- result.data,
+ withMediaTransfers(32 * 1024 ** 3, () =>
+ editVideoAsync(
+ job.jobId,
+ sourceUrl,
+ outputPresignedUrl,
+ thumbnailPresignedUrl,
+ previewGifPresignedUrl,
+ result.data,
+ ),
).catch((err) => {
console.error(`[video/edit] Async edit error for job ${jobId}:`, err);
const currentJob = getJob(jobId);
@@ -1589,6 +1601,8 @@ const strongObjectIdentitySchema = z
.max(1_024)
.regex(/^"[\x21\x23-\x7E\x80-\xFF]+"$/);
const recordingAttemptFields = {
+ processingPriority: z.enum(["interactive", "recovery"]).optional(),
+ downloadBudgetBytes: z.number().int().positive().safe().optional(),
generation: z.string().min(1).max(200).optional(),
attemptId: z.string().min(1).max(200).optional(),
outputKey: z.string().min(1).max(1_024).optional(),
@@ -1688,6 +1702,8 @@ function recordingWorkerResponse(job: Job, ownerJobId: string) {
}
function classifySourceError(error: unknown): RecordingErrorCode {
+ if (error instanceof MediaTransferBudgetError)
+ return "processing-budget-exhausted";
if (
isRetryableRecordingVerificationError(error) ||
isBusyError(error) ||
@@ -1753,7 +1769,7 @@ video.post("/verify-recording", async (c) => {
);
return c.json(recordingWorkerResponse(existing, ownerJobId));
}
- if (!canAcceptNewVideoProcess()) {
+ if (!canAcceptNewVideoProcess(body.processingPriority)) {
c.header("Retry-After", VIDEO_BUSY_RETRY_AFTER_SECONDS.toString());
return c.json(getMuxBusyResponseBody(getVideoCapacitySnapshot()), 503);
}
@@ -1785,7 +1801,19 @@ video.post("/verify-recording", async (c) => {
deleteJob(jobId);
return c.json(recordingWorkerResponse(job, ownerJobId));
}
- void verifyUploadedRecordingAsync(jobId, body);
+ void withMediaTransfers(body.downloadBudgetBytes ?? body.fileSize * 3, () =>
+ verifyUploadedRecordingAsync(jobId, body),
+ ).catch((error: unknown) => {
+ const current = getJob(jobId);
+ if (!current || ["complete", "error", "cancelled"].includes(current.phase))
+ return;
+ updateJob(jobId, {
+ phase: "error",
+ error: "Recording transfer could not complete",
+ errorCode: classifySourceError(error),
+ });
+ sendCurrentJobWebhook(jobId);
+ });
return c.json(recordingWorkerResponse(job, jobId));
});
@@ -1797,7 +1825,8 @@ async function verifyUploadedRecordingAsync(
if (!updateJob(jobId, { abortController, phase: "processing", progress: 0 }))
return;
try {
- const metadata = await probeVideo(body.videoUrl).catch(() => {
+ const metadata = await probeVideo(body.videoUrl).catch((error: unknown) => {
+ if (error instanceof MediaTransferBudgetError) throw error;
throw new Error(RECORDING_VERIFICATION_RETRY_ERROR);
});
if (
@@ -2067,7 +2096,7 @@ video.post("/mux-segments", async (c) => {
});
}
- if (!canAcceptNewVideoProcess()) {
+ if (!canAcceptNewVideoProcess(body.data.processingPriority)) {
c.header("Retry-After", VIDEO_BUSY_RETRY_AFTER_SECONDS.toString());
return c.json(getMuxBusyResponseBody(getVideoCapacitySnapshot()), 503);
}
@@ -2108,18 +2137,20 @@ video.post("/mux-segments", async (c) => {
});
}
- muxSegmentsAsync(
- jobId,
- videoId,
- outputUpload,
- thumbnailPresignedUrl,
- previewGifPresignedUrl,
- videoInitUrl,
- videoSegUrls,
- audioInitUrl ?? null,
- audioSegUrls ?? null,
- body.data.outputVerificationUrl,
- body.data,
+ withMediaTransfers(body.data.downloadBudgetBytes ?? 32 * 1024 ** 3, () =>
+ muxSegmentsAsync(
+ jobId,
+ videoId,
+ outputUpload,
+ thumbnailPresignedUrl,
+ previewGifPresignedUrl,
+ videoInitUrl,
+ videoSegUrls,
+ audioInitUrl ?? null,
+ audioSegUrls ?? null,
+ body.data.outputVerificationUrl,
+ body.data,
+ ),
).catch((err) => {
console.error(`[mux-segments] Async mux error for job ${jobId}:`, err);
const currentJob = getJob(jobId);
@@ -2218,7 +2249,23 @@ async function downloadUrlToFileOnce(
): Promise<void> {
const abortController = new AbortController();
const timeoutSignal = AbortSignal.timeout(120_000);
- const resp = await fetch(url, {
+ const local = await materializeMedia(
+ url,
+ abortSignal ? AbortSignal.any([abortSignal, timeoutSignal]) : timeoutSignal,
+ source?.objectIdentity,
+ );
+ if (local) {
+ if (source && local.target.size !== source.size)
+ throw new MediaDownloadError(
+ "Recording source size changed while downloading",
+ false,
+ "source-changed",
+ );
+ await link(local.path, destPath);
+ await releaseMaterializedMedia(local.path);
+ return;
+ }
+ const resp = await fetchMedia(url, {
headers: source
? {
"If-Match": source.objectIdentity,
@@ -2332,7 +2379,8 @@ async function downloadUrlToFile(
return;
} catch (error) {
if (abortSignal?.aborted) throw error;
- if (isBusyError(error)) throw error;
+ if (isBusyError(error) || error instanceof MediaTransferBudgetError)
+ throw error;
const downloadError =
error instanceof Error ? error : new Error(String(error));
@@ -2832,13 +2880,15 @@ async function muxSegmentsAsync(
? "cancelled"
: "error",
errorCode:
- error instanceof MediaDownloadError
- ? error.errorCode
- : isRetryableRecordingVerificationError(error) ||
- isBusyError(error) ||
- isTimeoutError(error)
- ? "processing-unavailable"
- : errorCode,
+ error instanceof MediaTransferBudgetError
+ ? "processing-budget-exhausted"
+ : error instanceof MediaDownloadError
+ ? error.errorCode
+ : isRetryableRecordingVerificationError(error) ||
+ isBusyError(error) ||
+ isTimeoutError(error)
+ ? "processing-unavailable"
+ : errorCode,
error: isRetryableRecordingVerificationError(error)
? "Recording verification temporarily unavailable (503)"
: error instanceof Error
diff --git a/apps/web/__tests__/unit/finalize-desktop-recording.test.ts b/apps/web/__tests__/unit/finalize-desktop-recording.test.ts
index 5c4a6d9f1..d4745e61f 100644
--- a/apps/web/__tests__/unit/finalize-desktop-recording.test.ts
+++ b/apps/web/__tests__/unit/finalize-desktop-recording.test.ts
@@ -5,6 +5,7 @@ import type {
DesktopRecordingAttempt,
DesktopRecordingJob,
} from "@/lib/desktop-recording-jobs";
+import { MediaProcessingBudgetError } from "@/lib/media-processing-budget";
const mocks = vi.hoisted(() => ({
state: vi.fn(),
@@ -27,6 +28,11 @@ const mocks = vi.hoisted(() => ({
fetch: vi.fn(),
put: vi.fn(),
databaseRows: vi.fn(),
+ reserveBudget: vi.fn(),
+}));
+vi.mock("@/lib/media-processing-budget", () => ({
+ reserveMediaProcessingBudget: mocks.reserveBudget,
+ MediaProcessingBudgetError: class extends Error {},
}));
vi.mock("@cap/database", () => ({
db: () => ({
@@ -141,6 +147,7 @@ function withCurrent(update: Partial<DesktopRecordingJob>) {
}
beforeEach(() => {
+ mocks.reserveBudget.mockResolvedValue(100_000_000);
mocks.databaseRows.mockResolvedValue([
{ id: "video", ownerId: "user", source: { type: "desktopSegments" } },
]);
@@ -501,6 +508,17 @@ describe("source commitment and media request compatibility", () => {
expect(mocks.fetch).not.toHaveBeenCalled();
});
+ it("blocks an exhausted transfer budget before dispatching media work", async () => {
+ const error = new MediaProcessingBudgetError("daily");
+ mocks.reserveBudget.mockRejectedValueOnce(error);
+ await expect(startDesktopRecordingJob(fixture)).rejects.toBe(error);
+ expect(mocks.blocked).toHaveBeenCalledWith(
+ expect.objectContaining({ errorCode: "processing-budget-exhausted" }),
+ );
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ expect(mocks.put).not.toHaveBeenCalled();
+ });
+
it("preserves incomplete originals without calling the media server", async () => {
withCurrent({ source: null, state: "committing" });
mocks.commitSource.mockRejectedValue(
@@ -547,6 +565,13 @@ describe("source commitment and media request compatibility", () => {
});
mocks.sourceUrls.mockResolvedValue({
videoUrl: "https://source.test/recording.mp4",
+ sourceObjects: [
+ {
+ url: "https://source.test/recording.mp4",
+ size: 1000,
+ objectIdentity: '"snapshot"',
+ },
+ ],
sourceObjectIdentity: '"snapshot"',
outputKey: "user/video/.recording/sources/generation/mp4/0.mp4",
});
@@ -584,6 +609,13 @@ describe("source commitment and media request compatibility", () => {
});
mocks.sourceUrls.mockResolvedValue({
videoUrl: "https://source.test/recording.mp4",
+ sourceObjects: [
+ {
+ url: "https://source.test/recording.mp4",
+ size: 1000,
+ objectIdentity: '"snapshot"',
+ },
+ ],
sourceObjectIdentity: '"snapshot"',
outputKey: "user/video/.recording/sources/generation/mp4/0.mp4",
});
diff --git a/apps/web/__tests__/unit/google-drive-storage.test.ts b/apps/web/__tests__/unit/google-drive-storage.test.ts
index ee9388b67..b426c9b57 100644
--- a/apps/web/__tests__/unit/google-drive-storage.test.ts
+++ b/apps/web/__tests__/unit/google-drive-storage.test.ts
@@ -19,6 +19,7 @@ import {
findGoogleDriveFileByObjectKey,
GOOGLE_DRIVE_FOLDER_MIME_TYPE,
type GoogleDriveTokenStore,
+ getGoogleDriveRecordingDownload,
getGoogleDriveRecordingResponse,
syncGoogleDriveVideoNames,
} from "../../../../packages/web-backend/src/Storage/GoogleDrive";
@@ -346,6 +347,45 @@ describe("Google Drive recording content identity", () => {
};
const identity = getGoogleDriveRecordingIdentity(file) as string;
+ it("issues only the pinned revision after validating the expected identity", async () => {
+ const fetch = vi.fn(async () => jsonResponse(file));
+ vi.stubGlobal("fetch", fetch);
+ const target = await Effect.runPromise(
+ getGoogleDriveRecordingDownload(
+ makeConfig(),
+ file.id,
+ { objectIdentity: identity },
+ makeTokenStore(),
+ ),
+ );
+ expect(target.url).toBe(
+ "https://www.googleapis.com/drive/v3/files/recording-file/revisions/revision-1?alt=media",
+ );
+ expect(target.objectIdentity).toBe(identity);
+ expect(target.sha256).toBe(file.sha256Checksum);
+ expect(target.size).toBe(8);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not issue a download descriptor for a changed recording", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ jsonResponse({ ...file, sha256Checksum: "b".repeat(64) }),
+ ),
+ );
+ await expect(
+ Effect.runPromise(
+ getGoogleDriveRecordingDownload(
+ makeConfig(),
+ file.id,
+ { objectIdentity: identity },
+ makeTokenStore(),
+ ),
+ ),
+ ).rejects.toThrow("Recording object changed");
+ });
+
it("matches the media-server upload identity wire vector", () => {
expect(
getGoogleDriveRecordingIdentity({
diff --git a/apps/web/__tests__/unit/storage-object-verification.test.ts b/apps/web/__tests__/unit/storage-object-verification.test.ts
index 21ea92792..961913352 100644
--- a/apps/web/__tests__/unit/storage-object-verification.test.ts
+++ b/apps/web/__tests__/unit/storage-object-verification.test.ts
@@ -7,6 +7,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
head: vi.fn(),
read: vi.fn(),
+ download: vi.fn(),
token: null as { videoId: string; key: string } | null,
video: {
id: "video",
@@ -27,7 +28,11 @@ vi.mock("@cap/web-backend", async () => {
Storage: {
getAccessForVideo: () =>
Effect.succeed([
- { headObject: mocks.head, getObjectResponse: mocks.read },
+ {
+ headObject: mocks.head,
+ getObjectResponse: mocks.read,
+ getInternalDownload: mocks.download,
+ },
]),
},
Videos: Effect.succeed({
@@ -39,6 +44,9 @@ vi.mock("@cap/web-backend", async () => {
verifyStorageObjectToken: () => mocks.token,
};
});
+vi.mock("@cap/env", () => ({
+ serverEnv: () => ({ MEDIA_SERVER_WEBHOOK_SECRET: "test-media-secret" }),
+}));
vi.mock("@/lib/server", async () => {
const { Effect } = await import("effect");
return { runPromise: Effect.runPromise };
@@ -76,6 +84,42 @@ describe("recording verification object reads", () => {
);
});
+ it("does not expose Drive credentials to ordinary clients", async () => {
+ expect((await request({ "x-cap-internal-download": "1" })).status).toBe(
+ 401,
+ );
+ expect(
+ (
+ await request({
+ "x-cap-internal-download": "1",
+ "x-media-server-secret": "invalid",
+ })
+ ).status,
+ ).toBe(401);
+ expect(mocks.download).not.toHaveBeenCalled();
+ });
+
+ it("authorizes an internal descriptor without downloading media", async () => {
+ mocks.download.mockReturnValue(
+ Effect.succeed({
+ version: 1,
+ url: "https://www.googleapis.com/drive/v3/files/file/revisions/revision?alt=media",
+ }),
+ );
+ const response = await request({
+ "x-cap-internal-download": "1",
+ "x-media-server-secret": "test-media-secret",
+ "if-match": '"identity"',
+ });
+ expect(response.status).toBe(200);
+ expect(response.headers.get("Cache-Control")).toBe("private, no-store");
+ expect(mocks.download).toHaveBeenCalledWith(
+ "owner/video/result.mp4",
+ expect.objectContaining({ objectIdentity: '"identity"' }),
+ );
+ expect(mocks.read).not.toHaveBeenCalled();
+ });
+
it("does not add metadata requests to ordinary playback", async () => {
const response = await request();
expect(response.status).toBe(206);
diff --git a/apps/web/app/api/storage/object/route.ts b/apps/web/app/api/storage/object/route.ts
index 8ff986953..bbbd1473d 100644
--- a/apps/web/app/api/storage/object/route.ts
+++ b/apps/web/app/api/storage/object/route.ts
@@ -1,3 +1,5 @@
+import { timingSafeEqual } from "node:crypto";
+import { serverEnv } from "@cap/env";
import {
provideOptionalAuth,
Storage,
@@ -122,6 +124,21 @@ const getPolicyVideo = (videoId: Video.VideoId) =>
});
export async function GET(request: NextRequest) {
+ const internalDownload =
+ request.headers.get("x-cap-internal-download") === "1";
+ if (internalDownload) {
+ const expected = serverEnv().MEDIA_SERVER_WEBHOOK_SECRET;
+ const provided = request.headers.get("x-media-server-secret");
+ if (
+ !expected ||
+ !provided ||
+ Buffer.byteLength(expected) !== Buffer.byteLength(provided) ||
+ !timingSafeEqual(Buffer.from(expected), Buffer.from(provided))
+ ) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+ }
+
const videoIdParam = request.nextUrl.searchParams.get("videoId");
const key = request.nextUrl.searchParams.get("key");
const token = request.nextUrl.searchParams.get("token");
@@ -165,6 +182,22 @@ export async function GET(request: NextRequest) {
return Response.redirect(url);
}
+ if (internalDownload) {
+ if (!("getInternalDownload" in storage))
+ return new Response("Unsupported storage", { status: 400 });
+ const target = yield* storage.getInternalDownload(key, {
+ objectIdentity: request.headers.get("if-match") ?? undefined,
+ signal: request.signal,
+ });
+ return Response.json(target, {
+ headers: {
+ "Cache-Control": "private, no-store",
+ "Vercel-CDN-Cache-Control": "no-store",
+ Vary: "x-cap-internal-download, x-media-server-secret",
+ },
+ });
+ }
+
const verificationRequested =
request.headers.get("x-cap-recording-verification") === "1";
const expectedIdentity = request.headers.get("if-match");
diff --git a/apps/web/lib/desktop-recording-publication.ts b/apps/web/lib/desktop-recording-publication.ts
index 35811fd32..bf60b928f 100644
--- a/apps/web/lib/desktop-recording-publication.ts
+++ b/apps/web/lib/desktop-recording-publication.ts
@@ -224,9 +224,12 @@ async function applyActiveRecordingProgress(payload: RecordingProgress) {
const errorCode = payload.errorCode ?? "processing-unavailable";
const blocked =
failed &&
- ["source-invalid", "source-missing", "source-changed"].includes(
- errorCode,
- );
+ [
+ "source-invalid",
+ "source-missing",
+ "source-changed",
+ "processing-budget-exhausted",
+ ].includes(errorCode);
await tx
.update(videoProcessingJobs)
.set({
diff --git a/apps/web/lib/media-processing-budget.ts b/apps/web/lib/media-processing-budget.ts
new file mode 100644
index 000000000..32f8bbdb1
--- /dev/null
+++ b/apps/web/lib/media-processing-budget.ts
@@ -0,0 +1,112 @@
+import { createHash } from "node:crypto";
+import { db } from "@cap/database";
+import { mediaProcessingBudgets } from "@cap/database/schema";
+import { asc, inArray, sql } from "drizzle-orm";
+
+const GiB = 1024 ** 3;
+const MiB = 1024 ** 2;
+export class MediaProcessingBudgetError extends Error {
+ constructor(readonly scope: "recording" | "daily") {
+ super(`Recording processing paused: ${scope} transfer budget exhausted`);
+ this.name = "MediaProcessingBudgetError";
+ }
+}
+const key = (parts: string[]) =>
+ createHash("sha256").update(JSON.stringify(parts)).digest("hex");
+
+export function getMediaProcessingReservation(sourceBytes: number) {
+ if (
+ !Number.isSafeInteger(sourceBytes) ||
+ sourceBytes <= 0 ||
+ sourceBytes > Number.MAX_SAFE_INTEGER / 12
+ )
+ throw new Error("Invalid processing source size");
+ return {
+ attemptBytes: sourceBytes * 3 + 16 * MiB,
+ recordingBytes: sourceBytes * 9 + 80 * MiB,
+ };
+}
+
+export async function reserveMediaProcessingBudget(input: {
+ videoId: string;
+ generation: string;
+ attemptId: string;
+ sourceBytes: number;
+ now?: Date;
+}) {
+ const now = input.now ?? new Date();
+ const { attemptBytes, recordingBytes } = getMediaProcessingReservation(
+ input.sourceBytes,
+ );
+ const configured = Number(
+ process.env.MEDIA_PROCESSING_DAILY_BUDGET_GIB ?? "100",
+ );
+ if (
+ !Number.isFinite(configured) ||
+ configured <= 0 ||
+ !Number.isSafeInteger(configured * GiB)
+ )
+ throw new Error("Invalid daily processing budget");
+ const attemptKey = key([
+ "attempt",
+ input.videoId,
+ input.generation,
+ input.attemptId,
+ ]);
+ const recordingKey = key(["recording", input.videoId, input.generation]);
+ const dailyKey = key(["daily", now.toISOString().slice(0, 10)]);
+ const expiresAt = new Date(now.getTime() + 30 * 24 * 60 * 60_000);
+ return db().transaction(async (tx) => {
+ const limits = [
+ { id: attemptKey, limitBytes: attemptBytes },
+ { id: recordingKey, limitBytes: recordingBytes },
+ { id: dailyKey, limitBytes: configured * GiB },
+ ].sort((left, right) => left.id.localeCompare(right.id));
+ await tx
+ .insert(mediaProcessingBudgets)
+ .values(limits.map((limit) => ({ ...limit, expiresAt })))
+ .onDuplicateKeyUpdate({ set: { id: sql`${mediaProcessingBudgets.id}` } });
+ const locked = await tx
+ .select()
+ .from(mediaProcessingBudgets)
+ .where(
+ inArray(
+ mediaProcessingBudgets.id,
+ limits.map((limit) => limit.id),
+ ),
+ )
+ .orderBy(asc(mediaProcessingBudgets.id))
+ .for("update");
+ const rows = new Map(locked.map((row) => [row.id, row]));
+ if (rows.size !== limits.length)
+ throw new Error("Processing budget is unavailable");
+
+ const attempt = rows.get(attemptKey);
+ if (attempt?.reservedBytes) {
+ if (attempt.reservedBytes !== attemptBytes)
+ throw new Error("Processing reservation changed");
+ return attemptBytes;
+ }
+ for (const [id, scope] of [
+ [recordingKey, "recording"],
+ [dailyKey, "daily"],
+ ] as const) {
+ const row = rows.get(id);
+ if (!row || row.reservedBytes + attemptBytes > row.limitBytes)
+ throw new MediaProcessingBudgetError(scope);
+ }
+ await tx
+ .update(mediaProcessingBudgets)
+ .set({
+ reservedBytes: sql`${mediaProcessingBudgets.reservedBytes} + ${attemptBytes}`,
+ })
+ .where(
+ inArray(
+ mediaProcessingBudgets.id,
+ limits.map((limit) => limit.id),
+ ),
+ );
+
+ return attemptBytes;
+ });
+}
diff --git a/apps/web/workflows/finalize-desktop-recording.ts b/apps/web/workflows/finalize-desktop-recording.ts
index 5b79e8b80..ac42c38a7 100644
--- a/apps/web/workflows/finalize-desktop-recording.ts
+++ b/apps/web/workflows/finalize-desktop-recording.ts
@@ -30,6 +30,10 @@ import {
} from "@/lib/desktop-recording-source";
import type { RecordingVerification } from "@/lib/desktop-recording-verification";
import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota-cache";
+import {
+ MediaProcessingBudgetError,
+ reserveMediaProcessingBudget,
+} from "@/lib/media-processing-budget";
import { transcribeVideo } from "@/lib/transcribe";
import { decodeStorageVideo } from "@/lib/video-storage";
import { runWorkflowPromise } from "@/lib/workflow-runtime";
@@ -435,8 +439,33 @@ export async function startDesktopRecordingJob(
}
throw error;
});
+ let downloadBudgetBytes: number;
+ try {
+ downloadBudgetBytes = await reserveMediaProcessingBudget({
+ videoId: current.videoId,
+ generation: current.generation,
+ attemptId: attempt.attemptId,
+ sourceBytes: urls.sourceObjects.reduce(
+ (total, object) => total + object.size,
+ 0,
+ ),
+ });
+ } catch (error) {
+ if (error instanceof MediaProcessingBudgetError) {
+ await markSourceBlocked({
+ videoId: current.videoId,
+ generation: current.generation,
+ attemptId: attempt.attemptId,
+ errorCode: "processing-budget-exhausted",
+ errorMessage: error.message,
+ });
+ }
+ throw error;
+ }
const webhookBaseUrl = env.MEDIA_SERVER_WEBHOOK_URL || env.WEB_URL;
const context = {
+ downloadBudgetBytes,
+ processingPriority: current.attemptCount > 1 ? "recovery" : "interactive",
videoId: current.videoId,
userId: current.ownerId,
generation: current.generation,
diff --git a/packages/database/migrations/0043_flimsy_caretaker.sql b/packages/database/migrations/0043_flimsy_caretaker.sql
new file mode 100644
index 000000000..ee475d74e
--- /dev/null
+++ b/packages/database/migrations/0043_flimsy_caretaker.sql
@@ -0,0 +1,9 @@
+CREATE TABLE `media_processing_budgets` (
+ `id` varchar(64) NOT NULL,
+ `reserved_bytes` bigint unsigned NOT NULL DEFAULT 0,
+ `limit_bytes` bigint unsigned NOT NULL,
+ `expires_at` datetime(3) NOT NULL,
+ CONSTRAINT `media_processing_budgets_id` PRIMARY KEY(`id`)
+);
+--> statement-breakpoint
+CREATE INDEX `media_budget_expiry_idx` ON `media_processing_budgets` (`expires_at`);
\ No newline at end of file
diff --git a/packages/database/migrations/meta/0043_snapshot.json b/packages/database/migrations/meta/0043_snapshot.json
new file mode 100644
index 000000000..230c197e5
--- /dev/null
+++ b/packages/database/migrations/meta/0043_snapshot.json
@@ -0,0 +1,4467 @@
+{
+ "version": "5",
+ "dialect": "mysql",
+ "id": "abd5c5ee-0381-4c1d-a6c7-257c04d094ed",
+ "prevId": "8b7635aa-9c42-41dc-993c-1f2ae7af6364",
+ "tables": {
+ "accounts": {
+ "name": "accounts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "providerAccountId": {
+ "name": "providerAccountId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_in": {
+ "name": "expires_in",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_expires_in": {
+ "name": "refresh_token_expires_in",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_type": {
+ "name": "token_type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "tempColumn": {
+ "name": "tempColumn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_id_idx": {
+ "name": "user_id_idx",
+ "columns": ["userId"],
+ "isUnique": false
+ },
+ "provider_account_id_idx": {
+ "name": "provider_account_id_idx",
+ "columns": ["providerAccountId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "accounts_id": {
+ "name": "accounts_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "agent_api_authorization_codes": {
+ "name": "agent_api_authorization_codes",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "codeHash": {
+ "name": "codeHash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "codeChallenge": {
+ "name": "codeChallenge",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirectUri": {
+ "name": "redirectUri",
+ "type": "varchar(512)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "consumedAt": {
+ "name": "consumedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "code_hash_idx": {
+ "name": "code_hash_idx",
+ "columns": ["codeHash"],
+ "isUnique": true
+ },
+ "expires_at_idx": {
+ "name": "expires_at_idx",
+ "columns": ["expiresAt"],
+ "isUnique": false
+ },
+ "user_created_at_idx": {
+ "name": "user_created_at_idx",
+ "columns": ["userId", "createdAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "agent_api_authorization_codes_id": {
+ "name": "agent_api_authorization_codes_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "agent_api_idempotency": {
+ "name": "agent_api_idempotency",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "operation": {
+ "name": "operation",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "keyHash": {
+ "name": "keyHash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "requestHash": {
+ "name": "requestHash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "statusCode": {
+ "name": "statusCode",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "response": {
+ "name": "response",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "user_operation_key_idx": {
+ "name": "user_operation_key_idx",
+ "columns": ["userId", "operation", "keyHash"],
+ "isUnique": true
+ },
+ "expires_at_idx": {
+ "name": "expires_at_idx",
+ "columns": ["expiresAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "agent_api_idempotency_id": {
+ "name": "agent_api_idempotency_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "agent_api_keys": {
+ "name": "agent_api_keys",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tokenHash": {
+ "name": "tokenHash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(100)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'Cap CLI'"
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "lastUsedAt": {
+ "name": "lastUsedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "token_hash_idx": {
+ "name": "token_hash_idx",
+ "columns": ["tokenHash"],
+ "isUnique": true
+ },
+ "user_created_at_idx": {
+ "name": "user_created_at_idx",
+ "columns": ["userId", "createdAt"],
+ "isUnique": false
+ },
+ "expires_at_idx": {
+ "name": "expires_at_idx",
+ "columns": ["expiresAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "agent_api_keys_id": {
+ "name": "agent_api_keys_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "agent_api_operations": {
+ "name": "agent_api_operations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "resourceId": {
+ "name": "resourceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "resultResourceId": {
+ "name": "resultResourceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "payload": {
+ "name": "payload",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "result": {
+ "name": "result",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "errorCode": {
+ "name": "errorCode",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "errorMessage": {
+ "name": "errorMessage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "completedAt": {
+ "name": "completedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_created_at_idx": {
+ "name": "user_created_at_idx",
+ "columns": ["userId", "createdAt"],
+ "isUnique": false
+ },
+ "state_updated_at_idx": {
+ "name": "state_updated_at_idx",
+ "columns": ["state", "updatedAt"],
+ "isUnique": false
+ },
+ "resource_id_idx": {
+ "name": "resource_id_idx",
+ "columns": ["resourceId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "agent_api_operations_id": {
+ "name": "agent_api_operations_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "auth_api_keys": {
+ "name": "auth_api_keys",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(36)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unknown'"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "user_id_created_at_idx": {
+ "name": "user_id_created_at_idx",
+ "columns": ["userId", "createdAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "auth_api_keys_id": {
+ "name": "auth_api_keys_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "comments": {
+ "name": "comments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(6)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "authorId": {
+ "name": "authorId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "parentCommentId": {
+ "name": "parentCommentId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "mediaKey": {
+ "name": "mediaKey",
+ "type": "varchar(512)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "mediaDuration": {
+ "name": "mediaDuration",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "mediaMeta": {
+ "name": "mediaMeta",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "video_type_created_idx": {
+ "name": "video_type_created_idx",
+ "columns": ["videoId", "type", "createdAt", "id"],
+ "isUnique": false
+ },
+ "author_id_idx": {
+ "name": "author_id_idx",
+ "columns": ["authorId"],
+ "isUnique": false
+ },
+ "parent_comment_id_idx": {
+ "name": "parent_comment_id_idx",
+ "columns": ["parentCommentId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "comments_id": {
+ "name": "comments_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "developer_api_keys": {
+ "name": "developer_api_keys",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "appId": {
+ "name": "appId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "keyType": {
+ "name": "keyType",
+ "type": "varchar(8)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "keyPrefix": {
+ "name": "keyPrefix",
+ "type": "varchar(12)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "keyHash": {
+ "name": "keyHash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "encryptedKey": {
+ "name": "encryptedKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lastUsedAt": {
+ "name": "lastUsedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "key_hash_idx": {
+ "name": "key_hash_idx",
+ "columns": ["keyHash"],
+ "isUnique": true
+ },
+ "app_key_type_idx": {
+ "name": "app_key_type_idx",
+ "columns": ["appId", "keyType"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "developer_api_keys_appId_developer_apps_id_fk": {
+ "name": "developer_api_keys_appId_developer_apps_id_fk",
+ "tableFrom": "developer_api_keys",
+ "tableTo": "developer_apps",
+ "columnsFrom": ["appId"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "developer_api_keys_id": {
+ "name": "developer_api_keys_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "developer_app_domains": {
+ "name": "developer_app_domains",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "appId": {
+ "name": "appId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "domain": {
+ "name": "domain",
+ "type": "varchar(253)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "developer_app_domains_appId_developer_apps_id_fk": {
+ "name": "developer_app_domains_appId_developer_apps_id_fk",
+ "tableFrom": "developer_app_domains",
+ "tableTo": "developer_apps",
+ "columnsFrom": ["appId"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "developer_app_domains_id": {
+ "name": "developer_app_domains_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {
+ "app_domain_unique": {
+ "name": "app_domain_unique",
+ "columns": ["appId", "domain"]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "developer_apps": {
+ "name": "developer_apps",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "environment": {
+ "name": "environment",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "logoUrl": {
+ "name": "logoUrl",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deletedAt": {
+ "name": "deletedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "owner_deleted_idx": {
+ "name": "owner_deleted_idx",
+ "columns": ["ownerId", "deletedAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "developer_apps_id": {
+ "name": "developer_apps_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "developer_credit_accounts": {
+ "name": "developer_credit_accounts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "appId": {
+ "name": "appId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "balanceMicroCredits": {
+ "name": "balanceMicroCredits",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripePaymentMethodId": {
+ "name": "stripePaymentMethodId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "autoTopUpEnabled": {
+ "name": "autoTopUpEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "autoTopUpThresholdMicroCredits": {
+ "name": "autoTopUpThresholdMicroCredits",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "autoTopUpAmountCents": {
+ "name": "autoTopUpAmountCents",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "app_id_unique": {
+ "name": "app_id_unique",
+ "columns": ["appId"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "developer_credit_accounts_appId_developer_apps_id_fk": {
+ "name": "developer_credit_accounts_appId_developer_apps_id_fk",
+ "tableFrom": "developer_credit_accounts",
+ "tableTo": "developer_apps",
+ "columnsFrom": ["appId"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "developer_credit_accounts_id": {
+ "name": "developer_credit_accounts_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "developer_credit_transactions": {
+ "name": "developer_credit_transactions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "accountId": {
+ "name": "accountId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "amountMicroCredits": {
+ "name": "amountMicroCredits",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "balanceAfterMicroCredits": {
+ "name": "balanceAfterMicroCredits",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "referenceType": {
+ "name": "referenceType",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "account_type_created_idx": {
+ "name": "account_type_created_idx",
+ "columns": ["accountId", "type", "createdAt"],
+ "isUnique": false
+ },
+ "account_ref_dedup_idx": {
+ "name": "account_ref_dedup_idx",
+ "columns": ["accountId", "referenceId", "referenceType"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "dev_credit_txn_account_fk": {
+ "name": "dev_credit_txn_account_fk",
+ "tableFrom": "developer_credit_transactions",
+ "tableTo": "developer_credit_accounts",
+ "columnsFrom": ["accountId"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "developer_credit_transactions_id": {
+ "name": "developer_credit_transactions_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "developer_daily_storage_snapshots": {
+ "name": "developer_daily_storage_snapshots",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "appId": {
+ "name": "appId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshotDate": {
+ "name": "snapshotDate",
+ "type": "varchar(10)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "totalDurationMinutes": {
+ "name": "totalDurationMinutes",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "videoCount": {
+ "name": "videoCount",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "microCreditsCharged": {
+ "name": "microCreditsCharged",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "processedAt": {
+ "name": "processedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "developer_daily_storage_snapshots_appId_developer_apps_id_fk": {
+ "name": "developer_daily_storage_snapshots_appId_developer_apps_id_fk",
+ "tableFrom": "developer_daily_storage_snapshots",
+ "tableTo": "developer_apps",
+ "columnsFrom": ["appId"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "developer_daily_storage_snapshots_id": {
+ "name": "developer_daily_storage_snapshots_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {
+ "app_date_unique": {
+ "name": "app_date_unique",
+ "columns": ["appId", "snapshotDate"]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "developer_videos": {
+ "name": "developer_videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "appId": {
+ "name": "appId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "externalUserId": {
+ "name": "externalUserId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'Untitled'"
+ },
+ "duration": {
+ "name": "duration",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "width": {
+ "name": "width",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "height": {
+ "name": "height",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fps": {
+ "name": "fps",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "s3Key": {
+ "name": "s3Key",
+ "type": "varchar(512)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "transcriptionStatus": {
+ "name": "transcriptionStatus",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deletedAt": {
+ "name": "deletedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "app_created_idx": {
+ "name": "app_created_idx",
+ "columns": ["appId", "createdAt"],
+ "isUnique": false
+ },
+ "app_user_idx": {
+ "name": "app_user_idx",
+ "columns": ["appId", "externalUserId"],
+ "isUnique": false
+ },
+ "app_deleted_idx": {
+ "name": "app_deleted_idx",
+ "columns": ["appId", "deletedAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "developer_videos_appId_developer_apps_id_fk": {
+ "name": "developer_videos_appId_developer_apps_id_fk",
+ "tableFrom": "developer_videos",
+ "tableTo": "developer_apps",
+ "columnsFrom": ["appId"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "developer_videos_id": {
+ "name": "developer_videos_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "folders": {
+ "name": "folders",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdById": {
+ "name": "createdById",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "parentId": {
+ "name": "parentId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "created_by_id_idx": {
+ "name": "created_by_id_idx",
+ "columns": ["createdById"],
+ "isUnique": false
+ },
+ "parent_id_idx": {
+ "name": "parent_id_idx",
+ "columns": ["parentId"],
+ "isUnique": false
+ },
+ "space_id_idx": {
+ "name": "space_id_idx",
+ "columns": ["spaceId"],
+ "isUnique": false
+ },
+ "public_parent_id_idx": {
+ "name": "public_parent_id_idx",
+ "columns": ["public", "parentId"],
+ "isUnique": false
+ },
+ "public_space_parent_id_idx": {
+ "name": "public_space_parent_id_idx",
+ "columns": ["public", "spaceId", "parentId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "folders_id": {
+ "name": "folders_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "imported_videos": {
+ "name": "imported_videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source_id": {
+ "name": "source_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "id_idx": {
+ "name": "id_idx",
+ "columns": ["id"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "imported_videos_orgId_source_source_id_pk": {
+ "name": "imported_videos_orgId_source_source_id_pk",
+ "columns": ["orgId", "source", "source_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "integration_installations": {
+ "name": "integration_installations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "externalId": {
+ "name": "externalId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "displayName": {
+ "name": "displayName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "installedByUserId": {
+ "name": "installedByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "encryptedCredentials": {
+ "name": "encryptedCredentials",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "provider_external_id_idx": {
+ "name": "provider_external_id_idx",
+ "columns": ["provider", "externalId"],
+ "isUnique": true
+ },
+ "organization_provider_display_name_idx": {
+ "name": "organization_provider_display_name_idx",
+ "columns": ["organizationId", "provider", "displayName"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "integration_installations_id": {
+ "name": "integration_installations_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "media_processing_budgets": {
+ "name": "media_processing_budgets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "reserved_bytes": {
+ "name": "reserved_bytes",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "limit_bytes": {
+ "name": "limit_bytes",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "datetime(3)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "media_budget_expiry_idx": {
+ "name": "media_budget_expiry_idx",
+ "columns": ["expires_at"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "media_processing_budgets_id": {
+ "name": "media_processing_budgets_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "messenger_conversations": {
+ "name": "messenger_conversations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent": {
+ "name": "agent",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mode": {
+ "name": "mode",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'agent'"
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "anonymousId": {
+ "name": "anonymousId",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "takeoverByUserId": {
+ "name": "takeoverByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "takeoverAt": {
+ "name": "takeoverAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "lastMessageAt": {
+ "name": "lastMessageAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "user_last_message_idx": {
+ "name": "user_last_message_idx",
+ "columns": ["userId", "lastMessageAt"],
+ "isUnique": false
+ },
+ "anonymous_last_message_idx": {
+ "name": "anonymous_last_message_idx",
+ "columns": ["anonymousId", "lastMessageAt"],
+ "isUnique": false
+ },
+ "mode_last_message_idx": {
+ "name": "mode_last_message_idx",
+ "columns": ["mode", "lastMessageAt"],
+ "isUnique": false
+ },
+ "updated_at_idx": {
+ "name": "updated_at_idx",
+ "columns": ["updatedAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "messenger_conversations_id": {
+ "name": "messenger_conversations_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "messenger_messages": {
+ "name": "messenger_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "conversationId": {
+ "name": "conversationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "anonymousId": {
+ "name": "anonymousId",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "conversation_created_at_idx": {
+ "name": "conversation_created_at_idx",
+ "columns": ["conversationId", "createdAt"],
+ "isUnique": false
+ },
+ "role_created_at_idx": {
+ "name": "role_created_at_idx",
+ "columns": ["role", "createdAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "messenger_messages_conversationId_messenger_conversations_id_fk": {
+ "name": "messenger_messages_conversationId_messenger_conversations_id_fk",
+ "tableFrom": "messenger_messages",
+ "tableTo": "messenger_conversations",
+ "columnsFrom": ["conversationId"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "messenger_messages_id": {
+ "name": "messenger_messages_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "messenger_support_emails": {
+ "name": "messenger_support_emails",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "conversationId": {
+ "name": "conversationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userEmail": {
+ "name": "userEmail",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "subject": {
+ "name": "subject",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "support_email_user_created_at_idx": {
+ "name": "support_email_user_created_at_idx",
+ "columns": ["userId", "createdAt"],
+ "isUnique": false
+ },
+ "support_email_conversation_created_at_idx": {
+ "name": "support_email_conversation_created_at_idx",
+ "columns": ["conversationId", "createdAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "support_email_conversation_fk": {
+ "name": "support_email_conversation_fk",
+ "tableFrom": "messenger_support_emails",
+ "tableTo": "messenger_conversations",
+ "columnsFrom": ["conversationId"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "messenger_support_emails_id": {
+ "name": "messenger_support_emails_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "notifications": {
+ "name": "notifications",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recipientId": {
+ "name": "recipientId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "data": {
+ "name": "data",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(50)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "dedupKey": {
+ "name": "dedupKey",
+ "type": "varchar(128)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "readAt": {
+ "name": "readAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "org_id_idx": {
+ "name": "org_id_idx",
+ "columns": ["orgId"],
+ "isUnique": false
+ },
+ "type_idx": {
+ "name": "type_idx",
+ "columns": ["type"],
+ "isUnique": false
+ },
+ "read_at_idx": {
+ "name": "read_at_idx",
+ "columns": ["readAt"],
+ "isUnique": false
+ },
+ "created_at_idx": {
+ "name": "created_at_idx",
+ "columns": ["createdAt"],
+ "isUnique": false
+ },
+ "recipient_read_idx": {
+ "name": "recipient_read_idx",
+ "columns": ["recipientId", "readAt"],
+ "isUnique": false
+ },
+ "recipient_created_idx": {
+ "name": "recipient_created_idx",
+ "columns": ["recipientId", "createdAt"],
+ "isUnique": false
+ },
+ "dedup_key_idx": {
+ "name": "dedup_key_idx",
+ "columns": ["dedupKey"],
+ "isUnique": true
+ },
+ "type_recipient_created_idx": {
+ "name": "type_recipient_created_idx",
+ "columns": ["type", "recipientId", "createdAt"],
+ "isUnique": false
+ },
+ "type_recipient_video_created_idx": {
+ "name": "type_recipient_video_created_idx",
+ "columns": ["type", "recipientId", "videoId", "createdAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "notifications_id": {
+ "name": "notifications_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "organization_invites": {
+ "name": "organization_invites",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invitedEmail": {
+ "name": "invitedEmail",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invitedByUserId": {
+ "name": "invitedByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "invited_email_idx": {
+ "name": "invited_email_idx",
+ "columns": ["invitedEmail"],
+ "isUnique": false
+ },
+ "invited_by_user_id_idx": {
+ "name": "invited_by_user_id_idx",
+ "columns": ["invitedByUserId"],
+ "isUnique": false
+ },
+ "status_idx": {
+ "name": "status_idx",
+ "columns": ["status"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "organization_invites_id": {
+ "name": "organization_invites_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "organization_members": {
+ "name": "organization_members",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hasProSeat": {
+ "name": "hasProSeat",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "user_id_organization_id_idx": {
+ "name": "user_id_organization_id_idx",
+ "columns": ["userId", "organizationId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "organization_members_id": {
+ "name": "organization_members_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "organization_sso": {
+ "name": "organization_sso",
+ "columns": {
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "purchasedByUserId": {
+ "name": "purchasedByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripePriceId": {
+ "name": "stripePriceId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unpaid'"
+ },
+ "paidThrough": {
+ "name": "paidThrough",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "currentPeriodEnd": {
+ "name": "currentPeriodEnd",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cancelAtPeriodEnd": {
+ "name": "cancelAtPeriodEnd",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "checkoutAttemptId": {
+ "name": "checkoutAttemptId",
+ "type": "varchar(36)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "checkoutCurrency": {
+ "name": "checkoutCurrency",
+ "type": "varchar(3)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "checkoutPriceId": {
+ "name": "checkoutPriceId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "checkoutSessionId": {
+ "name": "checkoutSessionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "checkoutStartedAt": {
+ "name": "checkoutStartedAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "sso_stripe_subscription_id_idx": {
+ "name": "sso_stripe_subscription_id_idx",
+ "columns": ["stripeSubscriptionId"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "organization_sso_organizationId": {
+ "name": "organization_sso_organizationId",
+ "columns": ["organizationId"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "organizations": {
+ "name": "organizations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tombstoneAt": {
+ "name": "tombstoneAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "allowedEmailDomain": {
+ "name": "allowedEmailDomain",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "customDomain": {
+ "name": "customDomain",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "domainVerified": {
+ "name": "domainVerified",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "iconUrl": {
+ "name": "iconUrl",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shareableLinkIconUrl": {
+ "name": "shareableLinkIconUrl",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "workosOrganizationId": {
+ "name": "workosOrganizationId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workosConnectionId": {
+ "name": "workosConnectionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "owner_id_tombstone_idx": {
+ "name": "owner_id_tombstone_idx",
+ "columns": ["ownerId", "tombstoneAt"],
+ "isUnique": false
+ },
+ "custom_domain_idx": {
+ "name": "custom_domain_idx",
+ "columns": ["customDomain"],
+ "isUnique": false
+ },
+ "workos_organization_id_idx": {
+ "name": "workos_organization_id_idx",
+ "columns": ["workosOrganizationId"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "organizations_id": {
+ "name": "organizations_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "s3_buckets": {
+ "name": "s3_buckets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "region": {
+ "name": "region",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bucketName": {
+ "name": "bucketName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "accessKeyId": {
+ "name": "accessKeyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secretAccessKey": {
+ "name": "secretAccessKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "('aws')"
+ },
+ "active": {
+ "name": "active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "owner_organization_idx": {
+ "name": "owner_organization_idx",
+ "columns": ["ownerId", "organizationId"],
+ "isUnique": false
+ },
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "organization_active_idx": {
+ "name": "organization_active_idx",
+ "columns": ["organizationId", "active", "updatedAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "s3_buckets_id": {
+ "name": "s3_buckets_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sessionToken": {
+ "name": "sessionToken",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "session_token_idx": {
+ "name": "session_token_idx",
+ "columns": ["sessionToken"],
+ "isUnique": true
+ },
+ "user_id_idx": {
+ "name": "user_id_idx",
+ "columns": ["userId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "sessions_id": {
+ "name": "sessions_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "shared_videos": {
+ "name": "shared_videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "folderId": {
+ "name": "folderId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sharedByUserId": {
+ "name": "sharedByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sharedAt": {
+ "name": "sharedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "folder_id_idx": {
+ "name": "folder_id_idx",
+ "columns": ["folderId"],
+ "isUnique": false
+ },
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "shared_by_user_id_idx": {
+ "name": "shared_by_user_id_idx",
+ "columns": ["sharedByUserId"],
+ "isUnique": false
+ },
+ "video_id_organization_id_idx": {
+ "name": "video_id_organization_id_idx",
+ "columns": ["videoId", "organizationId"],
+ "isUnique": false
+ },
+ "video_id_folder_id_idx": {
+ "name": "video_id_folder_id_idx",
+ "columns": ["videoId", "folderId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "shared_videos_id": {
+ "name": "shared_videos_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "signed_baas": {
+ "name": "signed_baas",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "entityName": {
+ "name": "entityName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "entityType": {
+ "name": "entityType",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "entityAddress": {
+ "name": "entityAddress",
+ "type": "varchar(500)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "signerName": {
+ "name": "signerName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "signerTitle": {
+ "name": "signerTitle",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "noticesEmail": {
+ "name": "noticesEmail",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "signatureData": {
+ "name": "signatureData",
+ "type": "longtext",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "signedAt": {
+ "name": "signedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "emailSentAt": {
+ "name": "emailSentAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "signed_baa_organization_id_idx": {
+ "name": "signed_baa_organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": true
+ },
+ "signed_baa_stripe_subscription_idx": {
+ "name": "signed_baa_stripe_subscription_idx",
+ "columns": ["stripeSubscriptionId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "signed_baas_id": {
+ "name": "signed_baas_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "space_members": {
+ "name": "space_members",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'member'"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "user_id_idx": {
+ "name": "user_id_idx",
+ "columns": ["userId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "space_members_id": {
+ "name": "space_members_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {
+ "space_id_user_id_unique": {
+ "name": "space_id_user_id_unique",
+ "columns": ["spaceId", "userId"]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "space_videos": {
+ "name": "space_videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "folderId": {
+ "name": "folderId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "addedById": {
+ "name": "addedById",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "addedAt": {
+ "name": "addedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "folder_id_idx": {
+ "name": "folder_id_idx",
+ "columns": ["folderId"],
+ "isUnique": false
+ },
+ "video_id_idx": {
+ "name": "video_id_idx",
+ "columns": ["videoId"],
+ "isUnique": false
+ },
+ "added_by_id_idx": {
+ "name": "added_by_id_idx",
+ "columns": ["addedById"],
+ "isUnique": false
+ },
+ "space_id_video_id_idx": {
+ "name": "space_id_video_id_idx",
+ "columns": ["spaceId", "videoId"],
+ "isUnique": false
+ },
+ "space_id_folder_id_idx": {
+ "name": "space_id_folder_id_idx",
+ "columns": ["spaceId", "folderId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "space_videos_id": {
+ "name": "space_videos_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "spaces": {
+ "name": "spaces",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "primary": {
+ "name": "primary",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdById": {
+ "name": "createdById",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "iconUrl": {
+ "name": "iconUrl",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "varchar(1000)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "privacy": {
+ "name": "privacy",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'Private'"
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ }
+ },
+ "indexes": {
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "created_by_id_idx": {
+ "name": "created_by_id_idx",
+ "columns": ["createdById"],
+ "isUnique": false
+ },
+ "public_organization_id_idx": {
+ "name": "public_organization_id_idx",
+ "columns": ["public", "organizationId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "spaces_id": {
+ "name": "spaces_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "storage_integrations": {
+ "name": "storage_integrations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "displayName": {
+ "name": "displayName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "active": {
+ "name": "active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "encryptedConfig": {
+ "name": "encryptedConfig",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "googleDriveAccessToken": {
+ "name": "googleDriveAccessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "googleDriveAccessTokenExpiresAt": {
+ "name": "googleDriveAccessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "googleDriveTokenRefreshLeaseId": {
+ "name": "googleDriveTokenRefreshLeaseId",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "googleDriveTokenRefreshLeaseExpiresAt": {
+ "name": "googleDriveTokenRefreshLeaseExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "googleDriveStorageQuotaCache": {
+ "name": "googleDriveStorageQuotaCache",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "owner_provider_idx": {
+ "name": "owner_provider_idx",
+ "columns": ["ownerId", "provider"],
+ "isUnique": false
+ },
+ "owner_active_idx": {
+ "name": "owner_active_idx",
+ "columns": ["ownerId", "active"],
+ "isUnique": false
+ },
+ "organization_provider_idx": {
+ "name": "organization_provider_idx",
+ "columns": ["organizationId", "provider"],
+ "isUnique": false
+ },
+ "organization_active_idx": {
+ "name": "organization_active_idx",
+ "columns": ["organizationId", "active", "status"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "storage_integrations_id": {
+ "name": "storage_integrations_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "storage_objects": {
+ "name": "storage_objects",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "integrationId": {
+ "name": "integrationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "objectKey": {
+ "name": "objectKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "objectKeyHash": {
+ "name": "objectKeyHash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "providerObjectId": {
+ "name": "providerObjectId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "uploadSessionUrl": {
+ "name": "uploadSessionUrl",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "uploadStatus": {
+ "name": "uploadStatus",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "contentType": {
+ "name": "contentType",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "contentLength": {
+ "name": "contentLength",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "integration_key_hash_idx": {
+ "name": "integration_key_hash_idx",
+ "columns": ["integrationId", "objectKeyHash"],
+ "isUnique": true
+ },
+ "integration_status_idx": {
+ "name": "integration_status_idx",
+ "columns": ["integrationId", "uploadStatus"],
+ "isUnique": false
+ },
+ "integration_object_key_prefix_idx": {
+ "name": "integration_object_key_prefix_idx",
+ "columns": ["integrationId", "`objectKey`(191)"],
+ "isUnique": false
+ },
+ "video_id_idx": {
+ "name": "video_id_idx",
+ "columns": ["videoId"],
+ "isUnique": false
+ },
+ "owner_id_idx": {
+ "name": "owner_id_idx",
+ "columns": ["ownerId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "storage_objects_integrationId_storage_integrations_id_fk": {
+ "name": "storage_objects_integrationId_storage_integrations_id_fk",
+ "tableFrom": "storage_objects",
+ "tableTo": "storage_integrations",
+ "columnsFrom": ["integrationId"],
+ "columnsTo": ["id"],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "storage_objects_id": {
+ "name": "storage_objects_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastName": {
+ "name": "lastName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "thirdPartyStripeSubscriptionId": {
+ "name": "thirdPartyStripeSubscriptionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionStatus": {
+ "name": "stripeSubscriptionStatus",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionPriceId": {
+ "name": "stripeSubscriptionPriceId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "preferences": {
+ "name": "preferences",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "('null')"
+ },
+ "activeOrganizationId": {
+ "name": "activeOrganizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "onboardingSteps": {
+ "name": "onboardingSteps",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "onboarding_completed_at": {
+ "name": "onboarding_completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "customBucket": {
+ "name": "customBucket",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "inviteQuota": {
+ "name": "inviteQuota",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "defaultOrgId": {
+ "name": "defaultOrgId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "authSessionVersion": {
+ "name": "authSessionVersion",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "email_idx": {
+ "name": "email_idx",
+ "columns": ["email"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "users_id": {
+ "name": "users_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "verification_tokens": {
+ "name": "verification_tokens",
+ "columns": {
+ "identifier": {
+ "name": "identifier",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "verification_tokens_identifier": {
+ "name": "verification_tokens_identifier",
+ "columns": ["identifier"]
+ }
+ },
+ "uniqueConstraints": {
+ "verification_tokens_token_unique": {
+ "name": "verification_tokens_token_unique",
+ "columns": ["token"]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "video_edits": {
+ "name": "video_edits",
+ "columns": {
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sourceKey": {
+ "name": "sourceKey",
+ "type": "varchar(512)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "editSpec": {
+ "name": "editSpec",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "video_edits_videoId_videos_id_fk": {
+ "name": "video_edits_videoId_videos_id_fk",
+ "tableFrom": "video_edits",
+ "tableTo": "videos",
+ "columnsFrom": ["videoId"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "video_edits_videoId": {
+ "name": "video_edits_videoId",
+ "columns": ["videoId"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "video_processing_jobs": {
+ "name": "video_processing_jobs",
+ "columns": {
+ "video_id": {
+ "name": "video_id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "generation": {
+ "name": "generation",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "manifest_sha256": {
+ "name": "manifest_sha256",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'committing'"
+ },
+ "attempt_id": {
+ "name": "attempt_id",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attempt_count": {
+ "name": "attempt_count",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "lease_expires_at": {
+ "name": "lease_expires_at",
+ "type": "datetime(3)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_retry_at": {
+ "name": "next_retry_at",
+ "type": "datetime(3)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workflow_run_id": {
+ "name": "workflow_run_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "remote_job_id": {
+ "name": "remote_job_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "verification": {
+ "name": "verification",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "output": {
+ "name": "output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_code": {
+ "name": "error_code",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "datetime(3)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "datetime(3)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "processing_state_retry_video_idx": {
+ "name": "processing_state_retry_video_idx",
+ "columns": ["state", "next_retry_at", "video_id"],
+ "isUnique": false
+ },
+ "processing_state_lease_video_idx": {
+ "name": "processing_state_lease_video_idx",
+ "columns": ["state", "lease_expires_at", "video_id"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "video_processing_jobs_video_id": {
+ "name": "video_processing_jobs_video_id",
+ "columns": ["video_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "video_uploads": {
+ "name": "video_uploads",
+ "columns": {
+ "video_id": {
+ "name": "video_id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "uploaded": {
+ "name": "uploaded",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "total": {
+ "name": "total",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "mode": {
+ "name": "mode",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "phase": {
+ "name": "phase",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'uploading'"
+ },
+ "processing_progress": {
+ "name": "processing_progress",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "processing_message": {
+ "name": "processing_message",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "processing_error": {
+ "name": "processing_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "raw_file_key": {
+ "name": "raw_file_key",
+ "type": "varchar(512)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "phase_updated_at_video_id_idx": {
+ "name": "phase_updated_at_video_id_idx",
+ "columns": ["phase", "updated_at", "video_id"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "video_uploads_video_id": {
+ "name": "video_uploads_video_id",
+ "columns": ["video_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "videos": {
+ "name": "videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'My Video'"
+ },
+ "bucket": {
+ "name": "bucket",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "storageIntegrationId": {
+ "name": "storageIntegrationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration": {
+ "name": "duration",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "width": {
+ "name": "width",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "height": {
+ "name": "height",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fps": {
+ "name": "fps",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "settings": {
+ "name": "settings",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "transcriptionStatus": {
+ "name": "transcriptionStatus",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "('{\"type\":\"MediaConvert\"}')"
+ },
+ "folderId": {
+ "name": "folderId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "effectiveCreatedAt": {
+ "name": "effectiveCreatedAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "generated": {
+ "as": "COALESCE(\n STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.customCreatedAt')), '%Y-%m-%dT%H:%i:%s.%fZ'),\n STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.customCreatedAt')), '%Y-%m-%dT%H:%i:%sZ'),\n `createdAt`\n )",
+ "type": "stored"
+ }
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "xStreamInfo": {
+ "name": "xStreamInfo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "firstViewEmailSentAt": {
+ "name": "firstViewEmailSentAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "isScreenshot": {
+ "name": "isScreenshot",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "awsRegion": {
+ "name": "awsRegion",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "awsBucket": {
+ "name": "awsBucket",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "videoStartTime": {
+ "name": "videoStartTime",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "audioStartTime": {
+ "name": "audioStartTime",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "jobId": {
+ "name": "jobId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "jobStatus": {
+ "name": "jobStatus",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skipProcessing": {
+ "name": "skipProcessing",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ }
+ },
+ "indexes": {
+ "owner_id_idx": {
+ "name": "owner_id_idx",
+ "columns": ["ownerId"],
+ "isUnique": false
+ },
+ "is_public_idx": {
+ "name": "is_public_idx",
+ "columns": ["public"],
+ "isUnique": false
+ },
+ "folder_id_idx": {
+ "name": "folder_id_idx",
+ "columns": ["folderId"],
+ "isUnique": false
+ },
+ "storage_integration_id_idx": {
+ "name": "storage_integration_id_idx",
+ "columns": ["storageIntegrationId"],
+ "isUnique": false
+ },
+ "org_owner_folder_idx": {
+ "name": "org_owner_folder_idx",
+ "columns": ["orgId", "ownerId", "folderId"],
+ "isUnique": false
+ },
+ "org_effective_created_idx": {
+ "name": "org_effective_created_idx",
+ "columns": ["orgId", "effectiveCreatedAt"],
+ "isUnique": false
+ },
+ "screenshot_transcription_created_idx": {
+ "name": "screenshot_transcription_created_idx",
+ "columns": ["isScreenshot", "transcriptionStatus", "createdAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "videos_storageIntegrationId_storage_integrations_id_fk": {
+ "name": "videos_storageIntegrationId_storage_integrations_id_fk",
+ "tableFrom": "videos",
+ "tableTo": "storage_integrations",
+ "columnsFrom": ["storageIntegrationId"],
+ "columnsTo": ["id"],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "videos_id": {
+ "name": "videos_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ }
+ },
+ "views": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "tables": {},
+ "indexes": {
+ "integration_object_key_prefix_idx": {
+ "columns": {
+ "`objectKey`(191)": {
+ "isExpression": true
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json
index 462fb17ef..9a94099fc 100644
--- a/packages/database/migrations/meta/_journal.json
+++ b/packages/database/migrations/meta/_journal.json
@@ -302,6 +302,13 @@
"when": 1788437051131,
"tag": "0042_perf_indexes",
"breakpoints": true
+ },
+ {
+ "idx": 43,
+ "version": "5",
+ "when": 1788695529193,
+ "tag": "0043_flimsy_caretaker",
+ "breakpoints": true
}
]
}
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 7d2f9e854..e54a4d60d 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -1484,6 +1484,22 @@ export const videoProcessingJobs = mysqlTable(
],
);
+export const mediaProcessingBudgets = mysqlTable(
+ "media_processing_budgets",
+ {
+ id: varchar("id", { length: 64 }).primaryKey().notNull(),
+ reservedBytes: bigint("reserved_bytes", { mode: "number", unsigned: true })
+ .notNull()
+ .default(0),
+ limitBytes: bigint("limit_bytes", {
+ mode: "number",
+ unsigned: true,
+ }).notNull(),
+ expiresAt: datetime("expires_at", { fsp: 3 }).notNull(),
+ },
+ (table) => [index("media_budget_expiry_idx").on(table.expiresAt)],
+);
+
export const importedVideos = mysqlTable(
"imported_videos",
{
diff --git a/packages/web-backend/src/Storage/GoogleDrive.ts b/packages/web-backend/src/Storage/GoogleDrive.ts
index e9a619983..ead4134c3 100644
--- a/packages/web-backend/src/Storage/GoogleDrive.ts
+++ b/packages/web-backend/src/Storage/GoogleDrive.ts
@@ -1395,6 +1395,65 @@ export type GoogleDriveRecordingRead = {
signal?: AbortSignal;
};
+export const getGoogleDriveRecordingDownload = (
+ config: GoogleDriveIntegrationConfig,
+ fileId: string,
+ verification: { objectIdentity?: string; signal?: AbortSignal },
+ tokenStore?: GoogleDriveTokenStore,
+) =>
+ Effect.gen(function* () {
+ const metadata = yield* getGoogleDriveFileMetadata(
+ config,
+ fileId,
+ tokenStore,
+ verification.signal,
+ );
+ const identity = getRecordingObjectIdentity(
+ {
+ ETag: metadata.version
+ ? `"${metadata.id}:${metadata.version}"`
+ : undefined,
+ RecordingContentETag: getGoogleDriveRecordingIdentity(metadata),
+ },
+ verification.objectIdentity,
+ );
+ if (
+ metadata.id !== fileId ||
+ (verification.objectIdentity && identity !== verification.objectIdentity)
+ ) {
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new RecordingObjectReadError(412, "Recording object changed"),
+ }),
+ );
+ }
+ const size = getUsableGoogleDriveFileSize(metadata);
+ if (
+ !identity ||
+ !size ||
+ !metadata.headRevisionId ||
+ !metadata.sha256Checksum?.match(/^[a-fA-F0-9]{64}$/)
+ ) {
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new RecordingObjectReadError(
+ 503,
+ "Recording revision identity is unavailable",
+ ),
+ }),
+ );
+ }
+ const token = yield* loadGoogleDriveAccessToken(config, false, tokenStore);
+ return {
+ version: 1 as const,
+ url: `${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}/revisions/${encodeURIComponent(metadata.headRevisionId)}?alt=media`,
+ authorization: `Bearer ${token.accessToken}`,
+ objectIdentity: identity,
+ size,
+ sha256: metadata.sha256Checksum.toLowerCase(),
+ };
+ });
+
export const getGoogleDriveRecordingResponse = (
config: GoogleDriveIntegrationConfig,
fileId: string,
diff --git a/packages/web-backend/src/Storage/index.ts b/packages/web-backend/src/Storage/index.ts
index 41536251d..10455252b 100644
--- a/packages/web-backend/src/Storage/index.ts
+++ b/packages/web-backend/src/Storage/index.ts
@@ -25,6 +25,7 @@ import {
getGoogleDriveFileMetadata,
getGoogleDriveObjectResponse,
getGoogleDriveObjectText,
+ getGoogleDriveRecordingDownload,
getGoogleDriveRecordingResponse,
parseVideoIdFromObjectKey,
syncGoogleDriveVideoNames,
@@ -1030,6 +1031,20 @@ const makeGoogleDriveAccess = ({
mapStorageError,
Effect.map((url) => toDriveUploadTarget(url, input.contentType)),
),
+ getInternalDownload: (
+ key: string,
+ verification: { objectIdentity?: string; signal?: AbortSignal },
+ ) =>
+ getObjectRecord(key).pipe(
+ Effect.flatMap((object) =>
+ getGoogleDriveRecordingDownload(
+ config,
+ object.providerObjectId,
+ verification,
+ tokenStore,
+ ),
+ ),
+ ),
getObjectResponse: (
key: string,
range?: string | null,
@@ -1093,6 +1108,10 @@ function withPublishedRecordingOutput<
};
if (access.provider === "googleDrive") {
return Object.assign({}, access, shared, {
+ getInternalDownload: (
+ key: string,
+ verification: { objectIdentity?: string; signal?: AbortSignal },
+ ) => access.getInternalDownload(resolve(key), verification),
getObjectResponse: (
key: string,
range?: string | null,