@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.
Files changed (101) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +979 -2
  3. package/_dist/docs.d.ts +10 -0
  4. package/_dist/docs.d.ts.map +1 -0
  5. package/_dist/enqueue.d.ts +12 -0
  6. package/_dist/enqueue.d.ts.map +1 -0
  7. package/_dist/expire.d.ts +31 -0
  8. package/_dist/expire.d.ts.map +1 -0
  9. package/_dist/invocation.d.ts +36 -0
  10. package/_dist/invocation.d.ts.map +1 -0
  11. package/_dist/lease.d.ts +98 -0
  12. package/_dist/lease.d.ts.map +1 -0
  13. package/_dist/mod.d.ts +89 -0
  14. package/_dist/mod.d.ts.map +1 -0
  15. package/_dist/outage.d.ts +48 -0
  16. package/_dist/outage.d.ts.map +1 -0
  17. package/_dist/pool.d.ts +148 -0
  18. package/_dist/pool.d.ts.map +1 -0
  19. package/_dist/provisional.d.ts +8 -0
  20. package/_dist/provisional.d.ts.map +1 -0
  21. package/_dist/ready.d.ts +3 -0
  22. package/_dist/ready.d.ts.map +1 -0
  23. package/_dist/registration.d.ts +17 -0
  24. package/_dist/registration.d.ts.map +1 -0
  25. package/_dist/registry.d.ts +153 -0
  26. package/_dist/registry.d.ts.map +1 -0
  27. package/_dist/tools.d.ts +21 -0
  28. package/_dist/tools.d.ts.map +1 -0
  29. package/_dist/trace.d.ts +63 -0
  30. package/_dist/trace.d.ts.map +1 -0
  31. package/_dist/views.d.ts +15 -0
  32. package/_dist/views.d.ts.map +1 -0
  33. package/_dist/vocab.d.ts +11 -0
  34. package/_dist/vocab.d.ts.map +1 -0
  35. package/_dist/worker.d.ts +19 -0
  36. package/_dist/worker.d.ts.map +1 -0
  37. package/_dist/write.d.ts +25 -0
  38. package/_dist/write.d.ts.map +1 -0
  39. package/cleanup.js +75 -0
  40. package/cleanup.js.map +1 -0
  41. package/cleanup.ts +83 -0
  42. package/deno.json +1 -0
  43. package/docs.js +13 -0
  44. package/docs.js.map +1 -0
  45. package/docs.ts +13 -0
  46. package/enqueue.js +71 -0
  47. package/enqueue.js.map +1 -0
  48. package/enqueue.ts +86 -0
  49. package/expire.js +225 -0
  50. package/expire.js.map +1 -0
  51. package/expire.ts +244 -0
  52. package/invocation.js +245 -0
  53. package/invocation.js.map +1 -0
  54. package/invocation.ts +250 -0
  55. package/lease.js +343 -0
  56. package/lease.js.map +1 -0
  57. package/lease.ts +444 -0
  58. package/mod.js +89 -0
  59. package/mod.js.map +1 -0
  60. package/mod.ts +92 -0
  61. package/outage.js +77 -0
  62. package/outage.js.map +1 -0
  63. package/outage.ts +84 -0
  64. package/package.json +52 -4
  65. package/page.js +315 -0
  66. package/page.js.map +1 -0
  67. package/page.ts +524 -0
  68. package/pool.js +1474 -0
  69. package/pool.js.map +1 -0
  70. package/pool.ts +1635 -0
  71. package/provisional.js +20 -0
  72. package/provisional.js.map +1 -0
  73. package/provisional.ts +26 -0
  74. package/ready.js +48 -0
  75. package/ready.js.map +1 -0
  76. package/ready.ts +93 -0
  77. package/registration.js +21 -0
  78. package/registration.js.map +1 -0
  79. package/registration.ts +43 -0
  80. package/registry.js +872 -0
  81. package/registry.js.map +1 -0
  82. package/registry.ts +1196 -0
  83. package/tools.js +182 -0
  84. package/tools.js.map +1 -0
  85. package/tools.ts +229 -0
  86. package/trace.js +167 -0
  87. package/trace.js.map +1 -0
  88. package/trace.ts +217 -0
  89. package/views.js +18 -0
  90. package/views.js.map +1 -0
  91. package/views.ts +18 -0
  92. package/vocab.js +18 -0
  93. package/vocab.js.map +1 -0
  94. package/vocab.json +364 -0
  95. package/vocab.ts +20 -0
  96. package/worker.js +114 -0
  97. package/worker.js.map +1 -0
  98. package/worker.ts +146 -0
  99. package/write.js +38 -0
  100. package/write.js.map +1 -0
  101. package/write.ts +60 -0
