diff --git a/AGENTS.md b/AGENTS.md index fc0690c..04fb33d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -103,7 +103,7 @@ Folder names are category-prefixed (e.g. `ui-`, `data-`, `app-settings-`, `chat- | `audio-bundled-sfx` | How do I ship and play short sound effects from my client, dealing with the autoplay policy and Vite asset bundling? | — | — | | `chat-trigger-respond` | How do I make my app respond to user chat messages? | `server-messages` | `apps/leveling-leaderboard` | | `data-batch-prefetch` | How do I batch-prefetch related data (e.g. 50 user profiles for a list of activities) in one call instead of N+1 from the client? | `server-database`, `networking-app-services` | — | -| `data-paginated-list` | How do I paginate a server-side list with cursor-based queries and accumulate pages on the client? | `server-database`, `networking-app-services` | `apps/leveling-leaderboard` | +| `data-paginated-list` | How do I paginate a server-side list with cursor-based queries, accumulate pages on the client, and search it without breaking the paging? | `server-database`, `networking-app-services` | `apps/leveling-leaderboard` | | `error-rpc-exceptions` | How do I propagate domain-specific error codes from server to client and let the client branch on them? | `networking-app-services`, `server-key-value-store` | `apps/suggestion-box` | | `external-http-fetch` | How do I call an external HTTP API from my server with timeouts and typed error handling? | `networking-app-services` | `apps/github-release-watcher` | | `per-user-cooldown` | How do I rate-limit a per-user action so it can only happen once per N seconds, atomically? | `server-database`, `networking-app-services` | `apps/leveling-leaderboard` | diff --git a/recipes/data-paginated-list/AGENTS.md b/recipes/data-paginated-list/AGENTS.md index 5c6a717..bcf034e 100644 --- a/recipes/data-paginated-list/AGENTS.md +++ b/recipes/data-paginated-list/AGENTS.md @@ -1,7 +1,7 @@ --- kind: recipe category: data -question: How do I paginate a server-side list with cursor-based queries and accumulate pages on the client? +question: How do I paginate a server-side list with cursor-based queries, accumulate pages on the client, and search it without breaking the paging? composes: - server-database - networking-app-services @@ -10,9 +10,9 @@ exemplified_by: leveling-leaderboard # Recipe: Cursor-Based Pagination -> *"How do I paginate a server-side list with cursor-based queries and accumulate pages on the client?"* +> *"How do I paginate a server-side list with cursor-based queries, accumulate pages on the client, and search it without breaking the paging?"* -A SQLite-backed list of records, exposed via an RPC that returns one page at a time. The client accumulates pages with a "Load more" button. When the server returns an empty `next_cursor`, the list is exhausted. +A SQLite-backed list of records, exposed via an RPC that returns one page at a time. The client accumulates pages with a "Load more" button. When the server returns an empty `next_cursor`, the list is exhausted. A search box filters the list **on the server**, because a paginated response is a window and filtering it on the client searches the window instead of the list. The seeded data — 100 rows labelled `Record 1`…`Record 100` — is **placeholder**. Fork the recipe and replace the schema (and the seed in [`server/src/db.ts`](server/src/db.ts)) with whatever your real list shape is: audit log entries, posts, items in a queue, etc. The pagination mechanic is independent of row contents. @@ -31,6 +31,11 @@ click "Load more" append again …eventually the server returns next_cursor: "" — done. + +type "wid" in the search box (debounced 300ms) + → listRecords({ cursor: "", search: "wid" }) ► SELECT … WHERE id < MAX AND LOWER(label) LIKE '%wid%' LIMIT 20 + ◄─────── { records: [matches], next_cursor: "" } +REPLACE local state — this is a new query, not more of the old one ``` ## Why cursor, not offset @@ -51,6 +56,22 @@ If the client decodes a malformed cursor, the server falls back to "first page" The server detects end-of-list precisely by querying `pageSize + 1` rows and trimming the extra. If the trim happened, there's at least one more row → return a cursor. If it didn't (we got `pageSize` or fewer rows), there's nothing past this page → return empty cursor. The cost is one extra row of work per page; the win is the last user-facing page already knows it's the last. A cheaper variant — ask for exactly `pageSize` and infer end from "got fewer than asked" — sacrifices precision: the last full page returns a non-empty cursor that yields `[]` on the next call, making the user click "Load more" once for nothing. The extra-row variant is the canonical choice for user-facing pagination. +## Why the server filters, and the client never does + +The client holds the pages it has fetched. Filtering that array answers "which of the rows I already have match?", which is not the question the user asked. On a list of 40 with a page size of 20, a client-side filter searches half the data and looks completely correct. + +The failure has no symptom. There is no error, no empty state, and no wrong-looking output — matches that exist are simply not returned, and the behaviour degrades continuously as the table grows. It also cannot be caught by running the app: seed and fixture data are almost always smaller than one page, so during development every row is in the first page and the filter appears to work perfectly. + +So `search` goes in the request. The filter and the seek live in the same SQL, which means paging walks the matching rows rather than walking every row and discarding non-matches. + +## Why the cursor carries the search term + +A cursor means "the last id you saw" — but only within the query that produced it. Pair a cursor from an unfiltered listing with `search: "wid"` and the server seeks past every match above that id and returns a page that is missing rows for no visible reason. + +The cursor payload therefore carries the term it was issued under, and the server restarts from the first page when the term differs. This is the payoff of the opaque-cursor decision above: the payload gained a field and no client had to change. + +A well-behaved client also resets its own pagination when the term changes, which the client here does. Both halves are worth having — the client reset is the mechanism, the server check is what makes a client bug produce a correct-if-slower answer instead of a silently short list. + ## Composes | api-sample | What it teaches | What this recipe uses it for | @@ -112,15 +133,27 @@ Initial load fires on mount; subsequent loads on button click. Same `fetchPage` For an infinite-scroll variant: replace the button with an `IntersectionObserver` watching a sentinel at the bottom of the list. The observer's callback calls `fetchPage(cursor)`. Same state, different trigger. -## Does NOT cover +## Not covered here — safe to go elsewhere + +Nothing below is a trap. Each is a genuinely separate concern; build it where it belongs. | Concern | Lives in | |---|---| | **Live updates** — inserting new rows visible in already-loaded pages | A separate recipe (deferred until streaming-subscription test infrastructure lands) | -| **Filtering and search** — paginating a filtered subset | Independent concern; the cursor encoding extends naturally to carry the filter, but multi-axis pagination has its own design space | | **Virtualized rendering** — only paint visible rows for very long lists | Independent of pagination mechanics; a real app uses `react-window` or similar regardless of how data is fetched | | **Pull-to-refresh** — re-fetching the latest page from the top | Adjacent feature with its own state-machine wrinkles (overlap with already-loaded rows, dedup) | -| **Stable ordering across columns** — pagination over `ORDER BY total_xp DESC` with ties | The cursor extends to a tuple `(total_xp, id)` and the query becomes `WHERE (total_xp, id) < (?, ?)`. Same shape, more parameters. | + +## Not covered here — and the obvious approach is wrong + +These are extensions this recipe does not implement, where the naive version is silently broken rather than merely incomplete. Read the trap before you build one. + +| Extension | The trap | The shape that works | +|---|---|---| +| **Multi-field or multi-axis filtering** — filter by status *and* author *and* date | Adding filters client-side once one filter already lives on the server. The two disagree the moment the data exceeds a page, and the server-filtered subset makes the client-filtered result look plausible. | Every filter goes in the request, and all of them go into the cursor payload's fingerprint. One query, one cursor, one source of truth. | +| **Stable ordering across columns** — paging over `ORDER BY total_xp DESC` with ties | Seeking on the sort column alone. Rows with equal `total_xp` straddle the page boundary, so some are served twice and others never. | The cursor becomes a tuple `(total_xp, id)` and the query becomes `WHERE (total_xp, id) < (?, ?)` — the id breaks ties. Same shape, more parameters. | +| **Sorting chosen by the user** — a column-header click that reorders the list | Keeping the cursor across a sort change. It describes a position in the old ordering, so the new listing starts from an arbitrary point. | Treat a sort change exactly like a term change: it is a new query. Reset pagination, and put the sort key in the cursor payload so a mismatched pair restarts instead of seeking. | + +**The pattern behind all three:** a cursor is a position inside one specific query. Anything that changes the query — a filter, a term, an ordering — invalidates it. Encode enough of the query in the cursor that the server can tell, because the alternative is a page that is quietly missing rows. ## Test-only files in this recipe diff --git a/recipes/data-paginated-list/client/src/App.tsx b/recipes/data-paginated-list/client/src/App.tsx index d7affc1..66c3b82 100644 --- a/recipes/data-paginated-list/client/src/App.tsx +++ b/recipes/data-paginated-list/client/src/App.tsx @@ -5,26 +5,47 @@ // // State machine for accumulating pages: // -// - records[] — every record fetched so far, in order -// - cursor — the cursor for the NEXT call (empty string on first load) -// - loading — request in flight; disable the button to prevent double-fire -// - done — server returned an empty next_cursor; no more pages -// - error — last error message, if any (display + recover by retrying) +// - records[] — every record fetched so far, in order +// - cursor — the cursor for the NEXT call (empty string on first load) +// - loading — request in flight; disable the button to prevent double-fire +// - done — server returned an empty next_cursor; no more pages +// - error — last error message, if any (display + recover by retrying) +// - search — what the user has typed, updated on every keystroke +// - appliedSearch — the debounced term actually sent to the server // -// Initial load happens on mount via useEffect; subsequent loads are user-driven -// via the "Load more" button. Same fetchPage function for both — the only -// difference is whether the user clicked something. +// The client does NOT filter `records`. The server does the filtering, because +// `records` only holds the pages fetched so far — filtering it locally would +// search the window instead of the list, and would never find a match beyond +// the pages already pulled. That bug is invisible while the seed data fits in +// one page, which is exactly why it survives review. +// +// A term change resets pagination: records cleared, cursor cleared, first page +// re-fetched. Keeping the old cursor would seek into a result set that no +// longer exists. +// +// Why the first page REPLACES and later pages APPEND: it makes the first fetch +// idempotent, so React.StrictMode's deliberate double-invocation of effects in +// dev is harmless. An earlier version of this recipe appended on every page and +// needed a useRef latch to stop the mount effect duplicating records 100…81. +// Designing the operation to be repeatable beats latching around a repeat. // // Why we don't auto-load all pages: the recipe's lesson is the explicit pull // pattern (each page is a deliberate fetch). Real apps often replace the // button with an IntersectionObserver-driven infinite scroll, but the // underlying state machine is the same — replace the click handler with the -// observer callback. We use a button here because it's the simplest visible -// demonstration of "another page is available." +// observer callback. +// +// If you take the infinite-scroll route, note that it interacts badly with a +// client-side filter, which is a second reason not to write one: filtering the +// accumulated pages shrinks the rendered list, which can lift the sentinel out +// of the viewport, so the observer never fires and the list never grows to +// contain what the user is looking for. Searching then prevents its own results +// from loading. With the filter on the server this cannot happen — each term is +// its own query, starting from its own first page. // // ============================================================================ -import React, { useEffect, useRef, useState } from "react"; +import React, { useEffect, useState } from "react"; import { listServiceClient } from "@datapaginatedlist/gen-client"; import { Record as RecordMessage } from "@datapaginatedlist/gen-shared"; @@ -36,21 +57,28 @@ export const App: React.FC = () => { const [loading, setLoading] = useState(false); const [done, setDone] = useState(false); const [error, setError] = useState(undefined); - // Latch for the initial-load effect — see useEffect comment below. - const initialFetchRef = useRef(false); - - const fetchPage = async (currentCursor: string): Promise => { + const [search, setSearch] = useState(""); + const [appliedSearch, setAppliedSearch] = useState(""); + + const fetchPage = async ( + currentCursor: string, + term: string, + mode: "replace" | "append", + ): Promise => { setLoading(true); setError(undefined); try { const r = await listServiceClient.listRecords({ pageSize: PAGE_SIZE, cursor: currentCursor, + search: term, }); - // Append, don't replace. The previous-page records stay; the new page - // gets concatenated. This is what makes the "load more" pattern feel - // continuous to the user instead of paging in/out. - setRecords((prev) => [...prev, ...r.records]); + // Later pages append so "load more" feels continuous; the first page of + // any query replaces, which both clears the previous term's results and + // makes the call safe to repeat. + setRecords((prev) => + mode === "replace" ? r.records : [...prev, ...r.records], + ); setCursor(r.nextCursor); // Empty next_cursor = end of list. Flip done=true so the button // disables itself and we render the end-of-list message. @@ -62,26 +90,38 @@ export const App: React.FC = () => { } }; - // Initial load on mount, once. React.StrictMode in dev intentionally - // double-invokes effects to surface impure side-effect bugs — without a - // guard, fetchPage("") fires twice and the appending setRecords produces - // visible duplicates of records 100…81. The useRef latch is the canonical - // pattern: refs survive the StrictMode unmount/remount, so the second - // invocation no-ops. (Production builds don't double-invoke effects, but - // devhost is the canonical local-run path for this recipe, so the dev-mode - // duplication would be the first thing a learner sees and questions.) + // Debounce the input so a search costs one request per pause rather than one + // per keystroke. Clients are rate-limited to 10 app RPCs per second, and a + // fast typist exceeds that on a single word without this. useEffect(() => { - if (initialFetchRef.current) return; - initialFetchRef.current = true; - void fetchPage(""); + const timer = setTimeout(() => setAppliedSearch(search.trim()), 300); + return () => clearTimeout(timer); + }, [search]); + + // One effect covers both the initial load and every term change: appliedSearch + // starts as "" so the mount case is simply the first query. Clearing the + // cursor here is what stops a stale cursor being paired with a new term. + useEffect(() => { + setCursor(""); + setDone(false); + void fetchPage("", appliedSearch, "replace"); // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + }, [appliedSearch]); return (

Cursor-Based Pagination

+ setSearch(event.target.value)} + placeholder="Search labels" + aria-label="Search labels" + style={inputStyle} + /> +

