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
+214 -56

No files matched your search

@@ -0,0 +1 @@
ALTER TABLE "editorial_accounts" ADD COLUMN "approval_notice_status" text DEFAULT 'not_requested' NOT NULL;
+7
View File
@@ -8,6 +8,13 @@
"when": 1786299825190, "when": 1786299825190,
"tag": "0000_initial", "tag": "0000_initial",
"breakpoints": true "breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1786351200000,
"tag": "0001_editorial_approval_notice",
"breakpoints": true
} }
] ]
} }
+1
View File
@@ -23,6 +23,7 @@ export const editorialAccounts = pgTable("editorial_accounts", {
loginEmail: text("login_email").notNull().unique(), loginEmail: text("login_email").notNull().unique(),
status: accountStatus("status").notNull().default("pending_email"), status: accountStatus("status").notNull().default("pending_email"),
currentPriceCents: integer("current_price_cents"), currentPriceCents: integer("current_price_cents"),
approvalNoticeStatus: text("approval_notice_status").notNull().default("not_requested"),
currentBillingAddressVersionId: uuid("current_billing_address_version_id").references( currentBillingAddressVersionId: uuid("current_billing_address_version_id").references(
(): AnyPgColumn => billingAddressVersions.id, (): AnyPgColumn => billingAddressVersions.id,
{ onDelete: "restrict" }, { onDelete: "restrict" },
+60
View File
@@ -2,6 +2,7 @@ import { expect, test, vi } from "vitest";
import { import {
createEditorialService, createEditorialService,
EDITORIAL_MUTATION_LOCK_ORDER,
type EditorialServiceRepository, type EditorialServiceRepository,
} from "./service"; } from "./service";
@@ -11,6 +12,7 @@ function createRepository(): EditorialServiceRepository & {
recordApprovalNoticeFailure: ReturnType<typeof vi.fn>; recordApprovalNoticeFailure: ReturnType<typeof vi.fn>;
replaceBillingAddress: ReturnType<typeof vi.fn>; replaceBillingAddress: ReturnType<typeof vi.fn>;
transitionStatus: ReturnType<typeof vi.fn>; transitionStatus: ReturnType<typeof vi.fn>;
claimApprovalNotice: ReturnType<typeof vi.fn>;
} { } {
return { return {
prepareApproval: vi.fn().mockResolvedValue({ prepareApproval: vi.fn().mockResolvedValue({
@@ -22,6 +24,7 @@ function createRepository(): EditorialServiceRepository & {
recordApprovalNoticeFailure: vi.fn().mockResolvedValue(undefined), recordApprovalNoticeFailure: vi.fn().mockResolvedValue(undefined),
replaceBillingAddress: vi.fn().mockResolvedValue("address-2"), replaceBillingAddress: vi.fn().mockResolvedValue("address-2"),
transitionStatus: vi.fn().mockResolvedValue(undefined), 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",
]);
});
+137 -53
View File
@@ -1,6 +1,6 @@
import "server-only"; 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 type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client"; import { db } from "@/db/client";
@@ -36,6 +36,7 @@ export type EditorialServiceRepository = {
priceCents: number; priceCents: number;
adminUserId: string; adminUserId: string;
}): Promise<ApprovalNotice | null>; }): Promise<ApprovalNotice | null>;
claimApprovalNotice(input: { editorialId: string; adminUserId: string }): Promise<boolean>;
recordApprovalNoticeSent(input: { editorialId: string; adminUserId: string }): Promise<void>; recordApprovalNoticeSent(input: { editorialId: string; adminUserId: string }): Promise<void>;
recordApprovalNoticeFailure(input: { editorialId: string; adminUserId: string }): Promise<void>; recordApprovalNoticeFailure(input: { editorialId: string; adminUserId: string }): Promise<void>;
replaceBillingAddress(input: { replaceBillingAddress(input: {
@@ -50,6 +51,16 @@ export type EditorialServiceRepository = {
}): Promise<void>; }): 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 { export class EditorialServiceError extends Error {
readonly name = "EditorialServiceError"; readonly name = "EditorialServiceError";
@@ -85,7 +96,7 @@ export function createEditorialService({
} }
const notice = await repository.prepareApproval(input); const notice = await repository.prepareApproval(input);
if (!notice) { if (!notice || !(await repository.claimApprovalNotice(input))) {
return; return;
} }
@@ -133,6 +144,7 @@ export function createEditorialServiceRepository(
return { return {
async prepareApproval({ editorialId, priceCents, adminUserId }) { async prepareApproval({ editorialId, priceCents, adminUserId }) {
return database.transaction(async (transaction) => { return database.transaction(async (transaction) => {
await lockEditorialForMutation(transaction, editorialId);
const [editorial] = await transaction const [editorial] = await transaction
.select({ .select({
id: editorialAccounts.id, id: editorialAccounts.id,
@@ -143,6 +155,7 @@ export function createEditorialServiceRepository(
}) })
.from(editorialAccounts) .from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId)) .where(eq(editorialAccounts.id, editorialId))
.for("update")
.limit(1); .limit(1);
if (!editorial) { if (!editorial) {
@@ -156,36 +169,6 @@ export function createEditorialServiceRepository(
}; };
if (editorial.status === "active") { 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; return notice;
} }
@@ -205,6 +188,7 @@ export function createEditorialServiceRepository(
isNull(albumGrants.revokedAt), isNull(albumGrants.revokedAt),
), ),
) )
.for("update")
.limit(1); .limit(1);
if (!grant) { if (!grant) {
throw new EditorialServiceError("ALBUM_GRANT_REQUIRED"); throw new EditorialServiceError("ALBUM_GRANT_REQUIRED");
@@ -213,7 +197,12 @@ export function createEditorialServiceRepository(
const approvedAt = new Date(); const approvedAt = new Date();
const [approved] = await transaction const [approved] = await transaction
.update(editorialAccounts) .update(editorialAccounts)
.set({ status: "active", currentPriceCents: priceCents, updatedAt: approvedAt }) .set({
status: "active",
currentPriceCents: priceCents,
approvalNoticeStatus: "not_requested",
updatedAt: approvedAt,
})
.where( .where(
and( and(
eq(editorialAccounts.id, editorial.id), eq(editorialAccounts.id, editorial.id),
@@ -235,6 +224,51 @@ export function createEditorialServiceRepository(
newValues: { status: "active", priceCents }, newValues: { status: "active", priceCents },
occurredAt: approvedAt, 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({ await transaction.insert(auditEvents).values({
eventType: "editorial_approval_notice_dispatch_started", eventType: "editorial_approval_notice_dispatch_started",
actorUserId: adminUserId, actorUserId: adminUserId,
@@ -242,40 +276,73 @@ export function createEditorialServiceRepository(
entityType: "editorial_account", entityType: "editorial_account",
entityId: editorial.id, entityId: editorial.id,
newValues: { delivery: "dispatching" }, newValues: { delivery: "dispatching" },
occurredAt: approvedAt,
}); });
return notice; return true;
}); });
}, },
async recordApprovalNoticeSent({ editorialId, adminUserId }) { async recordApprovalNoticeSent({ editorialId, adminUserId }) {
await database.insert(auditEvents).values({ await database.transaction(async (transaction) => {
eventType: "editorial_approval_notice_sent", await lockEditorialForMutation(transaction, editorialId);
actorUserId: adminUserId, const [updated] = await transaction
actorType: "admin", .update(editorialAccounts)
entityType: "editorial_account", .set({ approvalNoticeStatus: "sent", updatedAt: new Date() })
entityId: editorialId, .where(
newValues: { delivery: "sent" }, 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 }) { async recordApprovalNoticeFailure({ editorialId, adminUserId }) {
await database.insert(auditEvents).values({ await database.transaction(async (transaction) => {
eventType: "editorial_approval_notice_failed", await lockEditorialForMutation(transaction, editorialId);
actorUserId: adminUserId, const [updated] = await transaction
actorType: "admin", .update(editorialAccounts)
entityType: "editorial_account", .set({ approvalNoticeStatus: "failed", updatedAt: new Date() })
entityId: editorialId, .where(
newValues: { delivery: "failed" }, 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 }) { async replaceBillingAddress({ editorialId, input }) {
return database.transaction(async (transaction) => { return database.transaction(async (transaction) => {
await lockEditorialForMutation(transaction, editorialId);
const [editorial] = await transaction const [editorial] = await transaction
.select({ id: editorialAccounts.id }) .select({ id: editorialAccounts.id })
.from(editorialAccounts) .from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId)) .where(eq(editorialAccounts.id, editorialId))
.for("update")
.limit(1); .limit(1);
if (!editorial) { if (!editorial) {
throw new EditorialServiceError("EDITORIAL_NOT_FOUND"); throw new EditorialServiceError("EDITORIAL_NOT_FOUND");
@@ -301,13 +368,21 @@ export function createEditorialServiceRepository(
async transitionStatus({ editorialId, from, to, adminUserId }) { async transitionStatus({ editorialId, from, to, adminUserId }) {
await database.transaction(async (transaction) => { 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 changedAt = new Date();
const [changed] = await transaction const [changed] = await transaction
.update(editorialAccounts) .update(editorialAccounts)
.set({ status: to, updatedAt: changedAt }) .set({ status: to, updatedAt: changedAt })
.where( .where(eq(editorialAccounts.id, editorialId))
and(eq(editorialAccounts.id, editorialId), eq(editorialAccounts.status, from)),
)
.returning({ id: editorialAccounts.id }); .returning({ id: editorialAccounts.id });
if (!changed) { if (!changed) {
throw new EditorialServiceError("INVALID_ACCOUNT_TRANSITION"); throw new EditorialServiceError("INVALID_ACCOUNT_TRANSITION");
@@ -363,13 +438,22 @@ function trim(value: unknown): string {
function isAllowedTransition(from: AccountStatus, to: AccountStatus): boolean { function isAllowedTransition(from: AccountStatus, to: AccountStatus): boolean {
return ( return (
(from === "pending_approval" && (to === "active" || to === "rejected")) || (from === "pending_approval" && to === "rejected") ||
(from === "active" && to === "suspended") || (from === "active" && to === "suspended") ||
(from === "suspended" && to === "active") || (from === "suspended" && to === "active") ||
(from === "pending_email" && to === "rejected") (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({ export const editorialService = createEditorialService({
repository: createEditorialServiceRepository(db), repository: createEditorialServiceRepository(db),
mailer, mailer,
+8 -3
View File
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises"; import { readdir, readFile } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { PostgreSqlContainer, type StartedPostgreSqlContainer } from "@testcontainers/postgresql"; import { PostgreSqlContainer, type StartedPostgreSqlContainer } from "@testcontainers/postgresql";
@@ -53,8 +53,13 @@ export async function startPostgres(): Promise<PostgresTestDatabase> {
} }
async function applyMigration(pool: Pool) { async function applyMigration(pool: Pool) {
const migration = await readFile(path.join(process.cwd(), "drizzle/0000_initial.sql"), "utf8"); const migrationDirectory = path.join(process.cwd(), "drizzle");
await pool.query(migration); 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<typeof schema>): Promise<DownloadSeed> { async function seedEditorialWithUsage(db: NodePgDatabase<typeof schema>): Promise<DownloadSeed> {