@highalch/story 0.0.0-stage → 0.0.1
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 +21 -0
- package/README.md +342 -2
- package/dist/index.d.mts +42 -0
- package/dist/index.mjs +321 -0
- package/dist/run-C2SdDPWE.d.mts +75 -0
- package/dist/run-DMO8Dcmq.mjs +131 -0
- package/dist/screen.d.mts +71 -0
- package/dist/screen.mjs +505 -0
- package/dist/steps-CvFOQHum.d.mts +599 -0
- package/dist/steps-DZBFsrQr.mjs +950 -0
- package/dist/xstate.d.mts +145 -0
- package/dist/xstate.mjs +405 -0
- package/package.json +93 -3
|
@@ -0,0 +1,950 @@
|
|
|
1
|
+
import { Cause, Data, Deferred, Effect, Exit, Layer, Option, Predicate, Schema, Stream } from "effect";
|
|
2
|
+
import * as HighAlch from "@highalch/db";
|
|
3
|
+
import { Defect, activate, createdKey } from "@highalch/db";
|
|
4
|
+
import * as DomainRead from "@alchemy.run/domain/Read";
|
|
5
|
+
import { getLiveQueryStatusFlags } from "@tanstack/db";
|
|
6
|
+
import { connectionOf, fromLive, keyOf } from "@highalch/db/internal";
|
|
7
|
+
import * as Domain from "@alchemy.run/domain";
|
|
8
|
+
import { RpcClientDefect, RpcClientError } from "effect/rpc/RpcClientError";
|
|
9
|
+
// src/stage.ts
|
|
10
|
+
/** A failed expectation inside a step: what it was about, what it expected and what it saw. */
|
|
11
|
+
var Mismatch = class extends Error {
|
|
12
|
+
reason;
|
|
13
|
+
detail;
|
|
14
|
+
constructor(reason, detail = []) {
|
|
15
|
+
super(reason);
|
|
16
|
+
this.reason = reason;
|
|
17
|
+
this.detail = detail;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* One run of a story, as every step sees it: the hosted world (`None` in a hostless story), the
|
|
22
|
+
* number of the step running, and the state that kinds of steps keep for the length of the run
|
|
23
|
+
* (a machine's snapshot or its actor). A step kind interprets itself against it: data steps read
|
|
24
|
+
* the world through `hosted`, machine steps keep their machines in a `slot`.
|
|
25
|
+
*/
|
|
26
|
+
var Stage = class {
|
|
27
|
+
world;
|
|
28
|
+
name;
|
|
29
|
+
/** The step running now (from 1). */
|
|
30
|
+
step = 0;
|
|
31
|
+
slots = /* @__PURE__ */ new Map();
|
|
32
|
+
afters = [];
|
|
33
|
+
ends = [];
|
|
34
|
+
constructor(world, name = Option.none()) {
|
|
35
|
+
this.world = world;
|
|
36
|
+
this.name = name;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Runs `run` after every later step that passed, the registering step included, before the
|
|
40
|
+
* invariants (a screen captures a frame). A failure in it is that step's failure.
|
|
41
|
+
*/
|
|
42
|
+
after = (run) => {
|
|
43
|
+
this.afters.push(run);
|
|
44
|
+
};
|
|
45
|
+
/** Runs `run` when the story ends, passed or failed, before its world is disposed. */
|
|
46
|
+
end = (run) => {
|
|
47
|
+
this.ends.push(run);
|
|
48
|
+
};
|
|
49
|
+
/** The runner calls this after each step that passed. */
|
|
50
|
+
passed = async (done) => {
|
|
51
|
+
for (const run of this.afters) await run(done);
|
|
52
|
+
};
|
|
53
|
+
/** The runner calls this once when the story ends; the first failure, if any. */
|
|
54
|
+
close = async () => {
|
|
55
|
+
let failure = Option.none();
|
|
56
|
+
for (const run of this.ends.splice(0).reverse()) await run().catch((error) => {
|
|
57
|
+
if (Option.isNone(failure)) failure = Option.some(error);
|
|
58
|
+
});
|
|
59
|
+
return failure;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* The hosted world, for a step that needs one (a data step, a running machine). In a hostless
|
|
63
|
+
* story it fails at once, naming the step.
|
|
64
|
+
*/
|
|
65
|
+
hosted = (label) => Option.getOrThrowWith(this.world, () => new Mismatch(`"${label}" needs a host, and this story has none: data steps and running machines need Story.make(hosting, options); a hostless story (Story.make()) steps machines purely`));
|
|
66
|
+
/** A value a step kind keeps for the length of the run, under its own private key. */
|
|
67
|
+
slot = (key, make) => {
|
|
68
|
+
const known = this.slots.get(key);
|
|
69
|
+
if (known) return known;
|
|
70
|
+
const made = make();
|
|
71
|
+
this.slots.set(key, made);
|
|
72
|
+
return made;
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
// src/clock.ts
|
|
76
|
+
/**
|
|
77
|
+
* The clock a story's clients schedule their waits on (retries, reload debounces, settle
|
|
78
|
+
* timeouts). `manual`: nothing fires until the story advances it, so a story decides when a retry
|
|
79
|
+
* or a timeout happens. `real`: the global `setTimeout`, with the waits still tracked so the story
|
|
80
|
+
* knows when something is about to happen.
|
|
81
|
+
*/
|
|
82
|
+
var Clock = class {
|
|
83
|
+
mode;
|
|
84
|
+
now = 0;
|
|
85
|
+
sequence = 0;
|
|
86
|
+
pending = /* @__PURE__ */ new Map();
|
|
87
|
+
constructor(mode) {
|
|
88
|
+
this.mode = mode;
|
|
89
|
+
}
|
|
90
|
+
/** The `timers` a client is given. */
|
|
91
|
+
timers = { set: (run, ms, wait) => {
|
|
92
|
+
const id = this.sequence += 1;
|
|
93
|
+
if (this.mode === "real") {
|
|
94
|
+
const timer = setTimeout(() => {
|
|
95
|
+
this.pending.delete(id);
|
|
96
|
+
run();
|
|
97
|
+
}, ms);
|
|
98
|
+
this.pending.set(id, {
|
|
99
|
+
id,
|
|
100
|
+
at: this.now + ms,
|
|
101
|
+
wait,
|
|
102
|
+
run
|
|
103
|
+
});
|
|
104
|
+
return () => {
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
this.pending.delete(id);
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
this.pending.set(id, {
|
|
110
|
+
id,
|
|
111
|
+
at: this.now + ms,
|
|
112
|
+
wait,
|
|
113
|
+
run
|
|
114
|
+
});
|
|
115
|
+
return () => {
|
|
116
|
+
this.pending.delete(id);
|
|
117
|
+
};
|
|
118
|
+
} };
|
|
119
|
+
/** Whether a wait of one of these kinds is scheduled. */
|
|
120
|
+
waiting = (...waits) => [...this.pending.values()].some((each) => waits.includes(each.wait));
|
|
121
|
+
/** The scheduled waits, soonest first (then in the order they were scheduled). */
|
|
122
|
+
scheduled = () => [...this.pending.values()].sort((a, b) => a.at - b.at || a.id - b.id).map((each) => ({
|
|
123
|
+
at: each.at,
|
|
124
|
+
wait: each.wait
|
|
125
|
+
}));
|
|
126
|
+
/** Fires the soonest wait due by `until` (of the given kinds, if any); whether one fired. */
|
|
127
|
+
fireNext = (until, waits) => {
|
|
128
|
+
const [next] = [...this.pending.values()].filter((each) => each.at <= until && (!waits || waits.includes(each.wait))).sort((a, b) => a.at - b.at || a.id - b.id);
|
|
129
|
+
if (!next) return false;
|
|
130
|
+
this.pending.delete(next.id);
|
|
131
|
+
this.now = Math.max(this.now, next.at);
|
|
132
|
+
next.run();
|
|
133
|
+
return true;
|
|
134
|
+
};
|
|
135
|
+
};
|
|
136
|
+
// src/wire.ts
|
|
137
|
+
/** A fresh transport failure, as the websocket protocol reports giving up. */
|
|
138
|
+
const transport = (message = "socket closed") => new RpcClientError({ reason: new RpcClientDefect({
|
|
139
|
+
message,
|
|
140
|
+
cause: new Error(message)
|
|
141
|
+
}) });
|
|
142
|
+
/** An Api client as its endpoints by name. */
|
|
143
|
+
const endpointsOf = (client) => client;
|
|
144
|
+
const isFeed = (endpoint) => Predicate.hasProperty(endpoint, "events") && Predicate.hasProperty(endpoint, "peek");
|
|
145
|
+
/**
|
|
146
|
+
* The faults and counts of one client's connection. The story's client of a scope talks to the
|
|
147
|
+
* Domain through it: it counts requests in flight (so the story knows when the network is quiet),
|
|
148
|
+
* records sent commands, and injects the world's events: a dropped feed (`drop`/`resume`), a
|
|
149
|
+
* feed that delivers nothing (`mute`), a failing query or command (`fail`/`recover`) and held
|
|
150
|
+
* answers (`hold`/`release`, a query answers with what it saw when asked, later).
|
|
151
|
+
*/
|
|
152
|
+
var Wire = class {
|
|
153
|
+
/** Requests running and not held. */
|
|
154
|
+
inflight = 0;
|
|
155
|
+
/** Feed connections open now. */
|
|
156
|
+
open = 0;
|
|
157
|
+
/** Feed connections made. */
|
|
158
|
+
connections = 0;
|
|
159
|
+
/** Commands sent, in order. */
|
|
160
|
+
sent = [];
|
|
161
|
+
/** Queries asked, by name, in order. */
|
|
162
|
+
asked = [];
|
|
163
|
+
down;
|
|
164
|
+
/** Whether the feed delivers nothing now (`mute`). */
|
|
165
|
+
muted = false;
|
|
166
|
+
/** Whether the feed was ever muted: the entries it dropped are lost to this connection. */
|
|
167
|
+
lossy = false;
|
|
168
|
+
/** Closed while the story is not letting time pass: command replies wait at it. */
|
|
169
|
+
network = Effect.runSync(Deferred.make());
|
|
170
|
+
cuts = /* @__PURE__ */ new Set();
|
|
171
|
+
failing = /* @__PURE__ */ new Map();
|
|
172
|
+
gate;
|
|
173
|
+
/** Whether the feed is held down (`drop` without `resume`). */
|
|
174
|
+
get dropped() {
|
|
175
|
+
return this.down !== void 0;
|
|
176
|
+
}
|
|
177
|
+
/** Fails every open feed with `error`; reconnections fail too until `resume`. */
|
|
178
|
+
drop = (error = transport()) => {
|
|
179
|
+
this.down = error;
|
|
180
|
+
Effect.runSync(Effect.forEach([...this.cuts], (cut) => Deferred.fail(cut, error)));
|
|
181
|
+
};
|
|
182
|
+
/** Lets feeds connect again. */
|
|
183
|
+
resume = () => {
|
|
184
|
+
this.down = void 0;
|
|
185
|
+
};
|
|
186
|
+
/** Drops feed entries (a feed that stays connected and delivers nothing) while on. */
|
|
187
|
+
mute = (on) => {
|
|
188
|
+
this.muted = on;
|
|
189
|
+
this.lossy ||= on;
|
|
190
|
+
};
|
|
191
|
+
/** The endpoint `name` fails with `error`, `times` times (or until `recover`). */
|
|
192
|
+
fail = (name, error, times = Number.POSITIVE_INFINITY) => {
|
|
193
|
+
this.failing.set(name, {
|
|
194
|
+
error,
|
|
195
|
+
times
|
|
196
|
+
});
|
|
197
|
+
};
|
|
198
|
+
recover = (name) => {
|
|
199
|
+
this.failing.delete(name);
|
|
200
|
+
};
|
|
201
|
+
/**
|
|
202
|
+
* Lets replies through (the story is settling) or holds them again (`flow(false)`): a command's
|
|
203
|
+
* reply reaches the client only while the story lets time pass, so the steps between `when`
|
|
204
|
+
* and the next settling step see the optimistic rows whatever the server already did.
|
|
205
|
+
*/
|
|
206
|
+
flow = (on) => {
|
|
207
|
+
if (!on) {
|
|
208
|
+
this.network ??= Effect.runSync(Deferred.make());
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const network = this.network;
|
|
212
|
+
this.network = void 0;
|
|
213
|
+
if (network) Effect.runSync(Deferred.succeed(network, void 0));
|
|
214
|
+
};
|
|
215
|
+
/** Holds every query's answer until `release`. */
|
|
216
|
+
hold = () => {
|
|
217
|
+
this.gate ??= Effect.runSync(Deferred.make());
|
|
218
|
+
};
|
|
219
|
+
release = () => {
|
|
220
|
+
const gate = this.gate;
|
|
221
|
+
this.gate = void 0;
|
|
222
|
+
if (gate) Effect.runSync(Deferred.succeed(gate, void 0));
|
|
223
|
+
};
|
|
224
|
+
/** Waits, uncounted, at a gate (if it is closed now). */
|
|
225
|
+
waitAt = (gate) => Effect.suspend(() => {
|
|
226
|
+
const closed = gate();
|
|
227
|
+
if (!closed) return Effect.void;
|
|
228
|
+
return Effect.sync(() => this.inflight -= 1).pipe(Effect.andThen(Deferred.await(closed)), Effect.ensuring(Effect.sync(() => this.inflight += 1)));
|
|
229
|
+
});
|
|
230
|
+
/**
|
|
231
|
+
* Counts a request while it runs; a held query's answer (read when asked) waits for `release`,
|
|
232
|
+
* a command's reply waits until the story lets time pass. Fails it when the story says so.
|
|
233
|
+
*/
|
|
234
|
+
counted = (name, effect, held, reply) => Effect.suspend(() => {
|
|
235
|
+
const failing = this.failing.get(name);
|
|
236
|
+
if (failing && failing.times > 0) {
|
|
237
|
+
failing.times -= 1;
|
|
238
|
+
return Effect.fail(failing.error);
|
|
239
|
+
}
|
|
240
|
+
this.inflight += 1;
|
|
241
|
+
return Effect.exit(effect).pipe(Effect.tap(() => this.waitAt(() => held ? this.gate : void 0)), Effect.tap(() => this.waitAt(() => reply ? this.network : void 0)), Effect.ensuring(Effect.sync(() => this.inflight -= 1)), Effect.flatMap((exit) => exit));
|
|
242
|
+
});
|
|
243
|
+
feed = (name, endpoint) => ({
|
|
244
|
+
peek: (...args) => this.counted(`${name}.peek`, endpoint.peek(...args), false, false),
|
|
245
|
+
events: (key, options) => Stream.unwrap(Effect.gen({ self: this }, function* () {
|
|
246
|
+
this.connections += 1;
|
|
247
|
+
if (this.down) return Stream.fail(this.down);
|
|
248
|
+
const cut = yield* Deferred.make();
|
|
249
|
+
this.cuts.add(cut);
|
|
250
|
+
this.open += 1;
|
|
251
|
+
const frames = endpoint.events(key, options).pipe(Stream.filter((frame) => !this.muted || Domain.Read.isCaughtUp(frame)));
|
|
252
|
+
return Stream.merge(frames, Stream.fromEffect(Deferred.await(cut)), { haltStrategy: "either" }).pipe(Stream.ensuring(Effect.sync(() => {
|
|
253
|
+
this.cuts.delete(cut);
|
|
254
|
+
this.open -= 1;
|
|
255
|
+
})));
|
|
256
|
+
}))
|
|
257
|
+
});
|
|
258
|
+
/** Wraps an Api client's endpoints: every endpoint goes through this wire. */
|
|
259
|
+
wrap = (endpoints, queries) => Object.fromEntries(Object.entries(endpoints).map(([name, endpoint]) => {
|
|
260
|
+
if (isFeed(endpoint)) return [name, this.feed(name, endpoint)];
|
|
261
|
+
if (!Predicate.isFunction(endpoint)) return [name, endpoint];
|
|
262
|
+
const call = (...args) => {
|
|
263
|
+
if (queries.has(name)) this.asked.push(name);
|
|
264
|
+
else this.sent.push({
|
|
265
|
+
name,
|
|
266
|
+
target: String(args[0]),
|
|
267
|
+
input: args[1] ?? {}
|
|
268
|
+
});
|
|
269
|
+
return this.counted(name, endpoint(...args), queries.has(name), !queries.has(name));
|
|
270
|
+
};
|
|
271
|
+
return [name, call];
|
|
272
|
+
}));
|
|
273
|
+
};
|
|
274
|
+
// src/world.ts
|
|
275
|
+
/** Removes TanStack DB's virtual fields. */
|
|
276
|
+
const plain = (row) => Object.fromEntries(Object.entries(row).filter(([name]) => !name.startsWith("$")));
|
|
277
|
+
/** A row as stable JSON (fields sorted), for comparisons. */
|
|
278
|
+
const json = (value) => JSON.stringify(value, (_key, field) => {
|
|
279
|
+
if (Predicate.isObject(field) && !Array.isArray(field)) return Object.fromEntries(Object.entries(field).sort(([a], [b]) => a.localeCompare(b)));
|
|
280
|
+
return field;
|
|
281
|
+
});
|
|
282
|
+
/**
|
|
283
|
+
* One source a story's client materialised and keeps observed, as a mounted `useLiveQuery`
|
|
284
|
+
* would: its rows now (with their pending flag) and every change it showed.
|
|
285
|
+
*/
|
|
286
|
+
var Observed = class {
|
|
287
|
+
world;
|
|
288
|
+
scope;
|
|
289
|
+
label;
|
|
290
|
+
collection;
|
|
291
|
+
rows = /* @__PURE__ */ new Map();
|
|
292
|
+
history = [];
|
|
293
|
+
subscription;
|
|
294
|
+
constructor(world, scope, label, collection) {
|
|
295
|
+
this.world = world;
|
|
296
|
+
this.scope = scope;
|
|
297
|
+
this.label = label;
|
|
298
|
+
this.collection = collection;
|
|
299
|
+
this.subscription = collection.subscribeChanges((changes) => {
|
|
300
|
+
const last = /* @__PURE__ */ new Map();
|
|
301
|
+
for (const change of changes) {
|
|
302
|
+
last.delete(String(change.key));
|
|
303
|
+
last.set(String(change.key), change);
|
|
304
|
+
}
|
|
305
|
+
for (const [key, change] of last) {
|
|
306
|
+
const shown = Option.liftPredicate({
|
|
307
|
+
row: plain(change.value),
|
|
308
|
+
pending: change.value.$hasPendingWrites === true
|
|
309
|
+
}, () => change.type !== "delete");
|
|
310
|
+
if (Option.isSome(shown)) this.rows.set(key, shown.value);
|
|
311
|
+
else this.rows.delete(key);
|
|
312
|
+
this.history.push({
|
|
313
|
+
tick: world.next(),
|
|
314
|
+
step: world.step,
|
|
315
|
+
key,
|
|
316
|
+
shown
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
}, { includeInitialState: true });
|
|
320
|
+
}
|
|
321
|
+
get id() {
|
|
322
|
+
return this.collection.id;
|
|
323
|
+
}
|
|
324
|
+
/** The entity whose subset this is, when it is one (a `HighAlch.query` result is not). */
|
|
325
|
+
entity = () => {
|
|
326
|
+
for (const subsets of connectionOf(this.world.client(this.scope).db).subsets.values()) for (const subset of subsets) if (subset.collection.id === this.collection.id) return Option.some(subset.entity);
|
|
327
|
+
return Option.none();
|
|
328
|
+
};
|
|
329
|
+
/** The rows now, by key. */
|
|
330
|
+
sorted = () => [...this.rows].sort(([a], [b]) => a.localeCompare(b));
|
|
331
|
+
/**
|
|
332
|
+
* The source's read state as `match` reads a stock live query result over it: `Loading`,
|
|
333
|
+
* `Retrying`, `Ready`, `Missing` (with `single`), or the typed error.
|
|
334
|
+
*/
|
|
335
|
+
state = (single = false) => {
|
|
336
|
+
const collection = this.collection;
|
|
337
|
+
const rows = [...collection.values()];
|
|
338
|
+
const data = Option.match(Option.liftPredicate(rows, () => single), {
|
|
339
|
+
onNone: () => rows,
|
|
340
|
+
onSome: (found) => found[0]
|
|
341
|
+
});
|
|
342
|
+
const flags = getLiveQueryStatusFlags(collection.status, collection.health);
|
|
343
|
+
return fromLive({
|
|
344
|
+
...flags,
|
|
345
|
+
data,
|
|
346
|
+
status: collection.status,
|
|
347
|
+
isEnabled: true,
|
|
348
|
+
collection
|
|
349
|
+
}).state;
|
|
350
|
+
};
|
|
351
|
+
close = () => this.subscription.unsubscribe();
|
|
352
|
+
};
|
|
353
|
+
const Outcome = Data.taggedEnum();
|
|
354
|
+
/** Retries transport failures (every 100 ms on the story's clock); stops for anything else. */
|
|
355
|
+
const retryTransport = (error) => Option.liftPredicate(100, () => Predicate.isTagged(error, "RpcClientError"));
|
|
356
|
+
/** Lets timers, I/O and the fibers they wake run once. */
|
|
357
|
+
const macrotask = () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
358
|
+
const Frame = Schema.Struct({
|
|
359
|
+
envelope: Schema.Struct({
|
|
360
|
+
seq: Schema.Number,
|
|
361
|
+
commandId: Schema.String
|
|
362
|
+
}),
|
|
363
|
+
event: Schema.Struct({
|
|
364
|
+
_tag: Schema.String,
|
|
365
|
+
entity: Schema.String,
|
|
366
|
+
key: Schema.optionalKey(Schema.String),
|
|
367
|
+
row: Schema.optionalKey(Schema.Unknown),
|
|
368
|
+
cause: Schema.optionalKey(Schema.String)
|
|
369
|
+
})
|
|
370
|
+
});
|
|
371
|
+
/**
|
|
372
|
+
* Everything one story run holds: its host, its clients (one per scope), the clock they wait on,
|
|
373
|
+
* the commands they ran and every row state they showed. Steps act on it; `check` steps and
|
|
374
|
+
* invariants read it. Nothing is global: a story builds its own world and disposes it.
|
|
375
|
+
*/
|
|
376
|
+
var World = class {
|
|
377
|
+
host;
|
|
378
|
+
home;
|
|
379
|
+
options;
|
|
380
|
+
/** The observation counter. */
|
|
381
|
+
tick = 0;
|
|
382
|
+
/** The step running now (from 1). */
|
|
383
|
+
step = 0;
|
|
384
|
+
/** The tick at which the world last settled. */
|
|
385
|
+
settled = -1;
|
|
386
|
+
clock;
|
|
387
|
+
runs = [];
|
|
388
|
+
clients = /* @__PURE__ */ new Map();
|
|
389
|
+
raws = /* @__PURE__ */ new Map();
|
|
390
|
+
/** Releases of clients `activate`d by steps, run when the story ends. */
|
|
391
|
+
releases = [];
|
|
392
|
+
/** Extra conditions for quiet, from extensions (a running machine). */
|
|
393
|
+
quiet = [];
|
|
394
|
+
queries;
|
|
395
|
+
/** The scope steps act as now: the story's first scope, or the one an `as` step names. */
|
|
396
|
+
scope;
|
|
397
|
+
constructor(host, home, options) {
|
|
398
|
+
this.host = host;
|
|
399
|
+
this.home = home;
|
|
400
|
+
this.options = options;
|
|
401
|
+
this.scope = home;
|
|
402
|
+
this.clock = new Clock(options.clock ?? "manual");
|
|
403
|
+
this.queries = new Set(host.api.serves.flatMap((each) => {
|
|
404
|
+
if (Predicate.hasProperty(each, "queryName") && Predicate.isString(each.queryName)) return [each.queryName];
|
|
405
|
+
return [];
|
|
406
|
+
}));
|
|
407
|
+
}
|
|
408
|
+
next = () => this.tick += 1;
|
|
409
|
+
/** The Api client a reader of `scope` uses, unwrapped: "another client". */
|
|
410
|
+
raw = (scope) => {
|
|
411
|
+
const known = this.raws.get(scope);
|
|
412
|
+
if (known) return known;
|
|
413
|
+
const made = this.host.client(scope).then(endpointsOf);
|
|
414
|
+
this.raws.set(scope, made);
|
|
415
|
+
return made;
|
|
416
|
+
};
|
|
417
|
+
/** Opens the client of `scope`. */
|
|
418
|
+
connect = async (scope = this.scope) => {
|
|
419
|
+
const known = this.clients.get(scope);
|
|
420
|
+
if (known) return known;
|
|
421
|
+
const wire = new Wire();
|
|
422
|
+
const raw = await this.raw(scope);
|
|
423
|
+
const api = this.host.api;
|
|
424
|
+
const { live, retry, settleTimeout, reloadDelay, gcTime } = this.options;
|
|
425
|
+
const layer = Layer.succeed(api.Client, wire.wrap(raw, this.queries));
|
|
426
|
+
const client = {
|
|
427
|
+
scope,
|
|
428
|
+
db: HighAlch.make({
|
|
429
|
+
api,
|
|
430
|
+
layer,
|
|
431
|
+
scope,
|
|
432
|
+
live,
|
|
433
|
+
gcTime,
|
|
434
|
+
reloadDelay: reloadDelay ?? 10,
|
|
435
|
+
settleTimeout: settleTimeout ?? 2e3,
|
|
436
|
+
retry: retry ?? retryTransport,
|
|
437
|
+
timers: this.clock.timers
|
|
438
|
+
}),
|
|
439
|
+
wire,
|
|
440
|
+
observed: /* @__PURE__ */ new Map()
|
|
441
|
+
};
|
|
442
|
+
this.clients.set(scope, client);
|
|
443
|
+
return client;
|
|
444
|
+
};
|
|
445
|
+
/** The client of `scope`; it must have been opened. */
|
|
446
|
+
client = (scope = this.scope) => {
|
|
447
|
+
const known = this.clients.get(scope);
|
|
448
|
+
if (!known) throw new Error(`The story has no client of ${scope} yet`);
|
|
449
|
+
return known;
|
|
450
|
+
};
|
|
451
|
+
/** Every client opened so far. */
|
|
452
|
+
all = () => [...this.clients.values()];
|
|
453
|
+
/** Every source observed so far, in every client. */
|
|
454
|
+
observed = () => this.all().flatMap((client) => [...client.observed.values()]);
|
|
455
|
+
/** Materialises a source in the client of `scope` and keeps it observed. */
|
|
456
|
+
observe = async (source, scope = this.scope) => {
|
|
457
|
+
const client = await this.connect(scope);
|
|
458
|
+
const known = client.observed.get(source.id ?? "");
|
|
459
|
+
if (known) return {
|
|
460
|
+
observed: known,
|
|
461
|
+
opened: false
|
|
462
|
+
};
|
|
463
|
+
const collection = client.db.collection(source);
|
|
464
|
+
const observed = new Observed(this, scope, collection.id, collection);
|
|
465
|
+
client.observed.set(collection.id, observed);
|
|
466
|
+
return {
|
|
467
|
+
observed,
|
|
468
|
+
opened: true
|
|
469
|
+
};
|
|
470
|
+
};
|
|
471
|
+
/** Runs one command on the client of `scope` and records it; returns the record. */
|
|
472
|
+
start = async (label, scope, by, input, call, command = Option.none()) => {
|
|
473
|
+
const client = await this.connect(scope);
|
|
474
|
+
const before = new Map([...client.observed.values()].map((each) => [each.id, new Map(each.rows)]));
|
|
475
|
+
const tick = this.next();
|
|
476
|
+
let value = Option.none();
|
|
477
|
+
const transaction = call(client.db, (settled) => {
|
|
478
|
+
value = Option.some(settled);
|
|
479
|
+
});
|
|
480
|
+
const key = transaction.metadata[createdKey];
|
|
481
|
+
const done = transaction.when("settled").then(() => Exit.void, (error) => Exit.fail(error)).then(async (exit) => {
|
|
482
|
+
await macrotask();
|
|
483
|
+
record.outcome = Exit.match(exit, {
|
|
484
|
+
onSuccess: () => Option.match(value, {
|
|
485
|
+
onNone: () => Outcome.Committed({ value }),
|
|
486
|
+
onSome: (settled) => {
|
|
487
|
+
if (Predicate.isTagged(settled, "Unconfirmed")) return Outcome.Unconfirmed({ value: settled });
|
|
488
|
+
return Outcome.Committed({ value });
|
|
489
|
+
}
|
|
490
|
+
}),
|
|
491
|
+
onFailure: (cause) => Option.match(Option.filter(Cause.findErrorOption(cause), (error) => Predicate.hasProperty(error, "_tag")), {
|
|
492
|
+
onSome: (error) => Outcome.Rejected({ error }),
|
|
493
|
+
onNone: () => Outcome.Died({ cause: Cause.die(Cause.squash(cause)) })
|
|
494
|
+
})
|
|
495
|
+
});
|
|
496
|
+
});
|
|
497
|
+
const record = {
|
|
498
|
+
label,
|
|
499
|
+
scope,
|
|
500
|
+
by,
|
|
501
|
+
key: Predicate.isString(key) ? key : "",
|
|
502
|
+
transaction,
|
|
503
|
+
command,
|
|
504
|
+
input,
|
|
505
|
+
tick,
|
|
506
|
+
step: this.step,
|
|
507
|
+
before,
|
|
508
|
+
outcome: Outcome.Pending(),
|
|
509
|
+
ended: -1,
|
|
510
|
+
done: done.then(() => {
|
|
511
|
+
record.ended = this.next();
|
|
512
|
+
})
|
|
513
|
+
};
|
|
514
|
+
this.runs.push(record);
|
|
515
|
+
return record;
|
|
516
|
+
};
|
|
517
|
+
/**
|
|
518
|
+
* The feed entries of every entity the clients of `scope` read, in order, with rows decoded by
|
|
519
|
+
* their entity's schema. Read from the Domain itself (not through the story's wire).
|
|
520
|
+
*/
|
|
521
|
+
entries = async (scope = this.scope) => {
|
|
522
|
+
const client = this.clients.get(scope);
|
|
523
|
+
if (!client) return [];
|
|
524
|
+
const entities = /* @__PURE__ */ new Map();
|
|
525
|
+
for (const subsets of connectionOf(client.db).subsets.values()) for (const subset of subsets) entities.set(subset.entity.entityName, subset.entity);
|
|
526
|
+
const streams = new Set([...entities.values()].map((entity) => entity.feed.streamName));
|
|
527
|
+
const raw = await this.raw(scope);
|
|
528
|
+
const read = [];
|
|
529
|
+
for (const stream of streams) {
|
|
530
|
+
const feed = raw[stream];
|
|
531
|
+
if (!isFeed(feed)) continue;
|
|
532
|
+
const frames = await Effect.runPromise(feed.events(scope, { after: 0 }).pipe(Stream.takeUntil(DomainRead.isCaughtUp), Stream.filter((frame) => !DomainRead.isCaughtUp(frame)), Stream.runCollect));
|
|
533
|
+
for (const frame of frames) {
|
|
534
|
+
const { envelope, event } = Schema.decodeUnknownSync(Frame)(frame);
|
|
535
|
+
const entity = entities.get(event.entity);
|
|
536
|
+
if (!entity) continue;
|
|
537
|
+
const row = Option.map(Option.fromUndefinedOr(event.row), (encoded) => plain(Schema.decodeUnknownSync(entity.rows.row)(encoded)));
|
|
538
|
+
const key = Option.match(row, {
|
|
539
|
+
onNone: () => event.key ?? "",
|
|
540
|
+
onSome: (decoded) => keyOf(entity.rows.key, decoded)
|
|
541
|
+
});
|
|
542
|
+
read.push({
|
|
543
|
+
seq: envelope.seq,
|
|
544
|
+
commandId: event.cause ?? envelope.commandId,
|
|
545
|
+
entity: entity.entityName,
|
|
546
|
+
key,
|
|
547
|
+
row
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
return read.sort((a, b) => a.seq - b.seq);
|
|
552
|
+
};
|
|
553
|
+
/** The server's latest `seq` of a stream for a scope, read from the Domain itself. */
|
|
554
|
+
cursor = async (scope, stream) => {
|
|
555
|
+
const feed = (await this.raw(scope))[stream];
|
|
556
|
+
if (!isFeed(feed)) return 0;
|
|
557
|
+
const latest = await Effect.runPromiseExit(feed.peek(scope));
|
|
558
|
+
return Exit.match(latest, {
|
|
559
|
+
onFailure: () => 0,
|
|
560
|
+
onSuccess: (entry) => entry?.envelope.seq ?? 0
|
|
561
|
+
});
|
|
562
|
+
};
|
|
563
|
+
/** Why the world is not quiet now, or `None`. */
|
|
564
|
+
busy = async () => {
|
|
565
|
+
if (this.host.idle && !await this.host.idle()) return Option.some("the server is busy");
|
|
566
|
+
if (this.clock.mode === "real" && this.clock.waiting("retry", "reload")) return Option.some("a retry or reload is about to run");
|
|
567
|
+
for (const client of this.all()) {
|
|
568
|
+
if (client.wire.inflight > 0) return Option.some(`${client.scope}: ${client.wire.inflight} request(s) in flight`);
|
|
569
|
+
const connection = connectionOf(client.db);
|
|
570
|
+
for (const [stream, feed] of connection.feeds) {
|
|
571
|
+
if (!feed.active) continue;
|
|
572
|
+
if (client.wire.lossy) continue;
|
|
573
|
+
if (!feed.current) {
|
|
574
|
+
if (client.wire.dropped || this.clock.waiting("retry")) continue;
|
|
575
|
+
return Option.some(`${client.scope}: the ${stream} feed is connecting`);
|
|
576
|
+
}
|
|
577
|
+
const cursor = await this.cursor(client.scope, stream);
|
|
578
|
+
if (feed.seq < cursor) return Option.some(`${client.scope}: the ${stream} feed is at ${feed.seq} of ${cursor}`);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
if (!this.quiet.every((check) => check())) return Option.some("a machine is busy");
|
|
582
|
+
return Option.none();
|
|
583
|
+
};
|
|
584
|
+
/**
|
|
585
|
+
* Waits until nothing more happens by itself: the server is idle, no request is in flight, every
|
|
586
|
+
* live feed delivered the server's latest entry, and (with the real clock) no retry or reload is
|
|
587
|
+
* due. Waits on the story's manual clock never fire here: `advance` fires them. Command replies
|
|
588
|
+
* reach the clients only while the world settles; `flow: false` waits without letting them
|
|
589
|
+
* through (the client and its machines catch up, the commands stay in flight).
|
|
590
|
+
*/
|
|
591
|
+
settle = async (flow = true) => {
|
|
592
|
+
let quiet = 0;
|
|
593
|
+
let reason = Option.none();
|
|
594
|
+
const deadline = Date.now() + 3e3;
|
|
595
|
+
if (flow) for (const client of this.all()) client.wire.flow(true);
|
|
596
|
+
while (quiet < 3 && Date.now() < deadline) {
|
|
597
|
+
await macrotask();
|
|
598
|
+
reason = await this.busy();
|
|
599
|
+
if (Option.isNone(reason)) quiet += 1;
|
|
600
|
+
else quiet = 0;
|
|
601
|
+
}
|
|
602
|
+
for (const client of this.all()) client.wire.flow(false);
|
|
603
|
+
if (quiet < 3) throw new Error(`The story did not settle: ${Option.getOrElse(reason, () => "it kept changing")}`);
|
|
604
|
+
this.settled = this.tick;
|
|
605
|
+
};
|
|
606
|
+
/**
|
|
607
|
+
* Settles, then fires the manual clock's waits due within `ms` (in time order), settling after
|
|
608
|
+
* each.
|
|
609
|
+
*/
|
|
610
|
+
advance = async (ms) => {
|
|
611
|
+
await this.settle();
|
|
612
|
+
const until = this.clock.now + ms;
|
|
613
|
+
while (this.clock.fireNext(until)) await this.settle();
|
|
614
|
+
this.clock.now = until;
|
|
615
|
+
await this.settle();
|
|
616
|
+
};
|
|
617
|
+
/**
|
|
618
|
+
* Closes a client. `HighAlch.close` waits until the commands it sent have settled, and a story
|
|
619
|
+
* holds them (replies wait at the wire, settle timeouts on the manual clock): a story that ended
|
|
620
|
+
* or failed with a command in flight lets its replies through and runs the clock's waits until
|
|
621
|
+
* the close returns, so disposing never hangs. Gives up waiting after `deadline`.
|
|
622
|
+
*/
|
|
623
|
+
close = async (client, deadline) => {
|
|
624
|
+
let closed = false;
|
|
625
|
+
const closing = HighAlch.close(client.db).finally(() => {
|
|
626
|
+
closed = true;
|
|
627
|
+
});
|
|
628
|
+
while (!closed && Date.now() < deadline) {
|
|
629
|
+
client.wire.flow(true);
|
|
630
|
+
client.wire.release();
|
|
631
|
+
this.clock.fireNext(Number.POSITIVE_INFINITY);
|
|
632
|
+
await macrotask();
|
|
633
|
+
}
|
|
634
|
+
if (closed) await closing;
|
|
635
|
+
};
|
|
636
|
+
/** Closes every client and the host. */
|
|
637
|
+
dispose = async () => {
|
|
638
|
+
for (const release of this.releases.splice(0)) release();
|
|
639
|
+
for (const each of this.observed()) each.close();
|
|
640
|
+
const deadline = Date.now() + 3e3;
|
|
641
|
+
for (const client of this.all()) await this.close(client, deadline);
|
|
642
|
+
await this.host.dispose();
|
|
643
|
+
};
|
|
644
|
+
};
|
|
645
|
+
/** A defect as a readable line. */
|
|
646
|
+
const describeDefect = (defect) => {
|
|
647
|
+
if (defect instanceof Defect) return `${defect.name}: ${Cause.pretty(defect.cause)}`;
|
|
648
|
+
return String(defect);
|
|
649
|
+
};
|
|
650
|
+
// src/steps.ts
|
|
651
|
+
/**
|
|
652
|
+
* Builds a data step: it acts on (or checks) the hosted world. In a hostless story it fails at
|
|
653
|
+
* once, naming the step.
|
|
654
|
+
*/
|
|
655
|
+
const step = (label, run) => ({
|
|
656
|
+
label,
|
|
657
|
+
run: (stage) => run(stage.hosted(label))
|
|
658
|
+
});
|
|
659
|
+
/**
|
|
660
|
+
* Builds a step of any kind from the stage: `stage.world` (the hosted world, `None` in a hostless
|
|
661
|
+
* story), `stage.hosted(label)` (the world, or a failure naming the step) and `stage.slot(key)`
|
|
662
|
+
* (state the kind keeps for the run). The machine steps are built so.
|
|
663
|
+
*/
|
|
664
|
+
const staged = (label, run) => ({
|
|
665
|
+
label,
|
|
666
|
+
run
|
|
667
|
+
});
|
|
668
|
+
const clip = (text, max = 100) => {
|
|
669
|
+
if (text.length <= max) return text;
|
|
670
|
+
return `${text.slice(0, max - 1)}…`;
|
|
671
|
+
};
|
|
672
|
+
/** A row in a report: its fields of interest (all when none are named), and its pending flag. */
|
|
673
|
+
const brief = (shown, fields) => {
|
|
674
|
+
const picked = Option.match(Option.liftPredicate(fields, (named) => named.length > 0), {
|
|
675
|
+
onNone: () => shown.row,
|
|
676
|
+
onSome: (named) => Object.fromEntries(named.map((field) => [field, shown.row[field]]))
|
|
677
|
+
});
|
|
678
|
+
return `${clip(json(picked))}${shown.pending ? " (pending)" : ""}`;
|
|
679
|
+
};
|
|
680
|
+
/** Every state one key showed in an observed source, in order: `a → b (pending) → -`. */
|
|
681
|
+
const historyOf = (observed, key, fields = []) => observed.history.flatMap((each) => {
|
|
682
|
+
if (each.key !== key) return [];
|
|
683
|
+
return [Option.match(each.shown, {
|
|
684
|
+
onNone: () => "-",
|
|
685
|
+
onSome: (shown) => brief(shown, fields)
|
|
686
|
+
})];
|
|
687
|
+
}).join(" → ");
|
|
688
|
+
/** Does `actual` hold every field of `expected`, deeply? */
|
|
689
|
+
const partial = (expected, actual) => {
|
|
690
|
+
if (Predicate.isObject(expected) && !Array.isArray(expected)) {
|
|
691
|
+
if (!Predicate.isObject(actual)) return false;
|
|
692
|
+
return Object.entries(expected).every(([field, value]) => partial(value, Object.entries(actual).find(([name]) => name === field)?.[1]));
|
|
693
|
+
}
|
|
694
|
+
return json(expected) === json(actual);
|
|
695
|
+
};
|
|
696
|
+
const asRow = (shown) => ({
|
|
697
|
+
...shown.row,
|
|
698
|
+
$hasPendingWrites: shown.pending
|
|
699
|
+
});
|
|
700
|
+
/** Opens a source (once) in the step's client; a newly opened source is settled. */
|
|
701
|
+
const opened = async (world, source, scope) => {
|
|
702
|
+
const { observed, opened: fresh } = await world.observe(source, scope);
|
|
703
|
+
if (fresh) await world.settle();
|
|
704
|
+
return observed;
|
|
705
|
+
};
|
|
706
|
+
/**
|
|
707
|
+
* Seeds history: events committed on an aggregate before the story continues, as alchemy's
|
|
708
|
+
* `Story.given(ref, ...events)` does (through the model's stores; they reach projections and so
|
|
709
|
+
* the row feed, but no policy). Then the world settles. Needs a host that can seed (`memory`).
|
|
710
|
+
*/
|
|
711
|
+
const given = (ref, ...events) => {
|
|
712
|
+
const tagged = events;
|
|
713
|
+
return step(`given ${ref.aggregate}/${String(ref.id)}: ${tagged.map((event) => event._tag).join(", ")}`, async (world) => {
|
|
714
|
+
if (!world.host.seed) throw new Mismatch("this host cannot seed history; use `remote`");
|
|
715
|
+
await world.host.seed(ref, tagged);
|
|
716
|
+
await world.settle();
|
|
717
|
+
});
|
|
718
|
+
};
|
|
719
|
+
function remote(target, command) {
|
|
720
|
+
if (Predicate.isString(target) && Predicate.isFunction(command)) return step(`remote ${target}`, async (world) => {
|
|
721
|
+
const api = await world.raw(world.scope);
|
|
722
|
+
const exit = await Effect.runPromiseExit(command(api));
|
|
723
|
+
if (Exit.isFailure(exit)) throw new Mismatch(`the remote write failed: ${String(exit.cause)}`);
|
|
724
|
+
await world.settle();
|
|
725
|
+
});
|
|
726
|
+
if (Predicate.isString(target) || Predicate.isFunction(command)) throw new Error("remote(ref, command) or remote(label, (api) => effect)");
|
|
727
|
+
const ref = target;
|
|
728
|
+
const sent = command;
|
|
729
|
+
return step(`remote ${ref.aggregate}/${String(ref.id)}: ${sent._tag}`, async (world) => {
|
|
730
|
+
if (!world.host.send) throw new Mismatch("this host cannot send to an aggregate");
|
|
731
|
+
const failed = await world.host.send(ref, sent, `story-remote:${world.next()}`);
|
|
732
|
+
if (Option.isSome(failed)) throw new Mismatch(`the remote ${sent._tag} failed: ${failed.value}`);
|
|
733
|
+
await world.settle();
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
/** Materialises a source in the step's client and keeps it observed (`settle: false`: as is). */
|
|
737
|
+
const open = (source, options = {}) => step(`open ${source.id ?? "source"}`, async (world) => {
|
|
738
|
+
await world.observe(source, options.as);
|
|
739
|
+
if (options.settle !== false) await world.settle();
|
|
740
|
+
});
|
|
741
|
+
/**
|
|
742
|
+
* What a source shows now in the step's client, as `useLiveQuery` over it would: its rows by key
|
|
743
|
+
* (each compared partially; `$hasPendingWrites` names a pending row), or a predicate over them.
|
|
744
|
+
* A source not yet observed is opened and settled first.
|
|
745
|
+
*/
|
|
746
|
+
const shows = (source, expected, options = {}) => step(`shows ${source.id ?? "source"}`, async (world) => {
|
|
747
|
+
const observed = await opened(world, source, options.as);
|
|
748
|
+
const rows = observed.sorted();
|
|
749
|
+
const actual = rows.map(([, shown]) => asRow(shown));
|
|
750
|
+
const list = Option.liftPredicate(expected, Array.isArray);
|
|
751
|
+
const fields = Option.match(list, {
|
|
752
|
+
onNone: () => [],
|
|
753
|
+
onSome: (rows) => [...new Set(rows.flatMap(Object.keys))]
|
|
754
|
+
});
|
|
755
|
+
if (Option.match(list, {
|
|
756
|
+
onSome: (rows) => rows.length === actual.length && rows.every((row, index) => partial(row, actual[index])),
|
|
757
|
+
onNone: () => {
|
|
758
|
+
return expected(actual);
|
|
759
|
+
}
|
|
760
|
+
})) return;
|
|
761
|
+
const keys = new Set(observed.history.map((each) => each.key));
|
|
762
|
+
throw new Mismatch(`${observed.label} does not show what was expected`, [
|
|
763
|
+
Option.match(list, {
|
|
764
|
+
onSome: (rows) => `expected ${clip(json(rows), 400)}`,
|
|
765
|
+
onNone: () => "expected rows for which the predicate holds"
|
|
766
|
+
}),
|
|
767
|
+
`observed ${clip(json(rows.map(([, shown]) => asRow(shown))), 400)}`,
|
|
768
|
+
...[...keys].map((key) => `${key}: ${historyOf(observed, key, fields)}`)
|
|
769
|
+
]);
|
|
770
|
+
});
|
|
771
|
+
/** Whether a state is what a `state` step expects: the tag (and fields), or the error's fields. */
|
|
772
|
+
const matches = (expected, fields, actual) => {
|
|
773
|
+
if (Predicate.isString(expected)) return Predicate.isTagged(actual, expected) && partial(fields, actual);
|
|
774
|
+
return actual.constructor === expected.constructor && json(actual) === json(expected);
|
|
775
|
+
};
|
|
776
|
+
/**
|
|
777
|
+
* The source's read state now, as `match` reads a `useLiveQuery` result over it (the same
|
|
778
|
+
* conversion): `Loading`, `Retrying`, `Ready`, `Missing` (with `single`, for a `findOne`),
|
|
779
|
+
* optionally with some of the state's fields (`state(list, "Retrying", { attempt: 2 })`), or the
|
|
780
|
+
* typed error, which compares by class and fields.
|
|
781
|
+
*/
|
|
782
|
+
const state = (source, expected, fields = {}, options = {}) => step(`state ${source.id ?? "source"}`, async (world) => {
|
|
783
|
+
const { observed } = await world.observe(source, options.as);
|
|
784
|
+
const actual = observed.state(options.single);
|
|
785
|
+
if (matches(expected, fields, actual)) return;
|
|
786
|
+
const shown = Object.fromEntries(Object.entries(actual).filter(([field]) => ![
|
|
787
|
+
"data",
|
|
788
|
+
"retry",
|
|
789
|
+
"feed"
|
|
790
|
+
].includes(field)));
|
|
791
|
+
throw new Mismatch(`${observed.label} is not in the expected state`, [`expected ${clip(json(expected))} ${clip(json(fields))}`, `observed ${clip(json(shown))}`]);
|
|
792
|
+
});
|
|
793
|
+
function when(command, argument) {
|
|
794
|
+
if (Predicate.isString(command) && Predicate.isFunction(argument)) return step(`when ${command}`, async (world) => {
|
|
795
|
+
await world.start(command, world.scope, "story", {}, (client) => argument({
|
|
796
|
+
client,
|
|
797
|
+
activate: () => {
|
|
798
|
+
const release = activate(client);
|
|
799
|
+
world.releases.push(release);
|
|
800
|
+
}
|
|
801
|
+
}));
|
|
802
|
+
});
|
|
803
|
+
if (Predicate.isString(command) || Predicate.isFunction(argument)) throw new Error("when(command, input) or when(label, (acting) => transaction)");
|
|
804
|
+
const input = argument;
|
|
805
|
+
return step(`when ${clip(json(input), 80)}`, async (world) => {
|
|
806
|
+
await world.start(clip(json(input), 80), world.scope, "story", input, (client, onCommitted) => command.with({ client })(input, { onCommitted }), Option.some(command));
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
/** The last command the story's clients ran (a `when` step or a machine's), or the one named. */
|
|
810
|
+
const last = (world) => {
|
|
811
|
+
const run = world.runs.at(-1);
|
|
812
|
+
if (!run) throw new Mismatch("no command ran before this step");
|
|
813
|
+
return run;
|
|
814
|
+
};
|
|
815
|
+
/** Waits until a run ended; fails when the world went quiet and it had not. */
|
|
816
|
+
const pending = (run) => Predicate.isTagged(run.outcome, "Pending");
|
|
817
|
+
const ended = async (world, run) => {
|
|
818
|
+
if (pending(run)) await world.settle();
|
|
819
|
+
for (let round = 0; round < 20 && pending(run); round += 1) await macrotask();
|
|
820
|
+
if (pending(run)) throw new Mismatch(`${run.label} has not settled and nothing more happens by itself`, [`waiting on the clock: ${json(world.clock.scheduled())} (advance it?)`]);
|
|
821
|
+
return run.outcome;
|
|
822
|
+
};
|
|
823
|
+
const outcomeOf = (run) => Option.match(Option.liftPredicate(run.outcome, (outcome) => Predicate.isTagged(outcome, "Rejected")), {
|
|
824
|
+
onSome: (outcome) => json(outcome),
|
|
825
|
+
onNone: () => run.outcome._tag
|
|
826
|
+
});
|
|
827
|
+
/**
|
|
828
|
+
* The last command settled (the transaction completed): as `Committed` (the feed delivered its
|
|
829
|
+
* change) or `Unconfirmed` (the settle timeout passed first), or either when no tag is given.
|
|
830
|
+
*/
|
|
831
|
+
const settled = (expected) => step(`settled${expected ? ` ${expected}` : ""}`, async (world) => {
|
|
832
|
+
const run = last(world);
|
|
833
|
+
const outcome = await ended(world, run);
|
|
834
|
+
if (!((Predicate.isTagged(outcome, "Committed") || Predicate.isTagged(outcome, "Unconfirmed")) && (expected === void 0 || Predicate.isTagged(outcome, expected)))) throw new Mismatch(`${run.label} did not settle as expected`, [`expected ${expected ?? "Committed | Unconfirmed"}`, `observed ${outcomeOf(run)}`]);
|
|
835
|
+
await world.settle();
|
|
836
|
+
});
|
|
837
|
+
/**
|
|
838
|
+
* The last command was rejected with this typed error: the same class (its original instance)
|
|
839
|
+
* with the same fields. The transaction rolled back.
|
|
840
|
+
*/
|
|
841
|
+
const rejected = (expected) => step(`rejected ${expected._tag}`, async (world) => {
|
|
842
|
+
const run = last(world);
|
|
843
|
+
const outcome = await ended(world, run);
|
|
844
|
+
if (!(Predicate.isTagged(outcome, "Rejected") && "error" in outcome && outcome.error.constructor === expected.constructor && json(outcome.error) === json(expected))) throw new Mismatch(`${run.label} was not rejected as expected`, [`expected ${json(expected)}`, `observed ${outcomeOf(run)}`]);
|
|
845
|
+
await world.settle();
|
|
846
|
+
});
|
|
847
|
+
/** The feed of the step's client drops (a transport failure); reconnecting fails until `resume`. */
|
|
848
|
+
const drop = (error = transport()) => step("drop the feed", async (world) => {
|
|
849
|
+
(await world.connect()).wire.drop(error);
|
|
850
|
+
await world.settle();
|
|
851
|
+
});
|
|
852
|
+
/** The feed can connect again; its pending retries run now, and the world settles. */
|
|
853
|
+
const resume = () => step("resume the feed", async (world) => {
|
|
854
|
+
(await world.connect()).wire.resume();
|
|
855
|
+
while (world.clock.fireNext(Number.POSITIVE_INFINITY, ["retry"])) await world.settle();
|
|
856
|
+
await world.settle();
|
|
857
|
+
});
|
|
858
|
+
/** The feed stays connected and delivers nothing while muted. */
|
|
859
|
+
const mute = (on = true) => step(on ? "mute the feed" : "unmute the feed", async (world) => {
|
|
860
|
+
(await world.connect()).wire.mute(on);
|
|
861
|
+
});
|
|
862
|
+
/**
|
|
863
|
+
* An endpoint (a query or command, by name) fails with a typed error for the step's client,
|
|
864
|
+
* `times` times or until `recover`.
|
|
865
|
+
*/
|
|
866
|
+
const fail = (name, error, times) => step(`fail ${name} with ${error._tag}`, async (world) => {
|
|
867
|
+
(await world.connect()).wire.fail(name, error, times);
|
|
868
|
+
});
|
|
869
|
+
/** The endpoint answers again. */
|
|
870
|
+
const recover = (name) => step(`recover ${name}`, async (world) => {
|
|
871
|
+
(await world.connect()).wire.recover(name);
|
|
872
|
+
});
|
|
873
|
+
/** Every query of the step's client answers with what it saw when asked, but only at `release`. */
|
|
874
|
+
const hold = () => step("hold query answers", async (world) => {
|
|
875
|
+
(await world.connect()).wire.hold();
|
|
876
|
+
});
|
|
877
|
+
const release = () => step("release query answers", async (world) => {
|
|
878
|
+
(await world.connect()).wire.release();
|
|
879
|
+
await world.settle();
|
|
880
|
+
});
|
|
881
|
+
const isEntity = (target) => Predicate.hasProperty(target, "entityName") && Predicate.isString(target.entityName);
|
|
882
|
+
function reload(target, options = {}) {
|
|
883
|
+
if (isEntity(target)) return step(`reload ${target.entityName}`, async (world) => {
|
|
884
|
+
HighAlch.reload((await world.connect(options.as)).db, target);
|
|
885
|
+
while (world.clock.fireNext(Number.POSITIVE_INFINITY, ["reload"])) await world.settle();
|
|
886
|
+
await world.settle();
|
|
887
|
+
});
|
|
888
|
+
return step(`reload ${target.id ?? "source"}`, async (world) => {
|
|
889
|
+
const { observed } = await world.observe(target, options.as);
|
|
890
|
+
observed.collection.reload().catch(() => void 0);
|
|
891
|
+
await world.settle();
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* Time passes on the story's manual clock: every retry, reload debounce and settle timeout due
|
|
896
|
+
* within `ms` fires, in time order, the world settling after each.
|
|
897
|
+
*/
|
|
898
|
+
const advance = (ms) => step(`advance ${ms} ms`, async (world) => {
|
|
899
|
+
await world.advance(ms);
|
|
900
|
+
});
|
|
901
|
+
/** Waits until nothing more happens by itself (see `World.settle`). */
|
|
902
|
+
const settle = () => step("settle", (world) => world.settle());
|
|
903
|
+
/** Waits until every command ran so far has ended, then settles. */
|
|
904
|
+
const idle = () => step("idle", async (world) => {
|
|
905
|
+
for (const run of world.runs) await ended(world, run);
|
|
906
|
+
await world.settle();
|
|
907
|
+
});
|
|
908
|
+
/** Any check of the world (the host's services, a client's wire, the runs); throw to fail. */
|
|
909
|
+
const check = (label, assert) => step(`check ${label}`, async (world) => {
|
|
910
|
+
await assert(world);
|
|
911
|
+
});
|
|
912
|
+
/** Runs steps as the client of another scope (opened on first use): two accounts in one story. */
|
|
913
|
+
const as = (scope, ...steps) => flatten(steps).map((inner) => {
|
|
914
|
+
const label = `[${scope}] ${inner.label}`;
|
|
915
|
+
return staged(label, async (stage) => {
|
|
916
|
+
const world = stage.hosted(label);
|
|
917
|
+
const previous = world.scope;
|
|
918
|
+
world.scope = scope;
|
|
919
|
+
try {
|
|
920
|
+
await inner.run(stage);
|
|
921
|
+
} finally {
|
|
922
|
+
world.scope = previous;
|
|
923
|
+
}
|
|
924
|
+
});
|
|
925
|
+
});
|
|
926
|
+
/** Steps as one list. */
|
|
927
|
+
const flatten = (steps) => steps.flatMap((each) => {
|
|
928
|
+
if (Array.isArray(each)) return flatten(each);
|
|
929
|
+
return [each];
|
|
930
|
+
});
|
|
931
|
+
/**
|
|
932
|
+
* Alchemy's own story steps, run on the story's host: `Story.given(ref, ...events)` seeds history
|
|
933
|
+
* (as `given`) and `Story.when(ref, command)` is another client's write (as `remote`). Other
|
|
934
|
+
* alchemy steps assert server decisions only: run them with alchemy's `Story.make`.
|
|
935
|
+
*/
|
|
936
|
+
const alchemy = (from) => {
|
|
937
|
+
if (Predicate.isTagged(from, "Given") && "events" in from) return step(`given ${from.ref.aggregate}/${String(from.ref.id)}`, async (world) => {
|
|
938
|
+
if (!world.host.seed) throw new Mismatch("this host cannot seed history; use `remote`");
|
|
939
|
+
await world.host.seed(from.ref, from.events);
|
|
940
|
+
await world.settle();
|
|
941
|
+
});
|
|
942
|
+
if (Predicate.isTagged(from, "When") && "command" in from) return step(`remote ${from.ref.aggregate}/${String(from.ref.id)}: ${from.command._tag}`, async (world) => {
|
|
943
|
+
if (!world.host.send) throw new Mismatch("this host cannot send to an aggregate");
|
|
944
|
+
const failed = await world.host.send(from.ref, from.command, from.commandId ?? `story-remote:${world.next()}`);
|
|
945
|
+
if (Option.isSome(failed)) throw new Mismatch(`the remote ${from.command._tag} failed: ${failed.value}`);
|
|
946
|
+
await world.settle();
|
|
947
|
+
});
|
|
948
|
+
throw new Error(`alchemy(${from._tag}): only Story.given and Story.when run on a HighAlch story`);
|
|
949
|
+
};
|
|
950
|
+
export { describeDefect as A, shows as C, when as D, step as E, Wire as F, transport as I, Mismatch as L, macrotask as M, plain as N, Observed as O, retryTransport as P, Stage as R, settled as S, state as T, release as _, drop as a, resume as b, given as c, idle as d, mute as f, rejected as g, recover as h, check as i, json as j, World as k, historyOf as l, partial as m, alchemy as n, fail as o, open as p, as as r, flatten as s, advance as t, hold as u, reload as v, staged as w, settle as x, remote as y };
|