fix: serialize editorial approval delivery

This commit is contained in:
Leon Tonhäuser committed 2026-08-09 21:23:32 +02:00
1 parent 3584b4a7a7
commit 3f84b840d9
6 files changed
+215 -57

No files matched your search

+137 -53
View File
@@ -1,6 +1,6 @@
import "server-only";
import { and, desc, eq, inArray, isNull } from "drizzle-orm";
import { and, eq, inArray, isNull, sql } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client";
@@ -36,6 +36,7 @@ export type EditorialServiceRepository = {
priceCents: number;
adminUserId: string;
}): Promise<ApprovalNotice | null>;
claimApprovalNotice(input: { editorialId: string; adminUserId: string }): Promise<boolean>;
recordApprovalNoticeSent(input: { editorialId: string; adminUserId: string }): Promise<void>;
recordApprovalNoticeFailure(input: { editorialId: string; adminUserId: string }): Promise<void>;
replaceBillingAddress(input: {
@@ -50,6 +51,16 @@ export type EditorialServiceRepository = {
}): Promise<void>;
};
/**
* All editorial/grant mutations must take these locks in this exact order.
* Task 6 grant and revocation transactions must use the same order.
*/
export const EDITORIAL_MUTATION_LOCK_ORDER = [
"pg_advisory_xact_lock(editorial account)",
"editorial_accounts FOR UPDATE",
"album_grants FOR UPDATE",
] as const;
export class EditorialServiceError extends Error {
readonly name = "EditorialServiceError";
@@ -85,7 +96,7 @@ export function createEditorialService({
}
const notice = await repository.prepareApproval(input);
if (!notice) {
if (!notice || !(await repository.claimApprovalNotice(input))) {
return;
}
@@ -133,6 +144,7 @@ export function createEditorialServiceRepository(
return {
async prepareApproval({ editorialId, priceCents, adminUserId }) {
return database.transaction(async (transaction) => {
await lockEditorialForMutation(transaction, editorialId);
const [editorial] = await transaction
.select({
id: editorialAccounts.id,
@@ -143,6 +155,7 @@ export function createEditorialServiceRepository(
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.for("update")
.limit(1);
if (!editorial) {
@@ -156,36 +169,6 @@ export function createEditorialServiceRepository(
};
if (editorial.status === "active") {
const [delivery] = await transaction
.select({ eventType: auditEvents.eventType })
.from(auditEvents)
.where(
and(
eq(auditEvents.entityType, "editorial_account"),
eq(auditEvents.entityId, editorial.id),
inArray(auditEvents.eventType, [
"editorial_approval_notice_dispatch_started",
"editorial_approval_notice_sent",
"editorial_approval_notice_failed",
]),
),
)
.orderBy(desc(auditEvents.occurredAt))
.limit(1);
if (delivery?.eventType === "editorial_approval_notice_sent") {
return null;
}
if (delivery?.eventType === "editorial_approval_notice_dispatch_started") {
throw new EditorialServiceError("APPROVAL_NOTICE_DELIVERY_UNKNOWN");
}
await transaction.insert(auditEvents).values({
eventType: "editorial_approval_notice_dispatch_started",
actorUserId: adminUserId,
actorType: "admin",
entityType: "editorial_account",
entityId: editorial.id,
newValues: { delivery: "dispatching" },
});
return notice;
}
@@ -205,6 +188,7 @@ export function createEditorialServiceRepository(
isNull(albumGrants.revokedAt),
),
)
.for("update")
.limit(1);
if (!grant) {
throw new EditorialServiceError("ALBUM_GRANT_REQUIRED");
@@ -213,7 +197,12 @@ export function createEditorialServiceRepository(
const approvedAt = new Date();
const [approved] = await transaction
.update(editorialAccounts)
.set({ status: "active", currentPriceCents: priceCents, updatedAt: approvedAt })
.set({
status: "active",
currentPriceCents: priceCents,
approvalNoticeStatus: "not_requested",
updatedAt: approvedAt,
})
.where(
and(
eq(editorialAccounts.id, editorial.id),
@@ -235,6 +224,51 @@ export function createEditorialServiceRepository(
newValues: { status: "active", priceCents },
occurredAt: approvedAt,
});
return notice;
});
},
async claimApprovalNotice({ editorialId, adminUserId }) {
return database.transaction(async (transaction) => {
await lockEditorialForMutation(transaction, editorialId);
const [editorial] = await transaction
.select({
id: editorialAccounts.id,
status: editorialAccounts.status,
approvalNoticeStatus: editorialAccounts.approvalNoticeStatus,
})
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.for("update")
.limit(1);
if (!editorial) {
throw new EditorialServiceError("EDITORIAL_NOT_FOUND");
}
if (editorial.status !== "active") {
throw new EditorialServiceError("INVALID_ACCOUNT_TRANSITION");
}
if (editorial.approvalNoticeStatus === "sent") {
return false;
}
if (editorial.approvalNoticeStatus === "dispatching") {
throw new EditorialServiceError("APPROVAL_NOTICE_DELIVERY_UNKNOWN");
}
const [claimed] = await transaction
.update(editorialAccounts)
.set({ approvalNoticeStatus: "dispatching", updatedAt: new Date() })
.where(
and(
eq(editorialAccounts.id, editorial.id),
eq(editorialAccounts.status, "active"),
inArray(editorialAccounts.approvalNoticeStatus, ["not_requested", "failed"]),
),
)
.returning({ id: editorialAccounts.id });
if (!claimed) {
throw new EditorialServiceError("APPROVAL_NOTICE_DELIVERY_UNKNOWN");
}
await transaction.insert(auditEvents).values({
eventType: "editorial_approval_notice_dispatch_started",
actorUserId: adminUserId,
@@ -242,40 +276,73 @@ export function createEditorialServiceRepository(
entityType: "editorial_account",
entityId: editorial.id,
newValues: { delivery: "dispatching" },
occurredAt: approvedAt,
});
return notice;
return true;
});
},
async recordApprovalNoticeSent({ editorialId, adminUserId }) {
await database.insert(auditEvents).values({
eventType: "editorial_approval_notice_sent",
actorUserId: adminUserId,
actorType: "admin",
entityType: "editorial_account",
entityId: editorialId,
newValues: { delivery: "sent" },
await database.transaction(async (transaction) => {
await lockEditorialForMutation(transaction, editorialId);
const [updated] = await transaction
.update(editorialAccounts)
.set({ approvalNoticeStatus: "sent", updatedAt: new Date() })
.where(
and(
eq(editorialAccounts.id, editorialId),
eq(editorialAccounts.approvalNoticeStatus, "dispatching"),
),
)
.returning({ id: editorialAccounts.id });
if (!updated) {
throw new EditorialServiceError("APPROVAL_NOTICE_DELIVERY_UNKNOWN");
}
await transaction.insert(auditEvents).values({
eventType: "editorial_approval_notice_sent",
actorUserId: adminUserId,
actorType: "admin",
entityType: "editorial_account",
entityId: editorialId,
newValues: { delivery: "sent" },
});
});
},
async recordApprovalNoticeFailure({ editorialId, adminUserId }) {
await database.insert(auditEvents).values({
eventType: "editorial_approval_notice_failed",
actorUserId: adminUserId,
actorType: "admin",
entityType: "editorial_account",
entityId: editorialId,
newValues: { delivery: "failed" },
await database.transaction(async (transaction) => {
await lockEditorialForMutation(transaction, editorialId);
const [updated] = await transaction
.update(editorialAccounts)
.set({ approvalNoticeStatus: "failed", updatedAt: new Date() })
.where(
and(
eq(editorialAccounts.id, editorialId),
eq(editorialAccounts.approvalNoticeStatus, "dispatching"),
),
)
.returning({ id: editorialAccounts.id });
if (!updated) {
throw new EditorialServiceError("APPROVAL_NOTICE_DELIVERY_UNKNOWN");
}
await transaction.insert(auditEvents).values({
eventType: "editorial_approval_notice_failed",
actorUserId: adminUserId,
actorType: "admin",
entityType: "editorial_account",
entityId: editorialId,
newValues: { delivery: "failed" },
});
});
},
async replaceBillingAddress({ editorialId, input }) {
return database.transaction(async (transaction) => {
await lockEditorialForMutation(transaction, editorialId);
const [editorial] = await transaction
.select({ id: editorialAccounts.id })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.for("update")
.limit(1);
if (!editorial) {
throw new EditorialServiceError("EDITORIAL_NOT_FOUND");
@@ -301,13 +368,21 @@ export function createEditorialServiceRepository(
async transitionStatus({ editorialId, from, to, adminUserId }) {
await database.transaction(async (transaction) => {
await lockEditorialForMutation(transaction, editorialId);
const [editorial] = await transaction
.select({ id: editorialAccounts.id, status: editorialAccounts.status })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.for("update")
.limit(1);
if (!editorial || editorial.status !== from) {
throw new EditorialServiceError("INVALID_ACCOUNT_TRANSITION");
}
const changedAt = new Date();
const [changed] = await transaction
.update(editorialAccounts)
.set({ status: to, updatedAt: changedAt })
.where(
and(eq(editorialAccounts.id, editorialId), eq(editorialAccounts.status, from)),
)
.where(eq(editorialAccounts.id, editorialId))
.returning({ id: editorialAccounts.id });
if (!changed) {
throw new EditorialServiceError("INVALID_ACCOUNT_TRANSITION");
@@ -363,13 +438,22 @@ function trim(value: unknown): string {
function isAllowedTransition(from: AccountStatus, to: AccountStatus): boolean {
return (
(from === "pending_approval" && (to === "active" || to === "rejected")) ||
(from === "pending_approval" && to === "rejected") ||
(from === "active" && to === "suspended") ||
(from === "suspended" && to === "active") ||
(from === "pending_email" && to === "rejected")
);
}
async function lockEditorialForMutation(
transaction: NodePgDatabase<typeof schema>,
editorialId: string,
): Promise<void> {
await transaction.execute(
sql`select pg_advisory_xact_lock(hashtextextended(${editorialId}, 0))`,
);
}
export const editorialService = createEditorialService({
repository: createEditorialServiceRepository(db),
mailer,