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

tanStackSourceListing.ts

146 lines6.1 KB

1import * as Effect from "effect/Effect";
2import * as Base64Url from "effect/encoding/Base64Url";
3import * as Result from "effect/Result";
4​
5/** A row of a Source listing, which comes newest first by creation within one state. */
6export interface ListedRow {
7 readonly createdAt: number;
8 readonly number: number;
9}
10​
11/**
12 * Where a listing carries on: the last row handed over, and per state the Source page to read
13 * from next. A state's page is re-read from where its first undelivered row was, so nothing
14 * between pages is skipped; `""` is the first page and `null` means the state has nothing more.
15 */
16const FIRST_PAGE = "";
17​
18interface ListCursor {
19 readonly after: { readonly createdAt: number; readonly number: number } | null;
20 readonly pages: Readonly<Record<string, string | null>>;
22​
23/**
24 * Written in the alphabet pull request list cursors allow (`[\w.:~+-]`, which the service checks)
25 * as `<createdAt>.<number>` or `_`, then `~<state>:<page>` per state: `-` for ended, `0` for the
26 * first page, else `p` and the Source page token in base64url.
27 */
28export function encodeCursor(cursor: ListCursor): string {
29 const after = cursor.after === null ? "_" : `${cursor.after.createdAt}.${cursor.after.number}`;
30 const pages = Object.entries(cursor.pages).map(
31 ([state, page]) =>
32 `~${state}:${page === null ? "-" : page === FIRST_PAGE ? "0" : `p${Base64Url.encode(page)}`}`,
33 );
34 return `${after}${pages.join("")}`;
36​
37export function decodeCursor(raw: string): ListCursor | null {
38 const [head, ...states] = raw.split("~");
39 const position = /^(\d+)\.(\d+)$/u.exec(head ?? "");
40 if (head !== "_" && position === null) return null;
41 const pages: Record<string, string | null> = {};
42 for (const entry of states) {
43 const match = /^([a-z]+):(-|0|p[\w-]*)$/u.exec(entry);
44 if (match === null) return null;
45 const value = match[2]!;
46 if (value === "-") pages[match[1]!] = null;
47 else if (value === "0") pages[match[1]!] = FIRST_PAGE;
48 else {
49 const decoded = Base64Url.decodeString(value.slice(1));
50 if (Result.isFailure(decoded)) return null;
51 pages[match[1]!] = decoded.success;
52 }
53 }
54 return {
55 after:
56 position === null ? null : { createdAt: Number(position[1]), number: Number(position[2]) },
57 pages,
58 };
60​
61const newer = (a: ListedRow, b: ListedRow) =>
62 a.createdAt > b.createdAt || (a.createdAt === b.createdAt && a.number > b.number);
63​
64/**
65 * Reads `states` (Source lists open and closed apart) and merges them newest first. A row is
66 * handed over only once every state that has more pages has been read past it, so a later page
67 * can never hold a row that belonged earlier. The cursor survives rows above it closing.
68 */
69export const readMerged = Effect.fn("TanStackSourceListing.readMerged")(function* <
70 A extends ListedRow,
71 E,
72>(input: {
73 readonly states: ReadonlyArray<string>;
74 readonly cursor: string | undefined;
75 readonly limit: number;
76 readonly maxPages: number;
77 readonly readPage: (
78 state: string,
79 page: string | null,
80 ) => Effect.Effect<{ readonly items: ReadonlyArray<A>; readonly next: string | null }, E>;
81 /** Rows a host-side filter could not exclude. Dropped rows still move the cursor. */
82 readonly keep?: (row: A) => boolean;
83}) {
84 const resumed: ListCursor | null = input.cursor === undefined ? null : decodeCursor(input.cursor);
85 const after = resumed?.after ?? null;
86 const isNew = (row: A) => after === null || newer(after, row);
87 const reads = yield* Effect.forEach(
88 input.states.filter((state) => resumed === null || resumed.pages[state] !== null),
89 Effect.fnUntraced(function* (state) {
90 let page: string = resumed?.pages[state] ?? FIRST_PAGE;
91 const rows: Array<{ readonly row: A; readonly page: string }> = [];
92 let oldest: A | undefined;
93 let pages = 0;
94 let next: string | null = null;
95 do {
96 const read: { readonly items: ReadonlyArray<A>; readonly next: string | null } =
97 yield* input.readPage(state, page === FIRST_PAGE ? null : page);
98 pages += 1;
99 for (const row of read.items) if (isNew(row)) rows.push({ row, page });
100 oldest = read.items.at(-1) ?? oldest;
101 next = read.items.length === 0 ? null : read.next;
102 if (next !== null) page = next;
103 } while (next !== null && rows.length <= input.limit && pages < input.maxPages);
104 return { state, rows, next, oldest };
105 }),
106 { concurrency: "unbounded" },
107 );
108 // Rows older than the oldest one read from a state that has more may yet be beaten by its next
109 // page, so they wait for a later call.
110 const unfinished = reads.filter((read) => read.next !== null && read.oldest !== undefined);
111 const cutoff = unfinished.reduce<A | undefined>(
112 (latest, read) => (latest === undefined || newer(read.oldest!, latest) ? read.oldest : latest),
113 undefined,
114 );
115 const seen = new Set<number>();
116 const merged = reads
117 .flatMap((read) => read.rows.map((entry) => ({ ...entry, state: read.state })))
118 .filter((entry) => cutoff === undefined || !newer(cutoff, entry.row))
119 .toSorted((a, b) => (newer(a.row, b.row) ? -1 : newer(b.row, a.row) ? 1 : 0))
120 // A row that changed state between the reads of two states is in both; it is one row.
121 .filter((entry) => !seen.has(entry.row.number) && seen.add(entry.row.number) !== undefined);
122 const keep = input.keep ?? (() => true);
123 const delivered: Array<(typeof merged)[number]> = [];
124 let consumed = 0;
125 for (const entry of merged) {
126 if (delivered.length >= input.limit) break;
127 consumed += 1;
128 if (keep(entry.row)) delivered.push(entry);
129 }
130 const last = merged[consumed - 1]?.row;
131 const pages: Record<string, string | null> = { ...resumed?.pages };
132 for (const read of reads) {
133 const pending = read.rows.find(({ row }) => last === undefined || newer(last, row));
134 pages[read.state] = pending !== undefined ? pending.page : read.next;
135 }
136 const more = Object.values(pages).some((page) => page !== null) || consumed < merged.length;
137 return {
138 items: delivered.map((entry) => entry.row),
139 next: more
140 ? encodeCursor({
141 after: last === undefined ? after : { createdAt: last.createdAt, number: last.number },
142 pages,
143 })
144 : null,
145 };
146});