This app puts the week's rules into real pages, Server Actions and route
handlers. It lists only records visible to a server-selected Ada fixture
(Day 1), validates and versions every write (Day 2), pages its JSON API by
cursor and answers errors with a public code and a request id (Day 3), and
lets a client retry a create safely with an idempotency key. Use it before
reading the implementation.
Review QueueNext.js · 23 filesimport "./globals.css";
import Link from "next/link";
export const metadata = {
title: { default: "Review Queue", template: "%s · Review Queue" },
};
export default function Layout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Review Queue</strong>
<p>
Practice app: the server uses a fixed Ada actor. No real
authentication is implemented.
</p>
<nav>
<Link href="/">Items</Link>
<Link href="/new">Add an item</Link>
<Link href="/reviews">Review a batch</Link>
<Link href="/console">API console</Link>
</nav>
</header>
{children}
</body>
</html>
);
}
import Link from "next/link";
import { Suspense } from "react";
import { repository } from "@/lib/repository.js";
import { currentActor } from "@/lib/actor.js";
export const dynamic = "force-dynamic";
async function Count({ count }) {
await new Promise((resolve) => setTimeout(resolve, 350));
return <p>{count} visible items</p>;
}
export default async function Page({ searchParams }) {
const params = await searchParams;
const raw = Array.isArray(params.q) ? params.q[0] : params.q;
const q = typeof raw === "string" ? raw.trim() : "";
const rows = repository.list(currentActor(), q);
return (
<main>
<h1>Review Queue</h1>
<form action="/">
<label>
Search <input name="q" defaultValue={q} />
</label>
<button>Search</button>
</form>
<ul>
{rows.map((row) => (
<li key={row.id}>
<Link href={`/items/${row.id}`}>{row.title}</Link> · version{" "}
{row.version}
</li>
))}
</ul>
{!rows.length && <p>No items match.</p>}
<Suspense key={q} fallback={<p>Counting…</p>}>
<Count count={rows.length} />
</Suspense>
</main>
);
}
"use server";
import { redirect } from "next/navigation";
import { revalidatePath } from "next/cache";
import { repository } from "@/lib/repository.js";
import { currentActor } from "@/lib/actor.js";
export async function saveItem(previous, formData) {
const raw = formData.get("title");
const title = typeof raw === "string" ? raw : "";
const id = Number(formData.get("id"));
const version = Number(formData.get("version"));
const result = id
? repository.edit(currentActor(), id, version, { title })
: repository.create(currentActor(), { title });
if (!result.ok)
return {
title,
error:
result.code === "conflict"
? "This item changed. Reload before saving."
: result.code === "not_found"
? "This item is unavailable."
: "Enter a title of 1–60 characters.",
};
revalidatePath("/");
revalidatePath(`/items/${result.item.id}`);
redirect(`/items/${result.item.id}`);
}
export async function removeItem(id) {
const result = repository.remove(currentActor(), id);
if (!result.ok) throw new Error("Item unavailable");
revalidatePath("/");
redirect("/");
}
"use client";
export default function ErrorPage({ retry }) {
return (
<main>
<h1>Could not load this view</h1>
<button onClick={() => retry()}>Try again</button>
</main>
);
}
"use client";
import { useActionState } from "react";
import { saveItem } from "./actions.js";
export default function ItemForm({ item }) {
const [state, action, pending] = useActionState(saveItem, {
error: null,
title: item?.title ?? "",
});
return (
<form action={action}>
<input type="hidden" name="id" value={item?.id ?? ""} />
<input type="hidden" name="version" value={item?.version ?? ""} />
<label>
Title{" "}
<input
name="title"
defaultValue={state.title}
aria-invalid={Boolean(state.error)}
aria-describedby="save-error"
/>
</label>
<p id="save-error" role="alert">
{state.error}
</p>
<button disabled={pending}>
{pending ? "Saving…" : item ? "Save changes" : "Add item"}
</button>
</form>
);
}
body {
font: 16px/1.5 system-ui;
background: #f5f8fc;
color: #183048;
margin: 0;
}
main,
header {
max-width: 850px;
margin: auto;
padding: 20px;
}
input,
button {
font: inherit;
padding: 8px;
margin: 4px;
}
a {
color: #075985;
}
li {
padding: 12px;
}
form {
margin: 16px 0;
}
nav {
display: flex;
gap: 16px;
}
[role="alert"] {
color: #a01818;
}
label {
display: block;
}
section {
padding: 12px;
background: white;
border-radius: 8px;
}
code {
overflow-wrap: anywhere;
}
textarea {
display: block;
max-width: 100%;
font: 14px/1.5 monospace;
padding: 8px;
box-sizing: border-box;
}
"use client";
import { useState } from "react";
export default function ApiConsole() {
const [method, setMethod] = useState("GET");
const [path, setPath] = useState("/api/items?limit=2");
const [key, setKey] = useState("");
const [ifMatch, setIfMatch] = useState("");
const [body, setBody] = useState("");
const [result, setResult] = useState("");
async function send() {
const headers = { "Content-Type": "application/json" };
if (key) headers["Idempotency-Key"] = key;
if (ifMatch) headers["If-Match"] = ifMatch;
const response = await fetch(path, {
method,
headers,
body: method === "GET" ? undefined : body,
});
const etag = response.headers.get("ETag");
const text = await response.text();
setResult(`${response.status} ${etag ? `ETag: ${etag} ` : ""}${text}`);
}
return (
<section>
<label>
Method{" "}
<select value={method} onChange={(event) => setMethod(event.target.value)}>
<option>GET</option>
<option>POST</option>
<option>PATCH</option>
<option>DELETE</option>
</select>
</label>{" "}
<label>
Path <input value={path} onChange={(event) => setPath(event.target.value)} />
</label>
<p>
<label>
Idempotency-Key{" "}
<input value={key} onChange={(event) => setKey(event.target.value)} />
</label>
</p>
<p>
<label>
If-Match{" "}
<input value={ifMatch} onChange={(event) => setIfMatch(event.target.value)} />
</label>
</p>
<p>
<label>
Body{" "}
<input value={body} onChange={(event) => setBody(event.target.value)} />
</label>
</p>
<button onClick={send}>Send request</button>
<p role="status">{result}</p>
</section>
);
}
import ApiConsole from "./ApiConsole.jsx";
export const metadata = { title: "API console" };
export default function Page() {
return (
<main>
<h1>API console</h1>
<p>Send requests to this app's route handlers as the fixed Ada actor.</p>
<ApiConsole />
</main>
);
}
import ItemForm from "../ItemForm.jsx";
export default function NewPage() {
return (
<main>
<h1>Add an item</h1>
<ItemForm />
</main>
);
}
"use server";
import { repository } from "@/lib/repository.js";
import { currentActor } from "@/lib/actor.js";
import { revalidatePath } from "next/cache";
export async function reviewBatch(previous, form) {
const source = form.get("edits");
let input;
try {
input = JSON.parse(typeof source === "string" ? source : "");
} catch {
return { message: "Enter a JSON array of edits.", ok: false };
}
const result = repository.applyBatch(currentActor(), input);
if (!result.ok)
return {
message: `No edits saved: ${result.code}. Refresh to get current versions.`,
ok: false,
};
revalidatePath("/");
for (const item of result.items) revalidatePath(`/items/${item.id}`);
return { message: `Saved ${result.items.length} edits together.`, ok: true };
}
import { repository } from "@/lib/repository.js";
import { currentActor } from "@/lib/actor.js";
import ReviewForm from "./ReviewForm.jsx";
export const dynamic = "force-dynamic";
export default function Reviews() {
return (
<main>
<h1>Review a batch</h1>
<p>
Edit titles in the JSON below. Every id must occur once; each version
must still match. A rejected edit saves none of the batch. Refresh this
page after saving to load current versions.
</p>
<ReviewForm items={repository.list(currentActor()).slice(0, 20)} />
</main>
);
}
"use client";
import { useActionState } from "react";
import { reviewBatch } from "./actions.js";
export default function ReviewForm({ items }) {
const [state, action, pending] = useActionState(reviewBatch, {
message: "",
ok: false,
});
return (
<form action={action}>
<label htmlFor="review-edits">Review batch</label>
<textarea
id="review-edits"
name="edits"
rows={10}
cols={45}
defaultValue={JSON.stringify(items, null, 2)}
aria-describedby="review-result"
/>
<button disabled={pending}>
{pending ? "Saving…" : "Save entire batch"}
</button>
<p id="review-result" role="status">
{state.message}
</p>
</form>
);
}
import { repository } from "@/lib/repository.js";
export async function GET() {
try {
const ready = repository.probe();
return Response.json(
{ ready },
{ status: ready ? 200 : 503, headers: { "Cache-Control": "no-store" } },
);
} catch {
return Response.json({ ready: false }, { status: 503 });
}
}
import { repository } from "@/lib/repository.js";
import { currentActor } from "@/lib/actor.js";
import { errorResponse, newRequestId, readJson } from "@/lib/http.js";
// GET /api/items?after=2&limit=2: a keyset page of the caller's items.
export async function GET(request) {
const requestId = newRequestId();
const params = new URL(request.url).searchParams;
const limit = params.has("limit") ? Number(params.get("limit")) : 10;
if (!Number.isInteger(limit) || limit < 1 || limit > 50)
return errorResponse("invalid_limit", requestId);
const after = params.has("after") ? Number(params.get("after")) : 0;
if (!Number.isInteger(after) || after < 0)
return errorResponse("invalid_cursor", requestId);
return Response.json(repository.page(currentActor(), { after, limit }), {
headers: { "Cache-Control": "private, no-store" },
});
}
// POST /api/items with an Idempotency-Key header: a retry with the same key
// and title returns the first result instead of saving twice.
export async function POST(request) {
const requestId = newRequestId();
const key = request.headers.get("Idempotency-Key");
if (!key) return errorResponse("missing_key", requestId);
const body = await readJson(request);
if (!body.ok) return errorResponse(body.code, requestId);
const result = repository.createOnce(currentActor(), key, body.value);
if (!result.ok) return errorResponse(result.code, requestId);
return Response.json(
{ item: result.item, replayed: Boolean(result.replayed) },
{ status: result.replayed ? 200 : 201 },
);
}
import { repository } from "@/lib/repository.js";
import { currentActor } from "@/lib/actor.js";
import { errorResponse, newRequestId, readJson } from "@/lib/http.js";
export async function PATCH(request) {
const requestId = newRequestId();
const body = await readJson(request);
if (!body.ok) return errorResponse(body.code, requestId);
const result = repository.applyBatch(currentActor(), body.value);
if (!result.ok) return errorResponse(result.code, requestId);
return Response.json(result, {
headers: { "Cache-Control": "private, no-store" },
});
}
import Link from "next/link";
export default function Missing() {
return (
<main>
<h1>Item unavailable</h1>
<p>It may be missing or not visible to this caller.</p>
<Link href="/">All items</Link>
</main>
);
}
import { notFound } from "next/navigation";
import { repository } from "@/lib/repository.js";
import { currentActor } from "@/lib/actor.js";
import ItemForm from "../../ItemForm.jsx";
import { removeItem } from "../../actions.js";
export const dynamic = "force-dynamic";
export default async function ItemPage({ params }) {
const { id } = await params;
const item = repository.get(currentActor(), Number(id));
if (!item) notFound();
return (
<main>
<h1>{item.title}</h1>
<p>Version {item.version}</p>
<ItemForm item={item} />
<form action={removeItem.bind(null, item.id)}>
<button>Remove item</button>
</form>
</main>
);
}
import { repository } from "@/lib/repository.js";
import { currentActor } from "@/lib/actor.js";
import { errorResponse, newRequestId, readJson } from "@/lib/http.js";
export async function GET(request, { params }) {
const { id } = await params;
const item = repository.get(currentActor(), Number(id));
if (!item) return errorResponse("not_found", newRequestId());
return Response.json(item, {
headers: { "Cache-Control": "private, no-store" },
});
}
export async function PATCH(request, { params }) {
const requestId = newRequestId();
const { id } = await params;
const body = await readJson(request);
if (!body.ok) return errorResponse(body.code, requestId);
const input = body.value;
if (!input || !Number.isInteger(input.version) || input.version < 1)
return errorResponse("invalid_version", requestId);
const result = repository.edit(currentActor(), Number(id), input.version, input);
if (!result.ok) return errorResponse(result.code, requestId);
return Response.json(result);
}
export async function DELETE(request, { params }) {
const { id } = await params;
const result = repository.remove(currentActor(), Number(id));
if (!result.ok) return errorResponse(result.code, newRequestId());
return Response.json(result);
}
export function currentActor() {
return { id: "ada", tenantId: "local" };
}
export function validateDraft(input) {
if (!input || typeof input.title !== "string")
return { ok: false, code: "invalid_title" };
const title = input.title.trim();
if (!title || title.length > 60) return { ok: false, code: "invalid_title" };
return { ok: true, title };
}
export function canWrite(actor, row) {
return Boolean(
actor && row && actor.tenantId === row.tenantId && actor.id === row.ownerId,
);
}
export function publicItem(row) {
return { id: row.id, title: row.title, version: row.version };
}
export const seed = [
{
id: 1,
title: "Read about server boundaries",
ownerId: "ada",
tenantId: "local",
version: 1,
},
{
id: 2,
title: "Test a stale edit",
ownerId: "ada",
tenantId: "local",
version: 1,
},
{
id: 3,
title: "Grace's private review",
ownerId: "grace",
tenantId: "local",
version: 1,
},
];
export function validateBatch(input) {
if (!Array.isArray(input) || input.length < 1 || input.length > 20)
return { ok: false, code: "invalid_batch" };
const ids = new Set();
const edits = [];
for (const edit of input) {
if (
!edit ||
!Number.isSafeInteger(edit.id) ||
edit.id < 1 ||
!Number.isSafeInteger(edit.version) ||
edit.version < 1 ||
ids.has(edit.id)
)
return { ok: false, code: "invalid_batch" };
const valid = validateDraft(edit);
if (!valid.ok) return valid;
ids.add(edit.id);
edits.push({ id: edit.id, version: edit.version, title: valid.title });
}
return { ok: true, edits };
}
// The service's public error vocabulary (Day 3). Clients branch on `code`
// and must treat an unknown code by its status class.
const STATUS = new Map(
Object.entries({
invalid_json: 400,
invalid_title: 400,
invalid_batch: 400,
invalid_version: 400,
invalid_limit: 400,
invalid_cursor: 400,
missing_key: 400,
unauthenticated: 401,
not_found: 404,
conflict: 409,
key_reused: 422,
}),
);
export function newRequestId() {
const bytes = crypto.getRandomValues(new Uint8Array(6));
return "req_" + Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}
// Known codes keep their status; anything else is a generic 500. Only the
// code and the request id reach the caller; details go to the server log.
export function errorResponse(code, requestId, detail) {
const status = STATUS.get(code) ?? 500;
const publicCode = status === 500 ? "internal_error" : code;
console.log(`${requestId} ${publicCode}${detail ? `: ${detail}` : ""}`);
return Response.json(
{ code: publicCode, requestId },
{ status, headers: { "Cache-Control": "private, no-store" } },
);
}
export async function readJson(request) {
try {
return { ok: true, value: await request.json() };
} catch {
return { ok: false, code: "invalid_json" };
}
}
import {
validateDraft,
validateBatch,
canWrite,
publicItem,
seed,
} from "./domain.js";
export function createRepository(initial = seed) {
let rows = initial.map((row) => ({ ...row }));
let nextId = Math.max(0, ...rows.map((row) => row.id)) + 1;
// Idempotency receipts (Day 2): one per actor and key, with the payload
// they were for. In SQLite this is a table written in the same transaction.
const receipts = new Map();
return {
list(actor, q = "") {
return rows
.filter(
(row) =>
canWrite(actor, row) &&
row.title.toLowerCase().includes(q.toLowerCase()),
)
.map(publicItem);
},
// Keyset pages (Day 3): rows after the cursor, one extra to learn whether
// another page exists.
page(actor, { after = 0, limit = 10 } = {}) {
const window = rows
.filter((row) => canWrite(actor, row) && row.id > after)
.toSorted((a, b) => a.id - b.id)
.slice(0, limit + 1);
const items = window.slice(0, limit).map(publicItem);
return { items, nextCursor: window.length > limit ? items.at(-1).id : null };
},
createOnce(actor, key, input) {
if (!actor) return { ok: false, code: "unauthenticated" };
const receiptKey = JSON.stringify([actor.tenantId, actor.id, key]);
const fingerprint = JSON.stringify(input?.title ?? null);
const receipt = receipts.get(receiptKey);
if (receipt) {
if (receipt.fingerprint !== fingerprint)
return { ok: false, code: "key_reused" };
return { ...receipt.result, replayed: true };
}
const result = this.create(actor, input);
// Only a successful create is remembered; an invalid draft may be
// corrected and sent again with the same key.
if (result.ok) receipts.set(receiptKey, { fingerprint, result });
return result;
},
get(actor, id) {
const row = rows.find((row) => row.id === id);
return canWrite(actor, row) ? publicItem(row) : null;
},
create(actor, input) {
if (!actor) return { ok: false, code: "unauthenticated" };
const valid = validateDraft(input);
if (!valid.ok) return valid;
const row = {
id: nextId++,
title: valid.title,
ownerId: actor.id,
tenantId: actor.tenantId,
version: 1,
};
rows = [...rows, row];
return { ok: true, item: publicItem(row) };
},
edit(actor, id, version, input) {
const row = rows.find((row) => row.id === id);
if (!canWrite(actor, row)) return { ok: false, code: "not_found" };
if (row.version !== version) return { ok: false, code: "conflict" };
const valid = validateDraft(input);
if (!valid.ok) return valid;
const next = { ...row, title: valid.title, version: row.version + 1 };
rows = rows.map((item) => (item.id === id ? next : item));
return { ok: true, item: publicItem(next) };
},
applyBatch(actor, input) {
const valid = validateBatch(input);
if (!valid.ok) return valid;
const draft = rows.map((row) => ({ ...row }));
const items = [];
for (const edit of valid.edits) {
const row = draft.find((row) => row.id === edit.id);
if (!canWrite(actor, row)) return { ok: false, code: "not_found" };
if (row.version !== edit.version)
return { ok: false, code: "conflict" };
row.title = edit.title;
row.version++;
items.push(publicItem(row));
}
rows = draft;
return { ok: true, items };
},
remove(actor, id) {
const row = rows.find((row) => row.id === id);
if (!canWrite(actor, row)) return { ok: false, code: "not_found" };
rows = rows.filter((row) => row.id !== id);
return { ok: true };
},
probe() {
return true;
},
close() {},
};
}
export const repository = createRepository();
import { createRepository } from "./repository.js";
export function reviewChecks() {
const make = () => createRepository();
const ada = { id: "ada", tenantId: "local" };
const tenant = make().get({ id: "ada", tenantId: "other" }, 1) === null;
const deletion =
make().remove({ id: "grace", tenantId: "local" }, 1).ok === false;
const projection = !Object.hasOwn(make().get(ada, 1), "ownerId");
const repo = make();
repo.edit(ada, 1, 1, { title: "First" });
const conflict = repo.edit(ada, 1, 1, { title: "Stale" }).code === "conflict";
const pager = make();
const first = pager.page(ada, { limit: 1 });
pager.remove(ada, first.items[0].id);
const second = pager.page(ada, { after: first.nextCursor, limit: 1 });
const paging =
second.items[0]?.id === 2 && second.nextCursor === null;
const once = make();
once.createOnce(ada, "k1", { title: "Retry me" });
const replay = once.createOnce(ada, "k1", { title: "Retry me" });
const idempotent =
replay.replayed === true &&
once.list(ada).filter((row) => row.title === "Retry me").length === 1;
return [
{ name: "Tenant isolation", pass: tenant },
{ name: "Deletion permission", pass: deletion },
{ name: "Public projection", pass: projection },
{ name: "Stale edit rejected", pass: conflict },
{ name: "Cursor page survives a delete", pass: paging },
{ name: "Retried create saves once", pass: idempotent },
];
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Trace the boundaries
Search for read. The page unwraps searchParams, normalizes the query
and asks repository.list for public items:
Follow API console and send GET /api/items?limit=1. The handler pages
by cursor with one extra row, as on Day 3, so the answer says whether to
ask again:
Text
200 {"items":[{"id":1,"title":"Read about server boundaries","version":1}],"nextCursor":1}
Send GET /api/items?after=1&limit=1: item 2, with "nextCursor":null.
Item 3 is Grace's, so the scoped query never reaches it.
Send GET /api/items/3. Every error goes through errorResponse in
lib/http.js, which maps a known code to its status, turns anything else
into internal_error, and logs the request id with the details:
Read lib/domain.js, lib/repository.js, lib/http.js, app/actions.js,
app/ItemForm.jsx and app/api/items/route.js in that order. Explain where each input becomes
trusted enough for the next operation. An id from a form is still untrusted.
Scope of this project
This is a boundary-design project, not a finished multi-user product.
currentActor() is a fixed server-side fixture, not authentication. A real
session provider must replace it before offering private data to real users.
The browser repository lives in memory; Run restarts it. The lab toolbar
downloads that memory version. Use the separate SQLite ZIP in the next lesson
for persistent storage and a conditional version update. The SQLite project's
JSON API is simpler than this one: it has no cursor pages, request ids or
idempotency keys, so adding them is a good exercise once you've finished the
course. Neither the simulator nor a pure policy test proves a production cache
or distributed deployment is correct.
A retry that saves once
A phone on a train sends POST /api/items, the response is lost, and the app
sends it again. Without protection that's two items. The handler asks for an
Idempotency-Key header, and the repository keeps a receipt per actor and key:
In the API console, choose POST, path /api/items, key k1 and body
{"title": "Retry me"}. Predict the status and body of each request before
sending it:
The request as given.
Exactly the same request again.
Key k1 with body {"title": "Other"}.
Then send GET /api/items?after=2 and predict how many Retry me items it
lists.
Hint 1: the idea
The receipt is keyed by who sent it and the key, and it remembers what the
payload was. Same key and same payload is a retry; same key and a different
payload is a client bug.
Hint 2: a first step
Before the first request there's no receipt, so createOnce calls create
and stores the result. Work out what the stored result is, then read the
if (receipt) branch for the other two.
The list shows one Retry me, id 4. The retry gets the first answer back,
including the same id, so the client can carry on as if the first response had
arrived. A different payload under the same key is refused with its own code,
not silently treated as a retry or as a new item. Only successful creates leave
a receipt, so a blank title can be corrected and sent again with the same key.
In the SQLite project, the receipt would be a table with a unique index on
(tenantId, actorId, key), written in the same transaction as the item, as
Day 2's receipt lesson traced. The in-memory version here can't crash between
the two writes, so it can't show that failure.
Trace an atomic batch
Open Review a batch. Each proposed edit carries an id, title and version.
The server validates the whole input shape and rejects duplicate ids and batches
larger than 20. The actor comes from the server fixture, not from the JSON.
Change both titles and set the second version to 99. Submit. The response
reports a conflict. Follow Items and confirm that neither title changed.
Refresh the review page to read current versions. Change both titles and
submit again. Both edits commit and both versions advance.
Submit the same versions again. The second submission is stale and must fail.
In the browser, applyBatch edits a separate draft and publishes it only after
all checks pass. In the download, BEGIN IMMEDIATE starts a SQLite transaction;
each UPDATE still includes owner, tenant and expected version predicates. A
failed later edit rolls back earlier writes before the handler responds.
tests/batch.test.mjs checks the same contract against both adapters. This
single-database transaction does not coordinate independent external services:
The PATCH handler at /api/reviews uses the same repository operation as the
Server Action. readJson turns malformed JSON into invalid_json, and every
refusal goes through errorResponse from lib/http.js, which maps the code to
its status (400 for a malformed batch, 404 for an inaccessible record, 409 for a
stale version) and adds a request id. An unexpected database exception isn't
caught here, so it reaches error handling instead of being reported as a
successful empty batch:
JavaScript
export async function PATCH(request) { const requestId = newRequestId(); const body = await readJson(request); if (!body.ok) return errorResponse(body.code, requestId); const result = repository.applyBatch(currentActor(), body.value); if (!result.ok) return errorResponse(result.code, requestId); return Response.json(result, { headers: { "Cache-Control": "private, no-store" }, });}
Completion is saved in this browser only. It does not measure mastery.