fix: harden download history and attempt ledger
This commit is contained in:
1 parent
510fde7afa
commit
ba673ad732
19 files changed
+2287
-311
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import "server-only";
|
||||
|
||||
import { and, eq, gt, inArray } from "drizzle-orm";
|
||||
import { and, eq, gt, inArray, sql, type SQL, type SQLWrapper } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { downloadEvents } from "@/db/schema";
|
||||
@@ -15,6 +15,23 @@ export function isFreeRepeatEligible(
|
||||
return billingStatus !== "voided" && deliveredOriginal;
|
||||
}
|
||||
|
||||
export function deliveredOriginalEventCondition(
|
||||
editorialId: string,
|
||||
usageId: string | SQLWrapper,
|
||||
): SQL {
|
||||
const scopedUsage =
|
||||
typeof usageId === "string"
|
||||
? eq(downloadEvents.usageId, usageId)
|
||||
: sql`${downloadEvents.usageId} = ${usageId}`;
|
||||
return and(
|
||||
eq(downloadEvents.editorialAccountId, editorialId),
|
||||
scopedUsage,
|
||||
eq(downloadEvents.intentKind, "new_usage"),
|
||||
inArray(downloadEvents.status, ["completed", "interrupted"]),
|
||||
gt(downloadEvents.transferredBytes, 0),
|
||||
)!;
|
||||
}
|
||||
|
||||
export async function hasDeliveredOriginal(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
editorialId: string,
|
||||
@@ -23,15 +40,7 @@ export async function hasDeliveredOriginal(
|
||||
const [delivery] = await database
|
||||
.select({ id: downloadEvents.id })
|
||||
.from(downloadEvents)
|
||||
.where(
|
||||
and(
|
||||
eq(downloadEvents.editorialAccountId, editorialId),
|
||||
eq(downloadEvents.usageId, usageId),
|
||||
eq(downloadEvents.intentKind, "new_usage"),
|
||||
inArray(downloadEvents.status, ["completed", "interrupted"]),
|
||||
gt(downloadEvents.transferredBytes, 0),
|
||||
),
|
||||
)
|
||||
.where(deliveredOriginalEventCondition(editorialId, usageId))
|
||||
.limit(1);
|
||||
return Boolean(delivery);
|
||||
}
|
||||
@@ -17,16 +17,15 @@ function createService() {
|
||||
const intents = new Map<string, PersistedRepeatIntent>();
|
||||
const events: RepeatIntentInput[] = [];
|
||||
let active = true;
|
||||
let eligible = true;
|
||||
let usageOwner = editorialId;
|
||||
let snapshotPrice = 1_500;
|
||||
|
||||
const repository: RepeatDownloadRepository = {
|
||||
async findIntent(requestEditorialId, key) {
|
||||
return intents.get(`${requestEditorialId}:${key}`) ?? null;
|
||||
},
|
||||
async createRepeatIntent(input) {
|
||||
if (!active) throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
|
||||
if (usageOwner !== input.editorialId) throw new UsageAccountingError("USAGE_NOT_FOUND");
|
||||
if (!eligible) throw new UsageAccountingError("USAGE_NOT_FOUND");
|
||||
const key = `${input.editorialId}:${input.idempotencyKey}`;
|
||||
const existing = intents.get(key);
|
||||
if (existing) return existing;
|
||||
@@ -54,6 +53,9 @@ function createService() {
|
||||
setActive(value: boolean) {
|
||||
active = value;
|
||||
},
|
||||
setEligible(value: boolean) {
|
||||
eligible = value;
|
||||
},
|
||||
setUsageOwner(value: string) {
|
||||
usageOwner = value;
|
||||
},
|
||||
@@ -127,6 +129,17 @@ test("returns the same free intent once for an equivalent retry", async () => {
|
||||
expect(events).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("revalidates eligibility under the repository lock for the same idempotency key", async () => {
|
||||
const { service, setEligible } = createService();
|
||||
const input = { editorialId, usageId, note: "noch einmal", idempotencyKey };
|
||||
await service.createRepeatDownload(input);
|
||||
setEligible(false);
|
||||
|
||||
await expect(service.createRepeatDownload(input)).rejects.toMatchObject({
|
||||
code: "USAGE_NOT_FOUND",
|
||||
});
|
||||
});
|
||||
|
||||
test("treats mixed-case UUID input as the same repeat intent", async () => {
|
||||
const { service, events } = createService();
|
||||
const uppercaseInput = {
|
||||
@@ -159,10 +172,10 @@ test.each([
|
||||
[undefined, "not-a-uuid"],
|
||||
] as const)("rejects malformed repeat input before repository side effects", async (note, key) => {
|
||||
const { service, repository } = createService();
|
||||
const findIntent = vi.spyOn(repository, "findIntent");
|
||||
const createRepeatIntent = vi.spyOn(repository, "createRepeatIntent");
|
||||
|
||||
await expect(
|
||||
service.createRepeatDownload({ editorialId, usageId, note, idempotencyKey: key }),
|
||||
).rejects.toMatchObject({ code: "INVALID_INPUT" });
|
||||
expect(findIntent).not.toHaveBeenCalled();
|
||||
expect(createRepeatIntent).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -36,7 +36,6 @@ export type RepeatIntentInput = {
|
||||
};
|
||||
|
||||
export type RepeatDownloadRepository = {
|
||||
findIntent(editorialId: string, idempotencyKey: string): Promise<PersistedDownloadIntent | null>;
|
||||
createRepeatIntent(input: RepeatIntentInput): Promise<PersistedRepeatIntent>;
|
||||
};
|
||||
|
||||
@@ -50,8 +49,6 @@ export function createDownloadService({ repository }: { repository: RepeatDownlo
|
||||
usageId: input.usageId,
|
||||
note: input.note ?? null,
|
||||
});
|
||||
const existing = await repository.findIntent(input.editorialId, input.idempotencyKey);
|
||||
if (existing) return resolveIntent(existing, fingerprint, "repeat_download");
|
||||
const persisted = await repository.createRepeatIntent({
|
||||
...input,
|
||||
requestFingerprint: fingerprint,
|
||||
@@ -65,109 +62,108 @@ export function createRepeatDownloadRepository(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
): RepeatDownloadRepository {
|
||||
return {
|
||||
findIntent(editorialId, idempotencyKey) {
|
||||
return findPersistedIntent(database, editorialId, idempotencyKey);
|
||||
},
|
||||
|
||||
async createRepeatIntent(input) {
|
||||
try {
|
||||
return await database.transaction(async (transaction) => {
|
||||
await lockEditorialAccounting(transaction, input.editorialId);
|
||||
const existing = await findPersistedIntent(
|
||||
transaction,
|
||||
input.editorialId,
|
||||
input.idempotencyKey,
|
||||
);
|
||||
if (
|
||||
existing &&
|
||||
(existing.kind !== "repeat_download" ||
|
||||
existing.requestFingerprint !== input.requestFingerprint)
|
||||
) {
|
||||
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
|
||||
}
|
||||
|
||||
const [editorial] = await transaction
|
||||
.select({ id: editorialAccounts.id, status: editorialAccounts.status })
|
||||
.from(editorialAccounts)
|
||||
.where(eq(editorialAccounts.id, input.editorialId))
|
||||
.for("update")
|
||||
.limit(1);
|
||||
if (!editorial || editorial.status !== "active") {
|
||||
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
|
||||
}
|
||||
|
||||
const [usage] = await transaction
|
||||
.select({
|
||||
id: usages.id,
|
||||
assetId: usages.immichAssetId,
|
||||
billingStatus: usages.billingStatus,
|
||||
})
|
||||
.from(usages)
|
||||
.where(
|
||||
and(
|
||||
eq(usages.id, input.usageId),
|
||||
eq(usages.editorialAccountId, input.editorialId),
|
||||
),
|
||||
)
|
||||
.for("update")
|
||||
.limit(1);
|
||||
if (!usage) throw new UsageAccountingError("USAGE_NOT_FOUND");
|
||||
const deliveredOriginal = await hasDeliveredOriginal(
|
||||
transaction,
|
||||
input.editorialId,
|
||||
usage.id,
|
||||
);
|
||||
if (!isFreeRepeatEligible(usage.billingStatus, deliveredOriginal)) {
|
||||
throw new UsageAccountingError("USAGE_NOT_FOUND");
|
||||
}
|
||||
if (existing) return asRepeatIntent(existing);
|
||||
|
||||
const authorizedAt = new Date();
|
||||
const [event] = await transaction
|
||||
.insert(downloadEvents)
|
||||
.values({
|
||||
editorialAccountId: input.editorialId,
|
||||
usageId: usage.id,
|
||||
immichAssetId: usage.assetId,
|
||||
authorizedAt,
|
||||
status: "authorized",
|
||||
repeatDownloadNote: input.note,
|
||||
requestId: randomUUID(),
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
intentKind: "repeat_download",
|
||||
requestFingerprint: input.requestFingerprint,
|
||||
})
|
||||
.onConflictDoNothing({
|
||||
target: [downloadEvents.editorialAccountId, downloadEvents.idempotencyKey],
|
||||
})
|
||||
.returning({ id: downloadEvents.id });
|
||||
if (!event) throw new RepeatIdempotencyRaceError();
|
||||
return {
|
||||
id: event.id,
|
||||
usageId: usage.id,
|
||||
assetId: usage.assetId,
|
||||
priceCents: 0,
|
||||
billable: false,
|
||||
status: "authorized" as const,
|
||||
authorizedAt,
|
||||
requestFingerprint: input.requestFingerprint,
|
||||
kind: "repeat_download" as const,
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
if (!(error instanceof RepeatIdempotencyRaceError)) throw error;
|
||||
const existing = await findPersistedIntent(
|
||||
database,
|
||||
input.editorialId,
|
||||
input.idempotencyKey,
|
||||
);
|
||||
if (existing) return asRepeatIntent(existing);
|
||||
throw error;
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
try {
|
||||
return await createRepeatIntentTransaction(database, input);
|
||||
} catch (error) {
|
||||
if (!(error instanceof RepeatIdempotencyRaceError) || attempt === 1) throw error;
|
||||
}
|
||||
}
|
||||
throw new RepeatIdempotencyRaceError();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function createRepeatIntentTransaction(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
input: RepeatIntentInput,
|
||||
): Promise<PersistedRepeatIntent> {
|
||||
return database.transaction(async (transaction) => {
|
||||
await lockEditorialAccounting(transaction, input.editorialId);
|
||||
const existing = await findPersistedIntent(
|
||||
transaction,
|
||||
input.editorialId,
|
||||
input.idempotencyKey,
|
||||
);
|
||||
if (
|
||||
existing &&
|
||||
(existing.kind !== "repeat_download" ||
|
||||
existing.requestFingerprint !== input.requestFingerprint)
|
||||
) {
|
||||
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
|
||||
}
|
||||
|
||||
const [editorial] = await transaction
|
||||
.select({ id: editorialAccounts.id, status: editorialAccounts.status })
|
||||
.from(editorialAccounts)
|
||||
.where(eq(editorialAccounts.id, input.editorialId))
|
||||
.for("update")
|
||||
.limit(1);
|
||||
if (!editorial || editorial.status !== "active") {
|
||||
throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE");
|
||||
}
|
||||
|
||||
const [usage] = await transaction
|
||||
.select({
|
||||
id: usages.id,
|
||||
assetId: usages.immichAssetId,
|
||||
billingStatus: usages.billingStatus,
|
||||
})
|
||||
.from(usages)
|
||||
.where(
|
||||
and(
|
||||
eq(usages.id, input.usageId),
|
||||
eq(usages.editorialAccountId, input.editorialId),
|
||||
),
|
||||
)
|
||||
.for("update")
|
||||
.limit(1);
|
||||
if (!usage) throw new UsageAccountingError("USAGE_NOT_FOUND");
|
||||
const deliveredOriginal = await hasDeliveredOriginal(
|
||||
transaction,
|
||||
input.editorialId,
|
||||
usage.id,
|
||||
);
|
||||
if (!isFreeRepeatEligible(usage.billingStatus, deliveredOriginal)) {
|
||||
throw new UsageAccountingError("USAGE_NOT_FOUND");
|
||||
}
|
||||
if (existing) return asRepeatIntent(existing);
|
||||
|
||||
const authorizedAt = new Date();
|
||||
const [event] = await transaction
|
||||
.insert(downloadEvents)
|
||||
.values({
|
||||
editorialAccountId: input.editorialId,
|
||||
usageId: usage.id,
|
||||
immichAssetId: usage.assetId,
|
||||
authorizedAt,
|
||||
status: "authorized",
|
||||
repeatDownloadNote: input.note,
|
||||
requestId: randomUUID(),
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
intentKind: "repeat_download",
|
||||
requestFingerprint: input.requestFingerprint,
|
||||
})
|
||||
.onConflictDoNothing({
|
||||
target: [downloadEvents.editorialAccountId, downloadEvents.idempotencyKey],
|
||||
})
|
||||
.returning({ id: downloadEvents.id });
|
||||
if (!event) throw new RepeatIdempotencyRaceError();
|
||||
return {
|
||||
id: event.id,
|
||||
usageId: usage.id,
|
||||
assetId: usage.assetId,
|
||||
priceCents: 0,
|
||||
billable: false,
|
||||
status: "authorized",
|
||||
authorizedAt,
|
||||
requestFingerprint: input.requestFingerprint,
|
||||
kind: "repeat_download",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeRepeatInput(input: CreateRepeatDownloadInput): CreateRepeatDownloadInput {
|
||||
if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT");
|
||||
const note = normalizeOptionalText(input.note, 200);
|
||||
|
||||
@@ -194,6 +194,7 @@ test("normalizes and bounds history pagination before the scoped repository quer
|
||||
const repository = {
|
||||
listEditorialUsageHistory: vi.fn().mockResolvedValue({
|
||||
items: [],
|
||||
attempts: [],
|
||||
page: HISTORY_MAX_PAGE,
|
||||
pageSize: 20,
|
||||
hasNext: false,
|
||||
|
||||
+112
-101
@@ -1,6 +1,6 @@
|
||||
import "server-only";
|
||||
|
||||
import { and, desc, eq, inArray, sql } from "drizzle-orm";
|
||||
import { and, desc, eq, exists, inArray, sql } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
@@ -8,11 +8,17 @@ import { auditEvents, downloadEvents, editorialAccounts, usages } from "@/db/sch
|
||||
import type * as schema from "@/db/schema";
|
||||
import { normalizeUuid, UsageAccountingError } from "@/modules/usages/types";
|
||||
|
||||
import { hasDeliveredOriginal, isFreeRepeatEligible } from "./eligibility";
|
||||
import {
|
||||
deliveredOriginalEventCondition,
|
||||
hasDeliveredOriginal,
|
||||
isFreeRepeatEligible,
|
||||
} from "./eligibility";
|
||||
|
||||
export const HISTORY_PAGE_SIZE = 20;
|
||||
export const HISTORY_MAX_PAGE = 1_000;
|
||||
export const HISTORY_ATTEMPT_PAGE_SIZE = 25;
|
||||
export const DOWNLOAD_OPTIONS_MAX_ASSETS = 60;
|
||||
export const DOWNLOAD_OPTIONS_MAX_USAGES = 300;
|
||||
|
||||
export type ClaimedDownload = {
|
||||
id: string;
|
||||
@@ -351,12 +357,18 @@ function assertByteCount(value: number) {
|
||||
|
||||
export type UsageHistoryAttempt = {
|
||||
downloadId: string;
|
||||
status: "completed" | "interrupted" | "failed_before_delivery";
|
||||
usageId: string;
|
||||
status: typeof downloadEvents.$inferSelect.status;
|
||||
requestedAt: Date;
|
||||
finishedAt: Date;
|
||||
finishedAt?: Date;
|
||||
transferredBytes: number;
|
||||
repeat: boolean;
|
||||
billableCents: number;
|
||||
filename: string;
|
||||
albumName: string;
|
||||
purpose: string;
|
||||
reference?: string;
|
||||
priceCents: number;
|
||||
};
|
||||
|
||||
export type UsageHistoryItem = {
|
||||
@@ -369,11 +381,11 @@ export type UsageHistoryItem = {
|
||||
billingStatus: "open" | "billed" | "reopened" | "voided";
|
||||
priceCents: number;
|
||||
billableCents: number;
|
||||
attempts: UsageHistoryAttempt[];
|
||||
};
|
||||
|
||||
export type UsageHistoryPage = {
|
||||
items: UsageHistoryItem[];
|
||||
attempts: UsageHistoryAttempt[];
|
||||
page: number;
|
||||
pageSize: number;
|
||||
hasNext: boolean;
|
||||
@@ -443,20 +455,9 @@ export function createPostgresDownloadHistoryRepository(
|
||||
.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,
|
||||
attemptPageSize: HISTORY_ATTEMPT_PAGE_SIZE,
|
||||
};
|
||||
}
|
||||
|
||||
const usageIds = pageRows.map((usage) => usage.usageId);
|
||||
const authorizedAtMicros = sql<string>`floor(extract(epoch from ${downloadEvents.authorizedAt}) * 1000000)::bigint`;
|
||||
const beforeCursor = attemptCursor
|
||||
? sql`(${authorizedAtMicros}, ${downloadEvents.id}) < (${attemptCursor.authorizedAtMicros}::bigint, ${attemptCursor.downloadId}::uuid)`
|
||||
? sql`(${downloadEvents.authorizedAt}, ${downloadEvents.id}) < (timestamptz 'epoch' + ${attemptCursor.authorizedAtMicros}::bigint * interval '1 microsecond', ${attemptCursor.downloadId}::uuid)`
|
||||
: undefined;
|
||||
const eventRowsWithNext = await database
|
||||
.select({
|
||||
@@ -468,17 +469,24 @@ export function createPostgresDownloadHistoryRepository(
|
||||
transferredBytes: downloadEvents.transferredBytes,
|
||||
intentKind: downloadEvents.intentKind,
|
||||
authorizedAtMicros,
|
||||
filename: usages.filenameSnapshot,
|
||||
albumName: usages.albumNameSnapshot,
|
||||
purpose: usages.purpose,
|
||||
reference: usages.internalReference,
|
||||
priceCents: usages.priceCents,
|
||||
billingStatus: usages.billingStatus,
|
||||
})
|
||||
.from(downloadEvents)
|
||||
.innerJoin(
|
||||
usages,
|
||||
and(
|
||||
eq(usages.id, downloadEvents.usageId),
|
||||
eq(usages.editorialAccountId, editorialId),
|
||||
),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(downloadEvents.editorialAccountId, editorialId),
|
||||
inArray(downloadEvents.usageId, usageIds),
|
||||
inArray(downloadEvents.status, [
|
||||
"completed",
|
||||
"interrupted",
|
||||
"failed_before_delivery",
|
||||
]),
|
||||
beforeCursor,
|
||||
),
|
||||
)
|
||||
@@ -495,13 +503,6 @@ export function createPostgresDownloadHistoryRepository(
|
||||
})
|
||||
: undefined;
|
||||
|
||||
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;
|
||||
@@ -515,20 +516,26 @@ export function createPostgresDownloadHistoryRepository(
|
||||
billingStatus: usage.billingStatus,
|
||||
priceCents: usage.priceCents,
|
||||
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,
|
||||
})),
|
||||
};
|
||||
}),
|
||||
attempts: eventRows.map((event) => ({
|
||||
downloadId: event.downloadId,
|
||||
usageId: event.usageId,
|
||||
status: event.status,
|
||||
requestedAt: event.requestedAt,
|
||||
...(event.finishedAt === null ? {} : { finishedAt: event.finishedAt }),
|
||||
transferredBytes: event.transferredBytes ?? 0,
|
||||
repeat: event.intentKind === "repeat_download",
|
||||
billableCents:
|
||||
event.intentKind === "new_usage" && event.billingStatus !== "voided"
|
||||
? event.priceCents
|
||||
: 0,
|
||||
filename: event.filename,
|
||||
albumName: event.albumName,
|
||||
purpose: event.purpose,
|
||||
...(event.reference === null ? {} : { reference: event.reference }),
|
||||
priceCents: event.priceCents,
|
||||
})),
|
||||
page,
|
||||
pageSize: HISTORY_PAGE_SIZE,
|
||||
hasNext,
|
||||
@@ -539,17 +546,6 @@ export function createPostgresDownloadHistoryRepository(
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -601,57 +597,72 @@ export type EditorialDownloadOptions = {
|
||||
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: {} };
|
||||
}
|
||||
export function createEditorialDownloadOptionsLoader(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
) {
|
||||
return async function loadOptions(
|
||||
editorialId: string,
|
||||
assetIds: string[],
|
||||
): Promise<EditorialDownloadOptions> {
|
||||
const normalizedEditorialId = normalizeUuid(editorialId);
|
||||
const normalizedAssets = [...new Set(assetIds.map(normalizeUuid))];
|
||||
if (normalizedAssets.length > DOWNLOAD_OPTIONS_MAX_ASSETS) {
|
||||
throw new UsageAccountingError("INVALID_INPUT");
|
||||
}
|
||||
const [editorial] = await database
|
||||
.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 deliveredOriginal = database
|
||||
.select({ id: downloadEvents.id })
|
||||
.from(downloadEvents)
|
||||
.where(deliveredOriginalEventCondition(normalizedEditorialId, usages.id));
|
||||
const rows = await database
|
||||
.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"]),
|
||||
exists(deliveredOriginal),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(usages.createdAt), desc(usages.id))
|
||||
.limit(DOWNLOAD_OPTIONS_MAX_USAGES);
|
||||
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 };
|
||||
};
|
||||
}
|
||||
|
||||
export const loadEditorialDownloadOptions = createEditorialDownloadOptionsLoader(db);
|
||||
|
||||
const downloadHistoryService = createDownloadHistoryService({
|
||||
repository: createPostgresDownloadHistoryRepository(db),
|
||||
});
|
||||
|
||||
@@ -80,6 +80,12 @@ function createRepository() {
|
||||
setStatus(value: string) {
|
||||
status = value;
|
||||
},
|
||||
setIntentStatus(value: string) {
|
||||
const key = `${editorialId}:${idempotencyKey}`;
|
||||
const intent = intents.get(key);
|
||||
if (!intent) throw new Error("intent missing");
|
||||
intents.set(key, { ...intent, status: value } as unknown as PersistedDownloadIntent);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -174,6 +180,16 @@ test("keeps the original snapshot after a price change while a new key uses the
|
||||
).resolves.toMatchObject({ priceCents: 2_100 });
|
||||
});
|
||||
|
||||
test("does not expose a terminal persisted event as an authorized intent", async () => {
|
||||
const { service, setIntentStatus } = createService();
|
||||
await service.createNewUsage(newUsageInput);
|
||||
setIntentStatus("failed_before_delivery");
|
||||
|
||||
await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({
|
||||
code: "USAGE_NOT_FOUND",
|
||||
});
|
||||
});
|
||||
|
||||
test.each([
|
||||
["zero", 0],
|
||||
["missing", null],
|
||||
|
||||
@@ -2,7 +2,7 @@ import "server-only";
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { and, desc, eq, exists, inArray, isNull, sql } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import type * as schema from "@/db/schema";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import type { ImmichAlbumSummary } from "@/modules/immich/types";
|
||||
import { deliveredOriginalEventCondition } from "@/modules/downloads/eligibility";
|
||||
|
||||
import {
|
||||
type CreateNewUsageInput,
|
||||
@@ -28,7 +29,8 @@ import {
|
||||
UsageAccountingError,
|
||||
} from "./types";
|
||||
|
||||
export type PersistedDownloadIntent = DownloadIntent & {
|
||||
export type PersistedDownloadIntent = Omit<DownloadIntent, "status"> & {
|
||||
status: typeof downloadEvents.$inferSelect.status;
|
||||
requestFingerprint: string;
|
||||
kind: "new_usage" | "repeat_download";
|
||||
};
|
||||
@@ -243,6 +245,10 @@ export function createUsageServiceRepository(
|
||||
},
|
||||
|
||||
async listPriorUsages(editorialId, assetId) {
|
||||
const deliveredOriginal = database
|
||||
.select({ id: downloadEvents.id })
|
||||
.from(downloadEvents)
|
||||
.where(deliveredOriginalEventCondition(editorialId, usages.id));
|
||||
const rows = await database
|
||||
.select({
|
||||
id: usages.id,
|
||||
@@ -262,6 +268,7 @@ export function createUsageServiceRepository(
|
||||
eq(usages.editorialAccountId, editorialId),
|
||||
eq(usages.immichAssetId, assetId),
|
||||
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
|
||||
exists(deliveredOriginal),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(usages.createdAt));
|
||||
@@ -331,8 +338,11 @@ export function resolveIntent(
|
||||
if (persisted.requestFingerprint !== fingerprint || persisted.kind !== kind) {
|
||||
throw new UsageAccountingError("IDEMPOTENCY_CONFLICT");
|
||||
}
|
||||
if (persisted.status !== "authorized") {
|
||||
throw new UsageAccountingError("USAGE_NOT_FOUND");
|
||||
}
|
||||
const { requestFingerprint: _fingerprint, kind: _kind, ...intent } = persisted;
|
||||
return intent;
|
||||
return { ...intent, status: "authorized" };
|
||||
}
|
||||
|
||||
class IdempotencyRaceError extends Error {}
|
||||
@@ -382,6 +392,7 @@ const intentSelection = {
|
||||
usageId: downloadEvents.usageId,
|
||||
assetId: downloadEvents.immichAssetId,
|
||||
authorizedAt: downloadEvents.authorizedAt,
|
||||
eventStatus: downloadEvents.status,
|
||||
intentKind: downloadEvents.intentKind,
|
||||
requestFingerprint: downloadEvents.requestFingerprint,
|
||||
usagePriceCents: usages.priceCents,
|
||||
@@ -392,6 +403,7 @@ function persistedIntent(row: {
|
||||
usageId: string;
|
||||
assetId: string;
|
||||
authorizedAt: Date;
|
||||
eventStatus: PersistedDownloadIntent["status"];
|
||||
intentKind: string;
|
||||
requestFingerprint: string;
|
||||
usagePriceCents: number;
|
||||
@@ -408,7 +420,7 @@ function persistedIntent(row: {
|
||||
assetId: row.assetId,
|
||||
priceCents: row.intentKind === "new_usage" ? row.usagePriceCents : 0,
|
||||
billable: row.intentKind === "new_usage",
|
||||
status: "authorized",
|
||||
status: row.eventStatus,
|
||||
authorizedAt: row.authorizedAt,
|
||||
requestFingerprint: row.requestFingerprint,
|
||||
kind: row.intentKind,
|
||||
|
||||
Reference in new issue
Block a user