Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 47 additions & 42 deletions rest/nodejs/src/api/checkout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ import {
getOrder,
getProduct,
logRequest,
releaseStock,
reserveStock,
runInTransaction,
saveCheckout,
saveIdempotencyRecord,
saveOrder,
Expand Down Expand Up @@ -1067,30 +1067,9 @@ export class CheckoutService {

// Atomic Inventory Reservation and Completion
try {
const reservedItems: Array<{ id: string; qty: number }> = [];

for (const line of checkout.line_items) {
const product = getProduct(line.item.id);
if (product) {
const success = reserveStock(line.item.id, line.quantity);
if (!success) {
// Rollback
for (const reserved of reservedItems) {
releaseStock(reserved.id, reserved.qty);
}
return ucpErrorResponse(
c,
new OutOfStockError(`Item ${line.item.id} is out of stock`, 409)
);
}
reservedItems.push({ id: line.item.id, qty: line.quantity });
}
}

// Success
checkout.status = CheckoutResponseStatusSchema.enum.completed;

// Create Order
// Build the order before opening the transaction: constructing it is
// pure computation, while the transaction must stay synchronous so the
// SQLite write lock never spans external I/O.
const orderId = `ord_${uuidv4()}`;

// Order Fulfillment
Expand Down Expand Up @@ -1184,34 +1163,60 @@ export class CheckoutService {
currency: checkout.currency,
};

saveOrder(order.id, order);
// Reserve stock, persist the order, mark the checkout completed and
// record the idempotent response as one SQLite transaction: a failure at
// any step — including a line item that runs out of stock after earlier
// lines were reserved — rolls every write back instead of leaving stock
// decremented behind a 409 or 500.
runInTransaction(() => {
for (const line of checkout.line_items) {
const product = getProduct(line.item.id);
// Throw rather than return: `db.transaction(fn)()` commits whenever
// the callback returns normally, so an early return here would
// commit the reservations made for the lines before this one.
if (product && !reserveStock(line.item.id, line.quantity)) {
throw new OutOfStockError(
`Item ${line.item.id} is out of stock`,
409
);
}
}

// Save Checkout
checkout.order = {
id: orderId,
permalink_url: order.permalink_url,
};
checkout.status = CheckoutResponseStatusSchema.enum.completed;
checkout.order = {
id: orderId,
permalink_url: order.permalink_url,
};

saveCheckout(id, checkout.status, checkout);
saveOrder(order.id, order);
saveCheckout(id, checkout.status, checkout);

// Recorded before the webhook so a retry that arrives while delivery
// is in flight replays this response instead of seeing `completed`
// and being answered 409.
if (idempotencyKey) {
saveIdempotencyRecord(
idempotencyKey,
requestHash,
200,
JSON.stringify(checkout)
);
}
});

// Notify webhook
// Notify webhook (outside the transaction: external I/O must not hold
// the SQLite write lock).
await this.notifyWebhook(
checkout,
"order_placed",
new URL(c.req.url).origin
);

if (idempotencyKey) {
saveIdempotencyRecord(
idempotencyKey,
requestHash,
200,
JSON.stringify(checkout)
);
}

return c.json(checkout, 200);
} catch (e) {
if (e instanceof UcpError) {
return ucpErrorResponse(c, e);
}
console.error("Error completing checkout", e);
return c.json({ detail: "Internal server error" }, 500);
}
Expand Down
17 changes: 17 additions & 0 deletions rest/nodejs/src/data/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,20 @@ export function saveIdempotencyRecord(
);
stmt.run(key, requestHash, status, responseBody);
}

/**
* Runs `fn` as a single SQLite transaction on the transactions database.
*
* Every write performed by `fn` (inventory, checkouts, orders) commits
* together; if `fn` throws, SQLite rolls all of them back and the error is
* rethrown so callers keep their existing error handling.
*
* @param fn The synchronous unit of work to commit atomically. It must not
* await: an external I/O call inside the transaction would hold the write
* lock across a network round trip.
* @returns Whatever `fn` returns.
*/
export function runInTransaction<T>(fn: () => T): T {
const db = getTransactionsDb();
return db.transaction(fn)();
}
189 changes: 181 additions & 8 deletions rest/nodejs/test/lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";

import { CheckoutService } from "../src/api/checkout";
import { getInventory, getOrder } from "../src/data";
import { getProductsDb, getTransactionsDb, initDbs } from "../src/data/db";
import {
CheckoutCompleteRequestSchema,
Expand Down Expand Up @@ -76,9 +77,14 @@ before(() => {
db.prepare(
"INSERT INTO products (id, title, price, image_url) VALUES (?, ?, ?, ?)"
).run("bouquet_roses", "Red Rose", 3500, "");
getTransactionsDb()
.prepare("INSERT INTO inventory (product_id, quantity) VALUES (?, ?)")
.run("bouquet_roses", 100);
db.prepare(
"INSERT INTO products (id, title, price, image_url) VALUES (?, ?, ?, ?)"
).run("mug_blue", "Blue Mug", 1500, "");
const inventory = getTransactionsDb().prepare(
"INSERT INTO inventory (product_id, quantity) VALUES (?, ?)"
);
inventory.run("bouquet_roses", 100);
inventory.run("mug_blue", 100);
});

const JSON_HEADERS = { "Content-Type": "application/json" };
Expand Down Expand Up @@ -134,16 +140,22 @@ async function complete(
// with a known-customer shipping destination, then choose the quoted option)
// and return its id ready to complete. See fulfillment.test.ts for the
// dedicated coverage of that selection flow.
type CheckoutItem = { id: string; quantity: number };

async function createReadyToComplete(
app: ReturnType<typeof buildApp>
app: ReturnType<typeof buildApp>,
items: CheckoutItem[] = [{ id: "bouquet_roses", quantity: 1 }]
): Promise<string> {
const created = (await (
await app.request("/checkout-sessions", {
method: "POST",
headers: JSON_HEADERS,
body: JSON.stringify({
currency: "USD",
line_items: [{ item: { id: "bouquet_roses" }, quantity: 1 }],
line_items: items.map((item) => ({
item: { id: item.id },
quantity: item.quantity,
})),
payment: {},
buyer: { email: "john.doe@example.com" },
fulfillment: {
Expand All @@ -153,6 +165,7 @@ async function createReadyToComplete(
})
).json()) as {
id: string;
line_items: { id: string; item: { id: string }; quantity: number }[];
fulfillment: {
methods: {
groups: {
Expand All @@ -170,9 +183,11 @@ async function createReadyToComplete(
headers: JSON_HEADERS,
body: JSON.stringify({
currency: "USD",
line_items: [
{ id: "line_1", item: { id: "bouquet_roses" }, quantity: 1 },
],
line_items: created.line_items.map((line) => ({
id: line.id,
item: { id: line.item.id },
quantity: line.quantity,
})),
buyer: { email: "john.doe@example.com" },
fulfillment: {
methods: [
Expand Down Expand Up @@ -374,3 +389,161 @@ test("an idempotent create replay still carries ucp.payment_handlers", async ()
const replayed = (await replay.json()) as { ucp?: unknown };
assertPaymentHandlers("idempotent replay", replayed.ucp);
});

// Completion writes three tables (inventory, orders, checkouts). A technical
// failure partway through must not leave stock decremented behind a 500: the
// whole unit has to roll back so the client can retry safely.
function countRows(table: "orders"): number {
const row = getTransactionsDb()
.prepare(`SELECT COUNT(*) AS n FROM ${table}`)
.get() as { n: number };
return row.n;
}

function failOnWrite(table: "orders" | "checkouts"): void {
// Fail only the completion writes, so the checkout can still be created and
// updated before the fault is armed.
const sql =
table === "orders"
? `CREATE TRIGGER fail_completion BEFORE INSERT ON orders
BEGIN SELECT RAISE(ABORT, 'injected order failure'); END`
: `CREATE TRIGGER fail_completion BEFORE UPDATE ON checkouts
WHEN NEW.status = 'completed'
BEGIN SELECT RAISE(ABORT, 'injected checkout failure'); END`;
getTransactionsDb().exec(sql);
}

function clearFault(): void {
getTransactionsDb().exec("DROP TRIGGER IF EXISTS fail_completion");
}

test("an order write failure rolls back the inventory reservation", async () => {
const app = buildApp();
const id = await createReadyToComplete(app);
const stockBefore = getInventory("bouquet_roses");
const ordersBefore = countRows("orders");

failOnWrite("orders");
try {
const res = await complete(app, id);
assert.equal(res.status, 500);
} finally {
clearFault();
}

assert.equal(
getInventory("bouquet_roses"),
stockBefore,
"a failed completion must not consume stock"
);
assert.equal(countRows("orders"), ordersBefore, "no order may be persisted");
const checkout = (await (
await app.request(`/checkout-sessions/${id}`)
).json()) as { status: string };
assert.equal(
checkout.status,
"ready_for_complete",
"the checkout must remain completable after the rollback"
);
});

test("a checkout write failure rolls back the order and the reservation", async () => {
const app = buildApp();
const id = await createReadyToComplete(app);
const stockBefore = getInventory("bouquet_roses");
const ordersBefore = countRows("orders");

failOnWrite("checkouts");
try {
const res = await complete(app, id);
assert.equal(res.status, 500);
} finally {
clearFault();
}

assert.equal(getInventory("bouquet_roses"), stockBefore);
assert.equal(
countRows("orders"),
ordersBefore,
"the order inserted before the failing checkout update must roll back"
);
const checkout = (await (
await app.request(`/checkout-sessions/${id}`)
).json()) as { status: string; order?: unknown };
assert.equal(checkout.status, "ready_for_complete");
assert.equal(checkout.order, undefined, "no order reference may survive");
});

test("an out-of-stock second line rolls back the first reservation", async () => {
const app = buildApp();
const id = await createReadyToComplete(app, [
{ id: "bouquet_roses", quantity: 1 },
{ id: "mug_blue", quantity: 1 },
]);
// The mug sells out between checkout creation and completion, so the first
// line is reserved and the second is not.
getTransactionsDb()
.prepare("UPDATE inventory SET quantity = 0 WHERE product_id = ?")
.run("mug_blue");
const rosesBefore = getInventory("bouquet_roses");
const ordersBefore = countRows("orders");

const res = await complete(app, id);
assert.equal(res.status, 409);

assert.equal(
getInventory("bouquet_roses"),
rosesBefore,
"the first line's reservation must roll back with the failure"
);
assert.equal(countRows("orders"), ordersBefore, "no order may be persisted");
const checkout = (await (
await app.request(`/checkout-sessions/${id}`)
).json()) as { status: string };
assert.equal(checkout.status, "ready_for_complete");
});

test("an idempotent completion replay reserves stock once", async () => {
const app = buildApp();
const id = await createReadyToComplete(app);
const stockBefore = getInventory("bouquet_roses");
const ordersBefore = countRows("orders");
const headers = { ...JSON_HEADERS, "Idempotency-Key": "complete-replay" };
const body = JSON.stringify(SUCCESS_PAYMENT);

const first = await app.request(`/checkout-sessions/${id}/complete`, {
method: "POST",
headers,
body,
});
assert.equal(first.status, 200);

const replay = await app.request(`/checkout-sessions/${id}/complete`, {
method: "POST",
headers,
body,
});
assert.equal(replay.status, 200);
const replayed = (await replay.json()) as { status: string };
assert.equal(replayed.status, "completed");

assert.equal(
getInventory("bouquet_roses"),
(stockBefore ?? 0) - 1,
"a replayed completion must not reserve stock again"
);
assert.equal(countRows("orders"), ordersBefore + 1);
});

test("a successful completion reserves stock exactly once", async () => {
const app = buildApp();
const id = await createReadyToComplete(app);
const stockBefore = getInventory("bouquet_roses");

const res = await complete(app, id);
assert.equal(res.status, 200);
const body = (await res.json()) as { order?: { id: string } };
assert.ok(body.order?.id);
assert.equal(getInventory("bouquet_roses"), (stockBefore ?? 0) - 1);
assert.ok(getOrder(body.order.id), "the order must be readable");
});
Loading