@nodii/pagination
v0.2.0
Published
The one keyset pagination library for Nodii (S-10): signed cursor codec, list-query parsing, keyset query helper, paginatedData wrapper and gRPC page tokens.
Readme
@nodii/pagination
The one keyset pagination library for Nodii (S-10). It has TypeScript, Python (nodii-pagination) and Go (nodii.co/nodii-libs/go/pagination) ports with the same wire format. A cursor issued by one port verifies in the others.
A service MUST NOT encode, decode or sign a cursor outside this library (S10-4).
Use
import { defineList, orderBySql, paginatedData, Paginator, parseListQuery, seekSql } from "@nodii/pagination";
const invoices = defineList({
operation: "invoices.list",
defaultLimit: 50,
maxLimit: 200,
search: true,
filters: ["status", "customer_id"],
sorts: [{ field: "due_at", column: "i.due_at", cast: "timestamptz" }],
defaultSort: "-due_at",
tieBreaker: { field: "invoice_id", column: "i.invoice_id", cast: "uuid" },
});
const paginator = new Paginator({ keys: { current: cursorKey } });
const query = parseListQuery(invoices, new URL(request.url).searchParams);
const page = await paginator.paginate(invoices, query, {
tenantId, // from the authenticated caller, never the request
fetch: async (read) => {
const seek = seekSql(read, 2); // $1 is tenant_id
const sql = `SELECT i.invoice_id::text AS invoice_id, i.due_at::text AS due_at
FROM invoices i WHERE i.tenant_id = $1 ${seek ? `AND ${seek}` : ""}
ORDER BY ${orderBySql(read)} LIMIT ${read.limit}`;
return (await db.query(sql, [tenantId, ...read.values])).rows;
},
});
return Response.json(paginatedData(page));Run every fetch of one request in one tenant transaction, so RLS applies and the reads see one snapshot. Without that, a write between the two reads can make a cursor describe a page that has just changed. paginate calls fetch once for the page and, on a page reached by a cursor, once more with limit 1 to learn whether a page exists the other way. That is what makes meta.previous_cursor and meta.next_cursor exact (S10-7).
Refusals throw PaginationError, which carries code and status (400) for REST. On gRPC, errorMap in @nodii/grpc-interceptors answers INVALID_ARGUMENT with code as the reason, because its standard catalog holds each refusal's name; a service must spread that catalog into its own (S09-15, S09-16). If fetch fails on either read, the request fails: there is no partial page. A wrong use of the library throws PaginationConfigError, which is a server fault.
gRPC
parsePageRequest(list, { pageSize, pageToken, sort, q, filters }) replaces parseListQuery, and pageTokens(page) gives next_page_token and previous_page_token. A token carries its own direction. Snapshot streams resume the same way: pass the tenant from the authenticated envelope (S10-16).
Rules for a list
- Sort columns MUST be NOT NULL. A row comparison skips NULLs, so such rows drop out of later pages. The page read's rows are checked and a null throws
PaginationConfigError, but that only catches a null it happens to read: a seek never returns one, and such a row is then lost with no error. Only the column's constraint protects the list. Nullable sort columns are not supported. - Qualify a sort column when its SELECT renames or casts it, as
i.due_atabove. InORDER BY, a bare name means the output column first. Withdue_at::text AS due_at, a baredue_atsorts the text while the seek compares the timestamp: the order is wrong, rows are skipped or repeated, and the index goes unused. - The tie-breaker MUST be unique (S10-12), and an index on
(sort column, tie-breaker)is what makes the read fast. - Sort values MUST reach the library as strings, safe integers or booleans. Select a timestamp as text: a JavaScript
Dateloses Postgres microseconds, and a float loses equality. Either would skip or repeat rows. Decimals and big integers are text too. - Keep sort values short. A token is at most 4096 characters, and issuing a longer one throws
PaginationConfigError, so sort on a short column. - Declare
castwhenever the value reaches the library as text and the column is not text. That covers timestamps, uuids, and big integers or decimals selected as text. The value then binds as text and SQL casts it, which every Postgres driver accepts. Without it, asyncpg refuses the value on every page reached by a cursor. A column that needs no cast is text, or an integer that arrives as a number.
Keys
The service supplies the key; this library reads no environment. A key is at least 32 bytes. During a rotation, set the old key in keys.previous: new cursors sign with current and both verify (S13-3).
Wire format
base64url(payload).base64url(signature). The payload is canonical JSON: b (SHA-256 of the binding), d (direction), e (expiry in seconds), p (position) and v (1). The signature is HMAC-SHA-256 over nodii.pagination.v1. plus the encoded payload. The binding hash covers the operation, tenant, normalised filters, q and sort, so the token shows none of them. Cursors last 24 hours unless ttlSeconds says otherwise.
Parity
scripts/parity/pagination-cases.json holds the shared vectors; run bun scripts/parity/gen-pagination-cases.ts to regenerate them. synthetic-consumers/pagination/parity-fence boots all three ports against real Postgres and compares every response byte for byte.
What the fence does not prove
The fence covers REST. gRPC parsing and each refusal's name are covered by the shared vectors, which grpc-interceptors reads too; no test drives a refusal through a full server with that interceptor. The fence's consumers use a superuser pool with a tenant column, so it does not exercise RLS or one-transaction reads: the first adopter proves those.
One known limit
When deletes empty a page reached by a cursor, the previous_cursor of that empty page starts strictly before the old position, so a row at that exact position is not shown on the way back.
