@yaks/d1 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/read.ts ADDED
@@ -0,0 +1,169 @@
1
+ // Reads: a query in, whole entities out. The compile half is the sibling
2
+ // packages' — @yaks/query parses the query text, @yaks/vocab describes the
3
+ // vocabulary, @yaks/sql compiles the two into a statement — and the per-
4
+ // component gather is @yaks/sqlite's `compSql`, so a property that the filter
5
+ // resolves one way cannot come back gathered another.
6
+ //
7
+ // What is this package's own is the number of round trips. @yaks/sqlite runs
8
+ // one statement at a time, because an embedded engine answers in microseconds;
9
+ // over D1 every statement is a network hop, so reading one component at a time
10
+ // would cost a hop per component per entity. Here the whole gather —
11
+ // every entity's spine, every entity's components — is built as one list of
12
+ // statements and sent as a single `batch()`. A read of any size takes two round
13
+ // trips: the compiled query, then the read of the components.
14
+ //
15
+ // Two, because the second list has to bind the eids the first one found. When
16
+ // those eids do not need binding — when the query that found them can simply be
17
+ // repeated as a subquery — the two collapse into one: `wholeSql` puts the
18
+ // query, the `entity` rows it matches and every component of them into a single
19
+ // batch, each statement ending `where o.eid in (<the query>)`. That is what
20
+ // @yaks/graph's `Tx.whole` asks for, and it is why an `about` read costs one
21
+ // trip rather than two. The cost is that the filter is evaluated once per
22
+ // component instead of once in total, which is why it is offered for a query
23
+ // naming a set and not for `read`, where a `.limit` re-evaluated per statement
24
+ // could break a tie differently each time.
25
+
26
+ import { type And, parse } from '@yaks/query'
27
+ import {
28
+ among,
29
+ type BindOpts,
30
+ col,
31
+ compile,
32
+ eq,
33
+ from,
34
+ type Raw,
35
+ select,
36
+ type Stmt,
37
+ val,
38
+ } from '@yaks/sql'
39
+ import { compSql, decoded, OWNER, setSql, spine } from '@yaks/sqlite'
40
+ import type { Bundle, Comp, Entity } from 'jsr:@yaks/graph@0.2.36'
41
+ import { tombstoned } from '@yaks/graph/bundle'
42
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
43
+ import type { Row } from './d1.ts'
44
+
45
+ /** A query, as text or as an already-built AST. Text is parsed; an AST passes
46
+ * through, so a caller may hand-build one with @yaks/query's builders. */
47
+ export type Query = string | And
48
+
49
+ export let ast = (q: Query): And => typeof q == 'string' ? parse(q) : q
50
+
51
+ /** The compiled statement for a query. */
52
+ export let sql = (v: Vocab, query: Query, opts: BindOpts = {}): Raw =>
53
+ compile(ast(query), v, opts)
54
+
55
+ /** The identity of an eid, as stored: its `num`, and whether it is buried. One
56
+ * statement, so a gather of many entities is one batch. */
57
+ export let spineSql = (v: Vocab, eid: string): Stmt =>
58
+ spine(v, eq(col('eid', 'e'), val(eid)))
59
+
60
+ /** What a gather asks about one entity: its spine, then one read per component
61
+ * the vocabulary declares, or per one of those `names` names. The order is
62
+ * what {@link bundles} reads back. */
63
+ export let gatherSql = (
64
+ v: Vocab,
65
+ eid: string,
66
+ opts: BindOpts = {},
67
+ names?: string[],
68
+ ): Stmt[] => [
69
+ spineSql(v, eid),
70
+ ...comps(v, names).map((comp) => compSql(v, comp, eid, opts.derived)),
71
+ ]
72
+
73
+ /** The components a gather reads, in the vocabulary's order: every one, or
74
+ * those `names` names — the spine is the identity, not a component of its
75
+ * own. */
76
+ export let comps = (v: Vocab, names?: string[]): string[] =>
77
+ v.all.filter((name) => name != 'entity' && (!names || names.includes(name)))
78
+
79
+ // One entity's answers, turned back into a bundle. The results arrive in the
80
+ // order `gatherSql` asked: the spine first, then a component per statement.
81
+ let bundleOf = (
82
+ v: Vocab,
83
+ eid: string,
84
+ answers: Row[][],
85
+ names?: string[],
86
+ ): Bundle | undefined => {
87
+ let spine = answers[0][0]
88
+ if (!spine) return undefined
89
+ let entity: Entity = {
90
+ eid,
91
+ ...(spine.num == null ? {} : { num: Number(spine.num) }),
92
+ }
93
+ if (spine.dead != null) return tombstoned(entity)
94
+ let out: Bundle = { entity }
95
+ comps(v, names).forEach((comp, i) => {
96
+ let row = answers[i + 1][0]
97
+ if (!row) return
98
+ delete row.present
99
+ out[comp] = decoded(v, comp, row) as Comp
100
+ })
101
+ return out
102
+ }
103
+
104
+ /**
105
+ * Turn the answers to a gather back into bundles, one per eid, in the order the
106
+ * eids were asked about. An eid no entity has is simply absent; a tombstoned
107
+ * one comes back carrying `tombstone` (it is still an identity, just a dead one).
108
+ *
109
+ * `answers` is the flat result list `batch()` returns for
110
+ * `eids.flatMap((e) => gatherSql(v, e, opts, names))` — one entry per
111
+ * statement, in order.
112
+ */
113
+ export let bundles = (
114
+ v: Vocab,
115
+ eids: string[],
116
+ answers: Row[][],
117
+ names?: string[],
118
+ ): Bundle[] => {
119
+ let width = comps(v, names).length + 1
120
+ return eids.flatMap((eid, i) => {
121
+ let b = bundleOf(v, eid, answers.slice(i * width, (i + 1) * width), names)
122
+ return b ? [b] : []
123
+ })
124
+ }
125
+
126
+ /**
127
+ * What a whole read asks, as one batch: the compiled query first — it names the
128
+ * hits and fixes their order — then the spine of everything it hits, then one
129
+ * statement per component over that same set. Nothing binds an eid: each
130
+ * statement repeats the query as a subquery, which is what lets the whole read
131
+ * come back in a single round trip. {@link whole} reads it back.
132
+ */
133
+ export let wholeSql = (v: Vocab, q: Raw, opts: BindOpts = {}): Stmt[] => {
134
+ let hits = select({ cols: [col('eid')], from: from(q) })
135
+ return [
136
+ q,
137
+ spine(v, among(col('eid', 'e'), hits)),
138
+ ...comps(v).map((comp) => setSql(v, comp, hits, opts.derived)),
139
+ ]
140
+ }
141
+
142
+ /**
143
+ * Turn those answers back into bundles: the hits in the order the query named
144
+ * them, each whole. Same shape as {@link bundles}, keyed by the owner column
145
+ * each set-shaped statement carries rather than by position.
146
+ */
147
+ export let whole = (v: Vocab, answers: Row[][]): Bundle[] => {
148
+ let [hits, spines, ...parts] = answers
149
+ let out = new Map<string, Bundle>()
150
+ for (let r of spines) {
151
+ let entity: Entity = {
152
+ eid: String(r.eid),
153
+ ...(r.num == null ? {} : { num: Number(r.num) }),
154
+ }
155
+ out.set(entity.eid, r.dead == null ? { entity } : tombstoned(entity))
156
+ }
157
+ comps(v).forEach((comp, i) => {
158
+ for (let row of parts[i] ?? []) {
159
+ let b = out.get(String(row[OWNER]))
160
+ delete row[OWNER]
161
+ delete row.present
162
+ if (b && b.tombstone == null) b[comp] = decoded(v, comp, row) as Comp
163
+ }
164
+ })
165
+ return hits.flatMap((r) => {
166
+ let b = r.eid == null ? undefined : out.get(String(r.eid))
167
+ return b ? [b] : []
168
+ })
169
+ }
package/receipt.js ADDED
@@ -0,0 +1,154 @@
1
+ import { mint } from "@yaks/graph/mint";
2
+ import { among, and, col, eq, fn, lit, lt, select, table, val } from "@yaks/sql";
3
+ import { retry } from "./retry.js";
4
+ let RECEIPT = 'yak_d1_receipt';
5
+ let KEEP = 86_400_000;
6
+ let SCHEMA = [
7
+ {
8
+ t: 'create table',
9
+ name: RECEIPT,
10
+ ifNot: true,
11
+ cols: [
12
+ {
13
+ name: 'op',
14
+ type: 'text',
15
+ notNull: true
16
+ },
17
+ {
18
+ name: 'pos',
19
+ type: 'integer',
20
+ notNull: true
21
+ },
22
+ {
23
+ name: 'at',
24
+ type: 'integer',
25
+ notNull: true
26
+ },
27
+ {
28
+ name: 'num',
29
+ type: 'integer'
30
+ }
31
+ ],
32
+ keys: [
33
+ {
34
+ pk: [
35
+ 'op',
36
+ 'pos'
37
+ ]
38
+ }
39
+ ]
40
+ },
41
+ {
42
+ t: 'create index',
43
+ name: 'yak_d1_receipt_at',
44
+ on: RECEIPT,
45
+ ifNot: true,
46
+ cols: [
47
+ col('at')
48
+ ]
49
+ }
50
+ ];
51
+ let record = (op, at)=>({
52
+ t: 'insert',
53
+ into: RECEIPT,
54
+ cols: [
55
+ 'op',
56
+ 'pos',
57
+ 'at'
58
+ ],
59
+ rows: [
60
+ [
61
+ val(op),
62
+ lit(-1),
63
+ val(at)
64
+ ]
65
+ ]
66
+ });
67
+ let expire = (at)=>({
68
+ t: 'delete',
69
+ from: RECEIPT,
70
+ where: among(col('rowid'), select({
71
+ cols: [
72
+ col('rowid')
73
+ ],
74
+ from: table(RECEIPT),
75
+ where: lt(col('at'), val(at - KEEP)),
76
+ limit: lit(100)
77
+ }))
78
+ });
79
+ // Capture the mint's answer before anything else can change or remove it.
80
+ // changes() is zero if the preceding mint found an existing eid.
81
+ let capture = (op, at, pos, eid)=>({
82
+ t: 'insert',
83
+ into: RECEIPT,
84
+ cols: [
85
+ 'op',
86
+ 'pos',
87
+ 'at',
88
+ 'num'
89
+ ],
90
+ q: select({
91
+ cols: [
92
+ val(op),
93
+ val(pos),
94
+ val(at),
95
+ col('num')
96
+ ],
97
+ from: table('entity'),
98
+ where: and(eq(col('eid'), val(eid)), eq(fn('changes'), lit(1)))
99
+ })
100
+ });
101
+ let recorded = (op)=>select({
102
+ cols: [
103
+ col('pos'),
104
+ col('num')
105
+ ],
106
+ from: table(RECEIPT),
107
+ where: eq(col('op'), val(op))
108
+ });
109
+ let duplicate = (e)=>String(e).includes(`UNIQUE constraint failed: ${RECEIPT}.op, ${RECEIPT}.pos`);
110
+ /** Commit a graph write once, including DDL and deletes that can't be replayed
111
+ * over newer state. The receipt's unique insert comes first, so a duplicate
112
+ * aborts the batch before any mutation. Only mint answers are consumed by the
113
+ * graph write path, so those are the answers the receipt keeps. */ export let writer = (db, prep, clock)=>{
114
+ let ready = false;
115
+ return async (stmts, births)=>{
116
+ let op = mint(), at = clock.now();
117
+ let head = [
118
+ ...ready ? [] : SCHEMA,
119
+ record(op, at),
120
+ expire(at)
121
+ ];
122
+ let positions = new Map();
123
+ let bound = head.map(prep);
124
+ stmts.forEach((s, pos)=>{
125
+ let eid = births?.get(pos);
126
+ if (eid != null) positions.set(pos, bound.length);
127
+ bound.push(prep(s));
128
+ if (eid != null) bound.push(prep(capture(op, at, pos, eid)));
129
+ });
130
+ let lookup = prep(recorded(op));
131
+ let answer = await retry(async ()=>{
132
+ try {
133
+ let out = await db.batch(bound);
134
+ let nums = new Map();
135
+ for (let [pos, at] of positions){
136
+ let row = out[at].results[0];
137
+ if (row) nums.set(pos, row.num == null ? null : Number(row.num));
138
+ }
139
+ return nums;
140
+ } catch (e) {
141
+ if (!duplicate(e)) throw e;
142
+ let { results } = await lookup.all();
143
+ if (!results.some((r)=>r.pos == -1)) throw e;
144
+ return new Map(results.filter((r)=>r.pos >= 0).map((r)=>[
145
+ r.pos,
146
+ r.num
147
+ ]));
148
+ }
149
+ }, undefined, clock);
150
+ ready = true;
151
+ return answer;
152
+ };
153
+ };
154
+ //# sourceMappingURL=receipt.js.map
package/receipt.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"receipt.js","sources":["./receipt.ts"],"names":[],"mappings":"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"}
package/receipt.ts ADDED
@@ -0,0 +1,139 @@
1
+ import type { Clock } from 'jsr:@yaks/fp@0.2.36'
2
+ import { mint } from '@yaks/graph/mint'
3
+ import {
4
+ among,
5
+ and,
6
+ col,
7
+ eq,
8
+ fn,
9
+ lit,
10
+ lt,
11
+ select,
12
+ type Stmt,
13
+ table,
14
+ val,
15
+ } from '@yaks/sql'
16
+ import type { D1Like, Prepared } from './d1.ts'
17
+ import { retry } from './retry.js'
18
+
19
+ let RECEIPT = 'yak_d1_receipt'
20
+ let KEEP = 86_400_000
21
+ let SCHEMA: Stmt[] = [
22
+ {
23
+ t: 'create table',
24
+ name: RECEIPT,
25
+ ifNot: true,
26
+ cols: [
27
+ { name: 'op', type: 'text', notNull: true },
28
+ { name: 'pos', type: 'integer', notNull: true },
29
+ { name: 'at', type: 'integer', notNull: true },
30
+ { name: 'num', type: 'integer' },
31
+ ],
32
+ keys: [{ pk: ['op', 'pos'] }],
33
+ },
34
+ {
35
+ t: 'create index',
36
+ name: 'yak_d1_receipt_at',
37
+ on: RECEIPT,
38
+ ifNot: true,
39
+ cols: [col('at')],
40
+ },
41
+ ]
42
+
43
+ let record = (op: string, at: number): Stmt => ({
44
+ t: 'insert',
45
+ into: RECEIPT,
46
+ cols: ['op', 'pos', 'at'],
47
+ rows: [[val(op), lit(-1), val(at)]],
48
+ })
49
+
50
+ let expire = (at: number): Stmt => ({
51
+ t: 'delete',
52
+ from: RECEIPT,
53
+ where: among(
54
+ col('rowid'),
55
+ select({
56
+ cols: [col('rowid')],
57
+ from: table(RECEIPT),
58
+ where: lt(col('at'), val(at - KEEP)),
59
+ limit: lit(100),
60
+ }),
61
+ ),
62
+ })
63
+
64
+ // Capture the mint's answer before anything else can change or remove it.
65
+ // changes() is zero if the preceding mint found an existing eid.
66
+ let capture = (op: string, at: number, pos: number, eid: string): Stmt => ({
67
+ t: 'insert',
68
+ into: RECEIPT,
69
+ cols: ['op', 'pos', 'at', 'num'],
70
+ q: select({
71
+ cols: [val(op), val(pos), val(at), col('num')],
72
+ from: table('entity'),
73
+ where: and(eq(col('eid'), val(eid)), eq(fn('changes'), lit(1))),
74
+ }),
75
+ })
76
+
77
+ let recorded = (op: string): Stmt =>
78
+ select({
79
+ cols: [col('pos'), col('num')],
80
+ from: table(RECEIPT),
81
+ where: eq(col('op'), val(op)),
82
+ })
83
+
84
+ let duplicate = (e: unknown): boolean =>
85
+ String(e).includes(`UNIQUE constraint failed: ${RECEIPT}.op, ${RECEIPT}.pos`)
86
+
87
+ /** Commit a graph write once, including DDL and deletes that can't be replayed
88
+ * over newer state. The receipt's unique insert comes first, so a duplicate
89
+ * aborts the batch before any mutation. Only mint answers are consumed by the
90
+ * graph write path, so those are the answers the receipt keeps. */
91
+ export let writer = <S extends Prepared<S>>(
92
+ db: D1Like<S>,
93
+ prep: (s: Stmt) => S,
94
+ clock: Clock,
95
+ ) => {
96
+ let ready = false
97
+ return async (
98
+ stmts: readonly Stmt[],
99
+ births?: ReadonlyMap<number, string>,
100
+ ): Promise<Map<number, number | null>> => {
101
+ let op = mint(), at = clock.now()
102
+ let head = [...ready ? [] : SCHEMA, record(op, at), expire(at)]
103
+ let positions = new Map<number, number>()
104
+ let bound = head.map(prep)
105
+ stmts.forEach((s, pos) => {
106
+ let eid = births?.get(pos)
107
+ if (eid != null) positions.set(pos, bound.length)
108
+ bound.push(prep(s))
109
+ if (eid != null) bound.push(prep(capture(op, at, pos, eid)))
110
+ })
111
+ let lookup = prep(recorded(op))
112
+ let answer = await retry(
113
+ async () => {
114
+ try {
115
+ let out = await db.batch(bound)
116
+ let nums = new Map<number, number | null>()
117
+ for (let [pos, at] of positions) {
118
+ let row = out[at].results[0]
119
+ if (row) nums.set(pos, row.num == null ? null : Number(row.num))
120
+ }
121
+ return nums
122
+ } catch (e) {
123
+ if (!duplicate(e)) throw e
124
+ let { results } = await lookup.all<
125
+ { pos: number; num: number | null }
126
+ >()
127
+ if (!results.some((r) => r.pos == -1)) throw e
128
+ return new Map(
129
+ results.filter((r) => r.pos >= 0).map((r) => [r.pos, r.num]),
130
+ )
131
+ }
132
+ },
133
+ undefined,
134
+ clock,
135
+ )
136
+ ready = true
137
+ return answer
138
+ }
139
+ }
package/retry.js ADDED
@@ -0,0 +1,74 @@
1
+ import { sleep, system } from "@yaks/fp";
2
+ // The D1 errors whose recommended action is "Retry the operation", from the
3
+ // List of D1_ERRORs in Cloudflare's docs
4
+ // (https://developers.cloudflare.com/d1/observability/debug-d1/#error-list).
5
+ // The rest there — an overloaded database, a query past its time, memory or
6
+ // size limits, a missing column — are a query or a quota to fix, not a moment
7
+ // to wait out.
8
+ let TRANSIENT = [
9
+ 'd1 db reset because its code was updated',
10
+ 'internal error while starting up d1 db storage caused object to be reset',
11
+ 'network connection lost',
12
+ 'replica disconnected from primary',
13
+ 'internal error in d1 db storage caused object to be reset',
14
+ 'cannot resolve d1 db due to transient issue on remote node',
15
+ "can't read from request stream because client disconnected"
16
+ ];
17
+ // The runtime failing inside itself, naming only a reference for Cloudflare
18
+ // to look up (`D1_ERROR: internal error; reference = …`). D1's list does not
19
+ // name it, and nothing in the query can be fixed for it; the statements here
20
+ // are safe to run twice, so it is tried again like the ones the list names,
21
+ // and one that persists through every try is still reported.
22
+ let OPAQUE = /(?:^|: )internal error(?:; reference = [\w-]+)?\.?$/;
23
+ /** Whether this failure is one to try again: one D1 says to retry, or the
24
+ * runtime's own internal error. */ export let transient = (e)=>{
25
+ let message = String(e).toLowerCase();
26
+ return TRANSIENT.some((said)=>message.includes(said)) || OPAQUE.test(message);
27
+ };
28
+ // D1 cannot cancel an in-flight call, so every send here must be replayable.
29
+ // A caller's deadline bounds all attempts. Otherwise D1 sets the first
30
+ // attempt's timeout and recovery gets its own short window once D1 fails.
31
+ export let retryFor = 2_000;
32
+ let BACKOFF = [
33
+ 25,
34
+ 100,
35
+ 400
36
+ ];
37
+ let before = async (send, until, clock, expired)=>{
38
+ let left = until - clock.now();
39
+ if (left <= 0) throw expired;
40
+ let timeout = Promise.withResolvers();
41
+ let cancel = clock.after(left, ()=>timeout.reject(expired));
42
+ try {
43
+ let answer = await Promise.race([
44
+ send(),
45
+ timeout.promise
46
+ ]);
47
+ if (clock.now() >= until) throw expired;
48
+ return answer;
49
+ } finally{
50
+ cancel();
51
+ }
52
+ };
53
+ /** A caller's deadline passing before D1 answered. D1 cannot cancel the call,
54
+ * so it may still have run. */ export class Expired extends Error {
55
+ constructor(){
56
+ super('D1 operation exceeded its deadline');
57
+ }
58
+ }
59
+ export let retry = async (send, until, clock = system)=>{
60
+ let last = new Expired();
61
+ for(let attempt = 0;; attempt++){
62
+ try {
63
+ return await (until == null ? send() : before(send, until, clock, last));
64
+ } catch (e) {
65
+ if (attempt == BACKOFF.length || !transient(e)) throw e;
66
+ last = e;
67
+ }
68
+ until ??= clock.now() + retryFor;
69
+ let pause = BACKOFF[attempt] * (1 + Math.random());
70
+ if (clock.now() + pause >= until) throw last;
71
+ await sleep(pause, undefined, clock);
72
+ }
73
+ };
74
+ //# sourceMappingURL=retry.js.map
package/retry.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.js","sources":["./retry.ts"],"names":[],"mappings":"AAAA,SAAqB,KAAK,EAAE,MAAM,wBAA6B;AAE/D,4EAA4E;AAC5E,yCAAyC;AACzC,6EAA6E;AAC7E,4EAA4E;AAC5E,8EAA8E;AAC9E,eAAe;AACf,IAAI,YAAY;EACd;EACA;EACA;EACA;EACA;EACA;EACA;CACD;AAED,4EAA4E;AAC5E,6EAA6E;AAC7E,6EAA6E;AAC7E,4EAA4E;AAC5E,6DAA6D;AAC7D,IAAI,SAAS;AAEb;iCACiC,GACjC,OAAO,IAAI,YAAY,CAAC;EACtB,IAAI,UAAU,OAAO,GAAG,WAAW;EACnC,OAAO,UAAU,IAAI,CAAC,CAAC,OAAS,QAAQ,QAAQ,CAAC,UAC/C,OAAO,IAAI,CAAC;AAChB,EAAC;AAED,6EAA6E;AAC7E,uEAAuE;AACvE,0EAA0E;AAC1E,OAAO,IAAI,WAAW,MAAK;AAC3B,IAAI,UAAU;EAAC;EAAI;EAAK;CAAI;AAE5B,IAAI,SAAS,OACX,MACA,OACA,OACA;EAEA,IAAI,OAAO,QAAQ,MAAM,GAAG;EAC5B,IAAI,QAAQ,GAAG,MAAM;EACrB,IAAI,UAAU,QAAQ,aAAa;EACnC,IAAI,SAAS,MAAM,KAAK,CAAC,MAAM,IAAM,QAAQ,MAAM,CAAC;EACpD,IAAI;IACF,IAAI,SAAS,MAAM,QAAQ,IAAI,CAAC;MAAC;MAAQ,QAAQ,OAAO;KAAC;IACzD,IAAI,MAAM,GAAG,MAAM,OAAO,MAAM;IAChC,OAAO;EACT,SAAU;IACR;EACF;AACF;AAEA;6BAC6B,GAC7B,OAAO,MAAM,gBAAgB;EAC3B,aAAc;IACZ,KAAK,CAAC;EACR;AACF;AAEA,OAAO,IAAI,QAAQ,OACjB,MACA,OACA,QAAe,MAAM;EAErB,IAAI,OAAgB,IAAI;EACxB,IAAK,IAAI,UAAU,IAAI,UAAW;IAChC,IAAI;MACF,OAAO,MAAM,CAAC,SAAS,OAAO,SAAS,OAAO,MAAM,OAAO,OAAO,KAAK;IACzE,EAAE,OAAO,GAAG;MACV,IAAI,WAAW,QAAQ,MAAM,IAAI,CAAC,UAAU,IAAI,MAAM;MACtD,OAAO;IACT;IACA,UAAU,MAAM,GAAG,KAAK;IACxB,IAAI,QAAQ,OAAO,CAAC,QAAQ,GAAG,CAAC,IAAI,KAAK,MAAM,EAAE;IACjD,IAAI,MAAM,GAAG,KAAK,SAAS,OAAO,MAAM;IACxC,MAAM,MAAM,OAAO,WAAW;EAChC;AACF,EAAC"}
package/retry.ts ADDED
@@ -0,0 +1,85 @@
1
+ import { type Clock, sleep, system } from '@yaks/fp'
2
+
3
+ // The D1 errors whose recommended action is "Retry the operation", from the
4
+ // List of D1_ERRORs in Cloudflare's docs
5
+ // (https://developers.cloudflare.com/d1/observability/debug-d1/#error-list).
6
+ // The rest there — an overloaded database, a query past its time, memory or
7
+ // size limits, a missing column — are a query or a quota to fix, not a moment
8
+ // to wait out.
9
+ let TRANSIENT = [
10
+ 'd1 db reset because its code was updated',
11
+ 'internal error while starting up d1 db storage caused object to be reset',
12
+ 'network connection lost',
13
+ 'replica disconnected from primary',
14
+ 'internal error in d1 db storage caused object to be reset',
15
+ 'cannot resolve d1 db due to transient issue on remote node',
16
+ "can't read from request stream because client disconnected",
17
+ ]
18
+
19
+ // The runtime failing inside itself, naming only a reference for Cloudflare
20
+ // to look up (`D1_ERROR: internal error; reference = …`). D1's list does not
21
+ // name it, and nothing in the query can be fixed for it; the statements here
22
+ // are safe to run twice, so it is tried again like the ones the list names,
23
+ // and one that persists through every try is still reported.
24
+ let OPAQUE = /(?:^|: )internal error(?:; reference = [\w-]+)?\.?$/
25
+
26
+ /** Whether this failure is one to try again: one D1 says to retry, or the
27
+ * runtime's own internal error. */
28
+ export let transient = (e: unknown): boolean => {
29
+ let message = String(e).toLowerCase()
30
+ return TRANSIENT.some((said) => message.includes(said)) ||
31
+ OPAQUE.test(message)
32
+ }
33
+
34
+ // D1 cannot cancel an in-flight call, so every send here must be replayable.
35
+ // A caller's deadline bounds all attempts. Otherwise D1 sets the first
36
+ // attempt's timeout and recovery gets its own short window once D1 fails.
37
+ export let retryFor = 2_000
38
+ let BACKOFF = [25, 100, 400]
39
+
40
+ let before = async <T>(
41
+ send: () => Promise<T>,
42
+ until: number,
43
+ clock: Clock,
44
+ expired: unknown,
45
+ ): Promise<T> => {
46
+ let left = until - clock.now()
47
+ if (left <= 0) throw expired
48
+ let timeout = Promise.withResolvers<never>()
49
+ let cancel = clock.after(left, () => timeout.reject(expired))
50
+ try {
51
+ let answer = await Promise.race([send(), timeout.promise])
52
+ if (clock.now() >= until) throw expired
53
+ return answer
54
+ } finally {
55
+ cancel()
56
+ }
57
+ }
58
+
59
+ /** A caller's deadline passing before D1 answered. D1 cannot cancel the call,
60
+ * so it may still have run. */
61
+ export class Expired extends Error {
62
+ constructor() {
63
+ super('D1 operation exceeded its deadline')
64
+ }
65
+ }
66
+
67
+ export let retry = async <T>(
68
+ send: () => Promise<T>,
69
+ until?: number,
70
+ clock: Clock = system,
71
+ ): Promise<T> => {
72
+ let last: unknown = new Expired()
73
+ for (let attempt = 0;; attempt++) {
74
+ try {
75
+ return await (until == null ? send() : before(send, until, clock, last))
76
+ } catch (e) {
77
+ if (attempt == BACKOFF.length || !transient(e)) throw e
78
+ last = e
79
+ }
80
+ until ??= clock.now() + retryFor
81
+ let pause = BACKOFF[attempt] * (1 + Math.random())
82
+ if (clock.now() + pause >= until) throw last
83
+ await sleep(pause, undefined, clock)
84
+ }
85
+ }