Loaded {records.length} record{records.length === 1 ? "" : "s"} + {appliedSearch ? ` matching ${JSON.stringify(appliedSearch)}` : ""} {done ? " (end of list)" : ""}

@@ -98,7 +138,7 @@ export const App: React.FC = () => { {!done && (
); }; @@ -150,6 +193,18 @@ const timestampStyle: React.CSSProperties = { marginLeft: 8, }; +const inputStyle: React.CSSProperties = { + width: "100%", + boxSizing: "border-box", + marginTop: 16, + padding: "10px 12px", + borderRadius: 8, + border: "1px solid var(--rootsdk-border)", + background: "var(--rootsdk-background-secondary)", + color: "var(--rootsdk-text-primary)", + fontSize: 14, +}; + const buttonStyle: React.CSSProperties = { padding: "10px 16px", borderRadius: 8, diff --git a/recipes/data-paginated-list/networking/src/list_service.proto b/recipes/data-paginated-list/networking/src/list_service.proto index 1efcebc..9cd8d75 100644 --- a/recipes/data-paginated-list/networking/src/list_service.proto +++ b/recipes/data-paginated-list/networking/src/list_service.proto @@ -21,11 +21,23 @@ package datapaginatedlist; // next_cursor field. Empty string means "first page". Clients never // inspect or construct cursors — they round-trip the value the server // gave them. Server owns the encoding (this recipe uses base64-encoded -// JSON of the last seen id), and is free to change it without breaking -// clients. +// JSON of the last seen id AND the search term it was issued under), and +// is free to change it without breaking clients. A cursor is only meaningful +// within the query that produced it: pairing one with a different `search` +// seeks into the middle of a result set it never described, so the server +// detects the mismatch and starts over. +// +// search — optional case-insensitive substring filter, applied by the SERVER +// against the record label. This field exists because the alternative is a +// silent bug: a client that fetches a page and filters it locally can only +// ever find matches inside the page it happens to hold, and there is no +// error, no empty state, and no symptom until the list outgrows one page. +// A filtered list is still paginated — the filter narrows what is paged +// over, it does not replace paging. message ListRecordsRequest { uint32 page_size = 1; string cursor = 2; + string search = 3; } // Page response. diff --git a/recipes/data-paginated-list/server/src/list-service.ts b/recipes/data-paginated-list/server/src/list-service.ts index 085103e..114e4c8 100644 --- a/recipes/data-paginated-list/server/src/list-service.ts +++ b/recipes/data-paginated-list/server/src/list-service.ts @@ -23,6 +23,19 @@ // ask for "everything" by sending a huge page_size and skipping // pagination entirely. // +// 5. Filtering happens HERE, not on the client. A paginated response is a +// window, so a client-side filter over it searches the window rather +// than the list. That failure is silent — no error, no empty state, +// correct-looking results — and it only appears once the data outgrows +// one page, which is long after the code ships. +// +// 6. A cursor belongs to the query that issued it. The cursor payload +// carries the search term, so a cursor paired with a different term is +// recognised as stale and the query restarts from the first page +// instead of seeking into a result set the cursor never described. +// This is what the opaque-cursor design in (2) buys: the server added +// a field to the payload and no client had to change. +// // ============================================================================ import { Client } from "@rootsdk/server-app"; @@ -57,7 +70,13 @@ export class ListService extends ListServiceBase { // Number.MAX_SAFE_INTEGER is the sentinel for "no upper bound" so the // SQL stays the same shape on every page; we don't need a separate // first-page query. - const cursorId = decodeCursor(request.cursor); + // Normalise once: the same string is used for the SQL parameter and for + // the cursor's fingerprint, so they cannot disagree. + const search = request.search.trim().toLowerCase(); + + // Empty string = first page (no upper bound on id). A cursor issued under + // a different search term is treated the same way — see decodeCursor. + const cursorId = decodeCursor(request.cursor, search); // Page query. ORDER BY id DESC means newest first. WHERE id < cursorId // is the seek; combined with LIMIT, it returns the next page beyond @@ -73,20 +92,33 @@ export class ListService extends ListServiceBase { // precision — the last full page returns a non-empty cursor that // yields [] on the next call. The extra-row variant is the canonical // choice for user-facing pagination.) + // The filter is part of the same query as the seek, so paging walks the + // matching rows rather than walking every row and discarding non-matches. + // LOWER(label) LIKE ? is deliberately the plainest thing that works on + // sqlite and Postgres alike; a real app with a large table wants an index + // built for the comparison it actually performs (a functional index on + // LOWER(label), or full-text search), because LIKE '%term%' cannot use a + // plain B-tree index on label. + const filterSql = search ? "AND LOWER(label) LIKE ?" : ""; + const params: (number | string)[] = search + ? [cursorId, `%${search}%`, pageSize + 1] + : [cursorId, pageSize + 1]; + const rows = await all( getDb(), `SELECT id, created_at, label FROM records WHERE id < ? + ${filterSql} ORDER BY id DESC LIMIT ?`, - [cursorId, pageSize + 1], + params, ); const hasMore = rows.length > pageSize; const pageRows = hasMore ? rows.slice(0, pageSize) : rows; const nextCursor = hasMore && pageRows.length > 0 - ? encodeCursor(pageRows[pageRows.length - 1].id) + ? encodeCursor(pageRows[pageRows.length - 1].id, search) : ""; const records: RecordMessage[] = pageRows.map((r) => ({ @@ -111,19 +143,28 @@ export const listService = new ListService(); interface CursorPayload { id: number; + q: string; } -function encodeCursor(lastId: number): string { - const payload: CursorPayload = { id: lastId }; +function encodeCursor(lastId: number, search: string): string { + const payload: CursorPayload = { id: lastId, q: search }; return Buffer.from(JSON.stringify(payload), "utf8").toString("base64"); } -function decodeCursor(cursor: string): number { +// Returns the seek bound, or MAX_SAFE_INTEGER meaning "start from the first +// page". A cursor whose search term differs from the current request's is +// stale, not malformed: the client changed what it was searching for while +// holding a cursor into the old result set. Restarting is the only correct +// answer — honouring the seek would silently skip every match above it. +// A well-behaved client resets its own pagination on a term change, so this +// is defence in depth rather than the primary mechanism. +function decodeCursor(cursor: string, search: string): number { if (!cursor) return Number.MAX_SAFE_INTEGER; try { const json = Buffer.from(cursor, "base64").toString("utf8"); const payload = JSON.parse(json) as CursorPayload; - if (typeof payload.id === "number" && Number.isFinite(payload.id)) { + const sameQuery = (payload.q ?? "") === search; + if (sameQuery && typeof payload.id === "number" && Number.isFinite(payload.id)) { return payload.id; } } catch { diff --git a/recipes/data-paginated-list/server/src/test-driver.ts b/recipes/data-paginated-list/server/src/test-driver.ts index e11c69c..704a612 100644 --- a/recipes/data-paginated-list/server/src/test-driver.ts +++ b/recipes/data-paginated-list/server/src/test-driver.ts @@ -164,6 +164,11 @@ async function onTestCommand(evt: ChannelMessageCreatedEvent): Promise { * record contents; the contract verified here is "pagination produces the * right page boundaries," not "the right rows are seeded" (which is a * concern of db.ts, not of the pagination mechanic). + * + * `search` is passed through so the harness can assert the filtered case, + * which is the one that cannot be checked by eye: with 100 seeded rows and a + * page size of 20, a client-side filter and a server-side filter look + * identical on the first page and diverge only past it. */ async function invoke( method: string, @@ -177,6 +182,7 @@ async function invoke( { pageSize: (request.pageSize as number) ?? 0, cursor: (request.cursor as string) ?? "", + search: (request.search as string) ?? "", }, client, );