@homeostate/tool-simulator 0.0.0-stage → 0.1.0

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/src/network.ts ADDED
@@ -0,0 +1,440 @@
1
+ import {
2
+ createSyncEngine,
3
+ defaultSyncFilter,
4
+ type CrdtBackend,
5
+ type PersistableDoc,
6
+ type StoreAdapter,
7
+ type SyncEngine,
8
+ type SyncEngineConfig,
9
+ type Unsubscribe,
10
+ } from "@homeostate/core";
11
+ import {
12
+ asJson,
13
+ firstDifference,
14
+ formatPath,
15
+ formatValue,
16
+ syncedJson,
17
+ } from "./compare.js";
18
+ import { createRandom, randomSeed } from "./random.js";
19
+
20
+ /**
21
+ * What a peer is made of: a store and a backend, as for `createSyncEngine`, and the backend's
22
+ * document as binary updates, which is what the network carries. Use the same document for
23
+ * `backend` and `doc`, e.g. `createYjsBackend(doc, "shared")` and `createYjsPersistable(doc)`.
24
+ */
25
+ // `any` so a `PeerSetup<TodoState>` fits: `setState` makes the adapter invariant in `S`.
26
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
27
+ export interface PeerSetup<S extends object = any> {
28
+ adapter: StoreAdapter<S>;
29
+ backend: CrdtBackend;
30
+ doc: PersistableDoc;
31
+ /** Passed to `createSyncEngine`; its `filter` also decides what convergence compares. */
32
+ config?: SyncEngineConfig;
33
+ /** Names the peer in convergence errors. Defaults to `peer-<index>`. */
34
+ name?: string;
35
+ /**
36
+ * Whether to connect the engine as the peer joins, before the network has delivered it the
37
+ * other peers' state. Defaults to `true`. Pass `false` and call `peer.engine.connect()`
38
+ * after `settle()` to model an app that waits for its provider to sync first.
39
+ */
40
+ connect?: boolean;
41
+ }
42
+
43
+ /** A peer on the network: its setup and the sync engine running between its store and backend. */
44
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
+ export interface Peer<S extends object = any> {
46
+ /** Position in `network.peers`. */
47
+ readonly index: number;
48
+ readonly name: string;
49
+ readonly adapter: StoreAdapter<S>;
50
+ readonly backend: CrdtBackend;
51
+ readonly doc: PersistableDoc;
52
+ readonly engine: SyncEngine;
53
+ /** The store's synced keys, as JSON. */
54
+ syncedState: () => unknown;
55
+ }
56
+
57
+ export interface NetworkOptions {
58
+ /** Seed for every random choice, so a run can be replayed. Defaults to a random seed. */
59
+ seed?: number;
60
+ /**
61
+ * Time a message takes, in virtual milliseconds: a number, or `[min, max]` for a random time
62
+ * in that range. Defaults to 0.
63
+ */
64
+ latency?: number | readonly [number, number];
65
+ /** Probability that an update is lost on its way. Defaults to 0. */
66
+ dropRate?: number;
67
+ /**
68
+ * Whether messages between two peers may overtake each other. Defaults to `false`, as over
69
+ * a WebSocket; with `true`, each takes its own random latency.
70
+ */
71
+ reorder?: boolean;
72
+ /**
73
+ * Deliveries one `settle()` makes before it gives up on a network that never quiets, such
74
+ * as two peers writing in a loop. Defaults to 100 000.
75
+ */
76
+ maxDeliveries?: number;
77
+ }
78
+
79
+ export interface NetworkStats {
80
+ /** Messages handed to the network, updates and the documents exchanged on connecting. */
81
+ sent: number;
82
+ delivered: number;
83
+ /** Updates lost to `dropRate`. */
84
+ dropped: number;
85
+ /** Messages lost because their link was cut while they were on their way. */
86
+ cut: number;
87
+ /** Messages on their way. */
88
+ inFlight: number;
89
+ }
90
+
91
+ /**
92
+ * Peers connected by a simulated network that runs on virtual time. Each change to a peer's
93
+ * document goes to every peer it is linked to, after the latency, unless it is dropped or its
94
+ * link is cut first. Linking two peers, as `connect` and `heal` do, makes them exchange their
95
+ * whole documents, as providers do on reconnecting, so what was lost on the way arrives.
96
+ */
97
+ export interface Network {
98
+ /** The seed of this network's random choices. */
99
+ readonly seed: number;
100
+ /** Every peer, in the order they joined. */
101
+ readonly peers: readonly Peer[];
102
+ /** Virtual time, in milliseconds. */
103
+ now: () => number;
104
+ /**
105
+ * Add a peer, linked to every peer already on the network, and connect its engine unless
106
+ * `setup.connect` is `false`. It exchanges its document with each of them.
107
+ */
108
+ addPeer: <S extends object>(setup: PeerSetup<S>) => Peer<S>;
109
+ /** Whether two peers are linked. */
110
+ linked: (a: Peer, b: Peer) => boolean;
111
+ /** Link two peers, and have them exchange their documents. */
112
+ connect: (a: Peer, b: Peer) => void;
113
+ /** Cut the link between two peers; messages on their way between them are lost. */
114
+ disconnect: (a: Peer, b: Peer) => void;
115
+ /** Cut a peer off from every other, as going offline does. */
116
+ isolate: (peer: Peer) => void;
117
+ /**
118
+ * Split the network: peers are linked only to the peers in their own group, and peers in
119
+ * no group to none. Links that come back exchange documents.
120
+ */
121
+ partition: (...groups: Peer[][]) => void;
122
+ /**
123
+ * Link every pair of peers and have each exchange documents, as if every peer reconnected,
124
+ * so that updates lost to drops and cut links arrive too.
125
+ */
126
+ heal: () => void;
127
+ /** Deliver the messages due within the next `ms` of virtual time, and move time on. */
128
+ advance: (ms: number) => Promise<void>;
129
+ /** Deliver every message on its way, and those they lead to, until none are left. */
130
+ settle: () => Promise<void>;
131
+ stats: () => NetworkStats;
132
+ /**
133
+ * Where the peers do not agree, one line each: a peer's document against the first peer's,
134
+ * a peer's store against the first peer's, and a connected peer's store against its own
135
+ * document. Empty once the peers have converged.
136
+ */
137
+ differences: () => string[];
138
+ /** Throws a `ConvergenceError` unless `differences()` is empty. */
139
+ expectConverged: () => void;
140
+ /** Disconnect every engine, stop listening to every document and drop what is on its way. */
141
+ destroy: () => void;
142
+ }
143
+
144
+ /** Thrown by `expectConverged`; the message lists the differences. */
145
+ export class ConvergenceError extends Error {
146
+ readonly differences: string[];
147
+ readonly seed: number;
148
+
149
+ constructor(message: string, differences: string[], seed: number) {
150
+ super(message);
151
+ this.name = "ConvergenceError";
152
+ this.differences = differences;
153
+ this.seed = seed;
154
+ }
155
+ }
156
+
157
+ interface Message {
158
+ from: Peer;
159
+ to: Peer;
160
+ update: Uint8Array;
161
+ at: number;
162
+ /** Breaks ties between messages due at the same time, in the order they were sent. */
163
+ order: number;
164
+ }
165
+
166
+ // Taken now, so a test that fakes timers later still lets `settle()` reach the event loop.
167
+ const realSetTimeout = globalThis.setTimeout.bind(globalThis);
168
+
169
+ /** Lets work a delivery started, such as a store that notifies asynchronously, finish. */
170
+ const yieldToEventLoop = (): Promise<void> =>
171
+ new Promise((resolve) => realSetTimeout(resolve, 0));
172
+
173
+ const linkKey = (a: Peer, b: Peer): string =>
174
+ a.index < b.index ? `${a.index}:${b.index}` : `${b.index}:${a.index}`;
175
+
176
+ /**
177
+ * Creates an empty network. Add peers with `addPeer`, change their stores, then `settle()` and
178
+ * `expectConverged()`.
179
+ *
180
+ * @example
181
+ * ```typescript
182
+ * const network = createNetwork({ latency: [5, 50], seed: 42 });
183
+ * const [alice, bob] = [0, 1].map(() => {
184
+ * const doc = new Y.Doc();
185
+ * const store = createStore(() => ({ todos: [] }));
186
+ * return network.addPeer({
187
+ * adapter: createZustandAdapter(store),
188
+ * backend: createYjsBackend(doc, "shared"),
189
+ * doc: createYjsPersistable(doc),
190
+ * });
191
+ * });
192
+ * network.isolate(alice);
193
+ * // ...edit both stores...
194
+ * network.heal();
195
+ * await network.settle();
196
+ * network.expectConverged();
197
+ * ```
198
+ */
199
+ export function createNetwork(options: NetworkOptions = {}): Network {
200
+ const {
201
+ seed = randomSeed(),
202
+ latency = 0,
203
+ dropRate = 0,
204
+ reorder = false,
205
+ maxDeliveries = 100_000,
206
+ } = options;
207
+ const random = createRandom(seed);
208
+ const peers: Peer[] = [];
209
+ const unsubscribers: Unsubscribe[] = [];
210
+ /** Pairs of peers whose link is cut; every other pair is linked. */
211
+ const cut = new Set<string>();
212
+ /** When the last message from one peer to another is due, to keep links in order. */
213
+ const lastDue = new Map<string, number>();
214
+ let queue: Message[] = [];
215
+ let now = 0;
216
+ let order = 0;
217
+ const stats = { sent: 0, delivered: 0, dropped: 0, cut: 0 };
218
+
219
+ const delay = (): number => {
220
+ if (typeof latency === "number") return latency;
221
+ const [min, max] = latency;
222
+ return min + random.next() * (max - min);
223
+ };
224
+
225
+ const schedule = (from: Peer, to: Peer, update: Uint8Array): void => {
226
+ stats.sent++;
227
+ let at = now + delay();
228
+ if (!reorder) {
229
+ const key = `${from.index}>${to.index}`;
230
+ at = Math.max(at, lastDue.get(key) ?? 0);
231
+ lastDue.set(key, at);
232
+ }
233
+ const message: Message = { from, to, update, at, order: order++ };
234
+ // Keep the queue sorted by due time, then by sending order.
235
+ let index = queue.length;
236
+ while (
237
+ index > 0 &&
238
+ (queue[index - 1].at > at ||
239
+ (queue[index - 1].at === at && queue[index - 1].order > message.order))
240
+ )
241
+ index--;
242
+ queue.splice(index, 0, message);
243
+ };
244
+
245
+ const linked = (a: Peer, b: Peer): boolean =>
246
+ a !== b && !cut.has(linkKey(a, b));
247
+
248
+ const broadcast = (from: Peer, update: Uint8Array): void => {
249
+ for (const to of peers) {
250
+ if (!linked(from, to)) continue;
251
+ if (random.chance(dropRate)) {
252
+ stats.sent++;
253
+ stats.dropped++;
254
+ continue;
255
+ }
256
+ // The document may reuse its buffer for the next update.
257
+ schedule(from, to, update.slice());
258
+ }
259
+ };
260
+
261
+ const link = (a: Peer, b: Peer): void => {
262
+ if (a === b) return;
263
+ cut.delete(linkKey(a, b));
264
+ // Never dropped, so linking always lets two peers catch up.
265
+ schedule(a, b, a.doc.encode());
266
+ schedule(b, a, b.doc.encode());
267
+ };
268
+
269
+ const unlink = (a: Peer, b: Peer): void => {
270
+ if (a === b) return;
271
+ cut.add(linkKey(a, b));
272
+ const before = queue.length;
273
+ queue = queue.filter(
274
+ ({ from, to }) => !((from === a && to === b) || (from === b && to === a)),
275
+ );
276
+ stats.cut += before - queue.length;
277
+ };
278
+
279
+ const deliver = (message: Message): void => {
280
+ now = Math.max(now, message.at);
281
+ stats.delivered++;
282
+ message.to.doc.apply(message.update);
283
+ };
284
+
285
+ /** Deliver messages due by `until`, letting each delivery's work finish before the next. */
286
+ const run = async (until: number): Promise<void> => {
287
+ let deliveries = 0;
288
+ for (;;) {
289
+ const next = queue[0];
290
+ if (next && next.at <= until) {
291
+ if (++deliveries > maxDeliveries)
292
+ throw new Error(
293
+ `The network did not settle after ${maxDeliveries} deliveries; is a peer writing in a loop?`,
294
+ );
295
+ queue.shift();
296
+ deliver(next);
297
+ await Promise.resolve();
298
+ continue;
299
+ }
300
+ // Asynchronous stores may still send; only stop once a full turn sends nothing.
301
+ await yieldToEventLoop();
302
+ const due = queue[0];
303
+ if (!due || due.at > until) return;
304
+ }
305
+ };
306
+
307
+ const view = (peer: Peer) => ({
308
+ store: peer.syncedState(),
309
+ document: asJson(peer.backend.read()),
310
+ });
311
+
312
+ const differences = (): string[] => {
313
+ const lines: string[] = [];
314
+ const describe = (subject: string, left: unknown, right: unknown): void => {
315
+ const difference = firstDifference(left, right);
316
+ if (difference)
317
+ lines.push(
318
+ `${subject} at ${formatPath(difference.path)}: ${formatValue(difference.left)} vs ${formatValue(difference.right)}`,
319
+ );
320
+ };
321
+
322
+ const views = peers.map(view);
323
+ peers.forEach((peer, i) => {
324
+ if (peer.engine.isConnected())
325
+ describe(
326
+ `${peer.name}'s store differs from its document`,
327
+ views[i].store,
328
+ views[i].document,
329
+ );
330
+ });
331
+ const [first] = peers;
332
+ for (let i = 1; i < peers.length; i++) {
333
+ describe(
334
+ `${peers[i].name}'s document differs from ${first.name}'s`,
335
+ views[i].document,
336
+ views[0].document,
337
+ );
338
+ describe(
339
+ `${peers[i].name}'s store differs from ${first.name}'s`,
340
+ views[i].store,
341
+ views[0].store,
342
+ );
343
+ }
344
+ return lines;
345
+ };
346
+
347
+ return {
348
+ seed,
349
+ peers,
350
+ now: () => now,
351
+
352
+ addPeer: <S extends object>(setup: PeerSetup<S>): Peer<S> => {
353
+ const index = peers.length;
354
+ const engine = createSyncEngine(
355
+ setup.backend,
356
+ setup.adapter,
357
+ setup.config,
358
+ );
359
+ const filter = setup.config?.filter ?? defaultSyncFilter;
360
+ const peer: Peer<S> = {
361
+ index,
362
+ name: setup.name ?? `peer-${index}`,
363
+ adapter: setup.adapter,
364
+ backend: setup.backend,
365
+ doc: setup.doc,
366
+ engine,
367
+ syncedState: () => syncedJson(setup.adapter.getState(), filter),
368
+ };
369
+ peers.push(peer);
370
+ unsubscribers.push(
371
+ setup.doc.subscribe((update) => broadcast(peer, update)),
372
+ );
373
+ for (const other of peers) link(peer, other);
374
+ if (setup.connect !== false) engine.connect();
375
+ return peer;
376
+ },
377
+
378
+ linked,
379
+
380
+ connect: link,
381
+
382
+ disconnect: unlink,
383
+
384
+ isolate: (peer) => {
385
+ for (const other of peers) unlink(peer, other);
386
+ },
387
+
388
+ partition: (...groups) => {
389
+ const groupOf = (peer: Peer): number =>
390
+ groups.findIndex((group) => group.includes(peer));
391
+ for (const a of peers)
392
+ for (const b of peers) {
393
+ if (a.index >= b.index) continue;
394
+ const together = groupOf(a) !== -1 && groupOf(a) === groupOf(b);
395
+ if (!together) unlink(a, b);
396
+ else if (!linked(a, b)) link(a, b);
397
+ }
398
+ },
399
+
400
+ heal: () => {
401
+ for (const a of peers)
402
+ for (const b of peers) if (a.index < b.index) link(a, b);
403
+ },
404
+
405
+ advance: async (ms) => {
406
+ const until = now + ms;
407
+ await run(until);
408
+ now = until;
409
+ },
410
+
411
+ settle: () => run(Infinity),
412
+
413
+ stats: () => ({ ...stats, inFlight: queue.length }),
414
+
415
+ differences,
416
+
417
+ expectConverged: () => {
418
+ const lines = differences();
419
+ if (lines.length === 0) return;
420
+ const inFlight =
421
+ queue.length > 0
422
+ ? `\n${queue.length} messages are still on their way: settle() delivers them.`
423
+ : "";
424
+ throw new ConvergenceError(
425
+ `${peers.length} peers did not converge (seed ${seed}):\n${lines
426
+ .map((line) => `- ${line}`)
427
+ .join("\n")}${inFlight}`,
428
+ lines,
429
+ seed,
430
+ );
431
+ },
432
+
433
+ destroy: () => {
434
+ for (const peer of peers) peer.engine.disconnect();
435
+ unsubscribers.forEach((unsubscribe) => unsubscribe());
436
+ unsubscribers.length = 0;
437
+ queue = [];
438
+ },
439
+ };
440
+ }
package/src/random.ts ADDED
@@ -0,0 +1,43 @@
1
+ /** A seeded source of random numbers: the same seed gives the same numbers. */
2
+ export interface Random {
3
+ /** The seed it started from. */
4
+ readonly seed: number;
5
+ /** A number from 0 up to, but not including, 1. */
6
+ next: () => number;
7
+ /** An integer from 0 up to, but not including, `max`. */
8
+ int: (max: number) => number;
9
+ /** True with probability `p`. */
10
+ chance: (p: number) => boolean;
11
+ /** One of `items`; throws on an empty list. */
12
+ pick: <T>(items: readonly T[]) => T;
13
+ }
14
+
15
+ /** A seed for a run that names none, drawn from `Math.random`. */
16
+ export const randomSeed = (): number => Math.floor(Math.random() * 2 ** 32);
17
+
18
+ /** Mulberry32: small and fast, and random enough for test inputs. */
19
+ export const createRandom = (seed: number): Random => {
20
+ let state = seed >>> 0;
21
+
22
+ const next = (): number => {
23
+ state = (state + 0x6d2b79f5) >>> 0;
24
+ let t = state;
25
+ t = Math.imul(t ^ (t >>> 15), t | 1);
26
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
27
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
28
+ };
29
+
30
+ const int = (max: number): number => Math.floor(next() * max);
31
+
32
+ return {
33
+ seed,
34
+ next,
35
+ int,
36
+ chance: (p) => next() < p,
37
+ pick: (items) => {
38
+ if (items.length === 0)
39
+ throw new Error("Cannot pick from an empty list.");
40
+ return items[int(items.length)];
41
+ },
42
+ };
43
+ };
@@ -0,0 +1,211 @@
1
+ import {
2
+ createNetwork,
3
+ type NetworkOptions,
4
+ type Peer,
5
+ type PeerSetup,
6
+ } from "./network.js";
7
+ import type { Path } from "./compare.js";
8
+ import { createRandom, randomSeed, type Random } from "./random.js";
9
+
10
+ /** One thing a step of a randomized run does to a peer's store. */
11
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
12
+ export type RandomAction<S extends object = any> = (
13
+ peer: Peer<S>,
14
+ random: Random,
15
+ ) => void;
16
+
17
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
+ export interface RandomizedOptions<S extends object = any> {
19
+ /** Makes peer `index`; called once per peer as the run starts. */
20
+ createPeer: (index: number) => PeerSetup<S>;
21
+ /** Seed of the run, which a failure reports so it can be replayed. Defaults to a random seed. */
22
+ seed?: number;
23
+ /** Defaults to 3. */
24
+ peers?: number;
25
+ /** Defaults to 100. */
26
+ steps?: number;
27
+ /** What a step may do to a random peer's store, one picked at random. Defaults to `[randomEdit]`. */
28
+ actions?: readonly RandomAction<S>[];
29
+ /** Latency, drops and reordering, as for `createNetwork`. */
30
+ network?: Omit<NetworkOptions, "seed">;
31
+ /** Chance that a step cuts or restores a random link instead of changing a store. Defaults to 0.1. */
32
+ linkChangeRate?: number;
33
+ /** Most virtual milliseconds between two steps; each wait is random. Defaults to 10. */
34
+ stepInterval?: number;
35
+ }
36
+
37
+ /**
38
+ * Runs random steps against a fresh network, then heals it, settles it and checks that every
39
+ * peer converged. Each step changes a random peer's store with a random action, or cuts or
40
+ * restores a random link, and lets some virtual time pass, so changes cross each other on
41
+ * their way.
42
+ *
43
+ * Rejects with an error that names the seed and step when a step throws or the peers do not
44
+ * converge; pass that `seed` to replay the same run. Give each document a fixed ID for runs
45
+ * that replay exactly, such as `doc.clientID = index + 1` for Yjs.
46
+ */
47
+ export async function runRandomized<S extends object>(
48
+ options: RandomizedOptions<S>,
49
+ ): Promise<void> {
50
+ const {
51
+ createPeer,
52
+ seed = randomSeed(),
53
+ peers: peerCount = 3,
54
+ steps = 100,
55
+ actions = [randomEdit],
56
+ network: networkOptions,
57
+ linkChangeRate = 0.1,
58
+ stepInterval = 10,
59
+ } = options;
60
+ // Apart from the network's, so adding an action does not change its latencies.
61
+ const random = createRandom(seed ^ 0x5bd1e995);
62
+ const network = createNetwork({ ...networkOptions, seed });
63
+ let step = 0;
64
+
65
+ try {
66
+ const peers = Array.from({ length: peerCount }, (_, index) =>
67
+ network.addPeer(createPeer(index)),
68
+ );
69
+
70
+ for (; step < steps; step++) {
71
+ if (peers.length > 1 && random.chance(linkChangeRate)) {
72
+ const a = random.pick(peers);
73
+ const b = random.pick(peers.filter((peer) => peer !== a));
74
+ if (network.linked(a, b)) network.disconnect(a, b);
75
+ else network.connect(a, b);
76
+ } else {
77
+ random.pick(actions)(random.pick(peers), random);
78
+ }
79
+ await network.advance(random.int(stepInterval + 1));
80
+ }
81
+
82
+ network.heal();
83
+ await network.settle();
84
+ network.expectConverged();
85
+ } catch (error) {
86
+ const when =
87
+ step < steps ? `at step ${step + 1} of ${steps}` : `after ${steps} steps`;
88
+ const message = error instanceof Error ? error.message : String(error);
89
+ throw Object.assign(
90
+ new Error(
91
+ `Randomized run failed ${when}; pass \`seed: ${seed}\` to replay it.\n${message}`,
92
+ ),
93
+ { cause: error },
94
+ );
95
+ } finally {
96
+ network.destroy();
97
+ }
98
+ }
99
+
100
+ type Plain = Record<string, unknown>;
101
+
102
+ const isRecord = (value: unknown): value is Plain =>
103
+ value !== null && typeof value === "object" && !Array.isArray(value);
104
+
105
+ /** Few keys, so peers often edit the same one at once. */
106
+ const KEYS = ["a", "b", "c", "d"];
107
+ /** Characters of one and two UTF-16 units, so string edits cross surrogate pairs. */
108
+ const CHARACTERS = ["x", "y", "é", "🙂", " "];
109
+
110
+ const randomText = (random: Random): string =>
111
+ Array.from({ length: random.int(4) }, () => random.pick(CHARACTERS)).join("");
112
+
113
+ const randomValue = (random: Random, depth = 0): unknown => {
114
+ const roll = random.next();
115
+ if (depth < 2 && roll < 0.15)
116
+ return Array.from({ length: random.int(3) }, () =>
117
+ randomValue(random, depth + 1),
118
+ );
119
+ if (depth < 2 && roll < 0.3)
120
+ return Object.fromEntries(
121
+ Array.from({ length: random.int(3) }, () => [
122
+ random.pick(KEYS),
123
+ randomValue(random, depth + 1),
124
+ ]),
125
+ );
126
+ if (roll < 0.55) return random.int(100);
127
+ if (roll < 0.8) return randomText(random);
128
+ if (roll < 0.95) return random.chance(0.5);
129
+ return null;
130
+ };
131
+
132
+ /** `node` with what `edit` makes of the value at `path`, copying only along the path. */
133
+ const updateIn = (
134
+ node: unknown,
135
+ path: Path,
136
+ edit: (value: unknown) => unknown,
137
+ ): unknown => {
138
+ if (path.length === 0) return edit(node);
139
+ const [key, ...rest] = path;
140
+ if (Array.isArray(node)) {
141
+ const copy = node.slice();
142
+ copy[key as number] = updateIn(node[key as number], rest, edit);
143
+ return copy;
144
+ }
145
+ return {
146
+ ...(node as Plain),
147
+ [key]: updateIn((node as Plain)[key], rest, edit),
148
+ };
149
+ };
150
+
151
+ /** A random change to `value`: an item or key added or removed, a string edited, or a new value. */
152
+ const editValue = (value: unknown, random: Random): unknown => {
153
+ if (Array.isArray(value) && random.chance(0.7)) {
154
+ const copy = value.slice();
155
+ if (copy.length > 0 && random.chance(0.4))
156
+ copy.splice(random.int(copy.length), 1);
157
+ else copy.splice(random.int(copy.length + 1), 0, randomValue(random, 1));
158
+ return copy;
159
+ }
160
+ if (isRecord(value) && random.chance(0.7)) {
161
+ const copy = { ...value };
162
+ const keys = Object.keys(copy);
163
+ if (keys.length > 0 && random.chance(0.4)) delete copy[random.pick(keys)];
164
+ else copy[random.pick(KEYS)] = randomValue(random, 1);
165
+ return copy;
166
+ }
167
+ if (typeof value === "string" && random.chance(0.7)) {
168
+ const characters = [...value];
169
+ const at = random.int(characters.length + 1);
170
+ if (characters.length > 0 && random.chance(0.4)) characters.splice(at, 1);
171
+ else characters.splice(at, 0, random.pick(CHARACTERS));
172
+ return characters.join("");
173
+ }
174
+ return randomValue(random);
175
+ };
176
+
177
+ /**
178
+ * Makes one random change to the peer's store through `adapter.setState`, under one of the
179
+ * synced keys it holds: adds or removes an array item or an object key, edits a string, or
180
+ * replaces a value, at a random depth. It never adds or removes the store's own keys, and
181
+ * leaves the others, actions included, as they are.
182
+ *
183
+ * Suits stores that take any JSON under their keys. For stores with a schema, such as
184
+ * MobX-State-Tree models, pass actions that call the store's own API instead.
185
+ */
186
+ export const randomEdit: RandomAction = (peer, random) => {
187
+ const synced = peer.syncedState();
188
+ if (!isRecord(synced)) return;
189
+ const keys = Object.keys(synced);
190
+ if (keys.length === 0) return;
191
+
192
+ const path: Path = [random.pick(keys)];
193
+ let node: unknown = synced[path[0]];
194
+ while (random.chance(0.5)) {
195
+ if (Array.isArray(node) && node.length > 0) {
196
+ const index = random.int(node.length);
197
+ path.push(index);
198
+ node = node[index];
199
+ } else if (isRecord(node) && Object.keys(node).length > 0) {
200
+ const key = random.pick(Object.keys(node));
201
+ path.push(key);
202
+ node = node[key];
203
+ } else break;
204
+ }
205
+
206
+ peer.adapter.setState(
207
+ updateIn(peer.adapter.getState(), path, (value) =>
208
+ editValue(value, random),
209
+ ) as object,
210
+ );
211
+ };