@yaks/durable-object 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.
Files changed (91) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +554 -2
  3. package/_dist/alarm.d.ts +35 -0
  4. package/_dist/alarm.d.ts.map +1 -0
  5. package/_dist/ceiling.d.ts +167 -0
  6. package/_dist/ceiling.d.ts.map +1 -0
  7. package/_dist/compose.d.ts +79 -0
  8. package/_dist/compose.d.ts.map +1 -0
  9. package/_dist/copy.d.ts +67 -0
  10. package/_dist/copy.d.ts.map +1 -0
  11. package/_dist/door.d.ts +172 -0
  12. package/_dist/door.d.ts.map +1 -0
  13. package/_dist/job.d.ts +26 -0
  14. package/_dist/job.d.ts.map +1 -0
  15. package/_dist/keys.d.ts +14 -0
  16. package/_dist/keys.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +65 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/object.d.ts +75 -0
  20. package/_dist/object.d.ts.map +1 -0
  21. package/_dist/profile.d.ts +32 -0
  22. package/_dist/profile.d.ts.map +1 -0
  23. package/_dist/query-memory.d.ts +27 -0
  24. package/_dist/query-memory.d.ts.map +1 -0
  25. package/_dist/resets.d.ts +208 -0
  26. package/_dist/resets.d.ts.map +1 -0
  27. package/_dist/rewind.d.ts +21 -0
  28. package/_dist/rewind.d.ts.map +1 -0
  29. package/_dist/sockets.d.ts +90 -0
  30. package/_dist/sockets.d.ts.map +1 -0
  31. package/_dist/sql.d.ts +72 -0
  32. package/_dist/sql.d.ts.map +1 -0
  33. package/_dist/store.d.ts +8 -0
  34. package/_dist/store.d.ts.map +1 -0
  35. package/alarm.js +126 -0
  36. package/alarm.js.map +1 -0
  37. package/alarm.ts +188 -0
  38. package/ceiling.js +536 -0
  39. package/ceiling.js.map +1 -0
  40. package/ceiling.ts +681 -0
  41. package/compose.js +201 -0
  42. package/compose.js.map +1 -0
  43. package/compose.ts +249 -0
  44. package/copy.js +394 -0
  45. package/copy.js.map +1 -0
  46. package/copy.ts +413 -0
  47. package/deno.json +1 -0
  48. package/door.js +364 -0
  49. package/door.js.map +1 -0
  50. package/door.ts +542 -0
  51. package/example.ts +108 -0
  52. package/holds.js +85 -0
  53. package/holds.js.map +1 -0
  54. package/holds.ts +72 -0
  55. package/job.js +151 -0
  56. package/job.js.map +1 -0
  57. package/job.ts +166 -0
  58. package/keys.js +59 -0
  59. package/keys.js.map +1 -0
  60. package/keys.ts +85 -0
  61. package/mod.js +65 -0
  62. package/mod.js.map +1 -0
  63. package/mod.ts +167 -0
  64. package/object.js +247 -0
  65. package/object.js.map +1 -0
  66. package/object.ts +385 -0
  67. package/package.json +68 -4
  68. package/profile.js +131 -0
  69. package/profile.js.map +1 -0
  70. package/profile.ts +150 -0
  71. package/query-memory.js +157 -0
  72. package/query-memory.js.map +1 -0
  73. package/query-memory.ts +240 -0
  74. package/resets.js +302 -0
  75. package/resets.js.map +1 -0
  76. package/resets.ts +353 -0
  77. package/rewind.js +68 -0
  78. package/rewind.js.map +1 -0
  79. package/rewind.ts +91 -0
  80. package/sockets.js +749 -0
  81. package/sockets.js.map +1 -0
  82. package/sockets.ts +991 -0
  83. package/sql.js +221 -0
  84. package/sql.js.map +1 -0
  85. package/sql.ts +330 -0
  86. package/store.js +58 -0
  87. package/store.js.map +1 -0
  88. package/store.ts +80 -0
  89. package/watches.js +8 -0
  90. package/watches.js.map +1 -0
  91. package/watches.ts +23 -0
