feat: stream originals with download accounting
This commit is contained in:
1 parent
c400167b8f
commit
8871e4794a
28 files changed
+4081
-8
No files matched your search
@@ -0,0 +1 @@
|
||||
ALTER TYPE "public"."usage_billing_status" ADD VALUE 'voided';
|
||||
File diff suppressed because it is too large.
Load diff
@@ -22,6 +22,13 @@
|
||||
"when": 1786354215684,
|
||||
"tag": "0002_accounting_intents",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 3,
|
||||
"version": "7",
|
||||
"when": 1786358492749,
|
||||
"tag": "0003_stream_delivery",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { createRepeatDownload } from "@/modules/downloads/service";
|
||||
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { createNewUsage } from "@/modules/usages/service";
|
||||
import { UsageAccountingError } from "@/modules/usages/types";
|
||||
|
||||
const newUsagePayload = z
|
||||
.object({
|
||||
kind: z.literal("new_usage"),
|
||||
assetId: z.string(),
|
||||
albumId: z.string(),
|
||||
purpose: z.string(),
|
||||
reference: z.string().optional(),
|
||||
idempotencyKey: z.string(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const repeatDownloadPayload = z
|
||||
.object({
|
||||
kind: z.literal("repeat_download"),
|
||||
usageId: z.string(),
|
||||
note: z.string().optional(),
|
||||
idempotencyKey: z.string(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const intentPayload = z.discriminatedUnion("kind", [newUsagePayload, repeatDownloadPayload]);
|
||||
|
||||
type IntentHandlerDependencies = {
|
||||
requireActiveEditorial: typeof requireActiveEditorial;
|
||||
createNewUsage: typeof createNewUsage;
|
||||
createRepeatDownload: typeof createRepeatDownload;
|
||||
};
|
||||
|
||||
export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) {
|
||||
return async function POST(request: Request): Promise<Response> {
|
||||
try {
|
||||
const principal = await dependencies.requireActiveEditorial(request.headers);
|
||||
const payload = intentPayload.safeParse(await readJson(request));
|
||||
if (!payload.success) return errorResponse(400, "INVALID_REQUEST");
|
||||
|
||||
const intent =
|
||||
payload.data.kind === "new_usage"
|
||||
? await dependencies.createNewUsage({
|
||||
editorialId: principal.editorialId,
|
||||
assetId: payload.data.assetId,
|
||||
albumId: payload.data.albumId,
|
||||
purpose: payload.data.purpose,
|
||||
...(payload.data.reference === undefined
|
||||
? {}
|
||||
: { reference: payload.data.reference }),
|
||||
idempotencyKey: payload.data.idempotencyKey,
|
||||
})
|
||||
: await dependencies.createRepeatDownload({
|
||||
editorialId: principal.editorialId,
|
||||
usageId: payload.data.usageId,
|
||||
...(payload.data.note === undefined ? {} : { note: payload.data.note }),
|
||||
idempotencyKey: payload.data.idempotencyKey,
|
||||
});
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
downloadId: intent.id,
|
||||
fileUrl: `/api/downloads/${encodeURIComponent(intent.id)}/file`,
|
||||
priceCents: intent.priceCents,
|
||||
billable: intent.billable,
|
||||
},
|
||||
{ status: 201, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
} catch (error) {
|
||||
return mappedError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function readJson(request: Request): Promise<unknown> {
|
||||
try {
|
||||
return await request.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function mappedError(error: unknown): Response {
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return errorResponse(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
if (error instanceof UsageAccountingError) {
|
||||
switch (error.code) {
|
||||
case "INVALID_INPUT":
|
||||
return errorResponse(400, "INVALID_REQUEST");
|
||||
case "IDEMPOTENCY_CONFLICT":
|
||||
return errorResponse(409, "IDEMPOTENCY_CONFLICT");
|
||||
case "ALBUM_NOT_GRANTED":
|
||||
case "ASSET_NOT_FOUND":
|
||||
case "ASSET_NOT_IN_ALBUM":
|
||||
case "USAGE_NOT_FOUND":
|
||||
return errorResponse(404, "NOT_FOUND");
|
||||
case "IMMICH_UNAVAILABLE":
|
||||
return errorResponse(503, "UPSTREAM_UNAVAILABLE");
|
||||
case "ASSET_NOT_IMAGE":
|
||||
return errorResponse(422, "INVALID_ASSET");
|
||||
case "EDITORIAL_NOT_ACTIVE":
|
||||
return errorResponse(403, "FORBIDDEN");
|
||||
case "INVALID_PRICE":
|
||||
return errorResponse(409, "ACCOUNTING_UNAVAILABLE");
|
||||
}
|
||||
}
|
||||
return errorResponse(500, "REQUEST_FAILED");
|
||||
}
|
||||
|
||||
function errorResponse(status: number, code: string): Response {
|
||||
return Response.json(
|
||||
{ code },
|
||||
{ status, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
}
|
||||
|
||||
export const authorizedDownloadIntentHandler = createDownloadIntentHandler({
|
||||
requireActiveEditorial,
|
||||
createNewUsage,
|
||||
createRepeatDownload,
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { createDownloadIntentHandler } from "./intent-handler";
|
||||
|
||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||
const assetId = "22222222-2222-4222-8222-222222222222";
|
||||
const albumId = "33333333-3333-4333-8333-333333333333";
|
||||
const usageId = "44444444-4444-4444-8444-444444444444";
|
||||
const idempotencyKey = "55555555-5555-4555-8555-555555555555";
|
||||
const downloadId = "66666666-6666-4666-8666-666666666666";
|
||||
|
||||
function dependencies() {
|
||||
return {
|
||||
requireActiveEditorial: vi.fn().mockResolvedValue({ editorialId }),
|
||||
createNewUsage: vi.fn().mockResolvedValue({
|
||||
id: downloadId,
|
||||
usageId,
|
||||
assetId,
|
||||
priceCents: 1_500,
|
||||
billable: true,
|
||||
status: "authorized",
|
||||
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
|
||||
}),
|
||||
createRepeatDownload: vi.fn().mockResolvedValue({
|
||||
id: downloadId,
|
||||
usageId,
|
||||
assetId,
|
||||
priceCents: 0,
|
||||
billable: false,
|
||||
status: "authorized",
|
||||
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function post(handler: ReturnType<typeof createDownloadIntentHandler>, body: unknown) {
|
||||
return handler(
|
||||
new Request("http://portal.test/api/download-intents", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
test("derives editorial scope and billable price exclusively on the server", async () => {
|
||||
const deps = dependencies();
|
||||
const response = await post(createDownloadIntentHandler(deps), {
|
||||
kind: "new_usage",
|
||||
assetId,
|
||||
albumId,
|
||||
purpose: "Titelgeschichte",
|
||||
idempotencyKey,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
downloadId,
|
||||
fileUrl: `/api/downloads/${downloadId}/file`,
|
||||
priceCents: 1_500,
|
||||
billable: true,
|
||||
});
|
||||
expect(deps.createNewUsage).toHaveBeenCalledWith({
|
||||
editorialId,
|
||||
assetId,
|
||||
albumId,
|
||||
purpose: "Titelgeschichte",
|
||||
idempotencyKey,
|
||||
});
|
||||
});
|
||||
|
||||
test("creates a zero-cost repeat intent scoped to the authenticated editorial", async () => {
|
||||
const deps = dependencies();
|
||||
const response = await post(createDownloadIntentHandler(deps), {
|
||||
kind: "repeat_download",
|
||||
usageId,
|
||||
note: "erneuter Abruf",
|
||||
idempotencyKey,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(deps.createRepeatDownload).toHaveBeenCalledWith({
|
||||
editorialId,
|
||||
usageId,
|
||||
note: "erneuter Abruf",
|
||||
idempotencyKey,
|
||||
});
|
||||
await expect(response.json()).resolves.toMatchObject({ priceCents: 0, billable: false });
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ field: "editorialId", value: "77777777-7777-4777-8777-777777777777" },
|
||||
{ field: "priceCents", value: 1 },
|
||||
])("rejects a client-controlled $field before any accounting side effect", async ({ field, value }) => {
|
||||
const deps = dependencies();
|
||||
const response = await post(createDownloadIntentHandler(deps), {
|
||||
kind: "new_usage",
|
||||
assetId,
|
||||
albumId,
|
||||
purpose: "Titelgeschichte",
|
||||
idempotencyKey,
|
||||
[field]: value,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||
expect(deps.createRepeatDownload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("rejects mixed new and repeat fields as an invalid discriminated payload", async () => {
|
||||
const deps = dependencies();
|
||||
const response = await post(createDownloadIntentHandler(deps), {
|
||||
kind: "repeat_download",
|
||||
usageId,
|
||||
assetId,
|
||||
idempotencyKey,
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(deps.createRepeatDownload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("passes one submitted idempotency key through unchanged", async () => {
|
||||
const deps = dependencies();
|
||||
const handler = createDownloadIntentHandler(deps);
|
||||
const body = {
|
||||
kind: "new_usage",
|
||||
assetId,
|
||||
albumId,
|
||||
purpose: "Titelgeschichte",
|
||||
idempotencyKey,
|
||||
};
|
||||
|
||||
const [first, retry] = await Promise.all([post(handler, body), post(handler, body)]);
|
||||
|
||||
expect(first.status).toBe(201);
|
||||
expect(retry.status).toBe(201);
|
||||
expect(deps.createNewUsage).toHaveBeenNthCalledWith(1, expect.objectContaining({ idempotencyKey }));
|
||||
expect(deps.createNewUsage).toHaveBeenNthCalledWith(2, expect.objectContaining({ idempotencyKey }));
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
import { authorizedDownloadIntentHandler } from "./intent-handler";
|
||||
|
||||
export const POST = authorizedDownloadIntentHandler;
|
||||
@@ -0,0 +1,162 @@
|
||||
import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream";
|
||||
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import type { ImmichBinary } from "@/modules/immich/types";
|
||||
import { normalizeUuid } from "@/modules/usages/types";
|
||||
|
||||
type DownloadFileRouteContext = Readonly<{ params: Promise<{ downloadId: string }> }>;
|
||||
|
||||
type DownloadFileHandlerDependencies = {
|
||||
requireActiveEditorial: typeof requireActiveEditorial;
|
||||
repository: typeof downloadDeliveryRepository;
|
||||
immich: { getOriginal(assetId: string, signal?: AbortSignal): Promise<ImmichBinary> };
|
||||
};
|
||||
|
||||
export function createDownloadFileHandler(dependencies: DownloadFileHandlerDependencies) {
|
||||
return async function GET(
|
||||
request: Request,
|
||||
context: DownloadFileRouteContext,
|
||||
): Promise<Response> {
|
||||
try {
|
||||
const principal = await dependencies.requireActiveEditorial(request.headers);
|
||||
const downloadId = safeDownloadId((await context.params).downloadId);
|
||||
if (!downloadId) return genericNotFound();
|
||||
|
||||
const claim = await dependencies.repository.claimAuthorized(
|
||||
principal.editorialId,
|
||||
downloadId,
|
||||
);
|
||||
if (claim.outcome === "not_found") return genericNotFound();
|
||||
if (claim.outcome === "not_authorized") {
|
||||
return jsonError(409, "DOWNLOAD_NOT_AVAILABLE");
|
||||
}
|
||||
|
||||
let original: ImmichBinary;
|
||||
try {
|
||||
original = await dependencies.immich.getOriginal(
|
||||
claim.download.assetId,
|
||||
request.signal,
|
||||
);
|
||||
} catch {
|
||||
await failClaimBeforeDelivery(dependencies, downloadId, claim.download.intentKind);
|
||||
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
|
||||
}
|
||||
|
||||
try {
|
||||
const body = streamWithAccounting({
|
||||
downloadId,
|
||||
upstream: original.body,
|
||||
voidNewUsageOnFailure: claim.download.intentKind === "new_usage",
|
||||
repository: dependencies.repository,
|
||||
});
|
||||
return new Response(body, {
|
||||
headers: downloadHeaders(original, claim.download.filename),
|
||||
});
|
||||
} catch {
|
||||
const cancellation = Promise.resolve().then(() => original.body.cancel());
|
||||
await Promise.allSettled([
|
||||
cancellation,
|
||||
failClaimBeforeDelivery(dependencies, downloadId, claim.download.intentKind),
|
||||
]);
|
||||
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function failClaimBeforeDelivery(
|
||||
dependencies: DownloadFileHandlerDependencies,
|
||||
downloadId: string,
|
||||
intentKind: "new_usage" | "repeat_download" | "legacy",
|
||||
) {
|
||||
await dependencies.repository
|
||||
.failBeforeDelivery(downloadId, { voidNewUsage: intentKind === "new_usage" })
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
function safeDownloadId(value: string): string | null {
|
||||
try {
|
||||
return normalizeUuid(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function downloadHeaders(original: ImmichBinary, snapshotFilename: string): Headers {
|
||||
const headers = new Headers({
|
||||
"cache-control": "private, no-store",
|
||||
"content-disposition": contentDisposition(original.filename || snapshotFilename),
|
||||
"content-type": safeContentType(original.contentType),
|
||||
"x-content-type-options": "nosniff",
|
||||
});
|
||||
if (
|
||||
original.contentLength !== null &&
|
||||
Number.isSafeInteger(original.contentLength) &&
|
||||
original.contentLength >= 0
|
||||
) {
|
||||
headers.set("content-length", String(original.contentLength));
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
export function contentDisposition(filename: string): string {
|
||||
const cleaned = cleanFilename(filename);
|
||||
const fallback = asciiFilename(cleaned);
|
||||
const encoded = encodeURIComponent(cleaned).replace(/[!'()*]/g, (character) =>
|
||||
`%${character.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||
);
|
||||
return `attachment; filename="${fallback}"; filename*=UTF-8''${encoded}`;
|
||||
}
|
||||
|
||||
function cleanFilename(filename: string): string {
|
||||
const cleaned = [...filename.normalize("NFC").replace(/[\uD800-\uDFFF]/gu, "_")]
|
||||
.slice(0, 180)
|
||||
.join("")
|
||||
.replace(/[\\/]/g, "_")
|
||||
.replace(/[\u0000-\u001f\u007f-\u009f]/g, "")
|
||||
.trim();
|
||||
return cleaned && cleaned !== "." && cleaned !== ".." ? cleaned : "download";
|
||||
}
|
||||
|
||||
function asciiFilename(filename: string): string {
|
||||
const fallback = filename
|
||||
.normalize("NFKD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.replace(/[^A-Za-z0-9._ ()+-]/g, "_")
|
||||
.replace(/[";]/g, "_")
|
||||
.trim();
|
||||
return fallback && fallback !== "." && fallback !== ".." ? fallback : "download";
|
||||
}
|
||||
|
||||
function safeContentType(value: string): string {
|
||||
return /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+(?:[ \t]*;[ \t]*[A-Za-z0-9!#$&^_.+-]+=[A-Za-z0-9!#$&^_.+"'()-]+)*$/.test(
|
||||
value,
|
||||
)
|
||||
? value
|
||||
: "application/octet-stream";
|
||||
}
|
||||
|
||||
function genericNotFound(): Response {
|
||||
return new Response(null, {
|
||||
status: 404,
|
||||
headers: { "cache-control": "private, no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
function jsonError(status: number, code: string): Response {
|
||||
return Response.json(
|
||||
{ code },
|
||||
{ status, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
}
|
||||
|
||||
export const authorizedDownloadFileHandler = createDownloadFileHandler({
|
||||
requireActiveEditorial,
|
||||
repository: downloadDeliveryRepository,
|
||||
immich: immichClient,
|
||||
});
|
||||
@@ -0,0 +1,228 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { contentDisposition, createDownloadFileHandler } from "./download-handler";
|
||||
|
||||
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||
const otherEditorialId = "22222222-2222-4222-8222-222222222222";
|
||||
const downloadId = "33333333-3333-4333-8333-333333333333";
|
||||
const usageId = "44444444-4444-4444-8444-444444444444";
|
||||
const assetId = "55555555-5555-4555-8555-555555555555";
|
||||
|
||||
function binary(overrides: Partial<{
|
||||
body: ReadableStream<Uint8Array>;
|
||||
contentType: string;
|
||||
contentLength: number | null;
|
||||
filename: string;
|
||||
}> = {}) {
|
||||
return {
|
||||
body: new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3]));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
contentType: "image/jpeg",
|
||||
contentLength: 3,
|
||||
filename: "heimspiel.jpg",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function dependencies(options: {
|
||||
claim?: "claimed" | "not_found" | "not_authorized";
|
||||
editorialError?: Error;
|
||||
original?: ReturnType<typeof binary>;
|
||||
originalError?: Error;
|
||||
intentKind?: "new_usage" | "repeat_download";
|
||||
} = {}) {
|
||||
const repository = {
|
||||
claimAuthorized: vi.fn().mockResolvedValue(
|
||||
options.claim === "not_found"
|
||||
? { outcome: "not_found" }
|
||||
: options.claim === "not_authorized"
|
||||
? { outcome: "not_authorized" }
|
||||
: {
|
||||
outcome: "claimed",
|
||||
download: {
|
||||
id: downloadId,
|
||||
usageId,
|
||||
assetId,
|
||||
filename: "snapshot.jpg",
|
||||
intentKind: options.intentKind ?? "new_usage",
|
||||
},
|
||||
},
|
||||
),
|
||||
failBeforeDelivery: vi.fn().mockResolvedValue(true),
|
||||
markCompleted: vi.fn().mockResolvedValue(true),
|
||||
markInterrupted: vi.fn().mockResolvedValue(true),
|
||||
};
|
||||
const values = {
|
||||
requireActiveEditorial: vi.fn().mockImplementation(async () => {
|
||||
if (options.editorialError) throw options.editorialError;
|
||||
return { editorialId };
|
||||
}),
|
||||
repository,
|
||||
immich: {
|
||||
getOriginal: vi.fn().mockImplementation(async () => {
|
||||
if (options.originalError) throw options.originalError;
|
||||
return options.original ?? binary();
|
||||
}),
|
||||
},
|
||||
};
|
||||
return values;
|
||||
}
|
||||
|
||||
function call(
|
||||
handler: ReturnType<typeof createDownloadFileHandler>,
|
||||
id = downloadId,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
return handler(new Request(`http://portal.test/api/downloads/${id}/file`, { signal }), {
|
||||
params: Promise.resolve({ downloadId: id }),
|
||||
});
|
||||
}
|
||||
|
||||
test("claims an owned authorized event before requesting and streaming the original", async () => {
|
||||
const deps = dependencies();
|
||||
const handler = createDownloadFileHandler(deps);
|
||||
|
||||
const response = await call(handler);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(deps.repository.claimAuthorized).toHaveBeenCalledWith(editorialId, downloadId);
|
||||
expect(deps.immich.getOriginal).toHaveBeenCalledWith(assetId, expect.any(AbortSignal));
|
||||
expect(await response.arrayBuffer()).toEqual(new Uint8Array([1, 2, 3]).buffer);
|
||||
expect(deps.repository.markCompleted).toHaveBeenCalledWith(downloadId, 3);
|
||||
});
|
||||
|
||||
test("returns the same generic 404 for an invalid id, missing event, and another editorial's event", async () => {
|
||||
const invalid = dependencies();
|
||||
const missing = dependencies({ claim: "not_found" });
|
||||
const foreign = dependencies({ claim: "not_found" });
|
||||
foreign.requireActiveEditorial.mockResolvedValue({ editorialId: otherEditorialId });
|
||||
|
||||
const responses = await Promise.all([
|
||||
call(createDownloadFileHandler(invalid), "not-a-uuid"),
|
||||
call(createDownloadFileHandler(missing)),
|
||||
call(createDownloadFileHandler(foreign)),
|
||||
]);
|
||||
const results = await Promise.all(
|
||||
responses.map(async (response) => ({ status: response.status, body: await response.text() })),
|
||||
);
|
||||
|
||||
expect(results[1]).toEqual(results[0]);
|
||||
expect(results[2]).toEqual(results[0]);
|
||||
expect(invalid.repository.claimAuthorized).not.toHaveBeenCalled();
|
||||
expect(foreign.immich.getOriginal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test.each(["streaming", "completed", "interrupted", "failed_before_delivery"])(
|
||||
"denies reuse of a %s attempt before reaching Immich",
|
||||
async () => {
|
||||
const deps = dependencies({ claim: "not_authorized" });
|
||||
const response = await call(createDownloadFileHandler(deps));
|
||||
|
||||
expect(response.status).toBe(409);
|
||||
await expect(response.json()).resolves.toEqual({ code: "DOWNLOAD_NOT_AVAILABLE" });
|
||||
expect(deps.immich.getOriginal).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
test("marks a pre-response Immich failure failed and voids a new usage", async () => {
|
||||
const deps = dependencies({ originalError: new Error("IMMICH_UNAVAILABLE") });
|
||||
|
||||
const response = await call(createDownloadFileHandler(deps));
|
||||
|
||||
expect(response.status).toBe(503);
|
||||
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("a repeat pre-response failure retains the original usage", async () => {
|
||||
const deps = dependencies({
|
||||
originalError: new Error("IMMICH_UNAVAILABLE"),
|
||||
intentKind: "repeat_download",
|
||||
});
|
||||
|
||||
await call(createDownloadFileHandler(deps));
|
||||
|
||||
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("accounts for a claimed attempt when the upstream body cannot be consumed", async () => {
|
||||
const original = binary();
|
||||
const lock = original.body.getReader();
|
||||
const deps = dependencies({ original });
|
||||
|
||||
const response = await call(createDownloadFileHandler(deps));
|
||||
|
||||
expect(response.status).toBe(503);
|
||||
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: true,
|
||||
});
|
||||
lock.releaseLock();
|
||||
});
|
||||
|
||||
test("emits only safe download headers for an injected Unicode filename", async () => {
|
||||
const deps = dependencies({
|
||||
original: binary({
|
||||
filename: "../München\r\nX-Internal: secret\\final.jpg",
|
||||
contentType: "image/jpeg",
|
||||
contentLength: 3,
|
||||
}),
|
||||
});
|
||||
|
||||
const response = await call(createDownloadFileHandler(deps));
|
||||
const disposition = response.headers.get("content-disposition") ?? "";
|
||||
|
||||
expect(response.headers.get("cache-control")).toBe("private, no-store");
|
||||
expect(response.headers.get("content-type")).toBe("image/jpeg");
|
||||
expect(response.headers.get("content-length")).toBe("3");
|
||||
expect(response.headers.has("x-api-key")).toBe(false);
|
||||
expect(disposition).not.toMatch(/[\r\n\\/]/);
|
||||
expect(disposition).toContain("filename*=UTF-8''");
|
||||
expect(disposition).toContain("M%C3%BCnchen");
|
||||
});
|
||||
|
||||
test("falls back from an untrustworthy media type and length without forwarding header injection", async () => {
|
||||
const deps = dependencies({
|
||||
original: binary({
|
||||
contentType: "image/jpeg;\r\nx-api-key=secret",
|
||||
contentLength: -1,
|
||||
}),
|
||||
});
|
||||
|
||||
const response = await call(createDownloadFileHandler(deps));
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("content-type")).toBe("application/octet-stream");
|
||||
expect(response.headers.has("content-length")).toBe(false);
|
||||
expect(response.headers.has("x-api-key")).toBe(false);
|
||||
});
|
||||
|
||||
test("builds a standards-safe disposition for malformed Unicode", () => {
|
||||
expect(() => contentDisposition("foto-\ud800.jpg")).not.toThrow();
|
||||
expect(contentDisposition("foto-\ud800.jpg")).toContain("filename*=UTF-8''foto-_.jpg");
|
||||
});
|
||||
|
||||
test("returns stable authentication semantics without exposing guard details", async () => {
|
||||
const unauthenticated = dependencies({
|
||||
editorialError: new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED"),
|
||||
});
|
||||
const inactive = dependencies({
|
||||
editorialError: new PrincipalAuthorizationError("ACCOUNT_SUSPENDED"),
|
||||
});
|
||||
|
||||
const [first, second] = await Promise.all([
|
||||
call(createDownloadFileHandler(unauthenticated)),
|
||||
call(createDownloadFileHandler(inactive)),
|
||||
]);
|
||||
|
||||
expect(first.status).toBe(401);
|
||||
expect(second.status).toBe(403);
|
||||
expect(await second.text()).not.toContain("SUSPENDED");
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
import { authorizedDownloadFileHandler } from "./download-handler";
|
||||
|
||||
export const GET = authorizedDownloadFileHandler;
|
||||
@@ -621,3 +621,308 @@ a {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
.download-trigger {
|
||||
width: 100%;
|
||||
min-height: 2.45rem;
|
||||
border: 0;
|
||||
border-top: 1px solid var(--ink);
|
||||
border-radius: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 750;
|
||||
letter-spacing: 0.07em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.download-trigger:hover {
|
||||
background: var(--ink);
|
||||
color: var(--paper);
|
||||
}
|
||||
|
||||
.usage-dialog {
|
||||
width: min(calc(100% - 2rem), 46rem);
|
||||
max-height: calc(100vh - 2rem);
|
||||
padding: 0;
|
||||
border: 1px solid var(--ink);
|
||||
border-radius: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.usage-dialog::backdrop {
|
||||
background: rgb(0 0 0 / 70%);
|
||||
}
|
||||
|
||||
.usage-dialog form {
|
||||
display: grid;
|
||||
gap: 1.5rem;
|
||||
padding: clamp(1.25rem, 4vw, 2.5rem);
|
||||
}
|
||||
|
||||
.usage-dialog-heading {
|
||||
padding-bottom: 1.25rem;
|
||||
border-bottom: 1px solid var(--ink);
|
||||
}
|
||||
|
||||
.usage-dialog-heading h2 {
|
||||
margin: 0;
|
||||
font-size: clamp(2rem, 6vw, 4rem);
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.055em;
|
||||
line-height: 0.95;
|
||||
}
|
||||
|
||||
.usage-dialog-heading > p:last-child {
|
||||
max-width: 38rem;
|
||||
margin: 1rem 0 0;
|
||||
color: var(--graphite);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.usage-options {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.usage-options legend,
|
||||
.usage-purpose {
|
||||
margin-bottom: 0.6rem;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 750;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.usage-option {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 0.9rem;
|
||||
padding: 0.9rem 0;
|
||||
border-top: 1px solid var(--line);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.usage-option:last-child {
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.usage-option input {
|
||||
width: 1.05rem;
|
||||
height: 1.05rem;
|
||||
accent-color: var(--ink);
|
||||
}
|
||||
|
||||
.usage-option span {
|
||||
display: grid;
|
||||
gap: 0.2rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.usage-option strong,
|
||||
.usage-option b {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.usage-option small {
|
||||
overflow: hidden;
|
||||
color: var(--metadata);
|
||||
font-size: 0.7rem;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.usage-purpose {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.usage-purpose textarea {
|
||||
width: 100%;
|
||||
resize: vertical;
|
||||
border: 1px solid var(--ink);
|
||||
border-radius: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
font: inherit;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.usage-purpose textarea:disabled {
|
||||
border-color: var(--line);
|
||||
background: var(--soft);
|
||||
}
|
||||
|
||||
.usage-dialog [role="alert"] {
|
||||
margin: 0;
|
||||
color: #8d1010;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.usage-dialog-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.usage-dialog-actions button {
|
||||
min-height: 2.8rem;
|
||||
border: 1px solid var(--ink);
|
||||
border-radius: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
padding-inline: 1rem;
|
||||
}
|
||||
|
||||
.usage-dialog-actions .download-confirm {
|
||||
background: var(--ink);
|
||||
color: var(--paper);
|
||||
}
|
||||
|
||||
.usage-dialog-actions button:disabled {
|
||||
cursor: wait;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.usage-history-empty {
|
||||
max-width: 38rem;
|
||||
}
|
||||
|
||||
.usage-history-empty p {
|
||||
color: var(--graphite);
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.usage-ledger,
|
||||
.usage-attempts {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.usage-ledger {
|
||||
display: grid;
|
||||
gap: 2.5rem;
|
||||
}
|
||||
|
||||
.usage-ledger-entry {
|
||||
border-top: 2px solid var(--ink);
|
||||
}
|
||||
|
||||
.usage-ledger-entry > header {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 0.8rem 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.usage-ledger-entry > header p {
|
||||
margin: 0;
|
||||
color: var(--metadata);
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 0.65rem;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.usage-ledger-entry h2 {
|
||||
overflow-wrap: anywhere;
|
||||
margin: 0;
|
||||
font-size: clamp(1.35rem, 3vw, 2.25rem);
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.035em;
|
||||
}
|
||||
|
||||
.usage-snapshot {
|
||||
display: grid !important;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr)) !important;
|
||||
gap: 1rem !important;
|
||||
max-width: none !important;
|
||||
margin: 0 !important;
|
||||
padding: 1rem 0 !important;
|
||||
border-top: 0 !important;
|
||||
}
|
||||
|
||||
.usage-snapshot div {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.usage-snapshot dd {
|
||||
overflow-wrap: anywhere;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
.usage-attempts {
|
||||
border-top: 1px solid var(--ink);
|
||||
}
|
||||
|
||||
.usage-attempts li {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(9rem, 1.2fr) minmax(11rem, 1.5fr) minmax(8rem, 1fr) 0.7fr 0.7fr;
|
||||
gap: 1rem;
|
||||
align-items: baseline;
|
||||
padding: 0.7rem 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.usage-attempts time,
|
||||
.usage-attempts span {
|
||||
color: var(--metadata);
|
||||
}
|
||||
|
||||
.usage-attempts b {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.usage-attempt-empty {
|
||||
margin: 0;
|
||||
padding: 1rem 0;
|
||||
border-top: 1px solid var(--line);
|
||||
color: var(--metadata);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
@media (max-width: 52rem) {
|
||||
.usage-snapshot {
|
||||
grid-template-columns: 1fr !important;
|
||||
}
|
||||
|
||||
.usage-attempts li {
|
||||
grid-template-columns: 1fr auto;
|
||||
}
|
||||
|
||||
.usage-attempts li > :nth-child(3),
|
||||
.usage-attempts li > :nth-child(4) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 40rem) {
|
||||
.usage-dialog-actions {
|
||||
flex-direction: column-reverse;
|
||||
}
|
||||
|
||||
.usage-dialog-actions button {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.usage-ledger-entry > header {
|
||||
align-items: flex-start;
|
||||
flex-direction: column-reverse;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { notFound } from "next/navigation";
|
||||
|
||||
import { AlbumCatalogError, albumCatalog } from "@/modules/albums/catalog";
|
||||
import { PhotoContactSheet } from "@/modules/albums/catalog-content";
|
||||
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
|
||||
|
||||
import { requireEditorial } from "../../access";
|
||||
|
||||
@@ -44,6 +45,7 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps
|
||||
<PhotoContactSheet
|
||||
albumId={result.album.id}
|
||||
albumName={result.album.albumName}
|
||||
downloadOptions={result.downloadOptions}
|
||||
page={result.page}
|
||||
query={query}
|
||||
/>
|
||||
@@ -73,7 +75,11 @@ async function loadAlbumPage({
|
||||
description: query,
|
||||
page,
|
||||
});
|
||||
return { album, page: results, unavailable: false as const };
|
||||
const downloadOptions = await loadEditorialDownloadOptions(
|
||||
editorialId,
|
||||
results.items.map((asset) => asset.id),
|
||||
);
|
||||
return { album, page: results, downloadOptions, unavailable: false as const };
|
||||
} catch (error) {
|
||||
if (error instanceof AlbumCatalogError && error.code === "IMMICH_UNAVAILABLE") {
|
||||
return { album: null, page: null, unavailable: true as const };
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
|
||||
import { UsageHistoryContent } from "./usage-history-content";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
test("renders every terminal attempt with its immutable usage snapshot", () => {
|
||||
render(
|
||||
<UsageHistoryContent
|
||||
history={{
|
||||
items: [
|
||||
{
|
||||
usageId: "usage-1",
|
||||
filename: "tor-des-monats.jpg",
|
||||
albumName: "Heimspiel gegen Nord",
|
||||
purpose: "Titelgeschichte",
|
||||
reference: "Ausgabe 8/26",
|
||||
createdAt: new Date("2026-08-09T10:00:00.000Z"),
|
||||
billingStatus: "open",
|
||||
billableCents: 1_500,
|
||||
attempts: [
|
||||
{
|
||||
downloadId: "download-3",
|
||||
status: "failed_before_delivery",
|
||||
requestedAt: new Date("2026-08-10T12:00:00.000Z"),
|
||||
finishedAt: new Date("2026-08-10T12:00:01.000Z"),
|
||||
transferredBytes: 0,
|
||||
repeat: true,
|
||||
billableCents: 0,
|
||||
},
|
||||
{
|
||||
downloadId: "download-2",
|
||||
status: "interrupted",
|
||||
requestedAt: new Date("2026-08-10T11:00:00.000Z"),
|
||||
finishedAt: new Date("2026-08-10T11:00:02.000Z"),
|
||||
transferredBytes: 40,
|
||||
repeat: true,
|
||||
billableCents: 0,
|
||||
},
|
||||
{
|
||||
downloadId: "download-1",
|
||||
status: "completed",
|
||||
requestedAt: new Date("2026-08-09T10:00:00.000Z"),
|
||||
finishedAt: new Date("2026-08-09T10:00:03.000Z"),
|
||||
transferredBytes: 100,
|
||||
repeat: false,
|
||||
billableCents: 1_500,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
hasNext: true,
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("heading", { name: /tor-des-monats\.jpg/i })).not.toBeNull();
|
||||
expect(screen.getByText("Heimspiel gegen Nord")).not.toBeNull();
|
||||
expect(screen.getByText("Titelgeschichte")).not.toBeNull();
|
||||
expect(screen.getByText("Abgeschlossen")).not.toBeNull();
|
||||
expect(screen.getByText("Unterbrochen")).not.toBeNull();
|
||||
expect(screen.getByText("Vor Auslieferung fehlgeschlagen")).not.toBeNull();
|
||||
expect(screen.getByText(/15,00\s*€/)).not.toBeNull();
|
||||
expect(screen.getAllByText(/0,00\s*€/)).toHaveLength(2);
|
||||
expect(screen.getByRole("link", { name: /nächste seite/i }).getAttribute("href")).toBe(
|
||||
"/redaktion/nutzungen?page=2",
|
||||
);
|
||||
});
|
||||
|
||||
test("renders a directional empty state", () => {
|
||||
render(
|
||||
<UsageHistoryContent
|
||||
history={{ items: [], page: 1, pageSize: 20, hasNext: false }}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByText(/noch keine nutzungen/i)).not.toBeNull();
|
||||
expect(screen.getByRole("link", { name: /zu den alben/i })).not.toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { listEditorialUsageHistory } from "@/modules/downloads/stream";
|
||||
|
||||
import { requireEditorial } from "../access";
|
||||
import { UsageHistoryContent } from "./usage-history-content";
|
||||
|
||||
type UsageHistoryPageProps = Readonly<{
|
||||
searchParams: Promise<{ page?: string | string[] }>;
|
||||
}>;
|
||||
|
||||
export default async function UsagesPage({ searchParams }: UsageHistoryPageProps) {
|
||||
const [principal, parameters] = await Promise.all([requireEditorial(), searchParams]);
|
||||
const result = await loadHistory(principal.editorialId, singleValue(parameters.page));
|
||||
if (result.unavailable) return <HistoryUnavailable />;
|
||||
return <UsageHistoryContent history={result.history} />;
|
||||
}
|
||||
|
||||
async function loadHistory(editorialId: string, page: string | undefined) {
|
||||
try {
|
||||
return {
|
||||
history: await listEditorialUsageHistory(editorialId, page),
|
||||
unavailable: false as const,
|
||||
};
|
||||
} catch {
|
||||
return { history: null, unavailable: true as const };
|
||||
}
|
||||
}
|
||||
|
||||
function HistoryUnavailable() {
|
||||
return (
|
||||
<section className="editorial-section editorial-state" aria-labelledby="usage-history-title">
|
||||
<p className="editorial-kicker">Abrechnung</p>
|
||||
<h1 id="usage-history-title">Nutzungen momentan nicht erreichbar</h1>
|
||||
<p role="status">Bitte laden Sie diese Seite in wenigen Minuten erneut.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function singleValue(value: string | string[] | undefined): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import type { UsageHistoryAttempt, UsageHistoryPage } from "@/modules/downloads/stream";
|
||||
|
||||
const dateTimeFormatter = new Intl.DateTimeFormat("de-DE", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
});
|
||||
const priceFormatter = new Intl.NumberFormat("de-DE", {
|
||||
style: "currency",
|
||||
currency: "EUR",
|
||||
});
|
||||
const byteFormatter = new Intl.NumberFormat("de-DE", {
|
||||
style: "unit",
|
||||
unit: "byte",
|
||||
unitDisplay: "short",
|
||||
maximumFractionDigits: 0,
|
||||
});
|
||||
|
||||
export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistoryPage }>) {
|
||||
return (
|
||||
<section className="editorial-section usage-history" aria-labelledby="usage-history-title">
|
||||
<p className="editorial-kicker">Abrechnung · Downloadprotokoll</p>
|
||||
<div className="editorial-title-row">
|
||||
<h1 id="usage-history-title">Ihre Nutzungen</h1>
|
||||
<p>Verwendungszwecke, Kosten und Auslieferungsversuche Ihrer Redaktion.</p>
|
||||
</div>
|
||||
|
||||
{history.items.length === 0 ? (
|
||||
<div className="usage-history-empty">
|
||||
<p>Noch keine Nutzungen erfasst. Wählen Sie ein Foto aus einem freigegebenen Album.</p>
|
||||
<Link className="quiet-link" href="/redaktion/alben">
|
||||
Zu den Alben
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<ol className="usage-ledger">
|
||||
{history.items.map((usage) => (
|
||||
<li key={usage.usageId}>
|
||||
<article className="usage-ledger-entry">
|
||||
<header>
|
||||
<p>{formatDateTime(usage.createdAt)}</p>
|
||||
<h2>{usage.filename}</h2>
|
||||
</header>
|
||||
<dl className="usage-snapshot">
|
||||
<div>
|
||||
<dt>Album</dt>
|
||||
<dd>{usage.albumName}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Verwendungszweck</dt>
|
||||
<dd>{usage.purpose}</dd>
|
||||
</div>
|
||||
{usage.reference ? (
|
||||
<div>
|
||||
<dt>Interne Referenz</dt>
|
||||
<dd>{usage.reference}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
</dl>
|
||||
{usage.attempts.length === 0 ? (
|
||||
<p className="usage-attempt-empty">Noch kein abgeschlossener Auslieferungsversuch.</p>
|
||||
) : (
|
||||
<ol className="usage-attempts" aria-label={`Auslieferungen für ${usage.filename}`}>
|
||||
{usage.attempts.map((attempt) => (
|
||||
<AttemptRow attempt={attempt} key={attempt.downloadId} />
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
</article>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
|
||||
<HistoryPagination history={history} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
|
||||
return (
|
||||
<li>
|
||||
<time dateTime={attempt.finishedAt.toISOString()}>{formatDateTime(attempt.finishedAt)}</time>
|
||||
<strong>{statusLabel(attempt.status)}</strong>
|
||||
<span>{attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"}</span>
|
||||
<span>{byteFormatter.format(attempt.transferredBytes)}</span>
|
||||
<b>{priceFormatter.format(attempt.billableCents / 100)}</b>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function HistoryPagination({ history }: Readonly<{ history: UsageHistoryPage }>) {
|
||||
if (history.page === 1 && !history.hasNext) return null;
|
||||
return (
|
||||
<nav aria-label="Seiten der Nutzungshistorie" className="photo-pagination">
|
||||
{history.page > 1 ? (
|
||||
<Link href={`/redaktion/nutzungen?page=${history.page - 1}`}>Vorherige Seite</Link>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
{history.hasNext ? (
|
||||
<Link href={`/redaktion/nutzungen?page=${history.page + 1}`}>Nächste Seite</Link>
|
||||
) : null}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
function statusLabel(status: UsageHistoryAttempt["status"]): string {
|
||||
const labels: Record<UsageHistoryAttempt["status"], string> = {
|
||||
completed: "Abgeschlossen",
|
||||
interrupted: "Unterbrochen",
|
||||
failed_before_delivery: "Vor Auslieferung fehlgeschlagen",
|
||||
};
|
||||
return labels[status];
|
||||
}
|
||||
|
||||
function formatDateTime(value: Date): string {
|
||||
return dateTimeFormatter.format(value);
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, expect, test, vi } from "vitest";
|
||||
|
||||
import { UsageDialog } from "./usage-dialog";
|
||||
|
||||
const idempotencyKey = "55555555-5555-4555-8555-555555555555";
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(HTMLDialogElement.prototype, "showModal", {
|
||||
configurable: true,
|
||||
value() {
|
||||
this.setAttribute("open", "");
|
||||
},
|
||||
});
|
||||
Object.defineProperty(HTMLDialogElement.prototype, "close", {
|
||||
configurable: true,
|
||||
value() {
|
||||
this.removeAttribute("open");
|
||||
this.dispatchEvent(new Event("close"));
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function renderDialog() {
|
||||
return render(
|
||||
<UsageDialog
|
||||
albumId="33333333-3333-4333-8333-333333333333"
|
||||
assetId="22222222-2222-4222-8222-222222222222"
|
||||
filename="tor-des-monats.jpg"
|
||||
newUsagePriceCents={1_500}
|
||||
priorUsages={[
|
||||
{
|
||||
id: "44444444-4444-4444-8444-444444444444",
|
||||
purpose: "Online-Nachbericht",
|
||||
createdAt: "2026-08-09T10:00:00.000Z",
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
test("offers an existing free use and a new server-priced use with required purpose", () => {
|
||||
renderDialog();
|
||||
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
|
||||
|
||||
expect(screen.getByRole("dialog", { name: /nutzung auswählen/i })).not.toBeNull();
|
||||
expect(
|
||||
(screen.getByRole("radio", {
|
||||
name: /online-nachbericht.*0,00\s*€/i,
|
||||
}) as HTMLInputElement).checked,
|
||||
).toBe(true);
|
||||
expect(
|
||||
(screen.getByRole("radio", { name: /neue nutzung.*15,00\s*€/i }) as HTMLInputElement)
|
||||
.checked,
|
||||
).toBe(false);
|
||||
expect(
|
||||
(screen.getByRole("textbox", { name: /^verwendungszweck$/i }) as HTMLTextAreaElement)
|
||||
.disabled,
|
||||
).toBe(true);
|
||||
|
||||
fireEvent.click(screen.getByRole("radio", { name: /neue nutzung/i }));
|
||||
expect(
|
||||
(screen.getByRole("textbox", { name: /^verwendungszweck$/i }) as HTMLTextAreaElement)
|
||||
.required,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("reuses one idempotency key when the same failed submission is retried", async () => {
|
||||
const randomUUID = vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(idempotencyKey);
|
||||
const fetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
||||
.mockResolvedValueOnce(
|
||||
Response.json({
|
||||
downloadId: "66666666-6666-4666-8666-666666666666",
|
||||
fileUrl: "/api/downloads/66666666-6666-4666-8666-666666666666/file",
|
||||
priceCents: 1_500,
|
||||
billable: true,
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
const anchorClick = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
|
||||
renderDialog();
|
||||
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: /neue nutzung/i }));
|
||||
fireEvent.change(screen.getByRole("textbox", { name: /^verwendungszweck$/i }), {
|
||||
target: { value: "Titelgeschichte" },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /download anfordern/i }));
|
||||
await screen.findByRole("alert");
|
||||
fireEvent.click(screen.getByRole("button", { name: /download erneut anfordern/i }));
|
||||
|
||||
await waitFor(() => expect(anchorClick).toHaveBeenCalledOnce());
|
||||
expect(randomUUID).toHaveBeenCalledOnce();
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
for (const [, init] of fetch.mock.calls) {
|
||||
expect(JSON.parse(String(init?.body))).toMatchObject({ idempotencyKey });
|
||||
}
|
||||
});
|
||||
|
||||
test("suppresses double-click submission while one request is pending", async () => {
|
||||
vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(idempotencyKey);
|
||||
let resolveRequest: ((response: Response) => void) | undefined;
|
||||
const fetch = vi.fn().mockReturnValue(
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
|
||||
renderDialog();
|
||||
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
|
||||
const submit = screen.getByRole("button", { name: /download anfordern/i });
|
||||
|
||||
fireEvent.click(submit);
|
||||
fireEvent.click(submit);
|
||||
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
resolveRequest?.(
|
||||
Response.json({
|
||||
downloadId: "66666666-6666-4666-8666-666666666666",
|
||||
fileUrl: "/api/downloads/66666666-6666-4666-8666-666666666666/file",
|
||||
priceCents: 0,
|
||||
billable: false,
|
||||
}),
|
||||
);
|
||||
await waitFor(() => expect((submit as HTMLButtonElement).disabled).toBe(false));
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState, type FormEvent } from "react";
|
||||
|
||||
import type { DownloadDialogUsage } from "@/modules/downloads/stream";
|
||||
|
||||
type UsageDialogProps = Readonly<{
|
||||
albumId: string;
|
||||
assetId: string;
|
||||
filename: string;
|
||||
newUsagePriceCents: number;
|
||||
priorUsages: DownloadDialogUsage[];
|
||||
}>;
|
||||
|
||||
type IntentResponse = {
|
||||
downloadId: string;
|
||||
fileUrl: string;
|
||||
priceCents: number;
|
||||
billable: boolean;
|
||||
};
|
||||
|
||||
const priceFormatter = new Intl.NumberFormat("de-DE", {
|
||||
style: "currency",
|
||||
currency: "EUR",
|
||||
});
|
||||
const dateFormatter = new Intl.DateTimeFormat("de-DE", {
|
||||
dateStyle: "medium",
|
||||
});
|
||||
|
||||
export function UsageDialog({
|
||||
albumId,
|
||||
assetId,
|
||||
filename,
|
||||
newUsagePriceCents,
|
||||
priorUsages,
|
||||
}: UsageDialogProps) {
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const firstChoiceRef = useRef<HTMLInputElement>(null);
|
||||
const idempotencyKeyRef = useRef<string | null>(null);
|
||||
const initialChoice = priorUsages[0] ? `repeat:${priorUsages[0].id}` : "new_usage";
|
||||
const [choice, setChoice] = useState(initialChoice);
|
||||
const [purpose, setPurpose] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
function openDialog() {
|
||||
setChoice(initialChoice);
|
||||
setPurpose("");
|
||||
setPending(false);
|
||||
setError(null);
|
||||
idempotencyKeyRef.current = null;
|
||||
dialogRef.current?.showModal();
|
||||
requestAnimationFrame(() => firstChoiceRef.current?.focus());
|
||||
}
|
||||
|
||||
function closeDialog() {
|
||||
if (!pending) dialogRef.current?.close();
|
||||
}
|
||||
|
||||
function resetSubmission() {
|
||||
idempotencyKeyRef.current = null;
|
||||
setError(null);
|
||||
}
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (pending) return;
|
||||
setPending(true);
|
||||
setError(null);
|
||||
idempotencyKeyRef.current ??= crypto.randomUUID();
|
||||
|
||||
const payload = choice.startsWith("repeat:")
|
||||
? {
|
||||
kind: "repeat_download" as const,
|
||||
usageId: choice.slice("repeat:".length),
|
||||
idempotencyKey: idempotencyKeyRef.current,
|
||||
}
|
||||
: {
|
||||
kind: "new_usage" as const,
|
||||
assetId,
|
||||
albumId,
|
||||
purpose,
|
||||
idempotencyKey: idempotencyKeyRef.current,
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/download-intents", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!response.ok) throw new Error("intent failed");
|
||||
const intent = (await response.json()) as IntentResponse;
|
||||
if (!isLocalDownloadUrl(intent.fileUrl, intent.downloadId)) {
|
||||
throw new Error("invalid download url");
|
||||
}
|
||||
const link = document.createElement("a");
|
||||
link.href = intent.fileUrl;
|
||||
link.download = filename;
|
||||
link.click();
|
||||
dialogRef.current?.close();
|
||||
idempotencyKeyRef.current = null;
|
||||
} catch {
|
||||
setError(
|
||||
"Der Download konnte nicht vorbereitet werden. Versuchen Sie dieselbe Anfrage erneut.",
|
||||
);
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
const isNewUsage = choice === "new_usage";
|
||||
|
||||
return (
|
||||
<>
|
||||
<button className="download-trigger" onClick={openDialog} type="button">
|
||||
Original laden
|
||||
</button>
|
||||
<dialog
|
||||
aria-labelledby={`usage-dialog-title-${assetId}`}
|
||||
className="usage-dialog"
|
||||
onCancel={(event) => {
|
||||
if (pending) event.preventDefault();
|
||||
}}
|
||||
onClose={() => {
|
||||
setError(null);
|
||||
idempotencyKeyRef.current = null;
|
||||
}}
|
||||
ref={dialogRef}
|
||||
>
|
||||
<form onSubmit={submit}>
|
||||
<div className="usage-dialog-heading">
|
||||
<p className="editorial-kicker">Download · {filename}</p>
|
||||
<h2 id={`usage-dialog-title-${assetId}`}>Nutzung auswählen</h2>
|
||||
<p>Ordnen Sie das Original einer bestehenden oder einer neuen Nutzung zu.</p>
|
||||
</div>
|
||||
|
||||
<fieldset className="usage-options" disabled={pending}>
|
||||
<legend>Abrechnung</legend>
|
||||
{priorUsages.map((usage, index) => (
|
||||
<label className="usage-option" key={usage.id}>
|
||||
<input
|
||||
checked={choice === `repeat:${usage.id}`}
|
||||
name={`usage-${assetId}`}
|
||||
onChange={() => {
|
||||
setChoice(`repeat:${usage.id}`);
|
||||
resetSubmission();
|
||||
}}
|
||||
ref={index === 0 ? firstChoiceRef : undefined}
|
||||
type="radio"
|
||||
value={`repeat:${usage.id}`}
|
||||
/>
|
||||
<span>
|
||||
<strong>{usage.purpose}</strong>
|
||||
<small>Bestehende Nutzung · {formatDate(usage.createdAt)}</small>
|
||||
</span>
|
||||
<b>{priceFormatter.format(0)}</b>
|
||||
</label>
|
||||
))}
|
||||
<label className="usage-option">
|
||||
<input
|
||||
checked={isNewUsage}
|
||||
name={`usage-${assetId}`}
|
||||
onChange={() => {
|
||||
setChoice("new_usage");
|
||||
resetSubmission();
|
||||
}}
|
||||
ref={priorUsages.length === 0 ? firstChoiceRef : undefined}
|
||||
type="radio"
|
||||
value="new_usage"
|
||||
/>
|
||||
<span>
|
||||
<strong>Neue Nutzung</strong>
|
||||
<small>Neue Veröffentlichung oder neuer Verwendungszweck</small>
|
||||
</span>
|
||||
<b>{priceFormatter.format(newUsagePriceCents / 100)}</b>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<label className="usage-purpose" htmlFor={`usage-purpose-${assetId}`}>
|
||||
Verwendungszweck
|
||||
<textarea
|
||||
disabled={!isNewUsage || pending}
|
||||
id={`usage-purpose-${assetId}`}
|
||||
maxLength={200}
|
||||
minLength={3}
|
||||
onChange={(event) => {
|
||||
setPurpose(event.target.value);
|
||||
resetSubmission();
|
||||
}}
|
||||
required={isNewUsage}
|
||||
rows={3}
|
||||
value={purpose}
|
||||
/>
|
||||
</label>
|
||||
|
||||
{error ? <p role="alert">{error}</p> : null}
|
||||
|
||||
<div className="usage-dialog-actions">
|
||||
<button disabled={pending} onClick={closeDialog} type="button">
|
||||
Abbrechen
|
||||
</button>
|
||||
<button className="download-confirm" disabled={pending} type="submit">
|
||||
{pending
|
||||
? "Download wird vorbereitet …"
|
||||
: error
|
||||
? "Download erneut anfordern"
|
||||
: "Download anfordern"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function formatDate(value: string): string {
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.valueOf()) ? "Datum unbekannt" : dateFormatter.format(date);
|
||||
}
|
||||
|
||||
function isLocalDownloadUrl(fileUrl: string, downloadId: string): boolean {
|
||||
return fileUrl === `/api/downloads/${encodeURIComponent(downloadId)}/file`;
|
||||
}
|
||||
@@ -15,6 +15,7 @@ export function PortalShell({ children }: Readonly<{ children: ReactNode }>) {
|
||||
<span>Redaktionsarchiv</span>
|
||||
<nav aria-label="Redaktion">
|
||||
<Link href="/redaktion/alben">Alben</Link>
|
||||
<Link href="/redaktion/nutzungen">Nutzungen</Link>
|
||||
<Link href="/redaktion/profil">Profil</Link>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
import { editorialAccounts } from "./editorials";
|
||||
import { billingReports } from "./billing";
|
||||
|
||||
export const usageBillingStatuses = ["open", "billed", "reopened"] as const;
|
||||
export const usageBillingStatuses = ["open", "billed", "reopened", "voided"] as const;
|
||||
export const usageBillingStatus = pgEnum("usage_billing_status", usageBillingStatuses);
|
||||
|
||||
export const downloadStatuses = [
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { expect, test } from "vitest";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
|
||||
import { AlbumContactSheet, PhotoContactSheet } from "./catalog-content";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
test("renders granted albums as labelled contact-sheet links", () => {
|
||||
render(
|
||||
<AlbumContactSheet
|
||||
@@ -60,3 +62,43 @@ test("renders a labelled photo search and descriptive contact-sheet metadata", (
|
||||
expect(screen.getByText("tor-des-sieges.jpg")).not.toBeNull();
|
||||
expect(screen.getByText(/1 foto gefunden/i)).not.toBeNull();
|
||||
});
|
||||
|
||||
test("renders the server-scoped download choices for a catalog photo", () => {
|
||||
render(
|
||||
<PhotoContactSheet
|
||||
albumId="33333333-3333-4333-8333-333333333333"
|
||||
albumName="Heimspiel gegen Nord"
|
||||
downloadOptions={{
|
||||
priceCents: 1_500,
|
||||
priorUsagesByAsset: {
|
||||
"22222222-2222-4222-8222-222222222222": [
|
||||
{
|
||||
id: "44444444-4444-4444-8444-444444444444",
|
||||
purpose: "Titelgeschichte",
|
||||
createdAt: "2026-08-09T10:00:00.000Z",
|
||||
},
|
||||
],
|
||||
},
|
||||
}}
|
||||
page={{
|
||||
items: [
|
||||
{
|
||||
id: "22222222-2222-4222-8222-222222222222",
|
||||
type: "IMAGE",
|
||||
originalFileName: "tor.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
localDateTime: null,
|
||||
fileCreatedAt: null,
|
||||
albums: [{ id: "33333333-3333-4333-8333-333333333333" }],
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
nextPage: null,
|
||||
previousPage: null,
|
||||
}}
|
||||
query=""
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("button", { name: /original laden/i })).not.toBeNull();
|
||||
});
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import { UsageDialog } from "@/components/download/usage-dialog";
|
||||
import type { EditorialDownloadOptions } from "@/modules/downloads/stream";
|
||||
import type { ImmichSearchPage } from "@/modules/immich/types";
|
||||
|
||||
import type { VisibleAlbum } from "./catalog";
|
||||
@@ -41,11 +43,13 @@ export function AlbumContactSheet({ albums }: Readonly<{ albums: VisibleAlbum[]
|
||||
export function PhotoContactSheet({
|
||||
albumId,
|
||||
albumName,
|
||||
downloadOptions,
|
||||
page,
|
||||
query,
|
||||
}: Readonly<{
|
||||
albumId?: string;
|
||||
albumName: string;
|
||||
downloadOptions?: EditorialDownloadOptions;
|
||||
page: ImmichSearchPage;
|
||||
query: string;
|
||||
}>) {
|
||||
@@ -81,6 +85,15 @@ export function PhotoContactSheet({
|
||||
<span className="contact-strip-name">{asset.originalFileName}</span>
|
||||
<span>{formatDate(asset.localDateTime ?? asset.fileCreatedAt)}</span>
|
||||
</figcaption>
|
||||
{albumId && downloadOptions ? (
|
||||
<UsageDialog
|
||||
albumId={albumId}
|
||||
assetId={asset.id}
|
||||
filename={asset.originalFileName}
|
||||
newUsagePriceCents={downloadOptions.priceCents}
|
||||
priorUsages={downloadOptions.priorUsagesByAsset[asset.id] ?? []}
|
||||
/>
|
||||
) : null}
|
||||
</figure>
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -2,7 +2,7 @@ import "server-only";
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
@@ -95,6 +95,7 @@ export function createRepeatDownloadRepository(
|
||||
and(
|
||||
eq(usages.id, input.usageId),
|
||||
eq(usages.editorialAccountId, input.editorialId),
|
||||
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
|
||||
),
|
||||
)
|
||||
.for("update")
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createDownloadHistoryService,
|
||||
HISTORY_MAX_PAGE,
|
||||
streamWithAccounting,
|
||||
} from "./stream";
|
||||
|
||||
const downloadId = "11111111-1111-4111-8111-111111111111";
|
||||
|
||||
function accounting() {
|
||||
return {
|
||||
failBeforeDelivery: vi.fn().mockResolvedValue(true),
|
||||
markCompleted: vi.fn().mockResolvedValue(true),
|
||||
markInterrupted: vi.fn().mockResolvedValue(true),
|
||||
};
|
||||
}
|
||||
|
||||
async function readAll(stream: ReadableStream<Uint8Array>) {
|
||||
const reader = stream.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) return chunks;
|
||||
chunks.push(value);
|
||||
}
|
||||
}
|
||||
|
||||
test("marks a new usage failed and voidable when upstream fails before its first byte", async () => {
|
||||
const repository = accounting();
|
||||
const upstream = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
controller.error(new Error("upstream unavailable"));
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
readAll(
|
||||
streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure: true,
|
||||
repository,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("upstream unavailable");
|
||||
|
||||
expect(repository.failBeforeDelivery).toHaveBeenCalledOnce();
|
||||
expect(repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: true,
|
||||
});
|
||||
expect(repository.markInterrupted).not.toHaveBeenCalled();
|
||||
expect(repository.markCompleted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("marks a repeat attempt failed without voiding its original usage", async () => {
|
||||
const repository = accounting();
|
||||
const upstream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.error(new Error("upstream unavailable"));
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
readAll(
|
||||
streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure: false,
|
||||
repository,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("upstream unavailable");
|
||||
|
||||
expect(repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||
voidNewUsage: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("marks a stream interrupted with the exact delivered byte count", async () => {
|
||||
const repository = accounting();
|
||||
let pull = 0;
|
||||
const upstream = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
if (pull++ === 0) {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3, 4]));
|
||||
return;
|
||||
}
|
||||
controller.error(new Error("connection reset"));
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
readAll(
|
||||
streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure: true,
|
||||
repository,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("connection reset");
|
||||
|
||||
expect(repository.markInterrupted).toHaveBeenCalledOnce();
|
||||
expect(repository.markInterrupted).toHaveBeenCalledWith(downloadId, 4);
|
||||
expect(repository.failBeforeDelivery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("marks a successful close completed with all delivered bytes", async () => {
|
||||
const repository = accounting();
|
||||
const upstream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2]));
|
||||
controller.enqueue(new Uint8Array([3, 4, 5]));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
readAll(
|
||||
streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure: true,
|
||||
repository,
|
||||
}),
|
||||
),
|
||||
).resolves.toHaveLength(2);
|
||||
|
||||
expect(repository.markCompleted).toHaveBeenCalledOnce();
|
||||
expect(repository.markCompleted).toHaveBeenCalledWith(downloadId, 5);
|
||||
expect(repository.markInterrupted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("cancels upstream and contains a rejecting upstream cancellation", async () => {
|
||||
const repository = accounting();
|
||||
const cancelError = new Error("cancel failed");
|
||||
const upstreamCancel = vi.fn().mockRejectedValue(cancelError);
|
||||
const upstream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array([1, 2, 3]));
|
||||
},
|
||||
cancel: upstreamCancel,
|
||||
});
|
||||
const stream = streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure: true,
|
||||
repository,
|
||||
});
|
||||
const reader = stream.getReader();
|
||||
await reader.read();
|
||||
|
||||
await expect(reader.cancel("browser disconnected")).resolves.toBeUndefined();
|
||||
|
||||
expect(upstreamCancel).toHaveBeenCalledWith("browser disconnected");
|
||||
expect(repository.markInterrupted).toHaveBeenCalledWith(downloadId, 3);
|
||||
expect(repository.markCompleted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("settles terminal accounting exactly once when error and cancel race", async () => {
|
||||
const repository = accounting();
|
||||
let rejectRead: ((error: Error) => void) | undefined;
|
||||
const upstream = new ReadableStream<Uint8Array>({
|
||||
pull() {
|
||||
return new Promise<void>((_resolve, reject) => {
|
||||
rejectRead = reject;
|
||||
});
|
||||
},
|
||||
cancel: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
const stream = streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure: true,
|
||||
repository,
|
||||
});
|
||||
const reader = stream.getReader();
|
||||
const pendingRead = reader.read();
|
||||
await Promise.resolve();
|
||||
const cancellation = reader.cancel("closed");
|
||||
rejectRead?.(new Error("late upstream error"));
|
||||
|
||||
await Promise.allSettled([pendingRead, cancellation]);
|
||||
|
||||
expect(
|
||||
repository.failBeforeDelivery.mock.calls.length +
|
||||
repository.markInterrupted.mock.calls.length +
|
||||
repository.markCompleted.mock.calls.length,
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
test("normalizes and bounds history pagination before the scoped repository query", async () => {
|
||||
const repository = {
|
||||
listEditorialUsageHistory: vi.fn().mockResolvedValue({
|
||||
items: [],
|
||||
page: HISTORY_MAX_PAGE,
|
||||
pageSize: 20,
|
||||
hasNext: false,
|
||||
}),
|
||||
};
|
||||
const history = createDownloadHistoryService({ repository });
|
||||
|
||||
await history.listEditorialUsageHistory(
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
"999999999999999999999999",
|
||||
);
|
||||
|
||||
expect(repository.listEditorialUsageHistory).toHaveBeenCalledWith(
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
HISTORY_MAX_PAGE,
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects an invalid editorial scope before querying usage history", async () => {
|
||||
const repository = { listEditorialUsageHistory: vi.fn() };
|
||||
const history = createDownloadHistoryService({ repository });
|
||||
|
||||
await expect(history.listEditorialUsageHistory("other-editorial", 1)).rejects.toMatchObject({
|
||||
code: "INVALID_INPUT",
|
||||
});
|
||||
expect(repository.listEditorialUsageHistory).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,510 @@
|
||||
import "server-only";
|
||||
|
||||
import { and, desc, eq, inArray } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import { auditEvents, downloadEvents, editorialAccounts, usages } from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
import { normalizeUuid, UsageAccountingError } from "@/modules/usages/types";
|
||||
|
||||
export const HISTORY_PAGE_SIZE = 20;
|
||||
export const HISTORY_MAX_PAGE = 1_000;
|
||||
|
||||
export type ClaimedDownload = {
|
||||
id: string;
|
||||
usageId: string;
|
||||
assetId: string;
|
||||
filename: string;
|
||||
intentKind: "new_usage" | "repeat_download" | "legacy";
|
||||
};
|
||||
|
||||
export type DownloadClaim =
|
||||
| { outcome: "claimed"; download: ClaimedDownload }
|
||||
| { outcome: "not_found" }
|
||||
| { outcome: "not_authorized" };
|
||||
|
||||
export type DownloadDeliveryRepository = {
|
||||
claimAuthorized(editorialId: string, downloadId: string): Promise<DownloadClaim>;
|
||||
failBeforeDelivery(
|
||||
downloadId: string,
|
||||
options: { voidNewUsage: boolean },
|
||||
): Promise<boolean>;
|
||||
markCompleted(downloadId: string, transferredBytes: number): Promise<boolean>;
|
||||
markInterrupted(downloadId: string, transferredBytes: number): Promise<boolean>;
|
||||
};
|
||||
|
||||
type StreamAccountingRepository = Pick<
|
||||
DownloadDeliveryRepository,
|
||||
"failBeforeDelivery" | "markCompleted" | "markInterrupted"
|
||||
>;
|
||||
|
||||
export function streamWithAccounting({
|
||||
downloadId,
|
||||
upstream,
|
||||
voidNewUsageOnFailure,
|
||||
repository,
|
||||
}: {
|
||||
downloadId: string;
|
||||
upstream: ReadableStream<Uint8Array>;
|
||||
voidNewUsageOnFailure: boolean;
|
||||
repository: StreamAccountingRepository;
|
||||
}): ReadableStream<Uint8Array> {
|
||||
const reader = upstream.getReader();
|
||||
let transferredBytes = 0;
|
||||
let stopped = false;
|
||||
let released = false;
|
||||
let terminal: Promise<void> | undefined;
|
||||
|
||||
function releaseReader() {
|
||||
if (released) return;
|
||||
released = true;
|
||||
try {
|
||||
reader.releaseLock();
|
||||
} catch {
|
||||
// The reader may still have a pending read during a client cancellation.
|
||||
}
|
||||
}
|
||||
|
||||
function settle(kind: "completed" | "interrupted" | "failed_before_delivery") {
|
||||
terminal ??= (async () => {
|
||||
if (kind === "completed") {
|
||||
await repository.markCompleted(downloadId, transferredBytes);
|
||||
} else if (kind === "interrupted") {
|
||||
await repository.markInterrupted(downloadId, transferredBytes);
|
||||
} else {
|
||||
await repository.failBeforeDelivery(downloadId, {
|
||||
voidNewUsage: voidNewUsageOnFailure,
|
||||
});
|
||||
}
|
||||
})();
|
||||
return terminal;
|
||||
}
|
||||
|
||||
return new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
if (stopped) return;
|
||||
try {
|
||||
const { done, value } = await reader.read();
|
||||
if (stopped) return;
|
||||
if (done) {
|
||||
await settle("completed");
|
||||
stopped = true;
|
||||
releaseReader();
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
controller.enqueue(value);
|
||||
transferredBytes += value.byteLength;
|
||||
if (!Number.isSafeInteger(transferredBytes)) {
|
||||
throw new Error("Transferred byte count exceeds the supported range");
|
||||
}
|
||||
} catch (error) {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
await settle(transferredBytes === 0 ? "failed_before_delivery" : "interrupted").catch(
|
||||
() => undefined,
|
||||
);
|
||||
releaseReader();
|
||||
controller.error(error);
|
||||
}
|
||||
},
|
||||
async cancel(reason) {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
const accounting = settle(
|
||||
transferredBytes === 0 ? "failed_before_delivery" : "interrupted",
|
||||
);
|
||||
await Promise.allSettled([reader.cancel(reason), accounting]);
|
||||
releaseReader();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function createDownloadDeliveryRepository(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
): DownloadDeliveryRepository {
|
||||
return {
|
||||
async claimAuthorized(editorialId, downloadId) {
|
||||
return database.transaction(async (transaction) => {
|
||||
const [claimed] = await transaction
|
||||
.update(downloadEvents)
|
||||
.set({ status: "streaming", startedAt: new Date() })
|
||||
.where(
|
||||
and(
|
||||
eq(downloadEvents.id, downloadId),
|
||||
eq(downloadEvents.editorialAccountId, editorialId),
|
||||
eq(downloadEvents.status, "authorized"),
|
||||
),
|
||||
)
|
||||
.returning({
|
||||
id: downloadEvents.id,
|
||||
usageId: downloadEvents.usageId,
|
||||
assetId: downloadEvents.immichAssetId,
|
||||
intentKind: downloadEvents.intentKind,
|
||||
});
|
||||
|
||||
if (!claimed) {
|
||||
const [owned] = await transaction
|
||||
.select({ id: downloadEvents.id })
|
||||
.from(downloadEvents)
|
||||
.where(
|
||||
and(
|
||||
eq(downloadEvents.id, downloadId),
|
||||
eq(downloadEvents.editorialAccountId, editorialId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return owned
|
||||
? ({ outcome: "not_authorized" } as const)
|
||||
: ({ outcome: "not_found" } as const);
|
||||
}
|
||||
|
||||
const [usage] = await transaction
|
||||
.select({ filename: usages.filenameSnapshot })
|
||||
.from(usages)
|
||||
.where(
|
||||
and(
|
||||
eq(usages.id, claimed.usageId),
|
||||
eq(usages.editorialAccountId, editorialId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (!usage) return { outcome: "not_found" } as const;
|
||||
|
||||
return {
|
||||
outcome: "claimed",
|
||||
download: {
|
||||
...claimed,
|
||||
filename: usage.filename,
|
||||
intentKind: claimedIntentKind(claimed.intentKind),
|
||||
},
|
||||
} as const;
|
||||
});
|
||||
},
|
||||
|
||||
async failBeforeDelivery(downloadId, options) {
|
||||
return database.transaction(async (transaction) => {
|
||||
const terminalAt = new Date();
|
||||
const [failed] = await transaction
|
||||
.update(downloadEvents)
|
||||
.set({
|
||||
status: "failed_before_delivery",
|
||||
transferredBytes: 0,
|
||||
completedAt: terminalAt,
|
||||
})
|
||||
.where(
|
||||
and(eq(downloadEvents.id, downloadId), eq(downloadEvents.status, "streaming")),
|
||||
)
|
||||
.returning({
|
||||
usageId: downloadEvents.usageId,
|
||||
editorialId: downloadEvents.editorialAccountId,
|
||||
intentKind: downloadEvents.intentKind,
|
||||
requestId: downloadEvents.requestId,
|
||||
});
|
||||
if (!failed) return false;
|
||||
|
||||
if (options.voidNewUsage && failed.intentKind === "new_usage") {
|
||||
const [voided] = await transaction
|
||||
.update(usages)
|
||||
.set({ billingStatus: "voided" })
|
||||
.where(
|
||||
and(
|
||||
eq(usages.id, failed.usageId),
|
||||
eq(usages.editorialAccountId, failed.editorialId),
|
||||
inArray(usages.billingStatus, ["open", "reopened"]),
|
||||
),
|
||||
)
|
||||
.returning({ id: usages.id });
|
||||
if (!voided) {
|
||||
throw new Error("Billable usage could not be voided before delivery");
|
||||
}
|
||||
await transaction.insert(auditEvents).values({
|
||||
eventType: "billable_usage_voided_before_delivery",
|
||||
actorType: "system",
|
||||
entityType: "usage",
|
||||
entityId: failed.usageId,
|
||||
previousValues: { billingStatus: "open" },
|
||||
newValues: {
|
||||
billingStatus: "voided",
|
||||
downloadId,
|
||||
reason: "failed_before_delivery",
|
||||
},
|
||||
occurredAt: terminalAt,
|
||||
requestId: failed.requestId,
|
||||
});
|
||||
}
|
||||
return true;
|
||||
});
|
||||
},
|
||||
|
||||
markCompleted(downloadId, transferredBytes) {
|
||||
return markTerminal(database, downloadId, "completed", transferredBytes);
|
||||
},
|
||||
|
||||
markInterrupted(downloadId, transferredBytes) {
|
||||
return markTerminal(database, downloadId, "interrupted", transferredBytes);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function markTerminal(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
downloadId: string,
|
||||
status: "completed" | "interrupted",
|
||||
transferredBytes: number,
|
||||
): Promise<boolean> {
|
||||
assertByteCount(transferredBytes);
|
||||
const [updated] = await database
|
||||
.update(downloadEvents)
|
||||
.set({ status, transferredBytes, completedAt: new Date() })
|
||||
.where(and(eq(downloadEvents.id, downloadId), eq(downloadEvents.status, "streaming")))
|
||||
.returning({ id: downloadEvents.id });
|
||||
return Boolean(updated);
|
||||
}
|
||||
|
||||
function assertByteCount(value: number) {
|
||||
if (!Number.isSafeInteger(value) || value < 0) {
|
||||
throw new Error("Invalid transferred byte count");
|
||||
}
|
||||
}
|
||||
|
||||
export type UsageHistoryAttempt = {
|
||||
downloadId: string;
|
||||
status: "completed" | "interrupted" | "failed_before_delivery";
|
||||
requestedAt: Date;
|
||||
finishedAt: Date;
|
||||
transferredBytes: number;
|
||||
repeat: boolean;
|
||||
billableCents: number;
|
||||
};
|
||||
|
||||
export type UsageHistoryItem = {
|
||||
usageId: string;
|
||||
filename: string;
|
||||
albumName: string;
|
||||
purpose: string;
|
||||
reference?: string;
|
||||
createdAt: Date;
|
||||
billingStatus: "open" | "billed" | "reopened" | "voided";
|
||||
billableCents: number;
|
||||
attempts: UsageHistoryAttempt[];
|
||||
};
|
||||
|
||||
export type UsageHistoryPage = {
|
||||
items: UsageHistoryItem[];
|
||||
page: number;
|
||||
pageSize: number;
|
||||
hasNext: boolean;
|
||||
};
|
||||
|
||||
export type DownloadHistoryRepository = {
|
||||
listEditorialUsageHistory(editorialId: string, page: number): Promise<UsageHistoryPage>;
|
||||
};
|
||||
|
||||
export function createDownloadHistoryService({
|
||||
repository,
|
||||
}: {
|
||||
repository: DownloadHistoryRepository;
|
||||
}) {
|
||||
return {
|
||||
async listEditorialUsageHistory(editorialId: string, rawPage: unknown) {
|
||||
return repository.listEditorialUsageHistory(
|
||||
normalizeUuid(editorialId),
|
||||
normalizeHistoryPage(rawPage),
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createPostgresDownloadHistoryRepository(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
): DownloadHistoryRepository {
|
||||
return {
|
||||
async listEditorialUsageHistory(editorialId, page) {
|
||||
const offset = (page - 1) * HISTORY_PAGE_SIZE;
|
||||
const usageRows = await database
|
||||
.select({
|
||||
usageId: usages.id,
|
||||
filename: usages.filenameSnapshot,
|
||||
albumName: usages.albumNameSnapshot,
|
||||
purpose: usages.purpose,
|
||||
reference: usages.internalReference,
|
||||
createdAt: usages.createdAt,
|
||||
billingStatus: usages.billingStatus,
|
||||
priceCents: usages.priceCents,
|
||||
})
|
||||
.from(usages)
|
||||
.where(eq(usages.editorialAccountId, editorialId))
|
||||
.orderBy(desc(usages.createdAt), desc(usages.id))
|
||||
.limit(HISTORY_PAGE_SIZE + 1)
|
||||
.offset(offset);
|
||||
const hasNext = usageRows.length > HISTORY_PAGE_SIZE;
|
||||
const pageRows = usageRows.slice(0, HISTORY_PAGE_SIZE);
|
||||
if (pageRows.length === 0) {
|
||||
return { items: [], page, pageSize: HISTORY_PAGE_SIZE, hasNext };
|
||||
}
|
||||
|
||||
const usageIds = pageRows.map((usage) => usage.usageId);
|
||||
const eventRows = await database
|
||||
.select({
|
||||
downloadId: downloadEvents.id,
|
||||
usageId: downloadEvents.usageId,
|
||||
status: downloadEvents.status,
|
||||
requestedAt: downloadEvents.authorizedAt,
|
||||
finishedAt: downloadEvents.completedAt,
|
||||
transferredBytes: downloadEvents.transferredBytes,
|
||||
intentKind: downloadEvents.intentKind,
|
||||
})
|
||||
.from(downloadEvents)
|
||||
.where(
|
||||
and(
|
||||
eq(downloadEvents.editorialAccountId, editorialId),
|
||||
inArray(downloadEvents.usageId, usageIds),
|
||||
inArray(downloadEvents.status, [
|
||||
"completed",
|
||||
"interrupted",
|
||||
"failed_before_delivery",
|
||||
]),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(downloadEvents.authorizedAt), desc(downloadEvents.id));
|
||||
|
||||
const eventsByUsage = new Map<string, typeof eventRows>();
|
||||
for (const event of eventRows) {
|
||||
const attempts = eventsByUsage.get(event.usageId) ?? [];
|
||||
attempts.push(event);
|
||||
eventsByUsage.set(event.usageId, attempts);
|
||||
}
|
||||
|
||||
return {
|
||||
items: pageRows.map((usage) => {
|
||||
const billableCents = usage.billingStatus === "voided" ? 0 : usage.priceCents;
|
||||
return {
|
||||
usageId: usage.usageId,
|
||||
filename: usage.filename,
|
||||
albumName: usage.albumName,
|
||||
purpose: usage.purpose,
|
||||
...(usage.reference === null ? {} : { reference: usage.reference }),
|
||||
createdAt: usage.createdAt,
|
||||
billingStatus: usage.billingStatus,
|
||||
billableCents,
|
||||
attempts: (eventsByUsage.get(usage.usageId) ?? []).map((event) => ({
|
||||
downloadId: event.downloadId,
|
||||
status: terminalStatus(event.status),
|
||||
requestedAt: event.requestedAt,
|
||||
finishedAt: event.finishedAt ?? event.requestedAt,
|
||||
transferredBytes: event.transferredBytes ?? 0,
|
||||
repeat: event.intentKind === "repeat_download",
|
||||
billableCents:
|
||||
event.intentKind === "new_usage" && usage.billingStatus !== "voided"
|
||||
? usage.priceCents
|
||||
: 0,
|
||||
})),
|
||||
};
|
||||
}),
|
||||
page,
|
||||
pageSize: HISTORY_PAGE_SIZE,
|
||||
hasNext,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function terminalStatus(status: string): UsageHistoryAttempt["status"] {
|
||||
if (
|
||||
status === "completed" ||
|
||||
status === "interrupted" ||
|
||||
status === "failed_before_delivery"
|
||||
) {
|
||||
return status;
|
||||
}
|
||||
throw new Error("Non-terminal download in history query");
|
||||
}
|
||||
|
||||
function claimedIntentKind(value: string): ClaimedDownload["intentKind"] {
|
||||
if (value === "new_usage" || value === "repeat_download" || value === "legacy") {
|
||||
return value;
|
||||
}
|
||||
throw new Error("Unsupported download intent kind");
|
||||
}
|
||||
|
||||
function normalizeHistoryPage(value: unknown): number {
|
||||
let page = 1;
|
||||
if (typeof value === "number" && Number.isSafeInteger(value)) {
|
||||
page = value;
|
||||
} else if (typeof value === "string" && /^\d+$/.test(value)) {
|
||||
const parsed = Number(value);
|
||||
page = Number.isSafeInteger(parsed) ? parsed : HISTORY_MAX_PAGE;
|
||||
}
|
||||
return Math.min(HISTORY_MAX_PAGE, Math.max(1, page));
|
||||
}
|
||||
|
||||
export type DownloadDialogUsage = {
|
||||
id: string;
|
||||
purpose: string;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
export type EditorialDownloadOptions = {
|
||||
priceCents: number;
|
||||
priorUsagesByAsset: Record<string, DownloadDialogUsage[]>;
|
||||
};
|
||||
|
||||
export async function loadEditorialDownloadOptions(
|
||||
editorialId: string,
|
||||
assetIds: string[],
|
||||
): Promise<EditorialDownloadOptions> {
|
||||
const normalizedEditorialId = normalizeUuid(editorialId);
|
||||
const normalizedAssets = [...new Set(assetIds.map(normalizeUuid))];
|
||||
const [editorial] = await db
|
||||
.select({ currentPriceCents: editorialAccounts.currentPriceCents })
|
||||
.from(editorialAccounts)
|
||||
.where(
|
||||
and(
|
||||
eq(editorialAccounts.id, normalizedEditorialId),
|
||||
eq(editorialAccounts.status, "active"),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
const priceCents = editorial?.currentPriceCents;
|
||||
if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) {
|
||||
throw new UsageAccountingError("INVALID_PRICE");
|
||||
}
|
||||
if (normalizedAssets.length === 0) {
|
||||
return { priceCents: priceCents!, priorUsagesByAsset: {} };
|
||||
}
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
id: usages.id,
|
||||
assetId: usages.immichAssetId,
|
||||
purpose: usages.purpose,
|
||||
createdAt: usages.createdAt,
|
||||
})
|
||||
.from(usages)
|
||||
.where(
|
||||
and(
|
||||
eq(usages.editorialAccountId, normalizedEditorialId),
|
||||
inArray(usages.immichAssetId, normalizedAssets),
|
||||
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(usages.createdAt));
|
||||
const priorUsagesByAsset: Record<string, DownloadDialogUsage[]> = {};
|
||||
for (const row of rows) {
|
||||
(priorUsagesByAsset[row.assetId] ??= []).push({
|
||||
id: row.id,
|
||||
purpose: row.purpose,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
});
|
||||
}
|
||||
return { priceCents: priceCents!, priorUsagesByAsset };
|
||||
}
|
||||
|
||||
const downloadHistoryService = createDownloadHistoryService({
|
||||
repository: createPostgresDownloadHistoryRepository(db),
|
||||
});
|
||||
|
||||
export const listEditorialUsageHistory = downloadHistoryService.listEditorialUsageHistory;
|
||||
export const downloadDeliveryRepository = createDownloadDeliveryRepository(db);
|
||||
@@ -2,7 +2,7 @@ import "server-only";
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { and, desc, eq, isNull, sql } from "drizzle-orm";
|
||||
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
@@ -261,6 +261,7 @@ export function createUsageServiceRepository(
|
||||
and(
|
||||
eq(usages.editorialAccountId, editorialId),
|
||||
eq(usages.immichAssetId, assetId),
|
||||
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(usages.createdAt));
|
||||
|
||||
@@ -35,7 +35,7 @@ export type PriorUsage = {
|
||||
purpose: string;
|
||||
reference: string | undefined;
|
||||
priceCents: number;
|
||||
billingStatus: "open" | "billed" | "reopened";
|
||||
billingStatus: "open" | "billed" | "reopened" | "voided";
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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() {
|
||||
|
||||
Reference in new issue
Block a user