@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/copy.ts ADDED
@@ -0,0 +1,413 @@
1
+ // One object's SQLite, copied table by table into another object at a new
2
+ // address. Cloudflare moves no Durable Object, so an object that should stand
3
+ // somewhere else is a new one holding the same file: every table's rows under
4
+ // their own rowids, then the indexes, triggers and views the catalogue keeps.
5
+ //
6
+ // The rows go first and the triggers after, so a copied row fires nothing, and
7
+ // foreign keys stay off while they arrive, since a table may reference one
8
+ // that comes later. The rows travel while the source still serves, so a second
9
+ // look (`chunks`, `stale`, `overwritten`) compares what each end holds a chunk
10
+ // at a time and sends again only what changed. A full-text index is made anew
11
+ // from its content table, so its shadow tables never travel. The planner's
12
+ // statistics live in tables an object may not write, so the far end analyzes
13
+ // what it now holds.
14
+
15
+ import {
16
+ and,
17
+ as,
18
+ col,
19
+ type Driver,
20
+ type Drop,
21
+ eq,
22
+ fn,
23
+ gt,
24
+ le,
25
+ queryPhysical,
26
+ select,
27
+ table,
28
+ val,
29
+ } from '@yaks/sql'
30
+ import { reserved } from './sql.js'
31
+ import { unit } from '@yaks/sqlite/unit'
32
+ import { fromBase64, toBase64 } from '@yaks/fp'
33
+
34
+ /** A value on its way between objects: a blob travels as base64. */
35
+ export type Cell = string | number | null | { bytes: string }
36
+ export type Cursor = number | string | null
37
+
38
+ /** Everything a far end must make before rows reach it, and after. */
39
+ export type Plan = {
40
+ tables: { name: string; sql: string; cols: string[]; key?: string }[]
41
+ /** views, made once the rows are in: a full-text index may read one */
42
+ views: string[]
43
+ /** indexes and triggers, made last */
44
+ after: string[]
45
+ /** full-text indexes, made and rebuilt from their content tables */
46
+ fts: { name: string; sql: string }[]
47
+ /** where each AUTOINCREMENT table's counter stands */
48
+ sequences: { name: string; seq: number }[]
49
+ }
50
+
51
+ /** How far a table has been read, and what it holds so far. */
52
+ export type Copied = { rows: number; digest: number }
53
+
54
+ const ROWID = '_rowid_'
55
+ type Table = Plan['tables'][number]
56
+
57
+ /** The cursor before a table's first copy page. */
58
+ export let first = (t: Table): Cursor => t.key ? null : 0
59
+
60
+ let schema = (driver: Driver) =>
61
+ driver.query(select({
62
+ cols: [col('type'), col('name'), col('sql')],
63
+ from: table('sqlite_schema'),
64
+ })).filter((o) => !reserved(String(o.name)) && o.sql != null)
65
+
66
+ let virtual = (sql: unknown) => /^create\s+virtual\b/i.test(String(sql))
67
+
68
+ /** What this object's file is made of. A table without a rowid uses its
69
+ * primary key to page through rows. */
70
+ export let plan = (driver: Driver): Plan => {
71
+ let objects = schema(driver)
72
+ let fts = ftsOf(objects)
73
+ let tables = objects.filter((o) => rowed(o, fts)).map((o) =>
74
+ tableOf(driver, o)
75
+ )
76
+ let sequences = objects.some((o) => /\bautoincrement\b/i.test(String(o.sql)))
77
+ ? driver.query(select({
78
+ cols: [col('name'), col('seq')],
79
+ from: table('sqlite_sequence'),
80
+ })).map((r) => ({ name: String(r.name), seq: Number(r.seq) }))
81
+ : []
82
+ return {
83
+ tables,
84
+ fts,
85
+ views: objects.filter((o) => o.type == 'view').map((o) => String(o.sql)),
86
+ after: objects.filter((o) => o.type == 'index' || o.type == 'trigger')
87
+ .map((o) => String(o.sql)),
88
+ sequences,
89
+ }
90
+ }
91
+
92
+ /** One table of the plan, as `plan` would give it, or null when the plan has
93
+ * none of that name: what a page of it asks, without a plan's every table. */
94
+ export let planFor = (
95
+ driver: Driver,
96
+ name: string,
97
+ ): Plan['tables'][number] | null => {
98
+ let objects = schema(driver)
99
+ let o = objects.find((o) => o.name == name)
100
+ return o && rowed(o, ftsOf(objects)) ? tableOf(driver, o) : null
101
+ }
102
+
103
+ type Listed = ReturnType<typeof schema>[number]
104
+
105
+ let ftsOf = (objects: Listed[]) =>
106
+ objects.filter((o) => virtual(o.sql)).map((o) => {
107
+ let [name, sql] = [String(o.name), String(o.sql)]
108
+ if (!/\busing\s+fts5\b/i.test(sql)) {
109
+ throw new Error(`${name} cannot be copied row by row: ${sql}`)
110
+ }
111
+ return { name, sql }
112
+ })
113
+
114
+ // Whether an object is a table whose rows travel: not a full-text index, and
115
+ // not one of the shadow tables an index is made anew from.
116
+ let rowed = (o: Listed, fts: Plan['fts']) =>
117
+ o.type == 'table' && !virtual(o.sql) &&
118
+ !fts.some((f) =>
119
+ ['data', 'idx', 'content', 'docsize', 'config'].some((s) =>
120
+ o.name == `${f.name}_${s}`
121
+ )
122
+ )
123
+
124
+ let tableOf = (driver: Driver, o: Listed) => {
125
+ let [name, sql] = [String(o.name), String(o.sql)]
126
+ let columns = queryPhysical(driver, {
127
+ t: 'pragma',
128
+ name: 'table_xinfo',
129
+ arg: name,
130
+ })
131
+ .filter((c) => Number(c.hidden) == 0)
132
+ let cols = columns.map((c) => String(c.name))
133
+ if (/\bwithout\s+rowid\s*$/i.test(sql)) {
134
+ let keys = columns.filter((c) => Number(c.pk) > 0)
135
+ if (keys.length != 1 || !/^(text|integer)$/i.test(String(keys[0].type))) {
136
+ throw new Error(
137
+ `${name} needs one text or integer primary key to copy its rows`,
138
+ )
139
+ }
140
+ return { name, sql, cols, key: String(keys[0].name) }
141
+ }
142
+ return { name, sql, cols }
143
+ }
144
+
145
+ let between = (t: Table, after: Cursor, last: Cursor) => {
146
+ let key = col(t.key ?? ROWID)
147
+ return and(
148
+ ...after == null ? [] : [gt(key, val(after))],
149
+ ...last == null ? [] : [le(key, val(last))],
150
+ )
151
+ }
152
+
153
+ let cell = (v: unknown): Cell =>
154
+ v instanceof Uint8Array ? { bytes: toBase64(v) } : v as Cell
155
+
156
+ let bound = (c: Cell) =>
157
+ c != null && typeof c == 'object' ? fromBase64(c.bytes) : c
158
+
159
+ // A row's mark on its table's running digest (a 32-bit FNV-1a). It finds a copy
160
+ // gone wrong; nothing here is adversarial.
161
+ let mixed = (digest: number, row: Cell[]) => {
162
+ let text = JSON.stringify(row)
163
+ for (let i = 0; i < text.length; i++) {
164
+ digest = Math.imul(digest ^ text.charCodeAt(i), 16777619)
165
+ }
166
+ return digest >>> 0
167
+ }
168
+
169
+ /** A table not yet read. */
170
+ export let raised = (): Copied => ({ rows: 0, digest: 2166136261 })
171
+
172
+ /** The next rows of a table after a rowid, up to `until` when one is named,
173
+ * each led by its rowid, and the tally with them in it. A page stops at
174
+ * `limit` rows or near `bytes`, so an answer stays small whatever its rows
175
+ * hold; `ended` says nothing is left to ask past it. */
176
+ export let page = (
177
+ driver: Driver,
178
+ t: Plan['tables'][number],
179
+ after: Cursor,
180
+ held: Copied,
181
+ limit = 200,
182
+ bytes = 256 * 1024,
183
+ until?: Cursor,
184
+ ): { rows: Cell[][]; last: Cursor; held: Copied; ended: boolean } => {
185
+ let read = ranged(driver, t, after, until ?? null, limit)
186
+ let rows: Cell[][] = [], size = 0, { rows: n, digest } = held
187
+ for (let row of read) {
188
+ rows.push(row)
189
+ n++
190
+ digest = mixed(digest, row)
191
+ size += JSON.stringify(row).length
192
+ if (size > bytes) break
193
+ }
194
+ return {
195
+ rows,
196
+ last: rows.length ? rows[rows.length - 1][0] as Cursor : null,
197
+ held: { rows: n, digest },
198
+ ended: rows.length == read.length &&
199
+ (read.length < limit || (until != null && rows.at(-1)?.[0] == until)),
200
+ }
201
+ }
202
+
203
+ /** Each table's last rowid as it stands, 0 for an empty one, so a reader
204
+ * can ask a long table in ranges at once. */
205
+ export let tips = (driver: Driver, p: Plan): Record<string, number> =>
206
+ Object.fromEntries(
207
+ p.tables.filter((t) => !t.key).map((t) => [
208
+ t.name,
209
+ Number(
210
+ queryPhysical(
211
+ driver,
212
+ select({
213
+ cols: [as(fn('max', col(ROWID)), 'tip')],
214
+ from: table(t.name),
215
+ }),
216
+ )[0]?.tip ?? 0,
217
+ ),
218
+ ]),
219
+ )
220
+
221
+ /** One run of a table's rows, its digest and where it ends. */
222
+ export type Chunk = {
223
+ table: string
224
+ after: Cursor
225
+ /** the last rowid in the run; null runs past every rowid the far end holds */
226
+ last: Cursor
227
+ held: Copied
228
+ }
229
+
230
+ let ranged = (
231
+ driver: Driver,
232
+ t: Plan['tables'][number],
233
+ after: Cursor,
234
+ last: Cursor,
235
+ limit?: number,
236
+ ) =>
237
+ queryPhysical(
238
+ driver,
239
+ select({
240
+ cols: [
241
+ ...t.key ? [] : [as(col(ROWID), ROWID)],
242
+ ...t.cols.map((c) => col(c)),
243
+ ],
244
+ from: table(t.name),
245
+ where: between(t, after, last),
246
+ order: [col(t.key ?? ROWID)],
247
+ ...limit ? { limit: val(limit) } : {},
248
+ }),
249
+ ).map((r) => [r[t.key ?? ROWID] as Cursor, ...t.cols.map((c) => cell(r[c]))])
250
+
251
+ let digestOf = (rows: Cell[][]): Copied => {
252
+ let held = raised()
253
+ for (let row of rows) {
254
+ held = { rows: held.rows + 1, digest: mixed(held.digest, row) }
255
+ }
256
+ return held
257
+ }
258
+
259
+ /** Every table as runs of `size` rows with their digests. Each table's last run
260
+ * stands for everything past the rows it has, so rows the far end holds that
261
+ * this end no longer does read as a difference too. */
262
+ export let chunks = (driver: Driver, p: Plan, size = 500): Chunk[] =>
263
+ p.tables.flatMap((t) => {
264
+ let found: Chunk[] = [], after = first(t)
265
+ while (true) {
266
+ let rows = ranged(driver, t, after, null, size)
267
+ if (rows.length < size) {
268
+ found.push({ table: t.name, after, last: null, held: digestOf(rows) })
269
+ return found
270
+ }
271
+ let last = rows[rows.length - 1][0] as Cursor
272
+ found.push({ table: t.name, after, last, held: digestOf(rows) })
273
+ after = last
274
+ }
275
+ })
276
+
277
+ /** Those of a source's chunks that this end holds differently. */
278
+ export let stale = (driver: Driver, p: Plan, source: Chunk[]): Chunk[] => {
279
+ let tables = new Map(p.tables.map((t) => [t.name, t]))
280
+ return source.filter((c) => {
281
+ let held = digestOf(ranged(driver, tables.get(c.table)!, c.after, c.last))
282
+ return held.rows != c.held.rows || held.digest != c.held.digest
283
+ })
284
+ }
285
+
286
+ /** A source's rows for a chunk. */
287
+ export let reread = (driver: Driver, p: Plan, c: Chunk): Cell[][] =>
288
+ ranged(driver, p.tables.find((t) => t.name == c.table)!, c.after, c.last)
289
+
290
+ /** A chunk's rows put in place of what this end holds there. */
291
+ export let overwritten = (
292
+ driver: Driver,
293
+ p: Plan,
294
+ c: Chunk,
295
+ rows: Cell[][],
296
+ ): void => {
297
+ let t = p.tables.find((t) => t.name == c.table)!
298
+ driver.query({ t: 'pragma', name: 'foreign_keys', value: 'off' })
299
+ unit(driver, () => {
300
+ queryPhysical(driver, {
301
+ t: 'delete',
302
+ from: t.name,
303
+ where: between(t, c.after, c.last),
304
+ })
305
+ })
306
+ arrived(driver, t, rows)
307
+ }
308
+
309
+ /** What a whole table holds, read as `page` reads it. */
310
+ export let tallied = (driver: Driver, t: Plan['tables'][number]): Copied => {
311
+ let held = raised(), after = first(t)
312
+ while (true) {
313
+ let next = page(driver, t, after, held)
314
+ if (next.last == null) return next.held
315
+ ;({ held } = next)
316
+ after = next.last
317
+ }
318
+ }
319
+
320
+ /** The far end's first step: its tables made, empty, with foreign keys off for
321
+ * this connection until `ending` turns them back on. */
322
+ export let copied = (driver: Driver, p: Plan): void => {
323
+ driver.query({ t: 'pragma', name: 'foreign_keys', value: 'off' })
324
+ unit(driver, () => {
325
+ for (let t of p.tables) driver.query({ t: 'catalogued', sql: t.sql })
326
+ })
327
+ }
328
+
329
+ /** Fit the far end's tables to a newer plan before comparing ranges. Keep
330
+ * rows in tables whose definitions still match. If the schema moved, leave
331
+ * indexes, triggers and views for `ending` once the rows agree. */
332
+ export let align = (driver: Driver, p: Plan): boolean => {
333
+ let objects = schema(driver)
334
+ let fts = ftsOf(objects)
335
+ let tables = objects.filter((o) => rowed(o, fts))
336
+ let virtuals = objects.filter((o) => virtual(o.sql))
337
+ let others = objects.filter((o) => o.type != 'table')
338
+ let held = new Set([...tables, ...virtuals, ...others].map((o) => o.sql))
339
+ let wanted = [
340
+ ...p.tables.map((t) => t.sql),
341
+ ...p.fts.map((t) => t.sql),
342
+ ...p.views,
343
+ ...p.after,
344
+ ]
345
+ if (held.size == wanted.length && wanted.every((sql) => held.has(sql))) {
346
+ return true
347
+ }
348
+
349
+ let definitions = new Set(p.tables.map((t) => t.sql))
350
+ let changed = tables.filter((o) => !definitions.has(String(o.sql)))
351
+ driver.query({ t: 'pragma', name: 'foreign_keys', value: 'off' })
352
+ unit(driver, () => {
353
+ for (let o of [...others, ...virtuals, ...changed]) {
354
+ queryPhysical(driver, {
355
+ t: 'drop',
356
+ kind: o.type as Drop['kind'],
357
+ name: String(o.name),
358
+ })
359
+ }
360
+ for (let t of p.tables) {
361
+ if (!held.has(t.sql)) driver.query({ t: 'catalogued', sql: t.sql })
362
+ }
363
+ })
364
+ return false
365
+ }
366
+
367
+ /** Rows into their table, under the rowids they have always had. */
368
+ export let arrived = (
369
+ driver: Driver,
370
+ t: Plan['tables'][number],
371
+ rows: Cell[][],
372
+ ): void => {
373
+ driver.query({ t: 'pragma', name: 'foreign_keys', value: 'off' })
374
+ unit(driver, () => {
375
+ for (let row of rows) {
376
+ driver.query({
377
+ t: 'insert',
378
+ or: 'replace',
379
+ into: t.name,
380
+ cols: t.key ? t.cols : [ROWID, ...t.cols],
381
+ rows: [(t.key ? row.slice(1) : row).map((c) => val(bound(c)))],
382
+ })
383
+ }
384
+ })
385
+ }
386
+
387
+ /** The far end's last step: indexes, triggers, views, counters and statistics,
388
+ * and foreign keys on. */
389
+ export let ending = (driver: Driver, p: Plan): void => {
390
+ unit(driver, () => {
391
+ for (let sql of p.views) driver.query({ t: 'catalogued', sql })
392
+ for (let { name, sql } of p.fts) {
393
+ driver.query({ t: 'catalogued', sql })
394
+ driver.query({
395
+ t: 'insert',
396
+ into: name,
397
+ cols: [name],
398
+ rows: [[val('rebuild')]],
399
+ })
400
+ }
401
+ for (let sql of p.after) driver.query({ t: 'catalogued', sql })
402
+ for (let { name, seq } of p.sequences) {
403
+ driver.query({
404
+ t: 'update',
405
+ table: 'sqlite_sequence',
406
+ set: { seq: val(seq) },
407
+ where: eq(col('name'), val(name)),
408
+ })
409
+ }
410
+ })
411
+ driver.query({ t: 'pragma', name: 'foreign_keys', value: 'on' })
412
+ for (let t of p.tables) driver.query({ t: 'analyze', table: t.name })
413
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"compilerOptions":{"lib":["dom","esnext"]},"publish":{"exclude":["**/*_test.ts","testing.ts","conform.ts","workers.json"]},"name":"@yaks/durable-object","version":"0.2.36","license":"Apache-2.0","description":"Provides graph storage on a Cloudflare Durable Object's embedded SQLite and connects hibernatable WebSockets to query subscriptions.","exports":{".":"./mod.ts","./sql":"./sql.ts","./store":"./store.ts","./resets":"./resets.ts","./ceiling":"./ceiling.ts","./keys":"./keys.ts","./alarm":"./alarm.ts","./object":"./object.ts","./door":"./door.ts","./compose":"./compose.ts","./rewind":"./rewind.ts"},"imports":{"@yaks/durable-object":"./mod.ts","@yaks/durable-object/sql":"./sql.ts","@yaks/durable-object/store":"./store.ts","@yaks/durable-object/resets":"./resets.ts","@yaks/durable-object/ceiling":"./ceiling.ts","@yaks/durable-object/keys":"./keys.ts","@yaks/durable-object/alarm":"./alarm.ts","@yaks/durable-object/object":"./object.ts","@yaks/durable-object/door":"./door.ts","@yaks/durable-object/compose":"./compose.ts","@yaks/durable-object/rewind":"./rewind.ts"}}