package/invocation.js ADDED
@@ -0,0 +1,245 @@
1
+ // A platform operation has one address and one answer, wherever it runs.
2
+ import { mint, signed, Stale, status, who } from "@yaks/graph";
3
+ import { derivedEid } from "@yaks/graph/identity";
4
+ import { token } from "@yaks/graph/sha256";
5
+ import { sleep } from "@yaks/fp";
6
+ import { Busy, CallError } from "@yaks/tools/errors";
7
+ import { labelled } from "@yaks/vocab";
8
+ /** A callable effect's vocabulary entity. */ export let effectEid = labelled(derivedEid).effect;
9
+ /** The effect run owned by this call. */ export let callRun = (call)=>derivedEid('effect call|' + call);
10
+ /** The answer kept for this invocation. */ export let effectResult = (id)=>derivedEid('effect result|' + id);
11
+ /** Interpret literals and the values captured by a declared match. */ export let boundArgs = (args, vars)=>{
12
+ let value = (v)=>{
13
+ if (typeof v == 'string' && /^\$\w+$/.test(v)) return vars[v.slice(1)];
14
+ if (Array.isArray(v)) return v.map(value);
15
+ if (v && typeof v == 'object') return boundArgs(v, vars);
16
+ return v;
17
+ };
18
+ return Object.fromEntries(Object.entries(args).map(([k, v])=>[
19
+ k,
20
+ value(v)
21
+ ]).filter(([, v])=>v !== undefined));
22
+ };
23
+ /** Capture a call as it stood when it became due. */ export let invocationOf = (row)=>{
24
+ let call = row.call;
25
+ let wake = row.wake;
26
+ let fired = row.fired?.at;
27
+ let source = row.entity.eid;
28
+ let actor = who(row) ?? undefined;
29
+ let each = fired && (wake?.every || Array.isArray(wake?.while) && wake.while.length) ? {
30
+ entity: {
31
+ eid: derivedEid(`call ${source} ${fired}`)
32
+ },
33
+ call: {
34
+ to: call.to,
35
+ args: call.args,
36
+ source
37
+ },
38
+ execution: {}
39
+ } : undefined;
40
+ return {
41
+ args: call.args ?? {},
42
+ call: each?.entity.eid ?? source,
43
+ ...each ? {
44
+ each
45
+ } : {},
46
+ ...actor ? {
47
+ actor
48
+ } : {},
49
+ ...typeof call.id == 'string' ? {
50
+ id: call.id
51
+ } : {}
52
+ };
53
+ };
54
+ /** Record an operation's result against its call, or its matched subject. */ export let answering = (name, run)=>async (e, tx, write, attempt)=>{
55
+ let invocation = e.invocation;
56
+ let key = invocation.call ?? e.run ?? mint();
57
+ let eid = effectResult(key);
58
+ let source = invocation.call ?? e.entity.eid;
59
+ let [prior] = await tx.get([
60
+ eid
61
+ ], [
62
+ 'result'
63
+ ]);
64
+ if (prior?.result) return;
65
+ if (invocation.each && !(await tx.get([
66
+ source
67
+ ], [
68
+ 'call'
69
+ ]))[0]?.call) {
70
+ await write(signed([
71
+ invocation.each
72
+ ], invocation.actor ?? null));
73
+ }
74
+ let began = performance.now();
75
+ let output = (answer)=>({
76
+ entity: {
77
+ eid
78
+ },
79
+ output: {
80
+ source,
81
+ id: invocation.id ?? key,
82
+ value: {
83
+ ...answer.value,
84
+ ...invocation.match ? {
85
+ match: invocation.match
86
+ } : {}
87
+ }
88
+ },
89
+ content: {
90
+ body: answer.body ?? ''
91
+ }
92
+ });
93
+ let finish = async (answer, error)=>{
94
+ try {
95
+ await write([
96
+ {
97
+ ...output(answer),
98
+ ...error,
99
+ result: {
100
+ ...invocation.call ? {
101
+ call: invocation.call
102
+ } : {},
103
+ ms: Math.round(performance.now() - began)
104
+ },
105
+ $was: {
106
+ result: {
107
+ ms: null
108
+ }
109
+ }
110
+ }
111
+ ]);
112
+ } catch (err) {
113
+ if (!(err instanceof Stale) || !(await tx.get([
114
+ eid
115
+ ], [
116
+ 'result'
117
+ ]))[0]?.result) {
118
+ throw err;
119
+ }
120
+ }
121
+ };
122
+ let answer;
123
+ try {
124
+ answer = await run(invocation.args, {
125
+ id: key,
126
+ source,
127
+ actor: invocation.call ? invocation.actor : e.actor,
128
+ progress: async (partial)=>{
129
+ try {
130
+ await write([
131
+ {
132
+ ...output(partial),
133
+ $was: {
134
+ result: {
135
+ ms: null
136
+ }
137
+ }
138
+ }
139
+ ]);
140
+ } catch (error) {
141
+ if (!(error instanceof Stale)) throw error;
142
+ }
143
+ }
144
+ });
145
+ } catch (error) {
146
+ let body = error instanceof Error ? error.message : String(error);
147
+ if (error instanceof CallError || status(error) < 500 && !(error instanceof Stale) && status(error) != 429) {
148
+ if (attempt?.retry) {
149
+ await attempt.retry(()=>finish({
150
+ body
151
+ }, {
152
+ entity: {
153
+ eid
154
+ },
155
+ refusal: {
156
+ code: error instanceof CallError ? error.code : 'refused'
157
+ }
158
+ }));
159
+ } else {
160
+ await finish({
161
+ body
162
+ }, {
163
+ entity: {
164
+ eid
165
+ },
166
+ refusal: {
167
+ code: error instanceof CallError ? error.code : 'refused'
168
+ }
169
+ });
170
+ }
171
+ return;
172
+ }
173
+ if (!attempt || attempt.last()) {
174
+ let failed = ()=>finish({
175
+ body
176
+ }, {
177
+ entity: {
178
+ eid
179
+ },
180
+ exception: {
181
+ type: error instanceof Error ? error.name : name,
182
+ value: body
183
+ }
184
+ });
185
+ if (attempt?.retry) await attempt.retry(failed);
186
+ else await failed();
187
+ }
188
+ throw error;
189
+ }
190
+ if (attempt?.retry) await attempt.retry(()=>finish(answer));
191
+ else await finish(answer);
192
+ };
193
+ /** Ask a callable effect and await its recorded answer. Cancelling the wait
194
+ * leaves the durable invocation to finish. */ export let requestEffect = async (g, name, args, options)=>{
195
+ let eid = options.id;
196
+ let [prior] = await g.get([
197
+ eid
198
+ ], [
199
+ 'call'
200
+ ]);
201
+ if (!prior?.call) {
202
+ try {
203
+ await g.apply(signed([
204
+ {
205
+ entity: {
206
+ eid
207
+ },
208
+ call: {
209
+ to: effectEid(name),
210
+ args: typeof args == 'function' ? await args() : args,
211
+ source: options.source
212
+ },
213
+ $was: {
214
+ call: {
215
+ to: token(null)
216
+ }
217
+ }
218
+ }
219
+ ], options.actor ?? null));
220
+ } catch (error) {
221
+ if (!(error instanceof Stale)) throw error;
222
+ }
223
+ }
224
+ let result = effectResult(eid);
225
+ let wait = 5;
226
+ for(;;){
227
+ let [answer] = await g.get([
228
+ result
229
+ ]);
230
+ if (answer?.result) return answer;
231
+ let [run] = await g.get([
232
+ callRun(eid)
233
+ ], [
234
+ 'effect'
235
+ ]);
236
+ if (run?.effect?.state == 'failed') {
237
+ throw new Error(String(run.effect.error));
238
+ }
239
+ if (options.signal?.aborted) throw options.signal.reason;
240
+ if (options.defer) throw new Busy('Waiting for ' + name, 250);
241
+ await sleep(wait, options.signal);
242
+ wait = Math.min(250, wait * 2);
243
+ }
244
+ };
245
+ //# sourceMappingURL=invocation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invocation.js","sources":["./invocation.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,SAME,IAAI,EACJ,MAAM,EACN,KAAK,EACL,MAAM,EACN,GAAG,2BAC0B;AAC/B,SAAS,UAAU,oCAAyC;AAC5D,SAAS,KAAK,kCAAuC;AACrD,SAAS,KAAK,wBAA6B;AAC3C,SAAS,IAAI,EAAE,SAAS,kCAAuC;AAC/D,SAAS,QAAQ,2BAAgC;AAGjD,2CAA2C,GAC3C,OAAO,IAAI,YAAmC,SAAS,YAAY,MAAM,CAAA;AAEzE,uCAAuC,GACvC,OAAO,IAAI,UAAU,CAAC,OAAmB,WAAW,iBAAiB,MAAK;AAE1E,yCAAyC,GACzC,OAAO,IAAI,eAAe,CAAC,KAAiB,WAAW,mBAAmB,IAAG;AA8B7E,oEAAoE,GACpE,OAAO,IAAI,YAAY,CACrB,MACA;EAEA,IAAI,QAAQ,CAAC;IACX,IAAI,OAAO,KAAK,YAAY,UAAU,IAAI,CAAC,IAAI,OAAO,IAAI,CAAC,EAAE,KAAK,CAAC,GAAG;IACtE,IAAI,MAAM,OAAO,CAAC,IAAI,OAAO,EAAE,GAAG,CAAC;IACnC,IAAI,KAAK,OAAO,KAAK,UAAU,OAAO,UAAU,GAAW;IAC3D,OAAO;EACT;EACA,OAAO,OAAO,WAAW,CACvB,OAAO,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,GAAK;MAAC;MAAG,MAAM;KAAG,EAC/C,MAAM,CAAC,CAAC,GAAG,EAAE,GAAK,MAAM;AAE/B,EAAC;AAED,mDAAmD,GACnD,OAAO,IAAI,eAAe,CAAC;EACzB,IAAI,OAAO,IAAI,IAAI;EACnB,IAAI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S;YACjD,QAAQ,QAAQ,MAAM;UACxB;UACA,MAAM;YAAE,MAAM;cAAE,IAAI,MAAM;YAAM;UAAE;QACpC;OAAE,EAAE,QAAQ,KAAK,IAAI;IACvB,EAAE,OAAO,OAAO;MACd,IAAI,CAAC,CAAC,iBAAiB,KAAK,GAAG,MAAM;IACvC;EACF;EACA,IAAI,SAAS,aAAa;EAC1B,IAAI,OAAO;EACX,OAAS;IACP,IAAI,CAAC,OAAO,GAAG,MAAM,EAAE,GAAG,CAAC;MAAC;KAAO;IACnC,IAAI,QAAQ,QAAQ,OAAO;IAC3B,IAAI,CAAC,IAAI,GAAG,MAAM,EAAE,GAAG,CAAC;MAAC,QAAQ;KAAK,EAAE;MAAC;KAAS;IAClD,IAAI,AAAC,KAAK,QAA6B,SAAS,UAAU;MACxD,MAAM,IAAI,MAAM,OAAO,AAAC,IAAI,MAAM,CAAU,KAAK;IACnD;IACA,IAAI,QAAQ,MAAM,EAAE,SAAS,MAAM,QAAQ,MAAM,CAAC,MAAM;IACxD,IAAI,QAAQ,KAAK,EAAE,MAAM,IAAI,KAAK,iBAAiB,MAAM;IACzD,MAAM,MAAM,MAAM,QAAQ,MAAM;IAChC,OAAO,KAAK,GAAG,CAAC,KAAK,OAAO;EAC9B;AACF,EAAC"}
package/invocation.ts ADDED
@@ -0,0 +1,250 @@
1
+ // A platform operation has one address and one answer, wherever it runs.
2
+ import {
3
+ type Actor,
4
+ type Bundle,
5
+ type Comp,
6
+ type Eid,
7
+ type Graph,
8
+ mint,
9
+ signed,
10
+ Stale,
11
+ status,
12
+ who,
13
+ } from '@yaks/graph'
14
+ import { derivedEid } from '@yaks/graph/identity'
15
+ import { token } from '@yaks/graph/sha256'
16
+ import { sleep } from '@yaks/fp'
17
+ import { Busy, CallError } from '@yaks/tools/errors'
18
+ import { labelled } from '@yaks/vocab'
19
+ import type { Handler } from './registry.ts'
20
+
21
+ /** A callable effect's vocabulary entity. */
22
+ export let effectEid: (name: string) => Eid = labelled(derivedEid).effect
23
+
24
+ /** The effect run owned by this call. */
25
+ export let callRun = (call: Eid): Eid => derivedEid('effect call|' + call)
26
+
27
+ /** The answer kept for this invocation. */
28
+ export let effectResult = (id: Eid): Eid => derivedEid('effect result|' + id)
29
+
30
+ /** What a declared match committed for an invocation, before platform I/O. */
31
+ export type Invocation = {
32
+ args: Record<string, unknown>
33
+ call?: Eid
34
+ /** A recurring firing's new call, prepared from the schedule. */
35
+ each?: Bundle
36
+ actor?: Actor
37
+ match?: string
38
+ id?: string
39
+ }
40
+
41
+ /** Who asked, and where a streaming operation may publish partial results. */
42
+ export type OperationContext = {
43
+ id: Eid
44
+ source: Eid
45
+ actor?: Actor
46
+ progress: (answer: EffectAnswer) => Promise<void>
47
+ }
48
+
49
+ /** The words and data one operation answers together. */
50
+ export type EffectAnswer = { body?: string; value?: Comp }
51
+
52
+ /** One operation over a capability lent by a host. */
53
+ export type Operation = (
54
+ args: Record<string, unknown>,
55
+ context: OperationContext,
56
+ ) => EffectAnswer | Promise<EffectAnswer>
57
+
58
+ /** Interpret literals and the values captured by a declared match. */
59
+ export let boundArgs = (
60
+ args: Record<string, unknown>,
61
+ vars: Record<string, unknown>,
62
+ ): Record<string, unknown> => {
63
+ let value = (v: unknown): unknown => {
64
+ if (typeof v == 'string' && /^\$\w+$/.test(v)) return vars[v.slice(1)]
65
+ if (Array.isArray(v)) return v.map(value)
66
+ if (v && typeof v == 'object') return boundArgs(v as Comp, vars)
67
+ return v
68
+ }
69
+ return Object.fromEntries(
70
+ Object.entries(args).map(([k, v]) => [k, value(v)])
71
+ .filter(([, v]) => v !== undefined),
72
+ )
73
+ }
74
+
75
+ /** Capture a call as it stood when it became due. */
76
+ export let invocationOf = (row: Bundle): Invocation => {
77
+ let call = row.call as Comp
78
+ let wake = row.wake as Comp | undefined
79
+ let fired = (row.fired as Comp | undefined)?.at
80
+ let source = row.entity.eid
81
+ let actor = who(row) ?? undefined
82
+ let each =
83
+ fired && (wake?.every || Array.isArray(wake?.while) && wake.while.length)
84
+ ? {
85
+ entity: { eid: derivedEid(`call ${source} ${fired}`) },
86
+ call: { to: call.to, args: call.args, source },
87
+ execution: {},
88
+ }
89
+ : undefined
90
+ return {
91
+ args: (call.args ?? {}) as Comp,
92
+ call: each?.entity.eid ?? source,
93
+ ...each ? { each } : {},
94
+ ...actor ? { actor } : {},
95
+ ...typeof call.id == 'string' ? { id: call.id } : {},
96
+ }
97
+ }
98
+
99
+ /** Record an operation's result against its call, or its matched subject. */
100
+ export let answering =
101
+ (name: string, run: Operation): Handler => async (e, tx, write, attempt) => {
102
+ let invocation = e.invocation!
103
+ let key = invocation.call ?? e.run ?? mint()
104
+ let eid = effectResult(key)
105
+ let source = invocation.call ?? e.entity.eid
106
+ let [prior] = await tx.get([eid], ['result'])
107
+ if (prior?.result) return
108
+
109
+ if (invocation.each && !(await tx.get([source], ['call']))[0]?.call) {
110
+ await write(signed([invocation.each], invocation.actor ?? null))
111
+ }
112
+ let began = performance.now()
113
+ let output = (answer: EffectAnswer): Bundle => ({
114
+ entity: { eid },
115
+ output: {
116
+ source,
117
+ id: invocation.id ?? key,
118
+ value: {
119
+ ...answer.value,
120
+ ...invocation.match ? { match: invocation.match } : {},
121
+ },
122
+ },
123
+ content: { body: answer.body ?? '' },
124
+ })
125
+ let finish = async (answer: EffectAnswer, error?: Bundle) => {
126
+ try {
127
+ await write([{
128
+ ...output(answer),
129
+ ...error,
130
+ result: {
131
+ ...invocation.call ? { call: invocation.call } : {},
132
+ ms: Math.round(performance.now() - began),
133
+ },
134
+ $was: { result: { ms: null } },
135
+ }])
136
+ } catch (err) {
137
+ if (
138
+ !(err instanceof Stale) ||
139
+ !(await tx.get([eid], ['result']))[0]?.result
140
+ ) {
141
+ throw err
142
+ }
143
+ }
144
+ }
145
+ let answer: EffectAnswer
146
+ try {
147
+ answer = await run(invocation.args, {
148
+ id: key,
149
+ source,
150
+ actor: invocation.call ? invocation.actor : e.actor,
151
+ progress: async (partial) => {
152
+ try {
153
+ await write([{
154
+ ...output(partial),
155
+ $was: { result: { ms: null } },
156
+ }])
157
+ } catch (error) {
158
+ if (!(error instanceof Stale)) throw error
159
+ }
160
+ },
161
+ })
162
+ } catch (error) {
163
+ let body = error instanceof Error ? error.message : String(error)
164
+ if (
165
+ error instanceof CallError ||
166
+ status(error) < 500 && !(error instanceof Stale) && status(error) != 429
167
+ ) {
168
+ if (attempt?.retry) {
169
+ await attempt.retry(() =>
170
+ finish({ body }, {
171
+ entity: { eid },
172
+ refusal: {
173
+ code: error instanceof CallError ? error.code : 'refused',
174
+ },
175
+ })
176
+ )
177
+ } else {
178
+ await finish({ body }, {
179
+ entity: { eid },
180
+ refusal: {
181
+ code: error instanceof CallError ? error.code : 'refused',
182
+ },
183
+ })
184
+ }
185
+ return
186
+ }
187
+ if (!attempt || attempt.last()) {
188
+ let failed = () =>
189
+ finish({ body }, {
190
+ entity: { eid },
191
+ exception: {
192
+ type: error instanceof Error ? error.name : name,
193
+ value: body,
194
+ },
195
+ })
196
+ if (attempt?.retry) await attempt.retry(failed)
197
+ else await failed()
198
+ }
199
+ throw error
200
+ }
201
+ if (attempt?.retry) await attempt.retry(() => finish(answer))
202
+ else await finish(answer)
203
+ }
204
+
205
+ /** Ask a callable effect and await its recorded answer. Cancelling the wait
206
+ * leaves the durable invocation to finish. */
207
+ export let requestEffect = async (
208
+ g: Graph,
209
+ name: string,
210
+ args: Comp | (() => Promise<Comp>),
211
+ options: {
212
+ id: Eid
213
+ source?: Eid
214
+ actor?: Actor | null
215
+ signal?: AbortSignal
216
+ defer?: boolean
217
+ },
218
+ ): Promise<Bundle> => {
219
+ let eid = options.id
220
+ let [prior] = await g.get([eid], ['call'])
221
+ if (!prior?.call) {
222
+ try {
223
+ await g.apply(signed([{
224
+ entity: { eid },
225
+ call: {
226
+ to: effectEid(name),
227
+ args: typeof args == 'function' ? await args() : args,
228
+ source: options.source,
229
+ },
230
+ $was: { call: { to: token(null) } },
231
+ }], options.actor ?? null))
232
+ } catch (error) {
233
+ if (!(error instanceof Stale)) throw error
234
+ }
235
+ }
236
+ let result = effectResult(eid)
237
+ let wait = 5
238
+ for (;;) {
239
+ let [answer] = await g.get([result])
240
+ if (answer?.result) return answer
241
+ let [run] = await g.get([callRun(eid)], ['effect'])
242
+ if ((run?.effect as Comp | undefined)?.state == 'failed') {
243
+ throw new Error(String((run.effect as Comp).error))
244
+ }
245
+ if (options.signal?.aborted) throw options.signal.reason
246
+ if (options.defer) throw new Busy('Waiting for ' + name, 250)
247
+ await sleep(wait, options.signal)
248
+ wait = Math.min(250, wait * 2)
249
+ }
250
+ }