fix: serialize editorial approval delivery
This commit is contained in:
1 parent
3584b4a7a7
commit
3f84b840d9
6 files changed
+202
-44
No files matched your search
@@ -0,0 +1 @@
|
||||
ALTER TABLE "editorial_accounts" ADD COLUMN "approval_notice_status" text DEFAULT 'not_requested' NOT NULL;
|
||||
@@ -8,6 +8,13 @@
|
||||
"when": 1786299825190,
|
||||
"tag": "0000_initial",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "7",
|
||||
"when": 1786351200000,
|
||||
"tag": "0001_editorial_approval_notice",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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" },
|
||||
|
||||
@@ -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<typeof vi.fn>;
|
||||
replaceBillingAddress: ReturnType<typeof vi.fn>;
|
||||
transitionStatus: ReturnType<typeof vi.fn>;
|
||||
claimApprovalNotice: ReturnType<typeof vi.fn>;
|
||||
} {
|
||||
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",
|
||||
]);
|
||||
});
|
||||
@@ -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,14 +276,28 @@ 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({
|
||||
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",
|
||||
@@ -257,10 +305,26 @@ export function createEditorialServiceRepository(
|
||||
entityId: editorialId,
|
||||
newValues: { delivery: "sent" },
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
async recordApprovalNoticeFailure({ editorialId, adminUserId }) {
|
||||
await database.insert(auditEvents).values({
|
||||
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",
|
||||
@@ -268,14 +332,17 @@ export function createEditorialServiceRepository(
|
||||
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,
|
||||
|
||||
@@ -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<PostgresTestDatabase> {
|
||||
}
|
||||
|
||||
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<typeof schema>): Promise<DownloadSeed> {
|
||||
|
||||
Reference in new issue
Block a user