@yaks/effects 0.0.0-stage → 0.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +979 -2
- package/_dist/docs.d.ts +10 -0
- package/_dist/docs.d.ts.map +1 -0
- package/_dist/enqueue.d.ts +12 -0
- package/_dist/enqueue.d.ts.map +1 -0
- package/_dist/expire.d.ts +31 -0
- package/_dist/expire.d.ts.map +1 -0
- package/_dist/invocation.d.ts +36 -0
- package/_dist/invocation.d.ts.map +1 -0
- package/_dist/lease.d.ts +98 -0
- package/_dist/lease.d.ts.map +1 -0
- package/_dist/mod.d.ts +89 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/outage.d.ts +48 -0
- package/_dist/outage.d.ts.map +1 -0
- package/_dist/pool.d.ts +148 -0
- package/_dist/pool.d.ts.map +1 -0
- package/_dist/provisional.d.ts +8 -0
- package/_dist/provisional.d.ts.map +1 -0
- package/_dist/ready.d.ts +3 -0
- package/_dist/ready.d.ts.map +1 -0
- package/_dist/registration.d.ts +17 -0
- package/_dist/registration.d.ts.map +1 -0
- package/_dist/registry.d.ts +153 -0
- package/_dist/registry.d.ts.map +1 -0
- package/_dist/tools.d.ts +21 -0
- package/_dist/tools.d.ts.map +1 -0
- package/_dist/trace.d.ts +63 -0
- package/_dist/trace.d.ts.map +1 -0
- package/_dist/views.d.ts +15 -0
- package/_dist/views.d.ts.map +1 -0
- package/_dist/vocab.d.ts +11 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/_dist/worker.d.ts +19 -0
- package/_dist/worker.d.ts.map +1 -0
- package/_dist/write.d.ts +25 -0
- package/_dist/write.d.ts.map +1 -0
- package/cleanup.js +75 -0
- package/cleanup.js.map +1 -0
- package/cleanup.ts +83 -0
- package/deno.json +1 -0
- package/docs.js +13 -0
- package/docs.js.map +1 -0
- package/docs.ts +13 -0
- package/enqueue.js +71 -0
- package/enqueue.js.map +1 -0
- package/enqueue.ts +86 -0
- package/expire.js +225 -0
- package/expire.js.map +1 -0
- package/expire.ts +244 -0
- package/invocation.js +245 -0
- package/invocation.js.map +1 -0
- package/invocation.ts +250 -0
- package/lease.js +343 -0
- package/lease.js.map +1 -0
- package/lease.ts +444 -0
- package/mod.js +89 -0
- package/mod.js.map +1 -0
- package/mod.ts +92 -0
- package/outage.js +77 -0
- package/outage.js.map +1 -0
- package/outage.ts +84 -0
- package/package.json +52 -4
- package/page.js +315 -0
- package/page.js.map +1 -0
- package/page.ts +524 -0
- package/pool.js +1474 -0
- package/pool.js.map +1 -0
- package/pool.ts +1635 -0
- package/provisional.js +20 -0
- package/provisional.js.map +1 -0
- package/provisional.ts +26 -0
- package/ready.js +48 -0
- package/ready.js.map +1 -0
- package/ready.ts +93 -0
- package/registration.js +21 -0
- package/registration.js.map +1 -0
- package/registration.ts +43 -0
- package/registry.js +872 -0
- package/registry.js.map +1 -0
- package/registry.ts +1196 -0
- package/tools.js +182 -0
- package/tools.js.map +1 -0
- package/tools.ts +229 -0
- package/trace.js +167 -0
- package/trace.js.map +1 -0
- package/trace.ts +217 -0
- package/views.js +18 -0
- package/views.js.map +1 -0
- package/views.ts +18 -0
- package/vocab.js +18 -0
- package/vocab.js.map +1 -0
- package/vocab.json +364 -0
- package/vocab.ts +20 -0
- package/worker.js +114 -0
- package/worker.js.map +1 -0
- package/worker.ts +146 -0
- package/write.js +38 -0
- package/write.js.map +1 -0
- package/write.ts +60 -0
package/README.md
CHANGED
|
@@ -1,3 +1,980 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @yaks/effects
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Runs application code after [graph](../graph/README.md#data-model) changes
|
|
4
|
+
commit, with isolated failures, an optional pool for persisted runs, and leases
|
|
5
|
+
for work held by one process. Use it to send mail, update an index, or call an
|
|
6
|
+
external API without making that work part of the transaction that triggered it.
|
|
7
|
+
|
|
8
|
+
An **effect** is work declared in a [vocabulary](../vocab/README.md#vocabulary)
|
|
9
|
+
with `effect: true`, such as
|
|
10
|
+
`send_receipt: { effect: true, changed: ['order.paid'] }`. Every process loading
|
|
11
|
+
that vocabulary knows what a commit owes. A **handler** is the function
|
|
12
|
+
registered to do that work (`Handler`).
|
|
13
|
+
|
|
14
|
+
An **observer** is a handler registered at runtime with `created`, `changed`,
|
|
15
|
+
`removed`, or `on`. Only its own process knows it; it runs after that process's
|
|
16
|
+
commits, at most once. A view refreshing what it shows is an observer.
|
|
17
|
+
|
|
18
|
+
The **registry** is the [plugin](../graph/README.md#data-model) returned by
|
|
19
|
+
`effects(vocab)`, holding effect declarations and observer registrations
|
|
20
|
+
(`Effects`). The optional **pool** stores runs as `effect`
|
|
21
|
+
[components](../graph/README.md#data-model), so processes can claim and run work
|
|
22
|
+
another process committed. A **run** is one invocation owed to an effect for a
|
|
23
|
+
target entity; its pool component records its state and attempts.
|
|
24
|
+
|
|
25
|
+
## Declare an effect and handle it
|
|
26
|
+
|
|
27
|
+
These introductory examples use the small [post vocabularies](./testing.ts):
|
|
28
|
+
`announceExample` declares `post` (`title`, `published`) and `post_announce`
|
|
29
|
+
(`created: ['post']`, `changed: ['post.published']`); `observerExample` declares
|
|
30
|
+
only `post.published`. Load these declarations with `loadVocab` in an
|
|
31
|
+
application.
|
|
32
|
+
|
|
33
|
+
Without the `effect` component, a handled effect runs in the process that
|
|
34
|
+
committed. A handler failure goes to `report` and cannot roll back the committed
|
|
35
|
+
[batch](../graph/README.md#data-model).
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { graph } from '@yaks/graph'
|
|
39
|
+
import { loadVocab } from '@yaks/vocab'
|
|
40
|
+
const vocab = loadVocab({
|
|
41
|
+
$defs: {
|
|
42
|
+
post: { component: true },
|
|
43
|
+
post_announce: {
|
|
44
|
+
effect: true,
|
|
45
|
+
created: ['post'],
|
|
46
|
+
description: 'tell subscribers about a post',
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
})
|
|
50
|
+
import { ram } from '@yaks/ram'
|
|
51
|
+
import { effects } from '@yaks/effects'
|
|
52
|
+
import { equal } from '@yaks/testing'
|
|
53
|
+
|
|
54
|
+
let fx = effects(vocab)
|
|
55
|
+
let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
|
|
56
|
+
let announced: string[] = []
|
|
57
|
+
fx.handle({ post_announce: (event) => announced.push(event.kind) })
|
|
58
|
+
|
|
59
|
+
await g.apply([{ entity: { eid: 'p1' }, post: {} }])
|
|
60
|
+
equal(announced, ['created'])
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`handle` throws for a name the vocabulary does not declare. Registrations can be
|
|
64
|
+
added before or after graph construction.
|
|
65
|
+
|
|
66
|
+
## Callable effects
|
|
67
|
+
|
|
68
|
+
A **callable effect** declares `effect: true` and `call: true` in its
|
|
69
|
+
vocabulary. The host supplies its operation and the effects pool applies the
|
|
70
|
+
declaration's `tries` and `idempotent` policy. Use `effectEid(name)` from
|
|
71
|
+
`@yaks/effects/invocation` as `call{to}` and put the operation's inputs in
|
|
72
|
+
`call{args}`. A scheduled call runs after its wake fires. Each recurring wake
|
|
73
|
+
creates a separate call and result.
|
|
74
|
+
|
|
75
|
+
A declared match can also owe a callable effect. This declaration supplies a
|
|
76
|
+
literal HTTP method and takes the URL from the match's `$url` binding.
|
|
77
|
+
|
|
78
|
+
```json
|
|
79
|
+
{
|
|
80
|
+
"request_fetch": {
|
|
81
|
+
"effect": true,
|
|
82
|
+
"match": "*request, .request.url=$url",
|
|
83
|
+
"owe": "fetch",
|
|
84
|
+
"args": { "method": "GET", "url": "$url" }
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The commit captures the arguments before dispatch. Each invocation records
|
|
90
|
+
`result{ms, call}`, `output{source, id, value}` and `content{body}` on one
|
|
91
|
+
entity. Query `.result.call=<call-eid>` for a call's answer. A match that owes
|
|
92
|
+
an effect directly records its subject in `output.source` and its declaration in
|
|
93
|
+
`output.value.match`. Streaming progress updates the answer entity until
|
|
94
|
+
`result.ms` is written.
|
|
95
|
+
|
|
96
|
+
## Install
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
deno add jsr:@yaks/effects
|
|
100
|
+
# or: npx jsr add @yaks/effects
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Exports
|
|
104
|
+
|
|
105
|
+
| Import | Exports |
|
|
106
|
+
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
107
|
+
| `@yaks/effects` | `effects`; registry, handler, registration and event types; `before`, `wanting`, `events`, `strip`, `BEFORE`; `generation`, `marked`, `unmark`, `ORIGIN`, `Write`; `pool`, `working`, `effectDoc`, pool types and retry settings; lease operations and types; `expire`, `expireDaily`, `expiration`; `PROVISIONAL`, `provisionalDoc`; `WORKER` and the `Worker` it says |
|
|
108
|
+
| `@yaks/effects/vocab` | `docs`, `description`, `effectDoc`, `provisionalDoc` |
|
|
109
|
+
| `@yaks/effects/outage` | `failing`, `answered`, `Outage`, `Failing`: the record of a failure that lasts, told once and its end logged |
|
|
110
|
+
| `@yaks/effects/tools` | `runs`, `Options`: implementation and configuration of `effect_check` |
|
|
111
|
+
| `@yaks/effects/views` | `destinations`, `inspectViews`, `icons`: the Effects page a browsing app offers |
|
|
112
|
+
|
|
113
|
+
`effectDoc` declares `effect`, `lease`, `worker`, `provisional`, and
|
|
114
|
+
`effect_check`. `docs` contains `effectDoc`; loading it alone does not install a
|
|
115
|
+
registry or work the pool. `provisionalDoc` declares only `provisional`; load
|
|
116
|
+
one document or the other.
|
|
117
|
+
|
|
118
|
+
## Observers and events
|
|
119
|
+
|
|
120
|
+
An **event** describes what triggered a handler (`Event`), with `kind`,
|
|
121
|
+
`entity`, and the component's `name`. The registry reads what each entity
|
|
122
|
+
carries before applying bundles, including entities a cascade will delete, and
|
|
123
|
+
derives events from the applied [patches](../graph/README.md#data-model).
|
|
124
|
+
|
|
125
|
+
| Observer | Effect declaration | Trigger |
|
|
126
|
+
| ------------------------------ | ------------------------ | -------------------------------------------------------- |
|
|
127
|
+
| `created(comp, handler)` | `created: [comp]` | An entity gains the component |
|
|
128
|
+
| `changed(comp, prop, handler)` | `changed: ['comp.prop']` | An applied patch includes that property |
|
|
129
|
+
| `changed(comp, handler)` | `changed: [comp]` | An applied patch updates that component |
|
|
130
|
+
| `removed(comp, handler)` | `removed: [comp]` | The component is removed, directly or by entity deletion |
|
|
131
|
+
| `on(pattern, handler)` | `match: pattern` | A pattern matches an entity touched by the batch |
|
|
132
|
+
|
|
133
|
+
A `changed` event describes the applied patch, not a comparison of old and new
|
|
134
|
+
values. `comp` holds the component on creation, the applied properties on
|
|
135
|
+
change, and is absent on removal. A removal carries `before` instead: the entity
|
|
136
|
+
holding the component that went, as it was before the commit, and nothing else
|
|
137
|
+
it lost. A handler that needs what a deleted link pointed at watches `edge`
|
|
138
|
+
going, narrowed by a `target`, and reads `before.edge`. `touched` lists every
|
|
139
|
+
component the same commit moved on that entity, including removals. A pooled run
|
|
140
|
+
keeps both, so a removal's row is never larger than the component it is about.
|
|
141
|
+
|
|
142
|
+
`actor` is who wrote the commit, the `{by, via}` its batch signed that entity
|
|
143
|
+
with, and is absent for automation. A pooled run keeps it too. What a handler
|
|
144
|
+
writes is unsigned, which is automation, unless it signs it: a run that writes
|
|
145
|
+
on the commit's behalf, such as a call it asks for, signs with
|
|
146
|
+
`signed(bundles, event.actor ?? null)` (@yaks/graph/provenance). The call then
|
|
147
|
+
runs as its writer, as it would from a tool door or from a rule inside the write
|
|
148
|
+
([@yaks/tools](../tools/README.md#runner-options)).
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
import { graph } from '@yaks/graph'
|
|
152
|
+
import { observerExample as vocab } from './testing.ts'
|
|
153
|
+
import { ram } from '@yaks/ram'
|
|
154
|
+
import { effects } from '@yaks/effects'
|
|
155
|
+
import { equal } from '@yaks/testing'
|
|
156
|
+
|
|
157
|
+
let fx = effects(vocab)
|
|
158
|
+
let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
|
|
159
|
+
let seen: unknown[] = []
|
|
160
|
+
fx.on('post', {
|
|
161
|
+
doc: 'refresh the post view',
|
|
162
|
+
created: (e) => seen.push([e.kind, e.comp]),
|
|
163
|
+
changed: { published: (e) => seen.push([e.kind, e.comp]) },
|
|
164
|
+
removed: (e) => seen.push([e.kind, e.before?.post]),
|
|
165
|
+
})
|
|
166
|
+
await g.apply([{ entity: { eid: 'p1' }, post: {} }])
|
|
167
|
+
await g.apply([{ entity: { eid: 'p1' }, post: { published: true } }])
|
|
168
|
+
await g.apply([{ entity: { eid: 'p1' }, $delete: true }])
|
|
169
|
+
equal(seen, [
|
|
170
|
+
['created', {}],
|
|
171
|
+
['changed', { published: true }],
|
|
172
|
+
['removed', { published: true }],
|
|
173
|
+
])
|
|
174
|
+
equal(fx.docs(), [{
|
|
175
|
+
comp: 'post',
|
|
176
|
+
hooks: ['created', 'changed(published)', 'removed'],
|
|
177
|
+
doc: 'refresh the post view',
|
|
178
|
+
}])
|
|
179
|
+
equal(fx.slots().length, 3)
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
`on(comp, registration)` groups related observers and their documentation.
|
|
183
|
+
`slots()` returns registrations, effects first; `docs()` derives grouped
|
|
184
|
+
observer documentation from them. A registration's `wants` supplies additional
|
|
185
|
+
reads for the graph to gather before commit.
|
|
186
|
+
|
|
187
|
+
Every handler receives `(event, tx, write)`: the event, a `ReadTx` for reading
|
|
188
|
+
committed state, and a callback for new graph writes when configured. A pooled
|
|
189
|
+
handler also receives its attempt as a fourth argument. The pool accepts the
|
|
190
|
+
graph's `Access` interface, including `outside` for detached reads, so the graph
|
|
191
|
+
may be owned by another thread.
|
|
192
|
+
|
|
193
|
+
### Patterns
|
|
194
|
+
|
|
195
|
+
An observer's [pattern](../query/README.md#multi-entity-matches) is evaluated
|
|
196
|
+
against the committed graph to find handler targets. It is checked only when a
|
|
197
|
+
batch moves a component it reads. A match triggers a handler only if the batch
|
|
198
|
+
touched an entity that the pattern bound. An entity that already matched can
|
|
199
|
+
trigger again when touched; this is not a false-to-true transition test. Use
|
|
200
|
+
`*component` to require the batch to write that component on the bound entity.
|
|
201
|
+
With several `*component` clauses, a write to any of them on its bound entity
|
|
202
|
+
can trigger the match.
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
import { graph } from '@yaks/graph'
|
|
206
|
+
import { loadVocab } from '@yaks/vocab'
|
|
207
|
+
const vocab = loadVocab({
|
|
208
|
+
$defs: {
|
|
209
|
+
post: { component: true, properties: { published: { type: 'boolean' } } },
|
|
210
|
+
},
|
|
211
|
+
})
|
|
212
|
+
import { ram } from '@yaks/ram'
|
|
213
|
+
import { effects } from '@yaks/effects'
|
|
214
|
+
import { equal } from '@yaks/testing'
|
|
215
|
+
|
|
216
|
+
let fx = effects(vocab)
|
|
217
|
+
let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
|
|
218
|
+
let matched: string[] = []
|
|
219
|
+
fx.on('.post !post.published', (e) => matched.push(e.entity.eid))
|
|
220
|
+
await g.apply([
|
|
221
|
+
{ entity: { eid: 'p1' }, post: {} },
|
|
222
|
+
{ entity: { eid: 'p2' }, post: { published: true } },
|
|
223
|
+
])
|
|
224
|
+
equal(matched, ['p1'])
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
A lone `-post` registers the same event as `removed('post', handler)`, including
|
|
228
|
+
cascaded deletions. Mixed patterns such as `.product, -shelf` need a storage
|
|
229
|
+
adapter that can query the batch's removal overlay. Queries joining multiple
|
|
230
|
+
entities need `bindings`, as provided by [@yaks/sqlite](../sqlite/README.md) and
|
|
231
|
+
[@yaks/durable-object](../durable-object/README.md). Matched events can carry
|
|
232
|
+
`vars` and `binding` for these results.
|
|
233
|
+
|
|
234
|
+
Required components absent from the vocabulary make a pattern inactive. An
|
|
235
|
+
absence condition on an undeclared component is dropped. Unsupported observer
|
|
236
|
+
pattern execution is reported after commit. Pool match evaluation happens in the
|
|
237
|
+
commit transaction. An observer is never replayed after a crash. An effect's
|
|
238
|
+
`match` is recorded with the commit when a pool is present.
|
|
239
|
+
|
|
240
|
+
### Event derivation helpers
|
|
241
|
+
|
|
242
|
+
`before(vocab)` reads what the batch's entities carry, which `events` needs;
|
|
243
|
+
`wanting` declares those reads for graph gathering. `strip` removes the
|
|
244
|
+
temporary `$before` request from the applied bundles.
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
import { type Bundle, graph } from '@yaks/graph'
|
|
248
|
+
import { loadVocab } from '@yaks/vocab'
|
|
249
|
+
import { ram } from '@yaks/ram'
|
|
250
|
+
import { before, events, strip } from '@yaks/effects'
|
|
251
|
+
import { equal } from '@yaks/testing'
|
|
252
|
+
|
|
253
|
+
let vocab = loadVocab({ $defs: { post: { component: true } } })
|
|
254
|
+
let storage = ram(vocab)
|
|
255
|
+
let g = graph({ storage, vocab })
|
|
256
|
+
await g.apply([{ entity: { eid: 'p1' }, post: {} }])
|
|
257
|
+
let bundles: Bundle[] = [{ entity: { eid: 'p1' }, post: null }]
|
|
258
|
+
await storage.tx(async (tx) => {
|
|
259
|
+
let prepared = await before(vocab)(bundles, tx)
|
|
260
|
+
equal(events(prepared).map((e) => [e.kind, e.name, e.touched]), [
|
|
261
|
+
['removed', 'post', ['post']],
|
|
262
|
+
])
|
|
263
|
+
equal(strip(prepared), bundles)
|
|
264
|
+
})
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## Failure isolation
|
|
268
|
+
|
|
269
|
+
Refused batches trigger no handlers. After commit, thrown errors and rejected
|
|
270
|
+
promises go to `report` while other handlers continue. The default reporter uses
|
|
271
|
+
`console.warn`. Synchronous handlers preserve a synchronous `apply()` result;
|
|
272
|
+
returning a promise makes that call asynchronous. Work started without returning
|
|
273
|
+
its promise must handle its own later failures.
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
import { graph } from '@yaks/graph'
|
|
277
|
+
import { loadVocab } from '@yaks/vocab'
|
|
278
|
+
import { ram } from '@yaks/ram'
|
|
279
|
+
import { effects } from '@yaks/effects'
|
|
280
|
+
import { equal } from '@yaks/testing'
|
|
281
|
+
|
|
282
|
+
let vocab = loadVocab({ $defs: { post: { component: true } } })
|
|
283
|
+
let reported: string[] = []
|
|
284
|
+
let seen: string[] = []
|
|
285
|
+
let fx = effects(vocab, {
|
|
286
|
+
report: (error, { handler }) => reported.push(`${handler}: ${error}`),
|
|
287
|
+
})
|
|
288
|
+
let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
|
|
289
|
+
fx.created('post', () => {
|
|
290
|
+
throw new Error('mail unavailable')
|
|
291
|
+
})
|
|
292
|
+
fx.created('post', (e) => seen.push(e.entity.eid))
|
|
293
|
+
await g.apply([{ entity: { eid: 'p1' }, post: {} }])
|
|
294
|
+
equal(reported, ['post.created: Error: mail unavailable'])
|
|
295
|
+
equal(seen, ['p1'])
|
|
296
|
+
equal((await g.get(['p1']))[0].post, {})
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
## Writing back
|
|
300
|
+
|
|
301
|
+
Configure `write` to apply a new batch through the graph. Return its result when
|
|
302
|
+
callers should await it. Use `{ trusted: true }` if the handler writes
|
|
303
|
+
server-owned properties. The new batch receives the graph's admission, rules,
|
|
304
|
+
stamps, journal and notifications; direct storage writes bypass that pipeline.
|
|
305
|
+
|
|
306
|
+
A **generation** counts how many handler writes preceded a batch: zero for an
|
|
307
|
+
initial write, one for its handler's write, and one more for each further
|
|
308
|
+
handler write. The `$effect` request carries it. Batches past `depth` (default
|
|
309
|
+
2) still commit but trigger no more handlers; `depth: 0` disables handlers for
|
|
310
|
+
all handler writes.
|
|
311
|
+
|
|
312
|
+
```ts
|
|
313
|
+
import { graph } from '@yaks/graph'
|
|
314
|
+
import { loadVocab } from '@yaks/vocab'
|
|
315
|
+
import { ram } from '@yaks/ram'
|
|
316
|
+
import { effects, generation, marked, unmark } from '@yaks/effects'
|
|
317
|
+
import { equal } from '@yaks/testing'
|
|
318
|
+
|
|
319
|
+
let vocab = loadVocab({
|
|
320
|
+
$defs: {
|
|
321
|
+
post: { component: true, properties: { count: { type: 'number' } } },
|
|
322
|
+
},
|
|
323
|
+
})
|
|
324
|
+
let fx = effects(vocab, { depth: 0, write: (b) => g.apply(b) })
|
|
325
|
+
let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
|
|
326
|
+
let calls = 0
|
|
327
|
+
fx.changed('post', 'count', (e, _tx, write) => {
|
|
328
|
+
calls++
|
|
329
|
+
return write([{
|
|
330
|
+
entity: e.entity,
|
|
331
|
+
post: { count: Number(e.comp?.count) + 1 },
|
|
332
|
+
}])
|
|
333
|
+
})
|
|
334
|
+
await g.apply([{ entity: { eid: 'p1' }, post: { count: 0 } }])
|
|
335
|
+
await g.apply([{ entity: { eid: 'p1' }, post: { count: 1 } }])
|
|
336
|
+
equal(calls, 1)
|
|
337
|
+
equal((await g.get(['p1']))[0].post, { count: 2 })
|
|
338
|
+
let bundles = [{ entity: { eid: 'p1' }, post: { count: 3 } }]
|
|
339
|
+
let tagged = marked(bundles, 1)
|
|
340
|
+
equal(generation(tagged), 1)
|
|
341
|
+
equal(generation(bundles), 0)
|
|
342
|
+
equal(unmark(tagged), bundles)
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
<a id="the-durable-tier-optional"></a>
|
|
346
|
+
|
|
347
|
+
## The pool (optional)
|
|
348
|
+
|
|
349
|
+
Load `effectDoc` beside your own vocabulary to record runs in the same
|
|
350
|
+
transaction as the batch that owes them. By default a process owes runs only for
|
|
351
|
+
the effects it handles (`owes: 'handled'`), so a declared effect without a
|
|
352
|
+
handler owes no run there; a process that writes for another to run passes
|
|
353
|
+
`owes: 'declared'` and owes a run for every declared effect. A crash after
|
|
354
|
+
commit cannot lose the recorded run. `work(g)` claims due runs and continues
|
|
355
|
+
until none can start; `work(g, undefined, {until})` stops starting them at that
|
|
356
|
+
instant, so a host whose invocation has limits does a bounded slice and calls
|
|
357
|
+
again; `work(g, signal)` with a live signal keeps working until the signal
|
|
358
|
+
aborts.
|
|
359
|
+
|
|
360
|
+
The first pass and every later pass use the same indexed selection of recorded
|
|
361
|
+
runs. A worker joining or replacing another worker resumes this queue; it does
|
|
362
|
+
not scan application entities to discover targets. The write that creates work
|
|
363
|
+
records its run in the same transaction, and unfinished runs remain available
|
|
364
|
+
after a process stops.
|
|
365
|
+
|
|
366
|
+
A run is the pool's bookkeeping rather than anyone's data, so `effect` is
|
|
367
|
+
declared `journal: false` ([@yaks/vocab](../vocab/README.md#the-format)): a
|
|
368
|
+
[journal](../journal/README.md) records nothing of a run, from the commit that
|
|
369
|
+
owes it to its deletion once done. Every write to a run under its claim goes
|
|
370
|
+
through the graph's `book`, straight through storage: nothing refers to it and
|
|
371
|
+
nothing derives from it, so none of `apply()`'s phases has anything to do, and
|
|
372
|
+
nothing stamps it. A finished run is erased, leaving no tombstone. A run costs a
|
|
373
|
+
store its insert, one row for its claim and two for its erasure.
|
|
374
|
+
|
|
375
|
+
A **claim** assigns a run to one worker until an expiry, using the run's
|
|
376
|
+
`lease_owner`, `lease_token`, and `lease_expiry` properties. Claims use graph
|
|
377
|
+
[preconditions](../graph/README.md#writes-and-reads), so rival workers cannot
|
|
378
|
+
claim the same run together. Workers renew their claims; expired claims are
|
|
379
|
+
available again, or available immediately when `gone` reports that the worker
|
|
380
|
+
ended.
|
|
381
|
+
|
|
382
|
+
```ts
|
|
383
|
+
import { graph } from '@yaks/graph'
|
|
384
|
+
import { loadVocab } from '@yaks/vocab'
|
|
385
|
+
import { ram } from '@yaks/ram'
|
|
386
|
+
import { effectDoc, effects } from '@yaks/effects'
|
|
387
|
+
import { equal } from '@yaks/testing'
|
|
388
|
+
|
|
389
|
+
let vocab = loadVocab([effectDoc, {
|
|
390
|
+
$defs: {
|
|
391
|
+
order: { component: true },
|
|
392
|
+
send_receipt: { effect: true, created: ['order'] },
|
|
393
|
+
},
|
|
394
|
+
}])
|
|
395
|
+
let fx = effects(vocab)
|
|
396
|
+
let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
|
|
397
|
+
let receipts: string[] = []
|
|
398
|
+
fx.handle({ send_receipt: (e) => receipts.push(e.entity.eid) })
|
|
399
|
+
await g.apply([{ entity: { eid: 'o1' }, order: {} }])
|
|
400
|
+
equal(receipts, [])
|
|
401
|
+
equal((await g.read('.effect'))[0].effect?.state, 'pending')
|
|
402
|
+
await fx.work(g)
|
|
403
|
+
equal(receipts, ['o1'])
|
|
404
|
+
equal(await g.read('.effect'), [])
|
|
405
|
+
await fx.stop()
|
|
406
|
+
equal(fx.running(), [])
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
A worker joining the pool claims runs its own commits owe and starts them after
|
|
410
|
+
commit. `defer: true` leaves those runs for `work`. How many runs go at once is
|
|
411
|
+
bounded by the worker's event loop, not a number: a turn starts at most a page
|
|
412
|
+
of runs, and a worker whose last turn came back more than `LATE` (50) ms behind
|
|
413
|
+
takes no more until its thread catches up, so runs waiting on the network go by
|
|
414
|
+
the thousand while a busy or starved thread stops taking. `max` sets a fixed
|
|
415
|
+
bound where a host wants one, and a run ending while every slot is taken wakes
|
|
416
|
+
the worker to fill it. Other processes' runs are heard as they land when the
|
|
417
|
+
host gives `watch`, a subscription calling back on each new `effect` row
|
|
418
|
+
(@yaks/sqlite's `Store.watch`, about 5 ms behind the other process's commit);
|
|
419
|
+
without it they are picked up on the next pass, at most a second (`CAP`) away.
|
|
420
|
+
`wake` starts that pass sooner. `nudge` notifies the host once after a commit
|
|
421
|
+
owes declared work, whether claimed here or left pending. A host can keep its
|
|
422
|
+
`work` promise alive through handler completion and wake another worker to drain
|
|
423
|
+
the remaining runs.
|
|
424
|
+
|
|
425
|
+
Each pass examines a bounded page of candidate runs, 32 by default, read for
|
|
426
|
+
every handler at once. A candidate starts only when it is due, claimable and has
|
|
427
|
+
a local slot. Selection shares turns among handled and explicitly disabled
|
|
428
|
+
effects, so one handler's backlog does not crowd out the others: where the page
|
|
429
|
+
comes back full, a handler it holds no run of reads a window of its own on its
|
|
430
|
+
turn. Disabled runs settle without spending attempts. The page bounds candidate
|
|
431
|
+
reads; the event loop, or `max`, separately limits concurrent handlers.
|
|
432
|
+
|
|
433
|
+
`pool(ctx, options)` exposes the same operations for a caller supplying registry
|
|
434
|
+
slots, a writer, and a reporter.
|
|
435
|
+
|
|
436
|
+
A worker with an `owner` entity and handlers for every enabled effect holds a
|
|
437
|
+
presence lease while its live `work` runs. `working(g)` checks these leases. A
|
|
438
|
+
one-shot `work` leaves the pool to a worker with a presence lease. A worker
|
|
439
|
+
handling only some effects holds no presence lease. Signal abort or `stop` stops
|
|
440
|
+
further claims; `idle` and `stop` wait for started runs while renewing their
|
|
441
|
+
claims. Abort the live `work` signal to end its loop.
|
|
442
|
+
|
|
443
|
+
### What a worker says
|
|
444
|
+
|
|
445
|
+
A worker with an `owner` entity says what it is doing while its live `work`
|
|
446
|
+
runs, every fifteen seconds (`SAY`, as often as it renews its presence lease),
|
|
447
|
+
as a `worker` component on that entity:
|
|
448
|
+
`worker{at, running, runs, ran, errors, history, cpu, lag}`. `running` counts
|
|
449
|
+
its runs going and `runs` lists the oldest twenty, each with its handler, target
|
|
450
|
+
and when it started; `ran` and `errors` count the runs it finished since it
|
|
451
|
+
started and how many of those threw; `history` holds how many it finished in
|
|
452
|
+
each of the last sixty whole seconds, oldest first. How busy it is holds however
|
|
453
|
+
many runs it takes at once: `cpu` is the share of a core its process used since
|
|
454
|
+
it last said (from the `cpu` option, the process's CPU time in ms; absent
|
|
455
|
+
without one), and `lag` the most its thread ran a timer late, in ms, which
|
|
456
|
+
climbs as its event loop fills. A row whose `at` stops moving is a worker that
|
|
457
|
+
stopped saying; a worker leaving the pool removes its row, and a worker starting
|
|
458
|
+
removes the rows of workers `gone` says are over.
|
|
459
|
+
|
|
460
|
+
### Single-owner stores
|
|
461
|
+
|
|
462
|
+
**Single-owner mode** means exactly one process exclusively owns the store,
|
|
463
|
+
including its effect execution. Set `singleOwner: true` only for such a store,
|
|
464
|
+
for example a Durable Object. Shared box workers leave this option unset.
|
|
465
|
+
|
|
466
|
+
`work` drains recorded runs without claims or presence leases. By default it
|
|
467
|
+
owes no start-up effects and runs no expiration duty. A host calls `work` on
|
|
468
|
+
writes and alarms, not on reads; it calls `startup` when a deployment owes
|
|
469
|
+
start-up runs. Attempts are persisted before handler invocation and outcomes
|
|
470
|
+
afterwards, so crash recovery, retry backoff, attempt limits and non-idempotent
|
|
471
|
+
interruption handling still apply. `max`, `defer`, and `Attempt.progressed` keep
|
|
472
|
+
their meaning. Overlapping calls to `work` on the same registry share its
|
|
473
|
+
running set.
|
|
474
|
+
|
|
475
|
+
To owe and deliver start-up runs together, call
|
|
476
|
+
`work(g, undefined, {startup: true, passes: 1})`. A run given a free slot starts
|
|
477
|
+
at once and keeps no row unless it fails: the host owes the pass again until it
|
|
478
|
+
has ended, which is the run's crash recovery, and a failure is written as the
|
|
479
|
+
row its retry reads. Overflow is recorded pending for a later pass. Start-up
|
|
480
|
+
admission shares the first pass's bounded window. `startup(g)` records runs
|
|
481
|
+
without invoking handlers. A numeric third argument to `work` still bounds its
|
|
482
|
+
queue passes.
|
|
483
|
+
|
|
484
|
+
```ts
|
|
485
|
+
import { graph } from '@yaks/graph'
|
|
486
|
+
import { loadVocab } from '@yaks/vocab'
|
|
487
|
+
import { ram } from '@yaks/ram'
|
|
488
|
+
import { effectDoc, effects } from '@yaks/effects'
|
|
489
|
+
import { equal } from '@yaks/testing'
|
|
490
|
+
|
|
491
|
+
let vocab = loadVocab([effectDoc, {
|
|
492
|
+
$defs: {
|
|
493
|
+
store: { component: true },
|
|
494
|
+
order: { component: true },
|
|
495
|
+
send_receipt: { effect: true, created: ['order'] },
|
|
496
|
+
prepare: { effect: true, start: true },
|
|
497
|
+
},
|
|
498
|
+
}])
|
|
499
|
+
let fx = effects(vocab, { singleOwner: true, defer: true, owner: 'store-1' })
|
|
500
|
+
let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
|
|
501
|
+
let sent = 0, prepared = 0
|
|
502
|
+
fx.handle({
|
|
503
|
+
send_receipt: () => void sent++,
|
|
504
|
+
prepare: () => void prepared++,
|
|
505
|
+
})
|
|
506
|
+
await g.apply([
|
|
507
|
+
{ entity: { eid: 'store-1' }, store: {} },
|
|
508
|
+
{ entity: { eid: 'order-1' }, order: {} },
|
|
509
|
+
])
|
|
510
|
+
await fx.startup(g) // The host's deployment pass owes these runs.
|
|
511
|
+
equal(prepared, 0)
|
|
512
|
+
await fx.work(g)
|
|
513
|
+
equal(sent, 1)
|
|
514
|
+
equal(prepared, 1)
|
|
515
|
+
await fx.work(g) // An empty alarm owes nothing and writes nothing.
|
|
516
|
+
equal(sent, 1)
|
|
517
|
+
equal(prepared, 1)
|
|
518
|
+
equal(await g.read('.lease'), [])
|
|
519
|
+
await fx.work(g, undefined, { startup: true, passes: 1 })
|
|
520
|
+
equal(prepared, 2)
|
|
521
|
+
equal(sent, 1)
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
### Attempts and retries
|
|
525
|
+
|
|
526
|
+
An **attempt** is one start of a pooled handler (`Attempt`). A failure is due
|
|
527
|
+
again after a backoff: one second, doubling, capped at five minutes. After
|
|
528
|
+
`tries` attempts (default three) the run stays `failed` with its error. An error
|
|
529
|
+
carrying `retry: { after: milliseconds }` delays the next attempt by at least
|
|
530
|
+
that amount and is reported only on its last attempt.
|
|
531
|
+
|
|
532
|
+
`attempt.last()` says whether a failure would be final. `progressed()` resets
|
|
533
|
+
its attempt count after progress, giving a subsequent failure its full retry
|
|
534
|
+
allowance. `attempt.retry(body)` retries a local completion while keeping the
|
|
535
|
+
claim, so the handler need not repeat its external work.
|
|
536
|
+
|
|
537
|
+
A pooled handler waiting for a dependency calls
|
|
538
|
+
`await attempt.defer(delayMs, reason)` and returns normally. The positive,
|
|
539
|
+
finite delay leaves the same run pending until it is due again, releases its
|
|
540
|
+
claim and slot, and spends no retry attempt. An optional reason is recorded in
|
|
541
|
+
`effect.waiting` for callers checking progress.
|
|
542
|
+
|
|
543
|
+
A handler can expose `waiting()` to report a dependency this worker still lacks.
|
|
544
|
+
A pending run deferred with that reason stays in the queue without another
|
|
545
|
+
claim. A worker that sees the dependency available can pick up the run when its
|
|
546
|
+
delay expires. An alarm-driven store rechecks deferred dependencies once a
|
|
547
|
+
minute while they are still waiting.
|
|
548
|
+
|
|
549
|
+
A commit-triggered effect can declare `fifo: true` to run one request at a time
|
|
550
|
+
in `effect.at` order. A running or deferred head keeps its place across workers.
|
|
551
|
+
Other effect handlers continue to run while it waits. A handler made with
|
|
552
|
+
`ranked(run, rank)` orders its queue instead: `rank` gives each pending run a
|
|
553
|
+
number, read whenever the head is chosen, and the lowest goes first, the oldest
|
|
554
|
+
among equals. A deferred head gives way to a run ranked above it; a running one
|
|
555
|
+
never does.
|
|
556
|
+
|
|
557
|
+
The complete waiting and retry lifecycle is covered by the
|
|
558
|
+
[deferral tests](./defer_test.ts).
|
|
559
|
+
|
|
560
|
+
```ts ignore
|
|
561
|
+
import { graph } from '@yaks/graph'
|
|
562
|
+
import { loadVocab } from '@yaks/vocab'
|
|
563
|
+
import { ram } from '@yaks/ram'
|
|
564
|
+
import { effectDoc, effects } from '@yaks/effects'
|
|
565
|
+
import { clock, equal } from '@yaks/testing'
|
|
566
|
+
|
|
567
|
+
let vocab = loadVocab([effectDoc, {
|
|
568
|
+
$defs: {
|
|
569
|
+
order: { component: true },
|
|
570
|
+
send_receipt: { effect: true, created: ['order'] },
|
|
571
|
+
},
|
|
572
|
+
}])
|
|
573
|
+
let time = clock(), calls = 0
|
|
574
|
+
let fx = effects(vocab, { clock: time })
|
|
575
|
+
let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
|
|
576
|
+
fx.handle({
|
|
577
|
+
send_receipt: async (_event, _tx, _write, attempt) => {
|
|
578
|
+
if (++calls == 1) {
|
|
579
|
+
await attempt!.defer!(1000)
|
|
580
|
+
return
|
|
581
|
+
}
|
|
582
|
+
},
|
|
583
|
+
})
|
|
584
|
+
await g.apply([{ entity: { eid: 'order-1' }, order: {} }])
|
|
585
|
+
await fx.work(g, undefined, 1)
|
|
586
|
+
await time.advance(999)
|
|
587
|
+
await fx.work(g, undefined, 1)
|
|
588
|
+
equal(calls, 1)
|
|
589
|
+
await time.advance(1)
|
|
590
|
+
await fx.work(g, undefined, 1)
|
|
591
|
+
equal(calls, 2)
|
|
592
|
+
equal(await g.read('.effect'), [])
|
|
593
|
+
await fx.stop()
|
|
594
|
+
```
|
|
595
|
+
|
|
596
|
+
Failures follow the declaration's attempt limit and backoff. The
|
|
597
|
+
[retry example tests](./readme_test.ts) prepare each attempt separately.
|
|
598
|
+
|
|
599
|
+
```ts ignore
|
|
600
|
+
import { graph } from '@yaks/graph'
|
|
601
|
+
import { loadVocab } from '@yaks/vocab'
|
|
602
|
+
import { ram } from '@yaks/ram'
|
|
603
|
+
import { effectDoc, effects } from '@yaks/effects'
|
|
604
|
+
import { clock, equal } from '@yaks/testing'
|
|
605
|
+
|
|
606
|
+
let vocab = loadVocab([effectDoc, {
|
|
607
|
+
$defs: {
|
|
608
|
+
order: { component: true },
|
|
609
|
+
send_receipt: { effect: true, created: ['order'], tries: 2 },
|
|
610
|
+
},
|
|
611
|
+
}])
|
|
612
|
+
let time = clock()
|
|
613
|
+
let reports: string[] = []
|
|
614
|
+
let fx = effects(vocab, {
|
|
615
|
+
clock: time,
|
|
616
|
+
report: (_e, job) => reports.push(job.handler),
|
|
617
|
+
})
|
|
618
|
+
let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
|
|
619
|
+
let last: boolean[] = []
|
|
620
|
+
fx.handle({
|
|
621
|
+
send_receipt: (_e, _tx, _write, attempt) => {
|
|
622
|
+
last.push(attempt!.last())
|
|
623
|
+
throw new Error('mail unavailable')
|
|
624
|
+
},
|
|
625
|
+
})
|
|
626
|
+
await g.apply([{ entity: { eid: 'o1' }, order: {} }])
|
|
627
|
+
await fx.work(g, undefined, 1)
|
|
628
|
+
equal(last, [false])
|
|
629
|
+
await time.advance(1000)
|
|
630
|
+
await fx.work(g, undefined, 1)
|
|
631
|
+
equal(last, [false, true])
|
|
632
|
+
equal((await g.read('.effect'))[0].effect?.state, 'failed')
|
|
633
|
+
equal(reports, ['send_receipt', 'send_receipt'])
|
|
634
|
+
await fx.stop()
|
|
635
|
+
```
|
|
636
|
+
|
|
637
|
+
For a completion with several local steps, retain external work and retry only
|
|
638
|
+
the step that failed:
|
|
639
|
+
|
|
640
|
+
```ts
|
|
641
|
+
import { graph } from '@yaks/graph'
|
|
642
|
+
import { loadVocab } from '@yaks/vocab'
|
|
643
|
+
import { ram } from '@yaks/ram'
|
|
644
|
+
import { effectDoc, effects } from '@yaks/effects'
|
|
645
|
+
import { equal } from '@yaks/testing'
|
|
646
|
+
|
|
647
|
+
let vocab = loadVocab([effectDoc, {
|
|
648
|
+
$defs: {
|
|
649
|
+
order: { component: true },
|
|
650
|
+
send_receipt: { effect: true, created: ['order'], tries: 2 },
|
|
651
|
+
},
|
|
652
|
+
}])
|
|
653
|
+
let fx = effects(vocab, { backoff: () => 0, report: () => {} })
|
|
654
|
+
let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
|
|
655
|
+
let sent = 0
|
|
656
|
+
let saved = 0
|
|
657
|
+
let last: boolean[] = []
|
|
658
|
+
fx.handle({
|
|
659
|
+
send_receipt: async (_e, _tx, _write, attempt) => {
|
|
660
|
+
sent++
|
|
661
|
+
await attempt!.retry!(async () => {
|
|
662
|
+
last.push(attempt!.last())
|
|
663
|
+
if (++saved == 1) throw new Error('storage unavailable')
|
|
664
|
+
})
|
|
665
|
+
await attempt!.progressed()
|
|
666
|
+
last.push(attempt!.last())
|
|
667
|
+
},
|
|
668
|
+
})
|
|
669
|
+
await g.apply([{ entity: { eid: 'o1' }, order: {} }])
|
|
670
|
+
await fx.work(g)
|
|
671
|
+
equal(sent, 1)
|
|
672
|
+
equal(saved, 2)
|
|
673
|
+
equal(last, [false, true, false])
|
|
674
|
+
equal(await g.read('.effect'), [])
|
|
675
|
+
await fx.stop()
|
|
676
|
+
```
|
|
677
|
+
|
|
678
|
+
An interrupted run is tried again unless its declaration says
|
|
679
|
+
`idempotent: false`; then it is left failed because replay could repeat an
|
|
680
|
+
external action. Each attempt records the code `version` the host names
|
|
681
|
+
(`PoolOpts.version`, a Worker version's id on yaks.app). A run resumed under
|
|
682
|
+
another version was cut off by a deploy and runs again as the same attempt; one
|
|
683
|
+
resumed under the same version, or where the host names none, crashed its
|
|
684
|
+
process and spends an attempt, so a crash loop stops at the attempt limit and is
|
|
685
|
+
reported. A pooled run rebuilds its event from the target's current state, so a
|
|
686
|
+
handler needing a historical value must store it itself.
|
|
687
|
+
|
|
688
|
+
### Startup and active effects
|
|
689
|
+
|
|
690
|
+
`start: true` owes each joining shared worker one `started` run, targeting its
|
|
691
|
+
`owner`. `startup: 'manual'` leaves that timing to the host; it is the default
|
|
692
|
+
with `singleOwner: true`. `startup: 'join'` chooses joining explicitly. Each
|
|
693
|
+
`fx.startup(g)` call persists a fresh run for every handled start-up effect,
|
|
694
|
+
without joining or executing handlers. A persistence failure rejects the call;
|
|
695
|
+
after it succeeds, `work` executes those runs with ordinary attempts and
|
|
696
|
+
retries. The host keeps track of which deployments owe the call. Without the
|
|
697
|
+
`effect` component, `startup` awaits the handled start-up effects inline. A
|
|
698
|
+
handler failure is reported and rejects the call, so the host can retry the
|
|
699
|
+
start-up work.
|
|
700
|
+
|
|
701
|
+
Commit-triggered runs can be gated with `active`, a query that must match an
|
|
702
|
+
entity. A `target` query limits triggers to subjects matching before or after
|
|
703
|
+
the write, including removals, moves out of scope and what a cascade deletes. An
|
|
704
|
+
`eligible` query selects subjects in the committed state and is checked again
|
|
705
|
+
before a queued run invokes its handler. A run whose subject no longer matches
|
|
706
|
+
is settled quietly. An `option` names the declaring plugin's boolean opt-in. The
|
|
707
|
+
composing host passes disabled names to the registry so every writer agrees with
|
|
708
|
+
its workers. Writes to pool entities owe no effects, preventing pool bookkeeping
|
|
709
|
+
from producing more runs.
|
|
710
|
+
|
|
711
|
+
Startup delivery and active gates are exercised in the
|
|
712
|
+
[startup tests](./startup_test.ts) and [declaration tests](./registry_test.ts).
|
|
713
|
+
|
|
714
|
+
```ts ignore
|
|
715
|
+
import { graph } from '@yaks/graph'
|
|
716
|
+
import { loadVocab } from '@yaks/vocab'
|
|
717
|
+
import { ram } from '@yaks/ram'
|
|
718
|
+
import { effectDoc, effects } from '@yaks/effects'
|
|
719
|
+
import { equal } from '@yaks/testing'
|
|
720
|
+
|
|
721
|
+
let vocab = loadVocab([effectDoc, {
|
|
722
|
+
$defs: {
|
|
723
|
+
enabled: { component: true },
|
|
724
|
+
order: { component: true },
|
|
725
|
+
send_receipt: {
|
|
726
|
+
effect: true,
|
|
727
|
+
created: ['order'],
|
|
728
|
+
active: '.enabled',
|
|
729
|
+
},
|
|
730
|
+
prepare: { effect: true, start: true },
|
|
731
|
+
},
|
|
732
|
+
}])
|
|
733
|
+
let fx = effects(vocab, { owner: 'w1', startup: 'manual' })
|
|
734
|
+
let g = graph({ storage: ram(vocab), vocab, plugins: [fx] })
|
|
735
|
+
let seen: string[] = []
|
|
736
|
+
fx.handle({
|
|
737
|
+
send_receipt: (e) => seen.push(`receipt:${e.entity.eid}`),
|
|
738
|
+
prepare: (e) => seen.push(`${e.kind}:${e.entity.eid}`),
|
|
739
|
+
})
|
|
740
|
+
await g.apply([{ entity: { eid: 'w1' }, worker: {}, enabled: {} }])
|
|
741
|
+
await g.apply([{ entity: { eid: 'o1' }, order: {} }])
|
|
742
|
+
equal((await g.read('.effect'))[0].effect?.state, 'pending')
|
|
743
|
+
await fx.startup(g)
|
|
744
|
+
await fx.work(g, undefined, 1)
|
|
745
|
+
equal(seen.sort(), ['receipt:o1', 'started:w1'])
|
|
746
|
+
equal(await g.read('.effect'), [])
|
|
747
|
+
await fx.stop()
|
|
748
|
+
```
|
|
749
|
+
|
|
750
|
+
### Settling stale runs
|
|
751
|
+
|
|
752
|
+
`fx.settle(g, handler)` completes unclaimed pending runs that the current
|
|
753
|
+
configuration disables or the declaration no longer owes. It uses guarded
|
|
754
|
+
successful-run cleanup, leaving failures, active claims and needed runs intact.
|
|
755
|
+
Workers also settle unclaimed runs for explicitly disabled names, including runs
|
|
756
|
+
an older writer leaves during a rolling restart. A removal's old scope is
|
|
757
|
+
unavailable after commit, so its run is preserved unless the effect is disabled.
|
|
758
|
+
|
|
759
|
+
```ts
|
|
760
|
+
import { graph } from '@yaks/graph'
|
|
761
|
+
import { loadVocab } from '@yaks/vocab'
|
|
762
|
+
import { ram } from '@yaks/ram'
|
|
763
|
+
import { effectDoc, effects } from '@yaks/effects'
|
|
764
|
+
import { equal } from '@yaks/testing'
|
|
765
|
+
|
|
766
|
+
let vocab = loadVocab([effectDoc, {
|
|
767
|
+
$defs: {
|
|
768
|
+
post: { component: true },
|
|
769
|
+
publish: { effect: true, created: ['post'] },
|
|
770
|
+
},
|
|
771
|
+
}])
|
|
772
|
+
let fx = effects(vocab, { disabled: ['publish'], owes: 'declared' })
|
|
773
|
+
let g = graph({ vocab, storage: ram(vocab), plugins: [fx] })
|
|
774
|
+
await g.apply([{ entity: { eid: 'p1' }, post: {} }])
|
|
775
|
+
equal(await g.read('.effect'), [])
|
|
776
|
+
await g.apply([{
|
|
777
|
+
entity: { eid: 'old-run' },
|
|
778
|
+
effect: {
|
|
779
|
+
handler: 'publish',
|
|
780
|
+
target: 'p1',
|
|
781
|
+
comp: 'post',
|
|
782
|
+
kind: 'created',
|
|
783
|
+
state: 'pending',
|
|
784
|
+
},
|
|
785
|
+
}], { trusted: true })
|
|
786
|
+
equal(await fx.settle(g, 'publish'), 1)
|
|
787
|
+
equal(await fx.settle(g, 'publish'), 0)
|
|
788
|
+
```
|
|
789
|
+
|
|
790
|
+
## Duties and leases
|
|
791
|
+
|
|
792
|
+
## Expiration
|
|
793
|
+
|
|
794
|
+
A component's [`expire` declaration](../vocab/README.md#expiration) selects
|
|
795
|
+
component rows to remove. The CLI's effects role serves expiration as a separate
|
|
796
|
+
upkeep duty named `@yaks/effects`, alongside the effect pool. The pool's startup
|
|
797
|
+
and work selection do not invoke it.
|
|
798
|
+
|
|
799
|
+
`expiration(g, {owner, signal, report})` keeps that duty running until its
|
|
800
|
+
signal aborts. It checks the persisted daily lease through `expireDaily`, with a
|
|
801
|
+
30-second cadence when leases are available. A successful pass keeps the
|
|
802
|
+
`@yaks/effects/expire` lease for a day; failure or interruption leaves a short
|
|
803
|
+
hold for recovery. Replacing a worker preserves that daily schedule, and a
|
|
804
|
+
failure is reported before the duty tries again.
|
|
805
|
+
|
|
806
|
+
`expire(g)` runs a pass explicitly and returns the number of matching component
|
|
807
|
+
rows removed. Expiration declarations are for regenerable caches. Tool result
|
|
808
|
+
text, session context accounting and call pairings have no age-based expiration.
|
|
809
|
+
Each transaction removes at most 100 rows by default, and before the next one
|
|
810
|
+
the pass rests as long as the last held the write lock. Removal uses the graph's
|
|
811
|
+
`apply()` with guards against values changed since selection.
|
|
812
|
+
|
|
813
|
+
Trash and tombstones have no automatic expiration. A person chooses any purge
|
|
814
|
+
from the trash; a daily sweep never erases retained identities or their
|
|
815
|
+
contents.
|
|
816
|
+
|
|
817
|
+
```ts
|
|
818
|
+
import { graph } from '@yaks/graph'
|
|
819
|
+
import { ram } from '@yaks/ram'
|
|
820
|
+
import { loadVocab } from '@yaks/vocab'
|
|
821
|
+
import { expire } from '@yaks/effects'
|
|
822
|
+
import { equal } from '@yaks/testing'
|
|
823
|
+
|
|
824
|
+
let vocab = loadVocab({
|
|
825
|
+
$defs: {
|
|
826
|
+
cache: {
|
|
827
|
+
component: true,
|
|
828
|
+
expire: '.cache.old=true',
|
|
829
|
+
properties: { old: { type: 'boolean' } },
|
|
830
|
+
},
|
|
831
|
+
item: { component: true },
|
|
832
|
+
},
|
|
833
|
+
})
|
|
834
|
+
let g = graph({ vocab, storage: ram(vocab) })
|
|
835
|
+
await g.apply([{ entity: { eid: 'one' }, cache: { old: true }, item: {} }])
|
|
836
|
+
equal(await expire(g, { batch: 10 }), 1)
|
|
837
|
+
equal((await g.get(['one']))[0].item, {})
|
|
838
|
+
equal(await expire(g), 0)
|
|
839
|
+
```
|
|
840
|
+
|
|
841
|
+
A **duty** is named work that one process should run at a time. A **lease** is
|
|
842
|
+
the `lease: { name, holder, until }` component recording who holds a duty and
|
|
843
|
+
when the hold expires. `leaseEid(name)` derives its eid from the duty name. The
|
|
844
|
+
holder is an entity reference and must name an existing entity.
|
|
845
|
+
|
|
846
|
+
```ts
|
|
847
|
+
import { graph } from '@yaks/graph'
|
|
848
|
+
import { loadVocab } from '@yaks/vocab'
|
|
849
|
+
import { ram } from '@yaks/ram'
|
|
850
|
+
import { effectDoc, held, take } from '@yaks/effects'
|
|
851
|
+
import { equal } from '@yaks/testing'
|
|
852
|
+
|
|
853
|
+
let vocab = loadVocab([effectDoc])
|
|
854
|
+
let g = graph({ storage: ram(vocab), vocab })
|
|
855
|
+
await g.apply([
|
|
856
|
+
{ entity: { eid: 'w1' }, worker: {} },
|
|
857
|
+
])
|
|
858
|
+
equal(await take(g, 'refresh-index', { holder: 'w1' }), true)
|
|
859
|
+
equal((await held(g, 'refresh-index'))?.holder, 'w1')
|
|
860
|
+
```
|
|
861
|
+
|
|
862
|
+
`take` uses preconditions on holder and expiry, and taking your own lease renews
|
|
863
|
+
it. `drop` releases only your own lease. `released(g, holder)` returns release
|
|
864
|
+
patches to apply with the batch recording that holder's ending. The default hold
|
|
865
|
+
lasts 30 seconds; `gone` permits immediate takeover of a lease whose holder
|
|
866
|
+
ended.
|
|
867
|
+
|
|
868
|
+
`holding` takes a lease, renews it while its callback runs, and releases it when
|
|
869
|
+
the callback finishes. Its callback signal also aborts when renewal finds
|
|
870
|
+
another holder; the callback must honor that signal. Renewals use timers, so the
|
|
871
|
+
callback must yield more often than a third of the hold. After losing the lease,
|
|
872
|
+
`holding` waits to take it again and returns the callback's last result. A store
|
|
873
|
+
failure while waiting is reported (`report`, default `console.error`) and
|
|
874
|
+
retried. With no signal, an already aborted signal, or `wait: false`, it makes
|
|
875
|
+
one attempt; store failures then throw. `until(signal)` lets finished startup
|
|
876
|
+
work keep the lease until shutdown.
|
|
877
|
+
|
|
878
|
+
Without a `lease` declaration, taking a lease succeeds without storing anything
|
|
879
|
+
and provides no coordination between processes.
|
|
880
|
+
|
|
881
|
+
## Provisional entities
|
|
882
|
+
|
|
883
|
+
The **provisional** component marks an entity whose write committed before an
|
|
884
|
+
asynchronous step finished: `provisional: { note: 'saving the key' }`. The
|
|
885
|
+
handler finishing the step removes it. `note` explains the unfinished step to a
|
|
886
|
+
reader. The component does not start a handler or clear itself.
|
|
887
|
+
|
|
888
|
+
```ts
|
|
889
|
+
import { graph } from '@yaks/graph'
|
|
890
|
+
import { loadVocab } from '@yaks/vocab'
|
|
891
|
+
import { ram } from '@yaks/ram'
|
|
892
|
+
import { PROVISIONAL, provisionalDoc } from '@yaks/effects'
|
|
893
|
+
import { equal } from '@yaks/testing'
|
|
894
|
+
|
|
895
|
+
let vocab = loadVocab([provisionalDoc, {
|
|
896
|
+
$defs: { post: { component: true } },
|
|
897
|
+
}])
|
|
898
|
+
let g = graph({ storage: ram(vocab), vocab })
|
|
899
|
+
await g.apply([{
|
|
900
|
+
entity: { eid: 'p1' },
|
|
901
|
+
post: {},
|
|
902
|
+
[PROVISIONAL]: { note: 'updating the index' },
|
|
903
|
+
}])
|
|
904
|
+
equal((await g.get(['p1']))[0].provisional, { note: 'updating the index' })
|
|
905
|
+
await g.apply([{ entity: { eid: 'p1' }, [PROVISIONAL]: null }])
|
|
906
|
+
equal((await g.get(['p1']))[0].provisional, undefined)
|
|
907
|
+
```
|
|
908
|
+
|
|
909
|
+
## The Effects page
|
|
910
|
+
|
|
911
|
+
`@yaks/effects/views` offers a browsing app (@yaks/browse) the page its sidebar
|
|
912
|
+
lists as Effects, at `/?page=effects`: how many workers are up, the runs going
|
|
913
|
+
every second over the last minute, what is waiting and what failed; a row for
|
|
914
|
+
each worker with how busy it is, its loop delay, its runs a second and how long
|
|
915
|
+
it has been up, or how long it has been silent; every run going, the longest
|
|
916
|
+
first; and every declared effect with the runs it is owed, running, waiting,
|
|
917
|
+
retrying and failed, each count a link to those runs. The workers' numbers are
|
|
918
|
+
their `worker` rows; the runs owed are the `effect` rows, tallied by handler.
|
|
919
|
+
Both are subscriptions, so the page moves as they do.
|
|
920
|
+
|
|
921
|
+
## Check recorded runs
|
|
922
|
+
|
|
923
|
+
`runs(host, options)` supplies `effect_check`. The check reports failed runs,
|
|
924
|
+
runs waiting for a handler no plugin declares (an orphan, which nothing will
|
|
925
|
+
ever work), and runs pending past their due time by more than `minutes` (default
|
|
926
|
+
ten), showing up to `sample` examples (default five). It does not retry runs or
|
|
927
|
+
repair them. Without an `effect` component it reports no findings.
|
|
928
|
+
|
|
929
|
+
Those runs are left for a person, and two tools act on them, each taking a
|
|
930
|
+
handler name (all its runs of that kind) or one run's id.
|
|
931
|
+
`yak effect retry
|
|
932
|
+
<of>` puts failed runs of a declared handler back to `pending`
|
|
933
|
+
with a fresh attempt allowance, so the pool claims them as it does a new run
|
|
934
|
+
(attempts, backoff, leases); if the cause is fixed they finish, if not they fail
|
|
935
|
+
again and the check names them again. `yak effect drop <of>` deletes failed runs
|
|
936
|
+
and orphans, whose work no one owes any more. Both refuse a name that matches
|
|
937
|
+
none and say how many runs they changed.
|
|
938
|
+
|
|
939
|
+
```ts
|
|
940
|
+
import { type Bundle, graph } from '@yaks/graph'
|
|
941
|
+
import { loadVocab } from '@yaks/vocab'
|
|
942
|
+
import { ram } from '@yaks/ram'
|
|
943
|
+
import { effectDoc } from '@yaks/effects/vocab'
|
|
944
|
+
import { runs } from '@yaks/effects/tools'
|
|
945
|
+
import { equal } from '@yaks/testing'
|
|
946
|
+
|
|
947
|
+
let vocab = loadVocab([effectDoc])
|
|
948
|
+
let g = graph({ storage: ram(vocab), vocab })
|
|
949
|
+
await g.apply([{
|
|
950
|
+
entity: { eid: 'r1' },
|
|
951
|
+
effect: { state: 'failed', error: 'mail unavailable' },
|
|
952
|
+
}], { trusted: true })
|
|
953
|
+
let result = await runs({ vocab }).effect_check({
|
|
954
|
+
entity: { eid: 'check1' },
|
|
955
|
+
call: { args: {} },
|
|
956
|
+
}, g) as Bundle[]
|
|
957
|
+
equal(result[0].finding?.level, 'fail')
|
|
958
|
+
```
|
|
959
|
+
|
|
960
|
+
## Limits and composition
|
|
961
|
+
|
|
962
|
+
The registry uses TypeScript and standard web APIs and runs in Deno, Node,
|
|
963
|
+
Workers, or browsers with compatible graph storage. The pool and leases survive
|
|
964
|
+
process restarts only with persistent storage; RAM is suitable for tests.
|
|
965
|
+
Pattern features depend on the adapter's query support.
|
|
966
|
+
|
|
967
|
+
Effects run after commit and cannot refuse a write. Use
|
|
968
|
+
[graph rules and hooks](../graph/README.md#data-model) for transactional work.
|
|
969
|
+
Without the pool, a crash after commit can lose an effect or observer run. The
|
|
970
|
+
pool coordinates claims and retries; handlers remain responsible for the
|
|
971
|
+
semantics of repeating their external actions.
|
|
972
|
+
|
|
973
|
+
`enqueue(graph, handler, target)` owes one invocation explicitly, for a resume
|
|
974
|
+
or work left during draining. Ordinary component transitions owe their runs
|
|
975
|
+
through declarations. The handler must be declared and the graph must keep a
|
|
976
|
+
durable effect pool. A run written this way, or put back to pending by a retry,
|
|
977
|
+
wakes this process's worker as its commit lands, since a store's `watch` hears
|
|
978
|
+
only other processes. `owe(tx, context, handler, target, next?)` owes one from a
|
|
979
|
+
hook inside a write's own transaction (a `commit` hook), so the run stands or
|
|
980
|
+
falls with the write, due at `next` or at once, and wakes the pool the same way.
|