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,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;
|
||||
Reference in new issue
Block a user