package/sql.js ADDED
@@ -0,0 +1,221 @@
1
+ // The Durable Object's SQLite, reduced to the two things a store needs from a
2
+ // connection — a parameterized statement, and a transaction — and shaped as
3
+ // @yaks/sql's `Driver`. That is the whole trick of this package: the schema,
4
+ // the compiled reads, the patches and the death cascade are @yaks/sqlite's
5
+ // already, and a Durable Object is one more place to run them.
6
+ //
7
+ // Two things about the runtime shape the code here, both checked against
8
+ // workerd rather than the docs alone:
9
+ //
10
+ // Values are narrow. A binding must be an ArrayBuffer, a string, a number or
11
+ // null. A boolean would bind as the text 'true' and a bigint throws, so both
12
+ // are converted before they reach the engine, and a blob comes back as an
13
+ // ArrayBuffer where every other adapter hands back bytes.
14
+ //
15
+ // Transactions are not SQL. `begin`, `savepoint` and their friends are
16
+ // refused as statements; `transactionSync` is the transaction, and it nests.
17
+ // That is what `Driver.tx` exists for.
18
+ import { as, asWritten, cardinality, DEPTH, fn, labeled, renderStable, select, shape, statement, tracked, VARIABLES, writing } from "@yaks/sql";
19
+ import { leaf, peek } from "@yaks/trace";
20
+ import { bounded } from "./ceiling.js";
21
+ import { QueryPage, queryRows } from "./query-memory.js";
22
+ /**
23
+ * A table Cloudflare owns inside the object's SQLite. `_cf_KV` is the one
24
+ * behind `ctx.storage.kv` — the docs spell it `__cf_kv` and the engine reports
25
+ * it as `_cf_KV`, so neither the case nor the number of underscores is worth
26
+ * trusting — and `_cf_METADATA` is its neighbour.
27
+ *
28
+ * These are not merely uninteresting: workerd's SQL authorizer refuses them to
29
+ * the object's own statements — `access to _cf_KV.key is prohibited:
30
+ * SQLITE_AUTH` — while still listing them in `sqlite_master`. So anything that
31
+ * enumerates tables and then reads them must skip these or throw (T-34019).
32
+ */ export let prohibited = (name)=>/^_+cf_/i.test(name);
33
+ /**
34
+ * Every table the object does not own: {@link prohibited} plus SQLite's own
35
+ * catalogue, which is readable but is nobody's data.
36
+ */ export let reserved = (name)=>prohibited(name) || /^sqlite_/i.test(name);
37
+ // A value as the engine takes it. `undefined` and `null` are the same absence;
38
+ // a boolean is the 0/1 an integer column holds; a bigint is a number (workerd
39
+ // refuses one outright); a byte array is the ArrayBuffer it is a window onto.
40
+ let bind = (value)=>value == null ? null : typeof value == 'boolean' ? Number(value) : typeof value == 'bigint' ? Number(value) : value instanceof Uint8Array ? value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength) : value;
41
+ // A row as the rest of the stack expects it: a blob is bytes, the way every
42
+ // other driver hands one back.
43
+ let unbind = (row)=>{
44
+ for(let key in row){
45
+ let value = row[key];
46
+ if (value instanceof ArrayBuffer) row[key] = new Uint8Array(value);
47
+ }
48
+ return row;
49
+ };
50
+ // The engine's refusal, with the statement it refused as its cause: the
51
+ // engine's message says what was wrong and never which statement, and a store
52
+ // sends hundreds. The statement is its shape, so no value rides along, and
53
+ // the first SHOWN characters of it, where its `with` list is. It is said on
54
+ // the console too, since the Workers log is read when the tracker cannot be.
55
+ // Workerd keeps each prepared statement by its text (SqlStorage's
56
+ // StatementCache), so every collection binds as one JSON array: a read's text
57
+ // is the same whatever ids it names, and is prepared once. Workerd refuses to
58
+ // name a common table expression past DEPTH cursors.
59
+ let render = (s, v)=>renderStable(s, VARIABLES, DEPTH, v);
60
+ // Drivers for the same database share a connection and its stored vocabulary
61
+ // (@yaks/sql `storeAs`). Erasure ends that connection even while the object lives.
62
+ let connections = new WeakMap();
63
+ /** Erase the database and release its connection. Open new drivers to use the
64
+ * empty storage so none of the old database's schema or rows stay cached. */ export let clearStorage = async (durable)=>{
65
+ await durable.deleteAll();
66
+ connections.delete(durable);
67
+ };
68
+ let SHOWN = 12_000;
69
+ let refused = (e, rendered)=>{
70
+ if (!(e instanceof Error) || e.cause != null) return e;
71
+ e.cause = {
72
+ statement: shape(rendered, SHOWN),
73
+ length: rendered.sql.length
74
+ };
75
+ console.error('sql refused', e.message, JSON.stringify(e.cause));
76
+ return e;
77
+ };
78
+ /**
79
+ * A {@link https://jsr.io/@yaks/sql | @yaks/sql} `Driver` over a Durable
80
+ * Object's storage. It converts the values the engine will not take, hands the
81
+ * transaction back to `transactionSync`, and turns foreign keys on — the
82
+ * enforcement the schema's references are written for, which workerd leaves off
83
+ * per connection.
84
+ *
85
+ * ```ts
86
+ * // let store = storage(ctx.storage, vocab) // …which is this, bound
87
+ * ```
88
+ */ export let driver = (durable, observe, measure)=>{
89
+ let reported = false;
90
+ // What this object's statements may cost together (./ceiling.ts).
91
+ let bound = bounded(durable);
92
+ let stored = connections.get(durable);
93
+ if (!stored) connections.set(durable, stored = {});
94
+ // The cursor is lazy: draining it is what runs the statement.
95
+ let execute = (s, counts)=>{
96
+ // A stopped object's refusal is the caller's to wait out, not the
97
+ // engine's: it is no statement the engine refused.
98
+ bound.admit(writing(s));
99
+ let rendered = render(s, stored.v);
100
+ let { sql, params } = rendered;
101
+ let cursor;
102
+ let returned = 0;
103
+ let matched = 0;
104
+ try {
105
+ cursor = durable.sql.exec(sql, ...params.map(bind));
106
+ let rows = (queryRows(cursor, durable) ?? cursor.toArray()).map(unbind);
107
+ returned = rows.length;
108
+ matched = cardinality(s, rows, cursor.rowsRead ?? 0);
109
+ if (observe && cursor.rowsRead != null && cursor.rowsWritten != null) {
110
+ try {
111
+ observe({
112
+ shape: shape(rendered),
113
+ rowsRead: cursor.rowsRead,
114
+ rowsWritten: cursor.rowsWritten
115
+ });
116
+ } catch (e) {
117
+ // A broken observer cannot change a store answer, but its defect must
118
+ // still be visible. Each driver reports it at most once.
119
+ if (!reported) console.error('row profile observer failed', e);
120
+ reported = true;
121
+ }
122
+ } else if (observe && !reported) {
123
+ console.error('row profile cursor counters unavailable');
124
+ reported = true;
125
+ }
126
+ return rows;
127
+ } catch (e) {
128
+ if (e instanceof QueryPage) throw e;
129
+ throw refused(e, rendered);
130
+ } finally{
131
+ // A statement that failed still cost a call to the engine.
132
+ if (counts) {
133
+ counts.statements = 1;
134
+ if (cursor?.rowsRead != null) counts.rowsRead = cursor.rowsRead;
135
+ if (cursor?.rowsWritten != null) counts.rowsWritten = cursor.rowsWritten;
136
+ }
137
+ let rowsRead = cursor?.rowsRead, rowsWritten = cursor?.rowsWritten;
138
+ let shaped = rowsRead != null && rowsWritten != null ? ()=>shape(rendered, SHOWN) : undefined;
139
+ try {
140
+ measure?.(rowsRead, rowsWritten, shaped);
141
+ } catch (e) {
142
+ if (!reported) console.error('statement meter failed', e);
143
+ reported = true;
144
+ }
145
+ // A statement that failed still read what it read.
146
+ if (shaped) {
147
+ bound.count({
148
+ shape: shaped,
149
+ rowsRead: rowsRead,
150
+ rowsWritten: rowsWritten,
151
+ returned,
152
+ matched
153
+ });
154
+ }
155
+ }
156
+ };
157
+ // Rows come back, and a refusal is told, under the names the statement
158
+ // wrote (@yaks/sql `asWritten`, `labeled`).
159
+ let query = (s)=>labeled(()=>asWritten(s, told(s), stored.v), stored.v);
160
+ let told = (s)=>{
161
+ let c = peek();
162
+ if (!c) return execute(s);
163
+ let counts = {};
164
+ return leaf(c.begin({
165
+ kind: 'sql',
166
+ name: statement(s),
167
+ package: '@yaks/durable-object'
168
+ }), ()=>execute(s, counts), ()=>counts);
169
+ };
170
+ query({
171
+ t: 'pragma',
172
+ name: 'foreign_keys',
173
+ value: 'on'
174
+ });
175
+ // Its transactions are the runtime's, not statements, so the revision every
176
+ // snapshot is held at must hear them from the first one (@yaks/sql
177
+ // `tracked`): a store's first act after a wake can be a transaction that
178
+ // rolls back, and a snapshot taken inside it must not outlive it.
179
+ return tracked({
180
+ query,
181
+ run: (s)=>{
182
+ query(s);
183
+ // Cursor rowsWritten includes indexes and triggers, whereas the writer
184
+ // needs rows this statement affected. changes() answers that without
185
+ // materializing RETURNING rows, and its scalar query reads no table.
186
+ return writing(s) ? Number(query(select({
187
+ cols: [
188
+ as(fn('changes'), 'n')
189
+ ]
190
+ }))[0].n) : 0;
191
+ },
192
+ tx: (body)=>durable.transactionSync(body),
193
+ stable: true,
194
+ render,
195
+ stored,
196
+ statistics: durable.sql.databaseSize == null ? undefined : {
197
+ bytes: ()=>durable.sql.databaseSize
198
+ },
199
+ connection: stored
200
+ });
201
+ };
202
+ /**
203
+ * A {@link driver} whose statements are counted against the object's ceiling
204
+ * (./ceiling.ts) and never refused, its transactions included: for work that
205
+ * must not stop half way, such as a copy of the whole object an admin
206
+ * started. What it costs is still told as it runs.
207
+ *
208
+ * ```ts
209
+ * // let sql = freely(ctx.storage)
210
+ * ```
211
+ */ export let freely = (durable, observe, measure)=>{
212
+ let { free } = bounded(durable);
213
+ let d = free(()=>driver(durable, observe, measure));
214
+ return {
215
+ ...d,
216
+ query: (s)=>free(()=>d.query(s)),
217
+ run: (s)=>free(()=>d.run(s)),
218
+ tx: (body)=>free(()=>d.tx(body))
219
+ };
220
+ };
221
+ //# sourceMappingURL=sql.js.map
package/sql.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sql.js","sources":["./sql.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,2EAA2E;AAC3E,+DAA+D;AAC/D,EAAE;AACF,yEAAyE;AACzE,sCAAsC;AACtC,EAAE;AACF,+EAA+E;AAC/E,+EAA+E;AAC/E,4EAA4E;AAC5E,4DAA4D;AAC5D,EAAE;AACF,yEAAyE;AACzE,+EAA+E;AAC/E,yCAAyC;AAEzC,SACE,EAAE,EACF,SAAS,EACT,WAAW,EACX,KAAK,EAEL,EAAE,EACF,OAAO,EAGP,YAAY,EAEZ,MAAM,EACN,KAAK,EACL,SAAS,EAET,OAAO,EACP,SAAS,EACT,OAAO,yBACoB;AAC7B,SAAS,IAAI,EAAE,IAAI,2BAAgC;AACnD,SAAS,OAAO,uBAAsB;AACtC,SAAS,SAAS,EAAE,SAAS,4BAA2B;AAMxD;;;;;;;;;;CAUC,GACD,OAAO,IAAI,aAAa,CAAC,OAA0B,UAAU,IAAI,CAAC,MAAK;AAEvE;;;CAGC,GACD,OAAO,IAAI,WAAW,CAAC,OACrB,WAAW,SAAS,YAAY,IAAI,CAAC,MAAK;AAiD5C,+EAA+E;AAC/E,8EAA8E;AAC9E,8EAA8E;AAC9E,IAAI,OAAO,CAAC,QACV,SAAS,OACL,OACA,OAAO,SAAS,YAChB,OAAO,SACP,OAAO,SAAS,WAChB,OAAO,SACP,iBAAiB,aACjB,MAAM,MAAM,CAAC,KAAK,CAClB,MAAM,UAAU,EAChB,MAAM,UAAU,GAAG,MAAM,UAAU,IAEnC;AAEN,4EAA4E;AAC5E,+BAA+B;AAC/B,IAAI,SAAS,CAAC;EACZ,IAAK,IAAI,OAAO,IAA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AK,IAAM,EAAE,EAAE,CAAE;EACjC;AACF,EAAC"}
package/sql.ts ADDED
@@ -0,0 +1,330 @@
1
+ // The Durable Object's SQLite, reduced to the two things a store needs from a
2
+ // connection — a parameterized statement, and a transaction — and shaped as
3
+ // @yaks/sql's `Driver`. That is the whole trick of this package: the schema,
4
+ // the compiled reads, the patches and the death cascade are @yaks/sqlite's
5
+ // already, and a Durable Object is one more place to run them.
6
+ //
7
+ // Two things about the runtime shape the code here, both checked against
8
+ // workerd rather than the docs alone:
9
+ //
10
+ // Values are narrow. A binding must be an ArrayBuffer, a string, a number or
11
+ // null. A boolean would bind as the text 'true' and a bigint throws, so both
12
+ // are converted before they reach the engine, and a blob comes back as an
13
+ // ArrayBuffer where every other adapter hands back bytes.
14
+ //
15
+ // Transactions are not SQL. `begin`, `savepoint` and their friends are
16
+ // refused as statements; `transactionSync` is the transaction, and it nests.
17
+ // That is what `Driver.tx` exists for.
18
+
19
+ import {
20
+ as,
21
+ asWritten,
22
+ cardinality,
23
+ DEPTH,
24
+ type Driver,
25
+ fn,
26
+ labeled,
27
+ type Param,
28
+ type Raw,
29
+ renderStable,
30
+ type Row,
31
+ select,
32
+ shape,
33
+ statement,
34
+ type Stmt,
35
+ tracked,
36
+ VARIABLES,
37
+ writing,
38
+ } from '@yaks/sql'
39
+ import { leaf, peek } from '@yaks/trace'
40
+ import { bounded } from './ceiling.js'
41
+ import { QueryPage, queryRows } from './query-memory.js'
42
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
43
+
44
+ /** A value the engine will bind: everything else is converted first. */
45
+ export type SqlValue = ArrayBuffer | string | number | null
46
+
47
+ /**
48
+ * A table Cloudflare owns inside the object's SQLite. `_cf_KV` is the one
49
+ * behind `ctx.storage.kv` — the docs spell it `__cf_kv` and the engine reports
50
+ * it as `_cf_KV`, so neither the case nor the number of underscores is worth
51
+ * trusting — and `_cf_METADATA` is its neighbour.
52
+ *
53
+ * These are not merely uninteresting: workerd's SQL authorizer refuses them to
54
+ * the object's own statements — `access to _cf_KV.key is prohibited:
55
+ * SQLITE_AUTH` — while still listing them in `sqlite_master`. So anything that
56
+ * enumerates tables and then reads them must skip these or throw (T-34019).
57
+ */
58
+ export let prohibited = (name: string): boolean => /^_+cf_/i.test(name)
59
+
60
+ /**
61
+ * Every table the object does not own: {@link prohibited} plus SQLite's own
62
+ * catalogue, which is readable but is nobody's data.
63
+ */
64
+ export let reserved = (name: string): boolean =>
65
+ prohibited(name) || /^sqlite_/i.test(name)
66
+
67
+ /** What `exec` hands back — the rows, drained with `toArray()`. */
68
+ export type SqlCursor<T> = Iterable<T> & {
69
+ /** every remaining row, read at once */
70
+ toArray(): T[]
71
+ /** The runtime's metered rows, available after the cursor is drained. */
72
+ rowsRead?: number
73
+ rowsWritten?: number
74
+ }
75
+
76
+ export type Sample = {
77
+ shape: string
78
+ rowsRead: number
79
+ rowsWritten: number
80
+ }
81
+
82
+ export type Observe = (sample: Sample) => void
83
+ export type Measure = (
84
+ rowsRead?: number,
85
+ rowsWritten?: number,
86
+ shape?: () => string,
87
+ ) => void
88
+
89
+ /**
90
+ * The synchronous SQLite handle of a Durable Object — the shape of
91
+ * `ctx.storage.sql`, reduced to the one method this package calls. Naming just
92
+ * this keeps the adapter free of any Cloudflare dependency; a `SqlStorage`
93
+ * satisfies it.
94
+ */
95
+ export type DurableSql = {
96
+ /** The runtime's stored-byte count, without a SQL statement. */
97
+ readonly databaseSize?: number
98
+ /** run a statement with its bindings and hand back the rows */
99
+ exec(query: string, ...bindings: SqlValue[]): SqlCursor<Row>
100
+ }
101
+
102
+ /**
103
+ * The object's storage — the shape of `ctx.storage`: its SQLite handle, and
104
+ * the transaction the runtime insists on. `transactionSync` nests, commits
105
+ * when the body returns, and rolls back when it throws.
106
+ */
107
+ export type DurableStorage = {
108
+ /** the embedded SQLite engine */
109
+ sql: DurableSql
110
+ /** run a body as one all-or-nothing unit of work */
111
+ transactionSync<T>(body: () => T): T
112
+ }
113
+
114
+ // A value as the engine takes it. `undefined` and `null` are the same absence;
115
+ // a boolean is the 0/1 an integer column holds; a bigint is a number (workerd
116
+ // refuses one outright); a byte array is the ArrayBuffer it is a window onto.
117
+ let bind = (value: Param): SqlValue =>
118
+ value == null
119
+ ? null
120
+ : typeof value == 'boolean'
121
+ ? Number(value)
122
+ : typeof value == 'bigint'
123
+ ? Number(value)
124
+ : value instanceof Uint8Array
125
+ ? value.buffer.slice(
126
+ value.byteOffset,
127
+ value.byteOffset + value.byteLength,
128
+ ) as ArrayBuffer
129
+ : value
130
+
131
+ // A row as the rest of the stack expects it: a blob is bytes, the way every
132
+ // other driver hands one back.
133
+ let unbind = (row: Row): Row => {
134
+ for (let key in row) {
135
+ let value = row[key]
136
+ if (value instanceof ArrayBuffer) row[key] = new Uint8Array(value)
137
+ }
138
+ return row
139
+ }
140
+
141
+ // The engine's refusal, with the statement it refused as its cause: the
142
+ // engine's message says what was wrong and never which statement, and a store
143
+ // sends hundreds. The statement is its shape, so no value rides along, and
144
+ // the first SHOWN characters of it, where its `with` list is. It is said on
145
+ // the console too, since the Workers log is read when the tracker cannot be.
146
+ // Workerd keeps each prepared statement by its text (SqlStorage's
147
+ // StatementCache), so every collection binds as one JSON array: a read's text
148
+ // is the same whatever ids it names, and is prepared once. Workerd refuses to
149
+ // name a common table expression past DEPTH cursors.
150
+ let render = (s: Stmt, v?: Vocab) => renderStable(s, VARIABLES, DEPTH, v)
151
+
152
+ // Drivers for the same database share a connection and its stored vocabulary
153
+ // (@yaks/sql `storeAs`). Erasure ends that connection even while the object lives.
154
+ let connections = new WeakMap<DurableStorage, { v?: Vocab }>()
155
+
156
+ /** Erase the database and release its connection. Open new drivers to use the
157
+ * empty storage so none of the old database's schema or rows stay cached. */
158
+ export let clearStorage = async (
159
+ durable: DurableStorage & { deleteAll(): Promise<void> },
160
+ ): Promise<void> => {
161
+ await durable.deleteAll()
162
+ connections.delete(durable)
163
+ }
164
+
165
+ let SHOWN = 12_000
166
+ let refused = (e: unknown, rendered: Raw) => {
167
+ if (!(e instanceof Error) || e.cause != null) return e
168
+ e.cause = {
169
+ statement: shape(rendered, SHOWN),
170
+ length: rendered.sql.length,
171
+ }
172
+ console.error('sql refused', e.message, JSON.stringify(e.cause))
173
+ return e
174
+ }
175
+
176
+ /**
177
+ * A {@link https://jsr.io/@yaks/sql | @yaks/sql} `Driver` over a Durable
178
+ * Object's storage. It converts the values the engine will not take, hands the
179
+ * transaction back to `transactionSync`, and turns foreign keys on — the
180
+ * enforcement the schema's references are written for, which workerd leaves off
181
+ * per connection.
182
+ *
183
+ * ```ts
184
+ * // let store = storage(ctx.storage, vocab) // …which is this, bound
185
+ * ```
186
+ */
187
+ export let driver = (
188
+ durable: DurableStorage,
189
+ observe?: Observe,
190
+ measure?: Measure,
191
+ ): Driver => {
192
+ let reported = false
193
+ // What this object's statements may cost together (./ceiling.ts).
194
+ let bound = bounded(durable)
195
+ let stored = connections.get(durable)
196
+ if (!stored) connections.set(durable, stored = {})
197
+ // The cursor is lazy: draining it is what runs the statement.
198
+ let execute = (s: Stmt, counts?: Record<string, number>): Row[] => {
199
+ // A stopped object's refusal is the caller's to wait out, not the
200
+ // engine's: it is no statement the engine refused.
201
+ bound.admit(writing(s))
202
+ let rendered = render(s, stored.v)
203
+ let { sql, params } = rendered
204
+ let cursor: SqlCursor<Row> | undefined
205
+ let returned = 0
206
+ let matched = 0
207
+ try {
208
+ cursor = durable.sql.exec(sql, ...params.map(bind))
209
+ let rows = (queryRows(cursor, durable) ?? cursor.toArray()).map(unbind)
210
+ returned = rows.length
211
+ matched = cardinality(s, rows, cursor.rowsRead ?? 0)
212
+ if (observe && cursor.rowsRead != null && cursor.rowsWritten != null) {
213
+ try {
214
+ observe({
215
+ shape: shape(rendered),
216
+ rowsRead: cursor.rowsRead,
217
+ rowsWritten: cursor.rowsWritten,
218
+ })
219
+ } catch (e) {
220
+ // A broken observer cannot change a store answer, but its defect must
221
+ // still be visible. Each driver reports it at most once.
222
+ if (!reported) console.error('row profile observer failed', e)
223
+ reported = true
224
+ }
225
+ } else if (observe && !reported) {
226
+ console.error('row profile cursor counters unavailable')
227
+ reported = true
228
+ }
229
+ return rows
230
+ } catch (e) {
231
+ if (e instanceof QueryPage) throw e
232
+ throw refused(e, rendered)
233
+ } finally {
234
+ // A statement that failed still cost a call to the engine.
235
+ if (counts) {
236
+ counts.statements = 1
237
+ if (cursor?.rowsRead != null) counts.rowsRead = cursor.rowsRead
238
+ if (cursor?.rowsWritten != null) counts.rowsWritten = cursor.rowsWritten
239
+ }
240
+ let rowsRead = cursor?.rowsRead, rowsWritten = cursor?.rowsWritten
241
+ let shaped = rowsRead != null && rowsWritten != null
242
+ ? () => shape(rendered, SHOWN)
243
+ : undefined
244
+ try {
245
+ measure?.(rowsRead, rowsWritten, shaped)
246
+ } catch (e) {
247
+ if (!reported) console.error('statement meter failed', e)
248
+ reported = true
249
+ }
250
+ // A statement that failed still read what it read.
251
+ if (shaped) {
252
+ bound.count({
253
+ shape: shaped,
254
+ rowsRead: rowsRead!,
255
+ rowsWritten: rowsWritten!,
256
+ returned,
257
+ matched,
258
+ })
259
+ }
260
+ }
261
+ }
262
+ // Rows come back, and a refusal is told, under the names the statement
263
+ // wrote (@yaks/sql `asWritten`, `labeled`).
264
+ let query = (s: Stmt): Row[] =>
265
+ labeled(() => asWritten(s, told(s), stored.v), stored.v)
266
+ let told = (s: Stmt): Row[] => {
267
+ let c = peek()
268
+ if (!c) return execute(s)
269
+ let counts: Record<string, number> = {}
270
+ return leaf(
271
+ c.begin({
272
+ kind: 'sql',
273
+ name: statement(s),
274
+ package: '@yaks/durable-object',
275
+ }),
276
+ () => execute(s, counts),
277
+ () => counts,
278
+ )
279
+ }
280
+ query({ t: 'pragma', name: 'foreign_keys', value: 'on' })
281
+ // Its transactions are the runtime's, not statements, so the revision every
282
+ // snapshot is held at must hear them from the first one (@yaks/sql
283
+ // `tracked`): a store's first act after a wake can be a transaction that
284
+ // rolls back, and a snapshot taken inside it must not outlive it.
285
+ return tracked({
286
+ query,
287
+ run: (s) => {
288
+ query(s)
289
+ // Cursor rowsWritten includes indexes and triggers, whereas the writer
290
+ // needs rows this statement affected. changes() answers that without
291
+ // materializing RETURNING rows, and its scalar query reads no table.
292
+ return writing(s)
293
+ ? Number(query(select({ cols: [as(fn('changes'), 'n')] }))[0].n)
294
+ : 0
295
+ },
296
+ tx: (body) => durable.transactionSync(body),
297
+ stable: true,
298
+ render,
299
+ stored,
300
+ statistics: durable.sql.databaseSize == null
301
+ ? undefined
302
+ : { bytes: () => durable.sql.databaseSize! },
303
+ connection: stored,
304
+ })
305
+ }
306
+
307
+ /**
308
+ * A {@link driver} whose statements are counted against the object's ceiling
309
+ * (./ceiling.ts) and never refused, its transactions included: for work that
310
+ * must not stop half way, such as a copy of the whole object an admin
311
+ * started. What it costs is still told as it runs.
312
+ *
313
+ * ```ts
314
+ * // let sql = freely(ctx.storage)
315
+ * ```
316
+ */
317
+ export let freely = (
318
+ durable: DurableStorage,
319
+ observe?: Observe,
320
+ measure?: Measure,
321
+ ): Driver => {
322
+ let { free } = bounded(durable)
323
+ let d = free(() => driver(durable, observe, measure))
324
+ return {
325
+ ...d,
326
+ query: (s) => free(() => d.query(s)),
327
+ run: (s) => free(() => d.run!(s)),
328
+ tx: (body) => free(() => d.tx!(body)),
329
+ }
330
+ }
package/store.js ADDED
@@ -0,0 +1,58 @@
1
+ // The store, bound. One line of composition: a Durable Object's storage
2
+ // becomes a driver (./sql.ts), and @yaks/sqlite turns that driver plus a
3
+ // vocabulary into a whole `Storage` implementation — schema, reads, patches,
4
+ // cascading deletes, transactions. This package writes no SQL of its own, which
5
+ // is the point: a graph reads the same inside an object as it does on a
6
+ // server.
7
+ import { storage as bind } from "@yaks/sqlite";
8
+ import { bounded } from "./ceiling.js";
9
+ import { driver } from "./sql.js";
10
+ /**
11
+ * Bind a store to a Durable Object's storage and a vocabulary — the
12
+ * {@link https://jsr.io/@yaks/graph | @yaks/graph} `Storage` a graph applies
13
+ * changes to, implemented synchronously because the object's SQLite is.
14
+ *
15
+ * `install()` it once (create-if-not-exists, so a constructor may call it every
16
+ * time the object wakes). `base` options — a derived-property registry, a fixed
17
+ * `now` for time phrases — are applied to every read, and the registry's
18
+ * `text` expressions (how a property whose stored value is not its text reads
19
+ * as text) to the schema.
20
+ *
21
+ * ```ts
22
+ * // let store = storage(ctx.storage, vocab)
23
+ * // store.install()
24
+ * // let g = graph({ storage: store, vocab })
25
+ * ```
26
+ */ // The share of each window a maintenance unit may spend: most of it for a
27
+ // large unit, which could otherwise never fit beside the object's own work.
28
+ let share = (written)=>written > 10_000 ? 0.9 : 0.5;
29
+ export let storage = (durable, vocab, base = {}, observe, measure)=>{
30
+ let store = bind(driver(durable, observe, measure), vocab, base);
31
+ let bound = bounded(durable);
32
+ return Object.assign(store, {
33
+ // Previewing a unit arms a host without running maintenance at boot.
34
+ // A unit no window can hold (an index over a spine past its writes in a
35
+ // minute) is taken, as a deploy's install is: paced, it would wait for a
36
+ // window that never comes, and the object would serve without it for
37
+ // good. Its rows are the file's, once, so it stops nothing and is never
38
+ // told as a runaway (./ceiling.ts `take`).
39
+ upkeep: (run = true)=>{
40
+ let wait = Infinity, huge = false;
41
+ let worked = store.maintain((written)=>{
42
+ let next = bound.under(share(written), written);
43
+ if (next == Infinity) {
44
+ huge = true;
45
+ wait = 0;
46
+ return false;
47
+ }
48
+ wait = Math.min(wait, next);
49
+ return run && next == 0;
50
+ });
51
+ if (!worked && huge && run) {
52
+ worked = bound.take(()=>store.maintain((written)=>bound.under(share(written), written) == Infinity));
53
+ }
54
+ return worked ? 0 : Number.isFinite(wait) ? wait : null;
55
+ }
56
+ });
57
+ };
58
+ //# sourceMappingURL=store.js.map
package/store.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sources":["./store.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,yEAAyE;AACzE,6EAA6E;AAC7E,gFAAgF;AAChF,wEAAwE;AACxE,UAAU;AAGV,SAAS,WAAW,IAAI,4BAAiC;AACzD,SAAS,OAAO,uBAAsB;AAEtC,SACE,MAAM,mBAIS;AAIjB;;;;;;;;;;;;;;;;CAgBC,GACD,0EAA0E;AAC1E,4EAA4E;AAC5E,IAAI,QAAQ,CAAC,UAAoB,UAAU,SAAS,MAAM;AAE1D,OAAO,IAAI,UAAU,CACnB,SACA,OACA,OAAa,CAAC,CAAC,EACf,SACA;EAEA,IAAI,QAAQ,KAAK,OAAO,SAAS,SAAS,UAAU,OAAO;EAC3D,IAAI,QAAQ,QAAQ;EACpB,OAAO,OAAO,MAAM,CAAC,OAAO;IAC1B,qEAAqE;IACrE,wEAAwE;IACxE,yEAAyE;IACzE,qEAAqE;IACrE,wEAAwE;IACxE,2CAA2C;IAC3C,QAAQ,CAAC,MAAM,IAAI;MACjB,IAAI,OAAO,UAAU,OAAO;MAC5B,IAAI,SAAS,MAAM,QAAQ,CAAC,CAAC;QAC3B,IAAI,OAAO,MAAM,KAAK,CAAC,MAAM,UAAU;QACvC,IAAI,QAAQ,UAAU;UACpB,OAAO;UACP,OAAO;UACP,OAAO;QACT;QACA,OAAO,KAAK,GAAG,CAAC,MAAM;QACtB,OAAO,OAAO,QAAQ;MACxB;MACA,IAAI,CAAC,UAAU,QAAQ,KAAK;QAC1B,SAAS,MAAM,IAAI,CAAC,IAClB,MAAM,QAAQ,CAAC,CAAC,UACd,MAAM,KAAK,CAAC,MAAM,UAAU,YAAY;MAG9C;MACA,OAAO,SAAS,IAAI,OAAO,QAAQ,CAAC,QAAQ,OAAO;IACrD;EACF;AACF,EAAC"}