|
| 1 | +/** |
| 2 | + * Complete, verified reads for platform-wide sweeps (issue #533). |
| 3 | + * |
| 4 | + * PostgREST caps every response at the project's configured API "Max rows" |
| 5 | + * (`supabase/config.toml:18` sets `max_rows = 1000` locally; the cloud project |
| 6 | + * carries no `pgrst.db_max_rows` role override, so it runs on Supabase's |
| 7 | + * hosted default of 1000). A capped response is a plain 200 with fewer rows — |
| 8 | + * indistinguishable from a complete one. Any caller that reads a whole |
| 9 | + * relation and then does arithmetic over it therefore produces a confidently |
| 10 | + * wrong number rather than an error: `getPayoutsOwed()` underpaid a school |
| 11 | + * when `transactions` truncated and overpaid it when `payouts` did, and the |
| 12 | + * `enforce-plan-limits` cron silently stopped visiting tenants past the cap. |
| 13 | + * |
| 14 | + * `fetchAllRows` pages until the relation is exhausted and then ASSERTS the |
| 15 | + * result is complete against PostgREST's own exact count, so a cap (or a |
| 16 | + * future change to it) surfaces as a thrown error instead of a quiet |
| 17 | + * shortfall. Nothing here depends on the cap's value: the page size is ours, |
| 18 | + * and the assertion is what actually guarantees completeness. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * Rows requested per page. Deliberately below the 1000 cap so the common case |
| 23 | + * never brushes against it — but the loop does not rely on that: a server |
| 24 | + * configured lower simply hands back shorter pages, and `fetchAllRows` adopts |
| 25 | + * the size it actually got (see below) rather than mistaking a capped page for |
| 26 | + * the end of the relation. Nothing here breaks if the cap is changed. |
| 27 | + */ |
| 28 | +export const FETCH_ALL_PAGE_SIZE = 500 |
| 29 | + |
| 30 | +/** |
| 31 | + * Runaway guard — a backstop against a server that keeps returning full pages |
| 32 | + * forever, and against a pathologically small cap turning a big relation into |
| 33 | + * an unbounded request storm. At the default page size this covers 1,000,000 |
| 34 | + * rows, far past anything these sweeps read. |
| 35 | + */ |
| 36 | +const MAX_PAGES = 2000 |
| 37 | + |
| 38 | +/** The shape of a `count: 'exact'` PostgREST response, narrowed to what this helper reads. */ |
| 39 | +interface CountedPage<T> { |
| 40 | + data: T[] | null |
| 41 | + error: { message: string } | null |
| 42 | + count: number | null |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Read every row of a query, verifying nothing was silently dropped. |
| 47 | + * |
| 48 | + * The caller builds one page per call. Two requirements, both load-bearing: |
| 49 | + * |
| 50 | + * - **`{ count: 'exact' }` on the select.** It is what the completeness |
| 51 | + * assertion compares against; without it there is nothing to verify and the |
| 52 | + * helper degrades to a plain paging loop. |
| 53 | + * - **A stable `.order()` on a unique column** (a primary key). `.range()` |
| 54 | + * windows over an unordered relation may overlap or skip rows between |
| 55 | + * requests, which would trade a truncation bug for a duplication bug. |
| 56 | + * |
| 57 | + * ```ts |
| 58 | + * const txns = await fetchAllRows('transactions', (from, to) => |
| 59 | + * admin |
| 60 | + * .from('transactions') |
| 61 | + * .select('tenant_id, amount', { count: 'exact' }) |
| 62 | + * .eq('status', 'successful') |
| 63 | + * .order('transaction_id') |
| 64 | + * .range(from, to) |
| 65 | + * ) |
| 66 | + * ``` |
| 67 | + * |
| 68 | + * @param relation Name used in error messages — the operator needs to know |
| 69 | + * which read came up short. |
| 70 | + * @throws if a page errors, if the relation is larger than `MAX_PAGES` pages, |
| 71 | + * or if fewer rows were collected than the server said exist. |
| 72 | + */ |
| 73 | +export async function fetchAllRows<T>( |
| 74 | + relation: string, |
| 75 | + page: (from: number, to: number) => PromiseLike<CountedPage<T>>, |
| 76 | + pageSize: number = FETCH_ALL_PAGE_SIZE, |
| 77 | +): Promise<T[]> { |
| 78 | + const rows: T[] = [] |
| 79 | + /** |
| 80 | + * The count reported by the FIRST page — a snapshot of the relation as the |
| 81 | + * sweep started. Later pages report a moving total under concurrent writes; |
| 82 | + * comparing against the snapshot keeps the assertion about truncation rather |
| 83 | + * than about how busy the table is. |
| 84 | + */ |
| 85 | + let expected: number | null = null |
| 86 | + /** |
| 87 | + * Shrinks to whatever the server is actually willing to return. PostgREST |
| 88 | + * applies "Max rows" to each ranged request too, so asking for a window |
| 89 | + * wider than the cap yields a short page that is NOT the end of the relation. |
| 90 | + * Adopting the observed size makes the loop correct for any cap without |
| 91 | + * knowing its value. |
| 92 | + */ |
| 93 | + let effectivePageSize = pageSize |
| 94 | + |
| 95 | + for (let request = 0; request < MAX_PAGES; request++) { |
| 96 | + // Offset by rows already collected rather than by page index: it stays |
| 97 | + // correct after `effectivePageSize` shrinks mid-sweep. |
| 98 | + const from = rows.length |
| 99 | + const { data, error, count } = await page(from, from + effectivePageSize - 1) |
| 100 | + if (error) { |
| 101 | + throw new Error(`fetchAllRows(${relation}): page at offset ${from} failed — ${error.message}`) |
| 102 | + } |
| 103 | + if (request === 0) expected = count |
| 104 | + |
| 105 | + const batch = data ?? [] |
| 106 | + rows.push(...batch) |
| 107 | + |
| 108 | + if (batch.length < effectivePageSize) { |
| 109 | + // Short page. Either the relation is exhausted, or the server capped this |
| 110 | + // request below what we asked for. The count settles it: if rows are |
| 111 | + // still owed and the server just proved it can return `batch.length` at a |
| 112 | + // time, keep going at that size. An empty page means it can return |
| 113 | + // nothing more, and the assertion below turns that into a loud error. |
| 114 | + if (expected != null && rows.length < expected && batch.length > 0) { |
| 115 | + effectivePageSize = batch.length |
| 116 | + continue |
| 117 | + } |
| 118 | + assertComplete(relation, rows.length, expected) |
| 119 | + return rows |
| 120 | + } |
| 121 | + // An exactly-full page is ambiguous — the next one may be empty — so we |
| 122 | + // always ask again. The trailing empty request is expected, not wasteful. |
| 123 | + } |
| 124 | + |
| 125 | + throw new Error( |
| 126 | + `fetchAllRows(${relation}): still returning full pages after ${MAX_PAGES} requests ` + |
| 127 | + `(${rows.length} rows); refusing to loop further.`, |
| 128 | + ) |
| 129 | +} |
| 130 | + |
| 131 | +/** |
| 132 | + * The last line of defence. Collecting FEWER rows than the server itself |
| 133 | + * reported is the failure this module exists to catch: the loop above handles |
| 134 | + * the ordinary row cap, so a shortfall here means something else ate rows — the |
| 135 | + * server refusing to return any more, or rows deleted mid-sweep shifting the |
| 136 | + * offsets. Either way the caller's totals would be wrong, so it gets an error |
| 137 | + * instead of a number. |
| 138 | + * |
| 139 | + * Collecting MORE is benign: rows inserted while the sweep ran. Treating that |
| 140 | + * as corruption would fail the platform payouts page whenever a sale lands |
| 141 | + * mid-render. |
| 142 | + */ |
| 143 | +function assertComplete(relation: string, fetched: number, expected: number | null) { |
| 144 | + if (expected == null) return |
| 145 | + if (fetched < expected) { |
| 146 | + throw new Error( |
| 147 | + `fetchAllRows(${relation}): incomplete read — fetched ${fetched} of ${expected} rows. ` + |
| 148 | + `Any total computed from this would be silently wrong, so nothing is returned.`, |
| 149 | + ) |
| 150 | + } |
| 151 | +} |
0 commit comments