Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: share in-flight Drive downloads across processing jobs

Richie McIlroy445309248084
diff --git a/apps/media-server/src/__tests__/lib/media-transfer.test.ts b/apps/media-server/src/__tests__/lib/media-transfer.test.ts
index 8ac2a27c7..23cfe4308 100644
--- a/apps/media-server/src/__tests__/lib/media-transfer.test.ts
+++ b/apps/media-server/src/__tests__/lib/media-transfer.test.ts
@@ -175,6 +175,60 @@ describe("parallel transfer admission and cache reuse", () => {
expect(downloads()).toBe(1);
});
+ test("downloads one revision once across six concurrent job contexts", async () => {
+ const downloads = network();
+ const input = url();
+ const paths = await Promise.all(
+ Array.from({ length: 6 }, () =>
+ withMediaTransfers(content.length, async () => {
+ const local = await materializeMedia(input);
+ if (!local) throw new Error("Missing materialized input");
+ expect(await readFile(local.path)).toEqual(content);
+ return local.path;
+ }),
+ ),
+ );
+ expect(new Set(paths).size).toBe(1);
+ expect(downloads()).toBe(1);
+ });
+
+ test("canceling a waiting job does not cancel the shared owner's download", async () => {
+ process.env.MEDIA_SERVER_WEBHOOK_SECRET = "worker-secret";
+ let downloads = 0;
+ let release = () => {};
+ let entered = () => {};
+ const started = new Promise<void>((resolve) => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ globalThis.fetch = fetcher(async (input) => {
+ if (String(input).startsWith("https://cap.so/"))
+ return Response.json(target());
+ downloads++;
+ entered();
+ await gate;
+ return new Response(content, {
+ headers: { "Content-Length": String(content.length) },
+ });
+ });
+ const input = url();
+ const owner = withMediaTransfers(content.length, () =>
+ materializeMedia(input),
+ );
+ await started;
+ const controller = new AbortController();
+ const waiting = withMediaTransfers(content.length, () =>
+ materializeMedia(input, controller.signal),
+ );
+ controller.abort(new Error("Waiting job canceled"));
+ await expect(waiting).rejects.toThrow("Waiting job canceled");
+ release();
+ expect(await owner).toBeDefined();
+ expect(downloads).toBe(1);
+ });
+
test("releases one cache retention after concurrent reads in the same job", async () => {
const downloads = network();
const input = url();
@@ -195,6 +249,28 @@ describe("parallel transfer admission and cache reuse", () => {
expect(downloads()).toBe(2);
});
+ test("keeps a shared pathname until both same-job consumers release it", async () => {
+ network();
+ const input = url();
+ await withMediaTransfers(content.length * 2, async () => {
+ const [first, second] = await Promise.all([
+ materializeMedia(input),
+ materializeMedia(input),
+ ]);
+ if (!first || !second) throw new Error("Missing shared input");
+ await releaseMaterializedMedia(first.path);
+ const now = Date.now();
+ const clock = spyOn(Date, "now").mockReturnValue(now + 31 * 60_000);
+ try {
+ await materializeMedia(url());
+ expect(await readFile(second.path)).toEqual(content);
+ await releaseMaterializedMedia(second.path);
+ } finally {
+ clock.mockRestore();
+ }
+ });
+ });
+
test("retains a worker input after its cache pathname is removed", async () => {
network();
await withMediaTransfers(content.length, async () => {
diff --git a/apps/media-server/src/lib/media-transfer.ts b/apps/media-server/src/lib/media-transfer.ts
index b63e19790..c1eeb0b42 100644
--- a/apps/media-server/src/lib/media-transfer.ts
+++ b/apps/media-server/src/lib/media-transfer.ts
@@ -28,11 +28,13 @@ type TransferContext = {
reserved: number;
cacheHits: number;
files: Map<string, CachedFile>;
+ references: Map<string, number>;
controller: AbortController;
pending: Map<string, Promise<{ path: string; target: MediaDownloadTarget }>>;
};
const transfers = new AsyncLocalStorage<TransferContext>();
const cache = new Map<string, CachedFile>();
+const pendingTransfers = new Map<string, Promise<void>>();
const cacheBase = join(tmpdir(), "cap-media-download-cache");
const cacheRoot = join(cacheBase, String(process.pid));
const CACHE_BYTES = 2 * 1024 ** 3;
@@ -99,6 +101,7 @@ async function pruneCache() {
)) {
if (
entry.users ||
+ pendingTransfers.has(key) ||
(cacheBytes <= CACHE_BYTES && Date.now() - entry.usedAt < CACHE_TTL_MS)
)
continue;
@@ -121,6 +124,7 @@ export async function withMediaTransfers<T>(
reserved: 0,
cacheHits: 0,
files: new Map(),
+ references: new Map(),
controller: new AbortController(),
pending: new Map(),
};
@@ -138,6 +142,7 @@ export async function withMediaTransfers<T>(
} finally {
clearTimeout(timeout);
context.controller.abort();
+ await Promise.allSettled(context.pending.values());
for (const [key, entry] of context.files) {
entry.users--;
if (cache.get(key) !== entry && !entry.users)
@@ -289,6 +294,39 @@ export async function downloadDriveRevision(
}
}
+async function serializeTransfer<T>(
+ key: string,
+ signal: AbortSignal,
+ run: () => Promise<T>,
+): Promise<T> {
+ const previous = pendingTransfers.get(key) ?? Promise.resolve();
+ let release = () => {};
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const tail = previous.then(() => gate);
+ pendingTransfers.set(key, tail);
+ let onAbort = () => {};
+ try {
+ await Promise.race([
+ previous,
+ new Promise<never>((_resolve, reject) => {
+ onAbort = () => reject(signal.reason);
+ signal.addEventListener("abort", onAbort, { once: true });
+ if (signal.aborted) onAbort();
+ }),
+ ]);
+ signal.throwIfAborted();
+ return await run();
+ } finally {
+ signal.removeEventListener("abort", onAbort);
+ release();
+ void tail.then(() => {
+ if (pendingTransfers.get(key) === tail) pendingTransfers.delete(key);
+ });
+ }
+}
+
export async function materializeMedia(
input: string,
signal?: AbortSignal,
@@ -316,7 +354,11 @@ export async function materializeMedia(
.digest("hex");
await pruneCache();
const pending = context.pending.get(key);
- if (pending) return pending;
+ if (pending) {
+ const result = await pending;
+ context.references.set(key, (context.references.get(key) ?? 0) + 1);
+ return result;
+ }
const download = async () => {
const existing = context.files.get(key) ?? cache.get(key);
if (existing) {
@@ -368,10 +410,12 @@ export async function materializeMedia(
context.reserved -= reservationRemaining;
}
};
- const operation = download();
+ const operation = serializeTransfer(key, combinedSignal, download);
context.pending.set(key, operation);
try {
- return await operation;
+ const result = await operation;
+ context.references.set(key, (context.references.get(key) ?? 0) + 1);
+ return result;
} finally {
context.pending.delete(key);
}
@@ -382,6 +426,12 @@ export async function releaseMaterializedMedia(path: string) {
if (!context) return;
for (const [key, entry] of context.files) {
if (entry.path !== path) continue;
+ const references = context.references.get(key) ?? 0;
+ if (references > 1) {
+ context.references.set(key, references - 1);
+ return;
+ }
+ context.references.delete(key);
context.files.delete(key);
entry.users--;
if (cache.get(key) !== entry && !entry.users)