Squash the 13 historical migrations into one generated baseline whose journal entry reuses the original 0000 timestamp: the migrator skips it on every existing database (prod journal stuck at 0006) and applies it only on fresh ones. Parity with the old chain verified via pg_dump diff plus fresh/existing/prod-simulated drizzle-kit migrate runs. Historical files move to drizzle-history/pre-squash-2026-08/ for integration tests that exercise legacy migration behavior. Also repair db tests that already failed before this change: - raw SQL targeted users, but the table has always been "user" - membership recheck mocked legacy getAsset.albums instead of searchPhotos - audit rollback assertion walks drizzle's wrapped error cause chain - keyset index probe pinned to NULLS LAST ordering, removing a planner cost tie-break that flipped with index creation order
436 lines
16 KiB
TypeScript
436 lines
16 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
|
|
import { afterAll, expect, test } from "vitest";
|
|
|
|
import {
|
|
createDownloadDeliveryRepository,
|
|
createDownloadHistoryService,
|
|
createEditorialDownloadOptionsLoader,
|
|
createPostgresDownloadHistoryRepository,
|
|
HISTORY_ATTEMPT_PAGE_SIZE,
|
|
} 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 });
|
|
await testDb.pool.query("update usages set billing_status = 'reopened' where id = $1", [
|
|
seed.usageId,
|
|
]);
|
|
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, previous_values 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",
|
|
previous_values: { billingStatus: "reopened" },
|
|
});
|
|
|
|
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("rejects a free repeat until a new-usage original delivered bytes", async () => {
|
|
const seed = await testDb.seedEditorialWithUsage();
|
|
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.each(["completed", "interrupted"] as const)(
|
|
"allows a free repeat after an original %s delivery",
|
|
async (terminalStatus) => {
|
|
const seed = await testDb.seedEditorialWithUsage();
|
|
const originalId = randomUUID();
|
|
await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id: originalId });
|
|
const delivery = createDownloadDeliveryRepository(testDb.database);
|
|
await delivery.claimAuthorized(seed.editorialId, originalId);
|
|
if (terminalStatus === "completed") {
|
|
await delivery.markCompleted(originalId, 120);
|
|
} else {
|
|
await delivery.markInterrupted(originalId, 80);
|
|
}
|
|
const repeats = createDownloadService({
|
|
repository: createRepeatDownloadRepository(testDb.database),
|
|
});
|
|
|
|
const repeat = await repeats.createRepeatDownload({
|
|
editorialId: seed.editorialId,
|
|
usageId: seed.usageId,
|
|
idempotencyKey: randomUUID(),
|
|
});
|
|
|
|
await expect(delivery.claimAuthorized(seed.editorialId, repeat.id)).resolves.toMatchObject({
|
|
outcome: "claimed",
|
|
});
|
|
},
|
|
);
|
|
|
|
test("a later new-use void invalidates a pre-authorized eligible repeat", async () => {
|
|
const seed = await testDb.seedEditorialWithUsage();
|
|
const originalId = randomUUID();
|
|
const failingNewId = randomUUID();
|
|
await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id: originalId });
|
|
await testDb.insertDownload({
|
|
...seed,
|
|
idempotencyKey: randomUUID(),
|
|
id: failingNewId,
|
|
});
|
|
const delivery = createDownloadDeliveryRepository(testDb.database);
|
|
await delivery.claimAuthorized(seed.editorialId, originalId);
|
|
await delivery.markCompleted(originalId, 120);
|
|
await delivery.claimAuthorized(seed.editorialId, failingNewId);
|
|
const repeats = createDownloadService({
|
|
repository: createRepeatDownloadRepository(testDb.database),
|
|
});
|
|
const repeatKey = randomUUID();
|
|
const repeatInput = {
|
|
editorialId: seed.editorialId,
|
|
usageId: seed.usageId,
|
|
idempotencyKey: repeatKey,
|
|
};
|
|
const repeatIntent = await repeats.createRepeatDownload(repeatInput);
|
|
|
|
const failed = await delivery.failBeforeDelivery(failingNewId, { voidNewUsage: true });
|
|
const repeatClaim = await delivery.claimAuthorized(seed.editorialId, repeatIntent.id);
|
|
|
|
expect(failed).toBe(true);
|
|
expect(repeatClaim.outcome).toBe("not_authorized");
|
|
const repeatRow = await testDb.pool.query(
|
|
"select status from download_events where id = $1",
|
|
[repeatIntent.id],
|
|
);
|
|
expect(repeatRow.rows[0]).toEqual({ status: "failed_before_delivery" });
|
|
await expect(repeats.createRepeatDownload(repeatInput)).rejects.toMatchObject({
|
|
code: "USAGE_NOT_FOUND",
|
|
});
|
|
});
|
|
|
|
test("dialog choices include only owned usages with delivered original bytes", async () => {
|
|
const own = await testDb.seedEditorialWithUsage();
|
|
const foreign = await testDb.seedEditorialWithUsage();
|
|
const billedAssetId = randomUUID();
|
|
const reopenedAssetId = randomUUID();
|
|
const zeroByteAssetId = randomUUID();
|
|
const deliveredOpen = await insertUsage(own.editorialId, own.assetId, "open", "Open geliefert");
|
|
const deliveredBilled = await insertUsage(
|
|
own.editorialId,
|
|
billedAssetId,
|
|
"billed",
|
|
"Abgerechnet geliefert",
|
|
);
|
|
const deliveredReopened = await insertUsage(
|
|
own.editorialId,
|
|
reopenedAssetId,
|
|
"reopened",
|
|
"Wieder geöffnet geliefert",
|
|
);
|
|
const zeroByte = await insertUsage(
|
|
own.editorialId,
|
|
zeroByteAssetId,
|
|
"open",
|
|
"Null Byte",
|
|
);
|
|
const eventSeeds = [
|
|
{ ...own, usageId: deliveredOpen, id: randomUUID(), bytes: 7, status: "completed" },
|
|
{
|
|
...own,
|
|
usageId: deliveredBilled,
|
|
assetId: billedAssetId,
|
|
id: randomUUID(),
|
|
bytes: 9,
|
|
status: "completed",
|
|
},
|
|
{
|
|
...own,
|
|
usageId: deliveredReopened,
|
|
assetId: reopenedAssetId,
|
|
id: randomUUID(),
|
|
bytes: 3,
|
|
status: "interrupted",
|
|
},
|
|
{
|
|
...own,
|
|
usageId: zeroByte,
|
|
assetId: zeroByteAssetId,
|
|
id: randomUUID(),
|
|
bytes: 0,
|
|
status: "completed",
|
|
},
|
|
{ ...foreign, id: randomUUID(), bytes: 11, status: "completed" },
|
|
] as const;
|
|
for (const event of eventSeeds) {
|
|
await testDb.insertDownload({
|
|
editorialId: event.editorialId,
|
|
usageId: event.usageId,
|
|
assetId: event.assetId,
|
|
id: event.id,
|
|
idempotencyKey: randomUUID(),
|
|
});
|
|
await testDb.pool.query(
|
|
"update download_events set status = $2, started_at = now(), completed_at = now(), transferred_bytes = $3 where id = $1",
|
|
[event.id, event.status, event.bytes],
|
|
);
|
|
}
|
|
const loadOptions = createEditorialDownloadOptionsLoader(testDb.database);
|
|
|
|
const options = await loadOptions(own.editorialId, [
|
|
own.assetId,
|
|
billedAssetId,
|
|
reopenedAssetId,
|
|
zeroByteAssetId,
|
|
]);
|
|
|
|
expect(options.priorUsagesByAsset[own.assetId]?.map((usage) => usage.purpose)).toEqual([
|
|
"Open geliefert",
|
|
]);
|
|
expect(options.priorUsagesByAsset[billedAssetId]?.map((usage) => usage.purpose)).toEqual([
|
|
"Abgerechnet geliefert",
|
|
]);
|
|
expect(options.priorUsagesByAsset[reopenedAssetId]?.map((usage) => usage.purpose)).toEqual([
|
|
"Wieder geöffnet geliefert",
|
|
]);
|
|
expect(options.priorUsagesByAsset[zeroByteAssetId]).toBeUndefined();
|
|
expect(
|
|
Object.values(options.priorUsagesByAsset)
|
|
.flat()
|
|
.some((usage) => usage.id === foreign.usageId),
|
|
).toBe(false);
|
|
});
|
|
|
|
test("a failed repeat attempt never mutates the original usage", async () => {
|
|
const seed = await testDb.seedEditorialWithUsage();
|
|
const originalId = randomUUID();
|
|
await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id: originalId });
|
|
const repository = createDownloadDeliveryRepository(testDb.database);
|
|
await repository.claimAuthorized(seed.editorialId, originalId);
|
|
await repository.markCompleted(originalId, 10);
|
|
const id = randomUUID();
|
|
await testDb.insertDownload({
|
|
...seed,
|
|
idempotencyKey: randomUUID(),
|
|
id,
|
|
intentKind: "repeat_download",
|
|
});
|
|
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 keeps the global all-status attempt stream editorial-scoped", 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.attempts.map((attempt) => attempt.downloadId))).toEqual(
|
|
new Set([ownAuthorized, ownInterrupted, ownCompleted]),
|
|
);
|
|
expect(page.attempts.some((attempt) => attempt.downloadId === foreignCompleted)).toBe(false);
|
|
expect(page.attempts.every((attempt) => attempt.filename === "bild.jpg")).toBe(true);
|
|
});
|
|
|
|
test("global attempt traversal is independent of usage pages and stable across status changes", async () => {
|
|
const own = await testDb.seedEditorialWithUsage();
|
|
const attemptIds: string[] = [];
|
|
for (let index = 0; index < HISTORY_ATTEMPT_PAGE_SIZE + 1; index += 1) {
|
|
const id = randomUUID();
|
|
attemptIds.push(id);
|
|
await testDb.insertDownload({
|
|
...own,
|
|
id,
|
|
idempotencyKey: randomUUID(),
|
|
intentKind: index === 0 ? "new_usage" : "repeat_download",
|
|
});
|
|
}
|
|
const history = createDownloadHistoryService({
|
|
repository: createPostgresDownloadHistoryRepository(testDb.database),
|
|
});
|
|
|
|
const first = await history.listEditorialUsageHistory(own.editorialId, 2);
|
|
expect(first.nextAttemptCursor).toBeDefined();
|
|
expect(first.items).toHaveLength(0);
|
|
await testDb.pool.query(
|
|
"update download_events set status = 'completed', started_at = now(), completed_at = now(), transferred_bytes = 5 where id = $1",
|
|
[first.attempts[0].downloadId],
|
|
);
|
|
const laterEventId = randomUUID();
|
|
await testDb.insertDownload({
|
|
...own,
|
|
id: laterEventId,
|
|
idempotencyKey: randomUUID(),
|
|
intentKind: "repeat_download",
|
|
});
|
|
const second = await history.listEditorialUsageHistory(
|
|
own.editorialId,
|
|
2,
|
|
first.nextAttemptCursor,
|
|
);
|
|
const firstIds = first.attempts.map((attempt) => attempt.downloadId);
|
|
const secondIds = second.attempts.map((attempt) => attempt.downloadId);
|
|
|
|
expect(firstIds).toHaveLength(HISTORY_ATTEMPT_PAGE_SIZE);
|
|
expect(secondIds).toHaveLength(1);
|
|
expect(second.nextAttemptCursor).toBeUndefined();
|
|
expect(new Set([...firstIds, ...secondIds])).toEqual(new Set(attemptIds));
|
|
expect([...firstIds, ...secondIds]).not.toContain(laterEventId);
|
|
});
|
|
|
|
test("history ordering queries can use the editorial keyset indexes", async () => {
|
|
const own = await testDb.seedEditorialWithUsage();
|
|
const client = await testDb.pool.connect();
|
|
try {
|
|
await client.query("begin");
|
|
await client.query("set local enable_seqscan = off");
|
|
await client.query("set local enable_sort = off");
|
|
// The keyset indexes sort NULLS LAST, so the probe queries must ask for the
|
|
// same null ordering. Otherwise the index cannot satisfy the ORDER BY, a
|
|
// Sort node is unavoidable and which scan feeds it is a cost tie-break
|
|
// between equal indexes that flips with index creation order.
|
|
const events = await client.query(
|
|
"explain (costs off) select id from download_events where editorial_account_id = $1 order by authorized_at desc nulls last, id desc nulls last limit 26",
|
|
[own.editorialId],
|
|
);
|
|
const usageRows = await client.query(
|
|
"explain (costs off) select id from usages where editorial_account_id = $1 order by created_at desc nulls last, id desc nulls last limit 21",
|
|
[own.editorialId],
|
|
);
|
|
const eventPlan = events.rows.map((row) => row["QUERY PLAN"]).join("\n");
|
|
const usagePlan = usageRows.rows.map((row) => row["QUERY PLAN"]).join("\n");
|
|
|
|
expect(eventPlan).toContain("download_events_editorial_authorized_id_idx");
|
|
expect(eventPlan).not.toContain("Sort");
|
|
expect(usagePlan).toContain("usages_editorial_created_id_idx");
|
|
expect(usagePlan).not.toContain("Sort");
|
|
} finally {
|
|
await client.query("rollback");
|
|
client.release();
|
|
}
|
|
});
|
|
|
|
async function insertUsage(
|
|
editorialId: string,
|
|
assetId: string,
|
|
billingStatus: "open" | "billed" | "reopened",
|
|
purpose: string,
|
|
): Promise<string> {
|
|
const usageId = randomUUID();
|
|
await testDb.pool.query(
|
|
`insert into usages (
|
|
id, editorial_account_id, immich_asset_id, filename_snapshot,
|
|
immich_album_id_snapshot, album_name_snapshot, purpose, price_cents, billing_status
|
|
) values ($1, $2, $3, 'dialog.jpg', 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', 'Dialog', $4, 1500, $5)`,
|
|
[usageId, editorialId, assetId, purpose, billingStatus],
|
|
);
|
|
return usageId;
|
|
}
|