@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/compose.js ADDED
@@ -0,0 +1,201 @@
1
+ /**
2
+ * An object's graph, composed from a named config through @yaks/host: what
3
+ * one kind of object holds is data (its config, the roles it serves, and where
4
+ * its plugins' facets load from), so two kinds that differ only by their
5
+ * plugins are the one class given two configs.
6
+ *
7
+ * - {@link planned} imports the facets a config's roles serve once an
8
+ * isolate (@yaks/host `prepare`), and assembles them once a vocabulary
9
+ * (`assemble`): every instance of a kind shares its plan, and binds it to
10
+ * its own storage.
11
+ * - {@link lent} is what an object lends what it composes. It hosts no
12
+ * process, so nothing it composes runs a duty, ends a process or keeps a
13
+ * secret past the instance.
14
+ * - {@link composed} is the whole {@link Spec}: the graph over the object's
15
+ * SQLite (`./store.ts`) with its blobs beside it, `api({graph, subs})` as
16
+ * its door and `/ws` as its sockets, and its wakes and effects pool as the
17
+ * works its alarm runs (`./alarm.ts`).
18
+ *
19
+ * ```ts
20
+ * import { Durable } from '@yaks/durable-object/object'
21
+ * import { composed } from '@yaks/durable-object/compose'
22
+ * import { durable } from './testing.ts'
23
+ * import { assertEquals } from '@std/assert'
24
+ *
25
+ * let config = { plugins: ['shelf'] }
26
+ * let load = () =>
27
+ * Promise.resolve({
28
+ * docs: [{
29
+ * $defs: {
30
+ * book: { component: true, properties: { title: { type: 'string' } } },
31
+ * },
32
+ * }],
33
+ * })
34
+ * let ctx = { storage: durable(), acceptWebSocket() {}, getWebSockets: () => [] }
35
+ * let shelf = new Durable(ctx, composed(config, load))
36
+ * await shelf.fetch(
37
+ * new Request('https://do/apply', {
38
+ * method: 'POST',
39
+ * body: JSON.stringify([{ entity: { eid: 'b' }, book: { title: 'Dune' } }]),
40
+ * }),
41
+ * )
42
+ * let read = await shelf.fetch(new Request('https://do/query?q=.book'))
43
+ * assertEquals((await read.json())[0].book, { title: 'Dune' })
44
+ * ```
45
+ *
46
+ * @module
47
+ */ import { assemble, prepare } from "@yaks/host/assembly";
48
+ import { lazy } from "@yaks/fp";
49
+ import { effects } from "@yaks/effects";
50
+ import { blobSchema, sqliteBlobs } from "@yaks/blob";
51
+ import { ramVault } from "@yaks/secrets/vault";
52
+ import { statements } from "@yaks/sqlite";
53
+ import { soonest, tick } from "@yaks/wake";
54
+ import { driver } from "./sql.js";
55
+ import { storage } from "./store.js";
56
+ /** What an object serves unless its config says otherwise: its graph, and
57
+ * the effects its alarm works. */ export let ROLES = [
58
+ 'graph',
59
+ 'effects'
60
+ ];
61
+ // Plans by config, load and roles: a kind is planned once an isolate, by
62
+ // whichever of its instances asks first.
63
+ let plans = new WeakMap();
64
+ /** The plan for `config`'s `roles`, with facets from `load`, made once an
65
+ * isolate. One whose import failed is imported again by the next to ask. */ export let planned = (config, load, roles = ROLES)=>{
66
+ let byLoad = plans.get(config);
67
+ if (!byLoad) plans.set(config, byLoad = new WeakMap());
68
+ let byRoles = byLoad.get(load);
69
+ if (!byRoles) byLoad.set(load, byRoles = new Map());
70
+ let key = roles.join(), plan = byRoles.get(key);
71
+ if (plan) return plan;
72
+ // Kept as a value once loaded: a plan is shared by every object and
73
+ // request of an isolate (@yaks/fp `lazy`).
74
+ plan = lazy(()=>prepare(config, roles, load).then((facets)=>{
75
+ let own;
76
+ let worded = new WeakMap();
77
+ let assembly = (words)=>assemble(config, roles, load, facets, words ? {
78
+ words
79
+ } : {});
80
+ return (words)=>{
81
+ if (!words) return own ??= assembly();
82
+ let held = worded.get(words);
83
+ if (!held) worded.set(words, held = assembly(words));
84
+ return held;
85
+ };
86
+ }));
87
+ byRoles.set(key, plan);
88
+ return plan;
89
+ };
90
+ /** What an object lends the plugins it composes, as `me`, its bodies kept in
91
+ * `blobs`. */ export let lent = (me, blobs)=>({
92
+ me,
93
+ vault: ramVault(),
94
+ blobs,
95
+ artifacts: blobs,
96
+ stopping: new AbortController().signal,
97
+ duties: ()=>Promise.resolve(),
98
+ end: ()=>Promise.resolve(),
99
+ bury: ()=>Promise.resolve([]),
100
+ gone: ()=>Promise.resolve(false)
101
+ });
102
+ /**
103
+ * The spec of an object composed from `config`, with facets from `load`: its
104
+ * graph over the object's SQLite, schema and blobs installed as it opens; its
105
+ * door `api({graph, subs, db})`, which keeps its receipts in the object's
106
+ * SQLite and hands `/ws` to its sockets; and as its
107
+ * works, the wakes due (@yaks/wake `tick`) and the effects pool, each
108
+ * answering when it is next owed. A write that moves a wake or owes a run arms
109
+ * the alarm.
110
+ */ export let composed = (config, load, options = {})=>{
111
+ let plan = planned(config, load, options.roles);
112
+ let report = options.report ?? ((error, entry)=>console.error(entry, error));
113
+ return {
114
+ report,
115
+ ...options.version ? {
116
+ version: options.version
117
+ } : {},
118
+ open: async (object)=>{
119
+ let assembly = (await plan())(options.words);
120
+ let { host } = bound(object, assembly, report);
121
+ let g = host.graph, fx = host.fx;
122
+ // The door, loaded only by an object that opens one.
123
+ let { api, subscriptions } = await import("@yaks/api");
124
+ let subs = subscriptions(g);
125
+ let door = api({
126
+ graph: g,
127
+ subs,
128
+ db: host.storage.statements
129
+ });
130
+ let wakes = !!host.vocab.comp('wake'), runs = !!host.vocab.comp('effect');
131
+ return {
132
+ serve: (request)=>new URL(request.url).pathname == '/ws' ? object.accept(request) : door(request),
133
+ subs,
134
+ works: {
135
+ ...wakes ? {
136
+ wakes: async ()=>{
137
+ let now = Date.now();
138
+ for (let { error } of (await tick(g, now)).refused){
139
+ report(error, 'alarm wakes');
140
+ }
141
+ return await soonest(g, now);
142
+ }
143
+ } : {},
144
+ ...runs ? {
145
+ effects: async (until)=>{
146
+ await fx.work(g, undefined, {
147
+ until
148
+ });
149
+ await fx.idle();
150
+ return await fx.next(g);
151
+ }
152
+ } : {}
153
+ }
154
+ };
155
+ }
156
+ };
157
+ };
158
+ // `assembly` bound inside `object`: its storage, its blobs and its pool.
159
+ let bound = (object, assembly, report)=>{
160
+ let { ctx } = object;
161
+ let sql = driver(ctx.storage);
162
+ let store;
163
+ let arm = (at)=>void object.clock.arm(at).catch((e)=>report(e, 'arm'));
164
+ let made = assembly.bind({
165
+ host: lent(ctx.id?.name ?? 'object', sqliteBlobs(statements(sql))),
166
+ storage: (host, extend)=>store = storage(ctx.storage, host.vocab, {
167
+ derived: host.derived,
168
+ extend
169
+ }),
170
+ schema: (_host, stmts)=>{
171
+ for (let stmt of blobSchema())sql.query(stmt);
172
+ store.install();
173
+ for (let stmt of stmts)sql.query(stmt);
174
+ },
175
+ effects: (host, disabled)=>effects(host.vocab, {
176
+ disabled,
177
+ singleOwner: true,
178
+ defer: true,
179
+ // How a run ended is written while the object is stopped too, so a
180
+ // run that finished never runs again (`./ceiling.ts`).
181
+ free: (write)=>object.ceiling.free(write),
182
+ nudge: ()=>arm(Date.now()),
183
+ report: (error, { handler })=>report(error, `effect ${handler}`)
184
+ })
185
+ });
186
+ if (made.host.vocab.comp('wake')) {
187
+ let at = (e)=>{
188
+ let when = Date.parse(String(e.comp?.at ?? ''));
189
+ if (Number.isFinite(when)) arm(when);
190
+ };
191
+ made.host.fx.on('wake', {
192
+ doc: 'arm the object for the wake a write just moved',
193
+ created: at,
194
+ changed: {
195
+ at
196
+ }
197
+ });
198
+ }
199
+ return made;
200
+ };
201
+ //# sourceMappingURL=compose.js.map
package/compose.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compose.js","sources":["./compose.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CC,GAKD,SACE,QAAQ,EAGR,OAAO,mCAC8B;AACvC,SAAS,IAAI,wBAA6B;AAC1C,SAAS,OAAO,6BAAkC;AAClD,SAAqB,UAAU,EAAE,WAAW,0BAA+B;AAC3E,SAAS,QAAQ,mCAAwC;AACzD,SAAS,UAAU,4BAAiC;AACpD,SAAS,OAAO,EAAE,IAAI,0BAA+B;AACrD,SAAS,MAAM,mBAAkB;AACjC,SAAS,OAAO,qBAAoB;AAWpC;gCACgC,GAChC,OAAO,IAAI,QAAyB;EAAC;EAAS;CAAU,CAAA;AAExD,yEAAyE;AACzE,yCAAyC;AACzC,IAAI,QAAQ,IAAI;AAEhB;0EAC0E,GAC1E,OAAO,IAAI,UAAU,CACnB,QACA,MACA,QAAyB,KAAK;EAE9B,IAAI,SAAS,MAAM,GAAG,CAAC;EACvB,IAAI,CAAC,QAAQ,MAAM,GAAG,CAAC,QAAQ,SAAS,IAAI;EAC5C,IAAI,UAAU,OAAO,GAAG,CAAC;EACzB,IAAI,CAAC,SAAS,OAAO,GAAG,CAAC,MAAM,UAAU,IAAI;EAC7C,IAAI,MAAM,MAAM,IAAI,IAAI,OAAO,QA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AAI,EAAE,EAAE,QAAQ,UAAU,YAAY,WAAW;IAC5D,SAAS,CAAC,MAAY,SACpB,QAAQ,QAAQ,IAAI,OAAO,EAAE,KAAK,KAAK,EAAE;QACvC,SAAS,KAAK,OAAO;QACrB;MACF;IACF,QAAQ,CAAC,OAAO;MACd,KAAK,IAAI,QAAQ,aAAc,IAAI,KAAK,CAAC;MACzC,MAAO,OAAO;MACd,KAAK,IAAI,QAAQ,MAAO,IAAI,KAAK,CAAC;IACpC;IACA,SAAS,CAAC,MAAM,WACd,QAAQ,KAAK,KAAK,EAAE;QAClB;QACA,aAAa;QACb,OAAO;QACP,mEAAmE;QACnE,uDAAuD;QACvD,MAAM,CAAC,QAAU,OAAO,OAAO,CAAC,IAAI,CAAC;QACrC,OAAO,IAAM,IAAI,KAAK,GAAG;QACzB,QAAQ,CAAC,OAAO,EAAE,OAAO,EAAE,GAAK,OAAO,OAAO,CAAC,OAAO,EAAE,SAAS;MACnE;EACJ;EACA,IAAI,KAAK,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS;IAChC,IAAI,KAAK,CAAC;MACR,IAAI,OAAO,KAAK,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM;MAC3C,IAAI,OAAO,QAAQ,CAAC,OAAO,IAAI;IACjC;IACA,KAAK,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC,QAAQ;MACtB,KAAK;MACL,SAAS;MACT,SAAS;QAAE;MAAG;IAChB;EACF;EACA,OAAO;AACT"}
package/compose.ts ADDED
@@ -0,0 +1,249 @@
1
+ /**
2
+ * An object's graph, composed from a named config through @yaks/host: what
3
+ * one kind of object holds is data (its config, the roles it serves, and where
4
+ * its plugins' facets load from), so two kinds that differ only by their
5
+ * plugins are the one class given two configs.
6
+ *
7
+ * - {@link planned} imports the facets a config's roles serve once an
8
+ * isolate (@yaks/host `prepare`), and assembles them once a vocabulary
9
+ * (`assemble`): every instance of a kind shares its plan, and binds it to
10
+ * its own storage.
11
+ * - {@link lent} is what an object lends what it composes. It hosts no
12
+ * process, so nothing it composes runs a duty, ends a process or keeps a
13
+ * secret past the instance.
14
+ * - {@link composed} is the whole {@link Spec}: the graph over the object's
15
+ * SQLite (`./store.ts`) with its blobs beside it, `api({graph, subs})` as
16
+ * its door and `/ws` as its sockets, and its wakes and effects pool as the
17
+ * works its alarm runs (`./alarm.ts`).
18
+ *
19
+ * ```ts
20
+ * import { Durable } from '@yaks/durable-object/object'
21
+ * import { composed } from '@yaks/durable-object/compose'
22
+ * import { durable } from './testing.ts'
23
+ * import { assertEquals } from '@std/assert'
24
+ *
25
+ * let config = { plugins: ['shelf'] }
26
+ * let load = () =>
27
+ * Promise.resolve({
28
+ * docs: [{
29
+ * $defs: {
30
+ * book: { component: true, properties: { title: { type: 'string' } } },
31
+ * },
32
+ * }],
33
+ * })
34
+ * let ctx = { storage: durable(), acceptWebSocket() {}, getWebSockets: () => [] }
35
+ * let shelf = new Durable(ctx, composed(config, load))
36
+ * await shelf.fetch(
37
+ * new Request('https://do/apply', {
38
+ * method: 'POST',
39
+ * body: JSON.stringify([{ entity: { eid: 'b' }, book: { title: 'Dune' } }]),
40
+ * }),
41
+ * )
42
+ * let read = await shelf.fetch(new Request('https://do/query?q=.book'))
43
+ * assertEquals((await read.json())[0].book, { title: 'Dune' })
44
+ * ```
45
+ *
46
+ * @module
47
+ */
48
+
49
+ import type { Host, Load, Role } from 'jsr:@yaks/host@0.2.36'
50
+ import type { Config } from 'jsr:@yaks/host@0.2.36/config'
51
+ import type { Words } from 'jsr:@yaks/host@0.2.36/words'
52
+ import {
53
+ assemble,
54
+ type Assembly,
55
+ type Binding,
56
+ prepare,
57
+ } from '@yaks/host/assembly'
58
+ import { lazy } from '@yaks/fp'
59
+ import { effects } from '@yaks/effects'
60
+ import { type Blobs, blobSchema, sqliteBlobs } from '@yaks/blob'
61
+ import { ramVault } from '@yaks/secrets/vault'
62
+ import { statements } from '@yaks/sqlite'
63
+ import { soonest, tick } from '@yaks/wake'
64
+ import { driver } from './sql.js'
65
+ import { storage } from './store.js'
66
+ import type { Durable, Spec } from './object.ts'
67
+
68
+ /** A kind's plan, once its facets are imported: its assembly under `words`,
69
+ * made once a vocabulary, or under the words its facets declare. */
70
+ export type Assembling = (words?: Words) => Assembly
71
+
72
+ /** What one kind of object composes: its facets, imported when first
73
+ * asked. */
74
+ export type Kind = () => Promise<Assembling>
75
+
76
+ /** What an object serves unless its config says otherwise: its graph, and
77
+ * the effects its alarm works. */
78
+ export let ROLES: readonly Role[] = ['graph', 'effects']
79
+
80
+ // Plans by config, load and roles: a kind is planned once an isolate, by
81
+ // whichever of its instances asks first.
82
+ let plans = new WeakMap<Config, WeakMap<Load, Map<string, Kind>>>()
83
+
84
+ /** The plan for `config`'s `roles`, with facets from `load`, made once an
85
+ * isolate. One whose import failed is imported again by the next to ask. */
86
+ export let planned = (
87
+ config: Config,
88
+ load: Load,
89
+ roles: readonly Role[] = ROLES,
90
+ ): Kind => {
91
+ let byLoad = plans.get(config)
92
+ if (!byLoad) plans.set(config, byLoad = new WeakMap())
93
+ let byRoles = byLoad.get(load)
94
+ if (!byRoles) byLoad.set(load, byRoles = new Map())
95
+ let key = roles.join(), plan = byRoles.get(key)
96
+ if (plan) return plan
97
+ // Kept as a value once loaded: a plan is shared by every object and
98
+ // request of an isolate (@yaks/fp `lazy`).
99
+ plan = lazy(() =>
100
+ prepare(config, roles, load).then((facets) => {
101
+ let own: Assembly | undefined
102
+ let worded = new WeakMap<Words, Assembly>()
103
+ let assembly = (words?: Words) =>
104
+ assemble(config, roles, load, facets, words ? { words } : {})
105
+ return (words?: Words) => {
106
+ if (!words) return own ??= assembly()
107
+ let held = worded.get(words)
108
+ if (!held) worded.set(words, held = assembly(words))
109
+ return held
110
+ }
111
+ })
112
+ )
113
+ byRoles.set(key, plan)
114
+ return plan
115
+ }
116
+
117
+ /** What an object lends the plugins it composes, as `me`, its bodies kept in
118
+ * `blobs`. */
119
+ export let lent = (me: string, blobs: Blobs): Binding['host'] => ({
120
+ me,
121
+ vault: ramVault(),
122
+ blobs,
123
+ artifacts: blobs,
124
+ stopping: new AbortController().signal,
125
+ duties: () => Promise.resolve(),
126
+ end: () => Promise.resolve(),
127
+ bury: () => Promise.resolve([]),
128
+ gone: () => Promise.resolve(false),
129
+ })
130
+
131
+ /** How {@link composed} composes. */
132
+ export type Composing = {
133
+ /** The roles served ({@link ROLES} by default). */
134
+ roles?: readonly Role[]
135
+ /** The words the graph speaks, where the object knows them before its
136
+ * facets do. */
137
+ words?: Words
138
+ /** A failure the object caught, by its entry (the console by default). */
139
+ report?: Spec['report']
140
+ /** The deploy the object runs (`Spec.version`). */
141
+ version?: string
142
+ }
143
+
144
+ /**
145
+ * The spec of an object composed from `config`, with facets from `load`: its
146
+ * graph over the object's SQLite, schema and blobs installed as it opens; its
147
+ * door `api({graph, subs, db})`, which keeps its receipts in the object's
148
+ * SQLite and hands `/ws` to its sockets; and as its
149
+ * works, the wakes due (@yaks/wake `tick`) and the effects pool, each
150
+ * answering when it is next owed. A write that moves a wake or owes a run arms
151
+ * the alarm.
152
+ */
153
+ export let composed = (
154
+ config: Config,
155
+ load: Load,
156
+ options: Composing = {},
157
+ ): Spec => {
158
+ let plan = planned(config, load, options.roles)
159
+ let report = options.report ??
160
+ ((error: unknown, entry: string) => console.error(entry, error))
161
+ return {
162
+ report,
163
+ ...options.version ? { version: options.version } : {},
164
+ open: async (object) => {
165
+ let assembly = (await plan())(options.words)
166
+ let { host } = bound(object, assembly, report)
167
+ let g = host.graph, fx = host.fx
168
+ // The door, loaded only by an object that opens one.
169
+ let { api, subscriptions } = await import('@yaks/api')
170
+ let subs = subscriptions(g)
171
+ let door = api({ graph: g, subs, db: host.storage.statements })
172
+ let wakes = !!host.vocab.comp('wake'), runs = !!host.vocab.comp('effect')
173
+ return {
174
+ serve: (request) =>
175
+ new URL(request.url).pathname == '/ws'
176
+ ? object.accept(request)
177
+ : door(request),
178
+ subs,
179
+ works: {
180
+ ...wakes
181
+ ? {
182
+ wakes: async () => {
183
+ let now = Date.now()
184
+ for (let { error } of (await tick(g, now)).refused) {
185
+ report(error, 'alarm wakes')
186
+ }
187
+ return await soonest(g, now)
188
+ },
189
+ }
190
+ : {},
191
+ ...runs
192
+ ? {
193
+ effects: async (until: number) => {
194
+ await fx.work(g, undefined, { until })
195
+ await fx.idle()
196
+ return await fx.next(g)
197
+ },
198
+ }
199
+ : {},
200
+ },
201
+ }
202
+ },
203
+ }
204
+ }
205
+
206
+ // `assembly` bound inside `object`: its storage, its blobs and its pool.
207
+ let bound = (object: Durable, assembly: Assembly, report: Spec['report']) => {
208
+ let { ctx } = object
209
+ let sql = driver(ctx.storage)
210
+ let store: ReturnType<typeof storage> | undefined
211
+ let arm = (at: number) =>
212
+ void object.clock.arm(at).catch((e) => report(e, 'arm'))
213
+ let made = assembly.bind({
214
+ host: lent(ctx.id?.name ?? 'object', sqliteBlobs(statements(sql))),
215
+ storage: (host: Host, extend) =>
216
+ store = storage(ctx.storage, host.vocab, {
217
+ derived: host.derived,
218
+ extend,
219
+ }),
220
+ schema: (_host, stmts) => {
221
+ for (let stmt of blobSchema()) sql.query(stmt)
222
+ store!.install()
223
+ for (let stmt of stmts) sql.query(stmt)
224
+ },
225
+ effects: (host, disabled) =>
226
+ effects(host.vocab, {
227
+ disabled,
228
+ singleOwner: true,
229
+ defer: true,
230
+ // How a run ended is written while the object is stopped too, so a
231
+ // run that finished never runs again (`./ceiling.ts`).
232
+ free: (write) => object.ceiling.free(write),
233
+ nudge: () => arm(Date.now()),
234
+ report: (error, { handler }) => report(error, `effect ${handler}`),
235
+ }),
236
+ })
237
+ if (made.host.vocab.comp('wake')) {
238
+ let at = (e: { comp?: { at?: unknown } }) => {
239
+ let when = Date.parse(String(e.comp?.at ?? ''))
240
+ if (Number.isFinite(when)) arm(when)
241
+ }
242
+ made.host.fx.on('wake', {
243
+ doc: 'arm the object for the wake a write just moved',
244
+ created: at,
245
+ changed: { at },
246
+ })
247
+ }
248
+ return made
249
+ }