feat: stream originals with download accounting

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 13:10:13 +02:00
1 parent c400167b8f
commit 8871e4794a
28 files changed
+4081 -8

No files matched your search

@@ -0,0 +1,14 @@
import { readFile } from "node:fs/promises";
import path from "node:path";
import { expect, test } from "vitest";
test("0003 adds a durable voided billing state without deleting usage history", async () => {
const migration = await readFile(
path.join(process.cwd(), "drizzle/0003_stream_delivery.sql"),
"utf8",
);
expect(migration).toContain("ALTER TYPE \"public\".\"usage_billing_status\" ADD VALUE 'voided'");
expect(migration).not.toMatch(/delete\s+from\s+"?usages"?/i);
});
+152
View File
@@ -0,0 +1,152 @@
import { randomUUID } from "node:crypto";
import { afterAll, expect, test } from "vitest";
import {
createDownloadDeliveryRepository,
createDownloadHistoryService,
createPostgresDownloadHistoryRepository,
} from "@/modules/downloads/stream";
import { createDownloadService, createRepeatDownloadRepository } from "@/modules/downloads/service";
import { startPostgres } from "./postgres";
const testDb = await startPostgres();
afterAll(() => testDb.stop());
test("concurrent claims let exactly one request own an authorized download", async () => {
const seed = await testDb.seedEditorialWithUsage();
const id = randomUUID();
await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id });
const repository = createDownloadDeliveryRepository(testDb.database);
const results = await Promise.all([
repository.claimAuthorized(seed.editorialId, id),
repository.claimAuthorized(seed.editorialId, id),
]);
expect(results.filter((result) => result.outcome === "claimed")).toHaveLength(1);
expect(results.filter((result) => result.outcome === "not_authorized")).toHaveLength(1);
});
test("a no-byte new failure retains the attempt and voids its billable usage", async () => {
const seed = await testDb.seedEditorialWithUsage();
const id = randomUUID();
await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id });
const repository = createDownloadDeliveryRepository(testDb.database);
await repository.claimAuthorized(seed.editorialId, id);
await expect(
repository.failBeforeDelivery(id, { voidNewUsage: true }),
).resolves.toBe(true);
const event = await testDb.pool.query(
"select status, transferred_bytes from download_events where id = $1",
[id],
);
const usage = await testDb.pool.query(
"select billing_status from usages where id = $1",
[seed.usageId],
);
const audit = await testDb.pool.query(
"select event_type from audit_events where entity_id = $1 order by occurred_at desc",
[seed.usageId],
);
expect(event.rows[0]).toMatchObject({ status: "failed_before_delivery" });
expect(Number(event.rows[0].transferred_bytes)).toBe(0);
expect(usage.rows[0]).toEqual({ billing_status: "voided" });
expect(audit.rows[0]).toEqual({ event_type: "billable_usage_voided_before_delivery" });
const repeats = createDownloadService({
repository: createRepeatDownloadRepository(testDb.database),
});
await expect(
repeats.createRepeatDownload({
editorialId: seed.editorialId,
usageId: seed.usageId,
idempotencyKey: randomUUID(),
}),
).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" });
});
test("a failed repeat attempt never mutates the original usage", async () => {
const seed = await testDb.seedEditorialWithUsage();
const id = randomUUID();
await testDb.insertDownload({
...seed,
idempotencyKey: randomUUID(),
id,
intentKind: "repeat_download",
});
const repository = createDownloadDeliveryRepository(testDb.database);
await repository.claimAuthorized(seed.editorialId, id);
await repository.failBeforeDelivery(id, { voidNewUsage: false });
const usage = await testDb.pool.query(
"select billing_status, price_cents from usages where id = $1",
[seed.usageId],
);
expect(usage.rows[0]).toEqual({ billing_status: "open", price_cents: 1500 });
});
test("terminal completion and interruption race to exactly one database transition", async () => {
const seed = await testDb.seedEditorialWithUsage();
const id = randomUUID();
await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id });
const repository = createDownloadDeliveryRepository(testDb.database);
await repository.claimAuthorized(seed.editorialId, id);
const results = await Promise.all([
repository.markCompleted(id, 120),
repository.markInterrupted(id, 80),
]);
expect(results.sort()).toEqual([false, true]);
const event = await testDb.pool.query(
"select status, transferred_bytes from download_events where id = $1",
[id],
);
expect(["completed", "interrupted"]).toContain(event.rows[0].status);
});
test("history is editorial-scoped, terminal-only, and paginated by usage", async () => {
const own = await testDb.seedEditorialWithUsage();
const foreign = await testDb.seedEditorialWithUsage();
const ownCompleted = randomUUID();
const ownInterrupted = randomUUID();
const ownAuthorized = randomUUID();
const foreignCompleted = randomUUID();
await Promise.all([
testDb.insertDownload({ ...own, idempotencyKey: randomUUID(), id: ownCompleted }),
testDb.insertDownload({
...own,
idempotencyKey: randomUUID(),
id: ownInterrupted,
intentKind: "repeat_download",
}),
testDb.insertDownload({ ...own, idempotencyKey: randomUUID(), id: ownAuthorized }),
testDb.insertDownload({ ...foreign, idempotencyKey: randomUUID(), id: foreignCompleted }),
]);
await testDb.pool.query(
"update download_events set status = 'completed', started_at = now(), completed_at = now(), transferred_bytes = 5 where id in ($1, $2)",
[ownCompleted, foreignCompleted],
);
await testDb.pool.query(
"update download_events set status = 'interrupted', started_at = now(), completed_at = now(), transferred_bytes = 3 where id = $1",
[ownInterrupted],
);
const history = createDownloadHistoryService({
repository: createPostgresDownloadHistoryRepository(testDb.database),
});
const page = await history.listEditorialUsageHistory(own.editorialId, 1);
expect(page.items).toHaveLength(1);
expect(page.items[0].usageId).toBe(own.usageId);
expect(new Set(page.items[0].attempts.map((attempt) => attempt.downloadId))).toEqual(
new Set([ownInterrupted, ownCompleted]),
);
expect(page.items[0].attempts.some((attempt) => attempt.downloadId === ownAuthorized)).toBe(false);
expect(page.items[0].attempts.some((attempt) => attempt.downloadId === foreignCompleted)).toBe(false);
});
+9 -1
View File
@@ -18,7 +18,13 @@ export type PostgresTestDatabase = {
database: NodePgDatabase<typeof schema>;
pool: Pool;
seedEditorialWithUsage(): Promise<DownloadSeed>;
insertDownload(input: DownloadSeed & { idempotencyKey: string }): Promise<void>;
insertDownload(
input: DownloadSeed & {
id?: string;
idempotencyKey: string;
intentKind?: "new_usage" | "repeat_download";
},
): Promise<void>;
applyRemainingMigrations(): Promise<void>;
stop(): Promise<void>;
};
@@ -47,12 +53,14 @@ export async function startPostgres({ through }: { through?: string } = {}): Pro
},
async insertDownload(input) {
await db.insert(schema.downloadEvents).values({
id: input.id,
editorialAccountId: input.editorialId,
usageId: input.usageId,
immichAssetId: input.assetId,
requestId: randomUUID(),
idempotencyKey: input.idempotencyKey,
requestFingerprint: "0".repeat(64),
intentKind: input.intentKind ?? "new_usage",
});
},
async applyRemainingMigrations() {