Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadDetailCursor.ts

62 lines2.6 KB

1import type { ThreadId } from "@t3tools/contracts";
2​
3/**
4 * Opaque, exclusive cursor for windowed thread detail reads. Encodes the thread
5 * id and the keyset boundary of an already-delivered page: the boundary turn's
6 * anchor timestamp (`COALESCE(requested_at, started_at, '')`) and turn id.
7 * Passing it back requests the adjacent disjoint slice of strictly older turns
8 * under `(anchor, turn_id)` ordering.
9 *
10 * The boundary is deliberately NOT a `projection_turns.row_id`: row ids are
11 * rewritten by the revert projector (delete + re-upsert) and by projection
12 * rebuilds, which would silently invalidate every persisted cursor with no
13 * event emitted. The (anchor, turnId) pair is derived from event content, so
14 * cursors survive both and no client-side refresh machinery is needed. The
15 * anchor doubles as the time bound for rows with no turn linkage (straggler
16 * user messages, turnless activities). The thread id is embedded so a cursor
17 * can never be replayed against a different thread. Clients must treat the
18 * string as opaque.
19 */
20export interface ThreadDetailPageCursor {
21 readonly threadId: ThreadId;
22 readonly beforeAnchorAt: string;
23 /** Boundary turn id; "" for the rare turn row with a null turn_id. */
24 readonly beforeTurnId: string;
26​
27export function encodeThreadDetailPageCursor(cursor: ThreadDetailPageCursor): string {
28 return Buffer.from(
29 JSON.stringify({ t: cursor.threadId, a: cursor.beforeAnchorAt, i: cursor.beforeTurnId }),
30 ).toString("base64url");
32​
33/**
34 * Returns null for anything that is not a well-formed cursor. Callers degrade
35 * a malformed or foreign-thread cursor to a first-page request.
36 */
37export function decodeThreadDetailPageCursor(encoded: string): ThreadDetailPageCursor | null {
38 let parsed: unknown;
39 try {
40 parsed = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
41 } catch {
42 return null;
43 }
44 if (parsed === null || typeof parsed !== "object") {
45 return null;
46 }
47 const record = parsed as Record<string, unknown>;
48 if (typeof record.t !== "string" || record.t.length === 0) {
49 return null;
50 }
51 // Empty strings are valid boundary values, not malformed input: the anchor
52 // is COALESCE(requested_at, started_at, ''), so a boundary turn with no
53 // timestamps encodes a: "" (and sorts before every real anchor, correctly
54 // ending the walk); the turn key is "" for a null turn_id.
55 if (typeof record.a !== "string") {
56 return null;
57 }
58 if (typeof record.i !== "string") {
59 return null;
60 }
61 return { threadId: record.t as ThreadId, beforeAnchorAt: record.a, beforeTurnId: record.i };