@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/ceiling.ts ADDED
@@ -0,0 +1,681 @@
1
+ // What an object's SQL may cost before it says so, and stops. Cloudflare bills
2
+ // every row a statement reads or writes, whether or not it is returned, and
3
+ // offers no cap on it: its budget alerts "are informational only. They do not
4
+ // pause or cap usage", and they arrive a day late
5
+ // (https://developers.cloudflare.com/billing/manage/budget-alerts/). So the
6
+ // bound is kept where statements run. The driver (./sql.ts) counts each
7
+ // statement against the windows here, and two failures are told as they
8
+ // happen, never an hour later:
9
+ //
10
+ // Scan one statement read `SCAN` rows or more, and `FAR` times what it
11
+ // represented in its answer or wrote.
12
+ // Runaway the object's statements together passed a window's rows.
13
+ //
14
+ // An object that `refuse`s takes no statement from then until the window
15
+ // ends: each is refused as `Stopped`, a 429 that says how long to wait, so a
16
+ // caller sends it again and a pool or a queue redelivers after the wait. Past
17
+ // its written rows it still reads; past its read rows it takes nothing. What a
18
+ // host must still write while stopped (keeping a person's write for later,
19
+ // or a pool's word on how a run ended) it runs in `free`, synchronously or
20
+ // across awaits, which counts against windows of its own: told past them,
21
+ // it stops nothing, so work that must not stop leaves no stop behind it.
22
+ // Work whose cost is the object's own size, once, is `take`n: a deploy's
23
+ // schema, or an index over a table past what any window writes, which SQLite
24
+ // builds in one statement no window can split. It stops nothing and is told
25
+ // only as a scan, since it never runs away: it ends when the file is built. A
26
+ // host asks `stopped` at its doors, so a stopped object answers there rather
27
+ // than failing deep inside, and one whose stopping costs more than its rows
28
+ // (every door reads it) is `spare`d: told, never refused.
29
+ //
30
+ // The tallies outlive the instance that counted them, so an object evicted
31
+ // or restarted mid-window (a deploy restarts every object) goes on where it
32
+ // stood rather than spending another window's rows. Keeping them costs no row
33
+ // a statement: a window is kept, in one row of the object's own key-value
34
+ // storage (`ctx.storage.kv`), only as its rows pass half of what it may and as
35
+ // they pass all of it. That is at most two rows written a window for reads and
36
+ // two for writes, and none for an object that spends under half; a new
37
+ // instance reads that row once, at its first statement. An instance that ends
38
+ // unkept loses less than half a window.
39
+
40
+ import { AsyncLocalStorage } from 'node:async_hooks'
41
+ import { type Cost, finish, type Group, group, id, tally } from './profile.js'
42
+
43
+ /** A span of time and the rows an object may read and write within it. */
44
+ export type Window = { ms: number; read: number; written: number }
45
+
46
+ /** What a window spent since it began, as an object keeps it past its
47
+ * instance. */
48
+ export type Spent = {
49
+ ms: number
50
+ since: number
51
+ read: number
52
+ written: number
53
+ /** What each lane's work spent of it ({@link Ceiling.lane}). */
54
+ lanes?: Record<string, { read: number; written: number }>
55
+ /** The window was opened by {@link Ceiling.resume}. */
56
+ resumed?: boolean
57
+ }
58
+
59
+ /** A minute and an hour. At Cloudflare's prices ($0.001 a million rows read,
60
+ * $1.00 a million written,
61
+ * https://developers.cloudflare.com/durable-objects/platform/pricing/) an
62
+ * object that refuses costs at most $0.20 of reads and $0.50 of writes in an
63
+ * hour of its window, and one statement more. The week before these were set
64
+ * (2026-11-03 to 11-10, Cloudflare's analytics) the platform's directory
65
+ * peaked at 13.7 million rows read in a minute and 15.6 million in an hour,
66
+ * and no object but the tracker in its storm wrote 100,000 in a minute. */
67
+ export let WINDOWS: Window[] = [
68
+ { ms: 60_000, read: 50e6, written: 100_000 },
69
+ { ms: 3_600_000, read: 200e6, written: 500_000 },
70
+ ]
71
+
72
+ /** The rows one statement reads before it can be a scan. */
73
+ export let SCAN = 100_000
74
+ /** How many times what its answer represents or it wrote a scan reads. */
75
+ export let FAR = 100
76
+ // A statement costing fewer rows than this is counted and never named: its
77
+ // shape is not rendered for the tally.
78
+ let NAMED = 1_000
79
+ // How much of a scan's shape its report keeps: the whole of what a reader's
80
+ // screen puts before the statement's own condition and order. Cut at 240, a
81
+ // screened page's report named only its screen (bug 766b671e).
82
+ let SHOWN = 12_000
83
+ let HOUR = 3_600_000
84
+
85
+ type Kind = 'read' | 'written'
86
+ let KINDS: Kind[] = ['read', 'written']
87
+
88
+ // A window as it is counted: since when, what it spent and by which
89
+ // statements, what an earlier instance spent of it, what each lane spent of
90
+ // it, whether it is past its rows, and at which rows it is kept next.
91
+ type Span = Window & {
92
+ since: number
93
+ all: Group
94
+ earlier: Record<Kind, number>
95
+ lanes: Map<string, Record<Kind, number>>
96
+ past: Record<Kind, boolean>
97
+ mark: Record<Kind, number>
98
+ resumed: boolean
99
+ }
100
+
101
+ /** One statement read far more rows than its answer represents. */
102
+ export class Scan extends Error {
103
+ override name = 'Scan'
104
+ }
105
+
106
+ /** An object's statements passed a window's rows. */
107
+ export class Runaway extends Error {
108
+ override name = 'Runaway'
109
+ }
110
+
111
+ /** A statement refused because its object is past a window: the caller's to
112
+ * send again once `retry.after` milliseconds have run, and no defect of its
113
+ * own, since the `Runaway` that stopped the object was told when it happened.
114
+ * `retry.defer` says the wait is no failure: @yaks/effects runs the attempt
115
+ * again as the same one, as it does a handler's `defer`. */
116
+ export class Stopped extends Error {
117
+ override name = 'Stopped'
118
+ status = 429
119
+ retry: { after: number; defer: true }
120
+ constructor(
121
+ after: number,
122
+ kind: Kind,
123
+ window?: { ms: number; limit: number; spent: number },
124
+ ) {
125
+ super(
126
+ `this store is over its ${kind == 'read' ? 'read' : 'write'} limit` +
127
+ (window
128
+ ? ` of ${window.limit.toLocaleString('en-US')} rows in a ${
129
+ span(window.ms)
130
+ } window ` +
131
+ `(${window.spent.toLocaleString('en-US')} rows ${kind})`
132
+ : '') +
133
+ ` — try again in ${Math.ceil(after / 1000)} s`,
134
+ )
135
+ this.retry = { after, defer: true }
136
+ }
137
+ }
138
+
139
+ /** Whether a failure is a statement an object refused as `Stopped`, met in
140
+ * that object or through its stub. An RPC hands its caller a new error with
141
+ * the name, message and own properties it was thrown with, never its class
142
+ * (https://developers.cloudflare.com/workers/runtime-apis/rpc/error-handling/,
143
+ * from compatibility date 2026-04-21), so it is known by those: its name and
144
+ * the wait it asks for. Another package's error of the same name asks none.
145
+ *
146
+ * ```ts
147
+ * import { equal } from '@yaks/testing'
148
+ * import { crossed } from './testing.ts'
149
+ * let stop = new Stopped(42_000, 'written'), over = crossed(stop)
150
+ * equal([stopped(stop), stopped(over), over instanceof Stopped], [true, true, false])
151
+ * equal(over.message, stop.message)
152
+ * equal(stopped(over) && over.retry, { after: 42_000, defer: true })
153
+ * equal(stopped(Object.assign(Error('esbuild ended'), { name: 'Stopped' })), false)
154
+ * ```
155
+ */
156
+ export let stopped = (error: unknown): error is Stopped =>
157
+ error instanceof Error && error.name == 'Stopped' &&
158
+ typeof (error as { retry?: { after?: unknown } }).retry?.after == 'number'
159
+
160
+ /** What a report is filed under: `fault` groups its occurrences on one bug
161
+ * (a scan by its statement, a runaway by which rows), and `tags` name the
162
+ * statement. The host adds which object. */
163
+ export type Told = { fault: string; tags: Record<string, string> }
164
+ export type Report = (error: Scan | Runaway, told: Told) => void
165
+
166
+ export type Options = {
167
+ windows?: Window[]
168
+ now?: () => number
169
+ /** Where a scan and a runaway go; each is also said on the console. */
170
+ report?: Report
171
+ /** Whether a statement past a window is refused, or only reported. */
172
+ refuse?: boolean
173
+ /** What an earlier instance of the object kept, asked at its first
174
+ * statement. */
175
+ kept?: () => Spent[] | undefined
176
+ /** Keep what the windows spent past this instance: at half and all of
177
+ * the object's allowance, and after a lane spends rows. */
178
+ keep?: (spent: Spent[]) => void
179
+ }
180
+
181
+ /** One statement as the driver counts it. `shape` is asked only of a
182
+ * statement costly enough to name. */
183
+ export type Counted = {
184
+ shape: () => string
185
+ rowsRead: number
186
+ rowsWritten: number
187
+ returned: number
188
+ /** Selected input rows represented by aggregate answers, when known. */
189
+ matched?: number
190
+ }
191
+
192
+ export type Ceiling = {
193
+ /** Refuse a statement while its object is stopped. */
194
+ admit: (writing: boolean) => void
195
+ count: (statement: Counted) => void
196
+ /** What a statement would be refused with now, if anything. */
197
+ refusal: (writing?: boolean) => Stopped | null
198
+ /** How long until a statement is admitted, in ms: 0 when one is now. */
199
+ stopped: (writing?: boolean) => number
200
+ /** How long until the object has spent under `share` of every window's
201
+ * rows, read and written, in ms: 0 when it has now. Work that can wait (a
202
+ * store's mover) asks it before it spends more, and leaves the rest of each
203
+ * window to the object's requests. `written` reserves a prospective unit;
204
+ * Infinity means it cannot fit even in an empty window at that share. With
205
+ * a `lane`, the share is of what that lane's own work spent ({@link lane}),
206
+ * so one lane's backlog never spends another's allowance. `burst` is how
207
+ * many milliseconds of a window's share are available in advance. With a
208
+ * burst shorter than the window, its share becomes available over time. */
209
+ under: (
210
+ share: number,
211
+ written?: number,
212
+ lane?: string,
213
+ burst?: number,
214
+ ) => number
215
+ /** Run `body` as a lane's work, across awaits until it settles. The lane
216
+ * counts ordinary and free statements and keeps its spend when it ends. */
217
+ lane: <T>(name: string, body: () => T) => T
218
+ /** Run statements a stopped object must still take: `body`'s own, and
219
+ * those of the work it awaits until it settles. What they cost is told,
220
+ * and stops nothing. */
221
+ free: <T>(body: () => T) => T
222
+ /** Run work the object takes whatever it costs, once: its schema, an index
223
+ * no window can hold. Like {@link free} it stops nothing, across awaits;
224
+ * its rows count against no window and are never told as a runaway, only
225
+ * as a scan. Work it awaits that runs `free` is told as free work is. */
226
+ take: <T>(body: () => T) => T
227
+ /** Refuse nothing from now on, and go on telling: for an object whose
228
+ * stopping costs more than its rows. */
229
+ spare: () => void
230
+ /** Current window counters, including those kept by an earlier instance. */
231
+ spent: () => Spent[]
232
+ /** Start fresh windows after an operator repairs a runaway, except one an
233
+ * earlier resume opened, which stands until it ends; return the old
234
+ * counters. */
235
+ resume: () => Spent[]
236
+ }
237
+
238
+ // An amount of rows as a person reads it: 264.5M, 480,000.
239
+ let rows = (n: number) =>
240
+ n >= 1e6
241
+ ? `${+(n / 1e6).toFixed(1)}M`
242
+ : String(Math.round(n)).replace(/\B(?=(\d{3})+$)/g, ',')
243
+
244
+ // Rows of a kind a tally spent.
245
+ let amount = (c: Cost, k: Kind) => k == 'read' ? c.rowsRead : c.rowsWritten
246
+
247
+ // What this instance's statements a runaway cannot name spent of its kind:
248
+ // those under `NAMED` rows, and those past the shapes it keeps. Many small
249
+ // ones (a mover's deletes, each a few rows with its indexes) can pass a window
250
+ // with no named statement that spent any. What an earlier instance spent is
251
+ // its own line, since only its total was kept.
252
+ let unnamed = (s: Span, k: Kind) =>
253
+ `${rows(amount(s.all.other, k))} rows ${k} by statements too small or ` +
254
+ `too many to name`
255
+ let earlier = (s: Span, k: Kind) =>
256
+ `${rows(s.earlier[k])} rows ${k} before this instance began`
257
+
258
+ let span = (ms: number) => ms >= HOUR ? `${ms / HOUR} h` : `${ms / 60_000} min`
259
+
260
+ /** An object's ceiling: its windows, and what it has told.
261
+ *
262
+ * ```ts
263
+ * import { ceiling, Stopped } from './ceiling.ts'
264
+ * import { equal, throws } from '@yaks/testing'
265
+ *
266
+ * let at = 0, said: string[] = []
267
+ * let c = ceiling({
268
+ * windows: [{ ms: 60_000, read: 1_000_000, written: 100 }],
269
+ * now: () => at,
270
+ * report: (e, told) => said.push(`${e.name} ${told.fault}`),
271
+ * refuse: true,
272
+ * })
273
+ * let ran = (rowsRead: number, returned = 0, rowsWritten = 0) =>
274
+ * c.count({ shape: () => 'select "t"', rowsRead, rowsWritten, returned })
275
+ * ran(200_000, 3)
276
+ * equal(said.map((s) => s.split('|')[0]), ['Scan scan'])
277
+ * c.admit(false)
278
+ * ran(900_000, 900_000)
279
+ * equal(said.at(-1), 'Runaway runaway|read')
280
+ * equal((await throws(() => c.admit(false))) instanceof Stopped, true)
281
+ * equal(c.free(() => (c.admit(true), 'kept')), 'kept')
282
+ * equal(c.stopped(), 60_000)
283
+ * at = 60_000
284
+ * c.admit(false)
285
+ * ```
286
+ */
287
+ export let ceiling = (
288
+ { windows = WINDOWS, now = Date.now, report, refuse = false, kept, keep }:
289
+ Options = {},
290
+ ): Ceiling => {
291
+ let spent = (s: Span, k: Kind) =>
292
+ k == 'read' ? s.all.total.rowsRead : s.all.total.rowsWritten
293
+ // Whether a span is past its rows of a kind, and the rows at which it is
294
+ // kept next: half of what it may, then all of it.
295
+ let marked = (s: Span, k: Kind) => {
296
+ let n = spent(s, k)
297
+ s.past[k] = n > s[k]
298
+ s.mark[k] = s.past[k] ? Infinity : n > s[k] / 2 ? s[k] : s[k] / 2
299
+ }
300
+ let turned = (
301
+ { ms, read, written }: Window,
302
+ since: number,
303
+ was?: Spent,
304
+ resumed = was?.resumed ?? false,
305
+ ): Span => {
306
+ let s = {
307
+ ms,
308
+ read,
309
+ written,
310
+ since,
311
+ resumed,
312
+ all: group(),
313
+ earlier: { read: was?.read ?? 0, written: was?.written ?? 0 },
314
+ lanes: new Map(),
315
+ past: { read: false, written: false },
316
+ mark: { read: 0, written: 0 },
317
+ }
318
+ if (was) {
319
+ s.all.total.rowsRead = was.read
320
+ s.all.total.rowsWritten = was.written
321
+ for (let [name, of] of Object.entries(was.lanes ?? {})) {
322
+ s.lanes.set(name, { read: of.read, written: of.written })
323
+ }
324
+ }
325
+ for (let k of KINDS) marked(s, k)
326
+ return s
327
+ }
328
+ // What the object's own statements spent, which stops it, and what it ran
329
+ // in `free`, which is told and stops nothing: a relocation's new object
330
+ // writes its whole file before it serves, and serves from then on. The
331
+ // first is taken up from where an earlier instance kept it.
332
+ let spans: Span[] | undefined
333
+ let begun = () => {
334
+ let was = kept?.() ?? []
335
+ return windows.map((w) => {
336
+ let k = was.find((k) => k.ms == w.ms)
337
+ return turned(w, k?.since ?? -Infinity, k)
338
+ })
339
+ }
340
+ let live = () => spans ??= begun()
341
+ let loose = windows.map((w) => turned(w, -Infinity))
342
+ // When each scanning statement was last told, by its shape.
343
+ let scans = new Map<string, number>()
344
+ // The work running in `free`, and how many such are running: a statement
345
+ // is free when it runs in one's async context while that work is open. A
346
+ // timer or task the work leaves behind runs charged once it ends.
347
+ let freeing = new AsyncLocalStorage<{ open: boolean; taken?: boolean }>()
348
+ let open = 0
349
+ let freed = () => open > 0 && freeing.getStore()?.open == true
350
+ let taken = () => freed() && freeing.getStore()?.taken == true
351
+ // The lane whose work is running, as `free` knows its own.
352
+ let laning = new AsyncLocalStorage<{
353
+ name: string
354
+ open: boolean
355
+ spent: boolean
356
+ }>()
357
+ // Runs `run` and closes `work` once it settles, across its awaits.
358
+ let settled = <T>(
359
+ work: { open: boolean },
360
+ run: () => T,
361
+ close = () => {},
362
+ ): T => {
363
+ let end = () => {
364
+ work.open = false
365
+ close()
366
+ }
367
+ let out
368
+ try {
369
+ out = run()
370
+ } catch (e) {
371
+ end()
372
+ throw e
373
+ }
374
+ if (!(out instanceof Promise)) return end(), out
375
+ return out.finally(end) as T
376
+ }
377
+ // Runs `body` free, or taken: counted against no window at all.
378
+ let unstopped = <T>(body: () => T, taken: boolean): T => {
379
+ let work = { open: true, taken }
380
+ open++
381
+ return settled(work, () => freeing.run(work, body), () => open--)
382
+ }
383
+ let broken = false
384
+ let say = (error: Scan | Runaway, told: Told) => {
385
+ console.error('storage', told.fault, error.message, JSON.stringify(told))
386
+ try {
387
+ report?.(error, told)
388
+ } catch (e) {
389
+ // A reporter that fails cannot change a store's answer.
390
+ if (!broken) console.error('storage ceiling report failed', e)
391
+ broken = true
392
+ }
393
+ }
394
+ // The window that holds a statement the longest. A read stop wins a tie.
395
+ let held = (writing: boolean) => {
396
+ let at = now(), until = at, kind: Kind = 'read'
397
+ let window: Span | undefined
398
+ for (let s of live()) {
399
+ if (at - s.since >= s.ms) continue
400
+ let end = s.since + s.ms
401
+ let past: Kind | null = s.past.read
402
+ ? 'read'
403
+ : writing && s.past.written
404
+ ? 'written'
405
+ : null
406
+ if (past && (end > until || end == until && past == 'read')) {
407
+ until = end
408
+ kind = past
409
+ window = s
410
+ }
411
+ }
412
+ return { wait: until - at, kind, window }
413
+ }
414
+ let under = (share: number, written = 0, lane?: string, burst = Infinity) => {
415
+ let at = now(), until = at
416
+ for (let s of live()) {
417
+ if (written > share * s.written) return Infinity
418
+ if (at - s.since >= s.ms) continue
419
+ let of = (k: Kind) =>
420
+ lane == null ? spent(s, k) : s.lanes.get(lane)?.[k] ?? 0
421
+ for (let k of KINDS) {
422
+ let allowance = share * s[k]
423
+ let reserved = k == 'written' ? written : 0
424
+ let used = of(k) + reserved
425
+ if (reserved ? used > allowance : used >= allowance) {
426
+ until = Math.max(until, s.since + s.ms)
427
+ } else if (burst < s.ms && used > 0) {
428
+ let earned = Math.ceil(s.ms * used / allowance)
429
+ until = Math.max(until, s.since + earned - burst)
430
+ }
431
+ }
432
+ }
433
+ return until - at
434
+ }
435
+ let windowAt = (windows: Span[], i: number, at: number): Span => {
436
+ let s = windows[i]
437
+ return at - s.since >= s.ms ? windows[i] = turned(s, at) : s
438
+ }
439
+ let remember = () => {
440
+ try {
441
+ keep?.(snapshot())
442
+ } catch (e) {
443
+ console.error('storage ceiling keep failed', e)
444
+ broken = true
445
+ }
446
+ }
447
+ let count = (
448
+ { shape, rowsRead, rowsWritten, returned, matched }: Counted,
449
+ ) => {
450
+ let at = now()
451
+ let named = rowsRead + rowsWritten >= NAMED ? shape() : ''
452
+ let cost: Cost = { calls: 1, rowsRead, rowsWritten }
453
+ let tell: [Scan | Runaway, Told][] = []
454
+ let charged = !freed(), moved = false
455
+ let list = charged ? live() : taken() ? [] : loose
456
+ let lane = taken() ? undefined : laning.getStore()
457
+ if (lane?.open && (rowsRead || rowsWritten)) {
458
+ let spans = live()
459
+ for (let i = 0; i < spans.length; i++) {
460
+ let s = windowAt(spans, i, at)
461
+ let of = s.lanes.get(lane.name) ?? { read: 0, written: 0 }
462
+ of.read += rowsRead
463
+ of.written += rowsWritten
464
+ s.lanes.set(lane.name, of)
465
+ }
466
+ lane.spent = true
467
+ }
468
+ for (let i = 0; i < list.length; i++) {
469
+ let s = windowAt(list, i, at)
470
+ if (named) tally(s.all, { shape: named, rowsRead, rowsWritten }, 16)
471
+ else {
472
+ for (let to of [s.all.total, s.all.other]) {
473
+ to.calls += cost.calls
474
+ to.rowsRead += cost.rowsRead
475
+ to.rowsWritten += cost.rowsWritten
476
+ }
477
+ }
478
+ for (let k of KINDS) {
479
+ let n = spent(s, k)
480
+ if (n <= s.mark[k]) continue
481
+ let was = s.past[k]
482
+ marked(s, k)
483
+ moved = true
484
+ if (was || !s.past[k]) continue
485
+ let top = finish(
486
+ {
487
+ ...s.all,
488
+ other: { ...s.all.other },
489
+ shapes: new Map(s.all.shapes),
490
+ },
491
+ k == 'read' ? 3 : 0,
492
+ k == 'read' ? 0 : 3,
493
+ ).statements.filter((e) => amount(e, k) > 0)
494
+ tell.push([
495
+ new Runaway(
496
+ `${rows(n)} rows ${k} in ${span(s.ms)}, past the ${rows(s[k])} ` +
497
+ `an object may` +
498
+ (!charged
499
+ ? ', in work it never stops'
500
+ : refuse
501
+ ? `: it takes no ${k == 'read' ? 'statement' : 'write'} for ` +
502
+ `${Math.ceil((s.since + s.ms - at) / 1000)} s`
503
+ : ''),
504
+ ),
505
+ {
506
+ fault: `runaway|${k}`,
507
+ tags: {
508
+ rows: String(n),
509
+ window: span(s.ms),
510
+ ...top[0] ? { statement: top[0].shape } : {},
511
+ statements: JSON.stringify(top.map((e) => ({
512
+ shape: e.shape.slice(0, 120),
513
+ calls: e.calls,
514
+ rowsRead: e.rowsRead,
515
+ rowsWritten: e.rowsWritten,
516
+ }))),
517
+ ...amount(s.all.other, k) ? { unnamed: unnamed(s, k) } : {},
518
+ ...s.earlier[k] ? { earlier: earlier(s, k) } : {},
519
+ },
520
+ },
521
+ ])
522
+ }
523
+ }
524
+ if (
525
+ rowsRead >= SCAN &&
526
+ rowsRead >= FAR * Math.max(1, returned, matched ?? 0, rowsWritten)
527
+ ) {
528
+ let key = id(named)
529
+ if (at - (scans.get(key) ?? -Infinity) >= HOUR) {
530
+ if (scans.size >= 64) scans.clear()
531
+ scans.set(key, at)
532
+ tell.push([
533
+ new Scan(
534
+ `one statement read ${rows(rowsRead)} rows and returned ` +
535
+ `${rows(returned)}: far more than its answer represents`,
536
+ ),
537
+ {
538
+ fault: `scan|${key}`,
539
+ tags: {
540
+ statement: named.slice(0, SHOWN),
541
+ rows: String(rowsRead),
542
+ returned: String(returned),
543
+ ...matched != null ? { matched: String(matched) } : {},
544
+ written: String(rowsWritten),
545
+ },
546
+ },
547
+ ])
548
+ }
549
+ }
550
+ if (charged && moved) remember()
551
+ // Told once the tallies stand: a reporter may run statements of its own.
552
+ for (let [error, told] of tell) say(error, told)
553
+ }
554
+ let refusal = (writing = true) => {
555
+ if (!refuse) return null
556
+ let { wait, kind, window } = held(writing)
557
+ return wait && window && !freed()
558
+ ? new Stopped(wait, kind, {
559
+ ms: window.ms,
560
+ limit: window[kind],
561
+ spent: spent(window, kind),
562
+ })
563
+ : null
564
+ }
565
+ let snapshot = (): Spent[] =>
566
+ live().map((s) => ({
567
+ ms: s.ms,
568
+ since: s.since,
569
+ read: s.all.total.rowsRead,
570
+ written: s.all.total.rowsWritten,
571
+ ...s.resumed ? { resumed: true } : {},
572
+ ...s.lanes.size
573
+ ? {
574
+ lanes: Object.fromEntries(
575
+ [...s.lanes].map(([name, of]) => [name, { ...of }]),
576
+ ),
577
+ }
578
+ : {},
579
+ }))
580
+ return {
581
+ admit: (writing) => {
582
+ let no = refusal(writing)
583
+ if (no) throw no
584
+ },
585
+ count,
586
+ refusal,
587
+ stopped: (writing) => refusal(writing)?.retry.after ?? 0,
588
+ under,
589
+ free: (body) => unstopped(body, false),
590
+ take: (body) => unstopped(body, true),
591
+ lane: (name, body) => {
592
+ let work = { name, open: true, spent: false }
593
+ return settled(work, () => laning.run(work, body), () => {
594
+ if (work.spent) remember()
595
+ })
596
+ },
597
+ spare: () => {
598
+ refuse = false
599
+ },
600
+ spent: snapshot,
601
+ // A resume opens each window once: a window an earlier resume opened
602
+ // keeps its count until it ends, so resuming again and again spends at
603
+ // most two windows' rows in one, never a fresh window a call.
604
+ resume: () => {
605
+ let before = snapshot(), at = now()
606
+ spans = live().map((s, i) =>
607
+ s.resumed && at - s.since < s.ms
608
+ ? s
609
+ : turned(windows[i], at, undefined, true)
610
+ )
611
+ keep?.(snapshot())
612
+ return before
613
+ },
614
+ }
615
+ }
616
+
617
+ // One ceiling an object: every driver over one storage is one connection
618
+ // (./sql.ts), so they count against the same windows.
619
+ let ceilings = new WeakMap<object, Ceiling>()
620
+
621
+ /** The synchronous key-value storage of a SQLite-backed object
622
+ * (`ctx.storage.kv`), as far as a ceiling keeps its windows in it. */
623
+ export type Kv = {
624
+ get(key: string): unknown
625
+ put(key: string, value: unknown): void
626
+ delete?(key: string): boolean | void
627
+ }
628
+
629
+ // Where an object keeps what its windows spent.
630
+ let KEPT = 'ceiling:spent'
631
+
632
+ // A ceiling's windows kept in an object's own storage. A window is kept once
633
+ // the turn that passed its mark is over: a statement's transaction can unwind
634
+ // after it was counted (the `Stopped` it passed unwinds it), and the engine
635
+ // read and wrote its rows all the same.
636
+ let lasting = (kv: Kv | undefined): Pick<Options, 'kept' | 'keep'> => {
637
+ if (!kv) return {}
638
+ let due: Spent[] | undefined
639
+ let put = () => {
640
+ let spent = due
641
+ due = undefined
642
+ try {
643
+ kv.put(KEPT, spent)
644
+ } catch (e) {
645
+ console.error('storage ceiling keep failed', e)
646
+ }
647
+ }
648
+ return {
649
+ kept: () => {
650
+ try {
651
+ let spent = kv.get(KEPT)
652
+ return Array.isArray(spent) ? spent : undefined
653
+ } catch (e) {
654
+ console.error('storage ceiling kept unread', e)
655
+ }
656
+ },
657
+ keep: (spent) => {
658
+ if (!due) queueMicrotask(put)
659
+ due = spent
660
+ },
661
+ }
662
+ }
663
+
664
+ /** The ceiling of the object whose storage this is. A host names its
665
+ * reporter and whether it refuses once, as it is constructed, before its
666
+ * first driver; a storage nobody spoke for is counted and reported on the
667
+ * console.
668
+ *
669
+ * ```ts
670
+ * // bounded(ctx.storage, { report, refuse: true })
671
+ * // let sql = driver(ctx.storage) // counted against it
672
+ * ```
673
+ */
674
+ export let bounded = (durable: object, options?: Options): Ceiling => {
675
+ let kv = (durable as { kv?: Kv }).kv
676
+ let made = options
677
+ ? ceiling({ ...lasting(kv), ...options })
678
+ : ceilings.get(durable) ?? ceiling(lasting(kv))
679
+ ceilings.set(durable, made)
680
+ return made
681
+ }