From 3f84b840d9ace91b42fee48829d97251123eb455 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Sun, 9 Aug 2026 21:23:32 +0200 Subject: [PATCH] fix: serialize editorial approval delivery --- drizzle/0001_editorial_approval_notice.sql | 1 + drizzle/meta/_journal.json | 9 +- src/db/schema/editorials.ts | 1 + src/modules/editorials/service.test.ts | 60 +++++++ src/modules/editorials/service.ts | 190 +++++++++++++++------ tests/db/postgres.ts | 11 +- 6 files changed, 215 insertions(+), 57 deletions(-) create mode 100644 drizzle/0001_editorial_approval_notice.sql diff --git a/drizzle/0001_editorial_approval_notice.sql b/drizzle/0001_editorial_approval_notice.sql new file mode 100644 index 0000000..5f3ca31 --- /dev/null +++ b/drizzle/0001_editorial_approval_notice.sql @@ -0,0 +1 @@ +ALTER TABLE "editorial_accounts" ADD COLUMN "approval_notice_status" text DEFAULT 'not_requested' NOT NULL; diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 1819924..9578f4a 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -8,6 +8,13 @@ "when": 1786299825190, "tag": "0000_initial", "breakpoints": true + }, + { + "idx": 1, + "version": "7", + "when": 1786351200000, + "tag": "0001_editorial_approval_notice", + "breakpoints": true } ] -} \ No newline at end of file +} diff --git a/src/db/schema/editorials.ts b/src/db/schema/editorials.ts index 3f58e82..d23ce71 100644 --- a/src/db/schema/editorials.ts +++ b/src/db/schema/editorials.ts @@ -23,6 +23,7 @@ export const editorialAccounts = pgTable("editorial_accounts", { loginEmail: text("login_email").notNull().unique(), status: accountStatus("status").notNull().default("pending_email"), currentPriceCents: integer("current_price_cents"), + approvalNoticeStatus: text("approval_notice_status").notNull().default("not_requested"), currentBillingAddressVersionId: uuid("current_billing_address_version_id").references( (): AnyPgColumn => billingAddressVersions.id, { onDelete: "restrict" }, diff --git a/src/modules/editorials/service.test.ts b/src/modules/editorials/service.test.ts index 3f61cc5..23a9081 100644 --- a/src/modules/editorials/service.test.ts +++ b/src/modules/editorials/service.test.ts @@ -2,6 +2,7 @@ import { expect, test, vi } from "vitest"; import { createEditorialService, + EDITORIAL_MUTATION_LOCK_ORDER, type EditorialServiceRepository, } from "./service"; @@ -11,6 +12,7 @@ function createRepository(): EditorialServiceRepository & { recordApprovalNoticeFailure: ReturnType; replaceBillingAddress: ReturnType; transitionStatus: ReturnType; + claimApprovalNotice: ReturnType; } { return { prepareApproval: vi.fn().mockResolvedValue({ @@ -22,6 +24,7 @@ function createRepository(): EditorialServiceRepository & { recordApprovalNoticeFailure: vi.fn().mockResolvedValue(undefined), replaceBillingAddress: vi.fn().mockResolvedValue("address-2"), transitionStatus: vi.fn().mockResolvedValue(undefined), + claimApprovalNotice: vi.fn().mockResolvedValue(true), }; } @@ -111,3 +114,60 @@ test("creates a new billing-address version instead of changing an existing addr }, }); }); + +test("rejects generic pending-approval activation so approval preconditions cannot be bypassed", async () => { + const repository = createRepository(); + const service = createEditorialService({ repository, mailer: { sendApprovalNotice: vi.fn() } }); + + await expect( + service.transitionEditorialStatus({ + editorialId: "e1", + from: "pending_approval", + to: "active", + adminUserId: "a1", + }), + ).rejects.toMatchObject({ code: "INVALID_ACCOUNT_TRANSITION" }); + expect(repository.transitionStatus).not.toHaveBeenCalled(); +}); + +test("does not resend an approval notice after a successful idempotent retry", async () => { + const repository = createRepository(); + repository.claimApprovalNotice.mockResolvedValueOnce(true).mockResolvedValueOnce(false); + const mailer = { sendApprovalNotice: vi.fn().mockResolvedValue(undefined) }; + const service = createEditorialService({ repository, mailer }); + + await service.approveEditorial({ editorialId: "e1", priceCents: 1500, adminUserId: "a1" }); + await service.approveEditorial({ editorialId: "e1", priceCents: 1500, adminUserId: "a1" }); + + expect(mailer.sendApprovalNotice).toHaveBeenCalledTimes(1); + expect(repository.claimApprovalNotice).toHaveBeenCalledTimes(2); +}); + +test("allows at most one concurrent failed-notice retry to claim SMTP dispatch", async () => { + const repository = createRepository(); + let claimed = false; + repository.claimApprovalNotice.mockImplementation(async () => { + if (claimed) { + return false; + } + claimed = true; + return true; + }); + const mailer = { sendApprovalNotice: vi.fn().mockResolvedValue(undefined) }; + const service = createEditorialService({ repository, mailer }); + + await Promise.all([ + service.approveEditorial({ editorialId: "e1", priceCents: 1500, adminUserId: "a1" }), + service.approveEditorial({ editorialId: "e1", priceCents: 1500, adminUserId: "a1" }), + ]); + + expect(mailer.sendApprovalNotice).toHaveBeenCalledTimes(1); +}); + +test("documents the shared editorial lock order for grant revocation", () => { + expect(EDITORIAL_MUTATION_LOCK_ORDER).toEqual([ + "pg_advisory_xact_lock(editorial account)", + "editorial_accounts FOR UPDATE", + "album_grants FOR UPDATE", + ]); +}); diff --git a/src/modules/editorials/service.ts b/src/modules/editorials/service.ts index a687c65..09ab2e7 100644 --- a/src/modules/editorials/service.ts +++ b/src/modules/editorials/service.ts @@ -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; + claimApprovalNotice(input: { editorialId: string; adminUserId: string }): Promise; recordApprovalNoticeSent(input: { editorialId: string; adminUserId: string }): Promise; recordApprovalNoticeFailure(input: { editorialId: string; adminUserId: string }): Promise; replaceBillingAddress(input: { @@ -50,6 +51,16 @@ export type EditorialServiceRepository = { }): Promise; }; +/** + * 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, + editorialId: string, +): Promise { + await transaction.execute( + sql`select pg_advisory_xact_lock(hashtextextended(${editorialId}, 0))`, + ); +} + export const editorialService = createEditorialService({ repository: createEditorialServiceRepository(db), mailer, diff --git a/tests/db/postgres.ts b/tests/db/postgres.ts index ff9364a..3527c75 100644 --- a/tests/db/postgres.ts +++ b/tests/db/postgres.ts @@ -1,5 +1,5 @@ import { randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; +import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { PostgreSqlContainer, type StartedPostgreSqlContainer } from "@testcontainers/postgresql"; @@ -53,8 +53,13 @@ export async function startPostgres(): Promise { } async function applyMigration(pool: Pool) { - const migration = await readFile(path.join(process.cwd(), "drizzle/0000_initial.sql"), "utf8"); - await pool.query(migration); + const migrationDirectory = path.join(process.cwd(), "drizzle"); + const migrationFiles = (await readdir(migrationDirectory)) + .filter((file) => /^\d+_.*\.sql$/.test(file)) + .sort(); + for (const file of migrationFiles) { + await pool.query(await readFile(path.join(migrationDirectory, file), "utf8")); + } } async function seedEditorialWithUsage(db: NodePgDatabase): Promise {