@homeostate/tool-simulator 0.0.0-stage → 0.2.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/CHANGELOG.md +52 -0
- package/LICENSE +21 -0
- package/README.md +71 -2
- package/dist/compare.d.ts +17 -0
- package/dist/compare.d.ts.map +1 -0
- package/dist/compare.js +59 -0
- package/dist/compare.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/network.d.ts +151 -0
- package/dist/network.d.ts.map +1 -0
- package/dist/network.js +245 -0
- package/dist/network.js.map +1 -0
- package/dist/random.d.ts +18 -0
- package/dist/random.d.ts.map +1 -0
- package/dist/random.js +26 -0
- package/dist/random.js.map +1 -0
- package/dist/randomized.d.ts +44 -0
- package/dist/randomized.d.ts.map +1 -0
- package/dist/randomized.js +150 -0
- package/dist/randomized.js.map +1 -0
- package/package.json +58 -3
- package/src/compare.ts +80 -0
- package/src/index.ts +12 -0
- package/src/network.ts +435 -0
- package/src/random.ts +43 -0
- package/src/randomized.ts +211 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# @homeostate/tool-simulator
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 7e7171a: `PeerSetup.config` is typed by the adapter's state, `SyncEngineConfig<S>`, so a peer can take the
|
|
8
|
+
engine's `keys` and `omit` with checked key names. Like `filter`, they also decide what
|
|
9
|
+
convergence compares.
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- cde0b51: A peer's `syncedState()` reads the engine's `getSyncedState()` instead of applying the filter
|
|
14
|
+
again, so convergence compares exactly what the engine syncs.
|
|
15
|
+
- Updated dependencies [39809d7]
|
|
16
|
+
- Updated dependencies [a80be3b]
|
|
17
|
+
- Updated dependencies [60331b4]
|
|
18
|
+
- Updated dependencies [567932b]
|
|
19
|
+
- Updated dependencies [55812ce]
|
|
20
|
+
- Updated dependencies [d2a66d8]
|
|
21
|
+
- Updated dependencies [8ed9541]
|
|
22
|
+
- Updated dependencies [ceca144]
|
|
23
|
+
- Updated dependencies [3bdd635]
|
|
24
|
+
- Updated dependencies [9a6e0c6]
|
|
25
|
+
- Updated dependencies [aa7cbc1]
|
|
26
|
+
- Updated dependencies [3b9d6dc]
|
|
27
|
+
- Updated dependencies [9ce5ff0]
|
|
28
|
+
- Updated dependencies [cde0b51]
|
|
29
|
+
- Updated dependencies [074eadc]
|
|
30
|
+
- Updated dependencies [7e7171a]
|
|
31
|
+
- @homeostate/core@0.4.0
|
|
32
|
+
|
|
33
|
+
## 0.1.0
|
|
34
|
+
|
|
35
|
+
### Minor Changes
|
|
36
|
+
|
|
37
|
+
- 4483caf: Add `@homeostate/tool-simulator`, to test that peers converge. `createNetwork` runs peers, each a store, a backend and a sync engine, on a simulated network on virtual time, with latency, dropped and reordered messages, cut links and partitions, and carries each backend's document as binary updates. `expectConverged()` checks that every peer's store and document agree and says where they differ. `runRandomized` drives random edits and link changes across a fresh network and names the seed of a run that does not converge, so it can be replayed.
|
|
38
|
+
|
|
39
|
+
### Patch Changes
|
|
40
|
+
|
|
41
|
+
- Updated dependencies [732c2c8]
|
|
42
|
+
- Updated dependencies [f901667]
|
|
43
|
+
- Updated dependencies [d858951]
|
|
44
|
+
- Updated dependencies [f77d8a6]
|
|
45
|
+
- Updated dependencies [29f8f0d]
|
|
46
|
+
- Updated dependencies [456fbad]
|
|
47
|
+
- Updated dependencies [30e31df]
|
|
48
|
+
- Updated dependencies [314e268]
|
|
49
|
+
- Updated dependencies [4564712]
|
|
50
|
+
- Updated dependencies [d8e9906]
|
|
51
|
+
- Updated dependencies [008091c]
|
|
52
|
+
- @homeostate/core@0.3.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aliaksandr Mialeshka
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,72 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @homeostate/tool-simulator
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@homeostate/tool-simulator)
|
|
4
|
+
[](https://bundlejs.com/?q=%40homeostate%2Ftool-simulator&config=%7B%22esbuild%22%3A%7B%22external%22%3A%5B%22%40homeostate%2Fcore%22%5D%7D%7D)
|
|
5
|
+
[](https://www.npmjs.com/package/@homeostate/tool-simulator)
|
|
6
|
+
[](https://github.com/mixedrays/homeostate/blob/main/packages/tool-simulator/LICENSE)
|
|
7
|
+
|
|
8
|
+
Test that peers synced by [`@homeostate/core`](https://github.com/mixedrays/homeostate/tree/main/packages/core)
|
|
9
|
+
converge. It runs several peers, each a store, a backend and a sync engine, on a simulated
|
|
10
|
+
network with latency, dropped and reordered messages and partitions, on virtual time, and
|
|
11
|
+
checks that every peer ends up with the same state.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install -D @homeostate/tool-simulator
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
It works with any test runner: a failed check throws an error that says where peers differ.
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import * as Y from "yjs";
|
|
25
|
+
import { createStore } from "zustand/vanilla";
|
|
26
|
+
import { createYjsBackend, createYjsPersistable } from "@homeostate/crdt-yjs";
|
|
27
|
+
import { createZustandAdapter } from "@homeostate/store-zustand";
|
|
28
|
+
import { createNetwork } from "@homeostate/tool-simulator";
|
|
29
|
+
|
|
30
|
+
const network = createNetwork({ latency: [5, 50], seed: 42 });
|
|
31
|
+
const stores = [0, 1, 2].map(() => {
|
|
32
|
+
const doc = new Y.Doc();
|
|
33
|
+
const store = createStore(() => ({ todos: [] }));
|
|
34
|
+
network.addPeer({
|
|
35
|
+
adapter: createZustandAdapter(store),
|
|
36
|
+
backend: createYjsBackend(doc, "shared"),
|
|
37
|
+
doc: createYjsPersistable(doc),
|
|
38
|
+
});
|
|
39
|
+
return store;
|
|
40
|
+
});
|
|
41
|
+
await network.settle();
|
|
42
|
+
|
|
43
|
+
const [alice, bob] = network.peers;
|
|
44
|
+
network.disconnect(alice, bob);
|
|
45
|
+
stores[0].setState({ todos: [{ title: "milk" }] });
|
|
46
|
+
stores[1].setState({ todos: [{ title: "bread" }] });
|
|
47
|
+
|
|
48
|
+
network.heal();
|
|
49
|
+
await network.settle();
|
|
50
|
+
network.expectConverged();
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Each peer's `doc` is its backend's document as binary updates, from the CRDT package's
|
|
54
|
+
`create*Persistable`: that is what the network carries. `settle()` delivers every message on
|
|
55
|
+
its way, and `expectConverged()` throws unless every peer's store and document agree.
|
|
56
|
+
|
|
57
|
+
`runRandomized` drives random edits, link cuts and reconnections across a fresh network, then
|
|
58
|
+
checks convergence and names the seed of a run that fails:
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
await runRandomized({
|
|
62
|
+
createPeer: (index) => makePeer(index),
|
|
63
|
+
network: { latency: [0, 20], reorder: true, dropRate: 0.1 },
|
|
64
|
+
});
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
See the [documentation](https://homeostate.pages.dev/docs/tool-simulator/introduction) for
|
|
68
|
+
every network control and what convergence compares.
|
|
69
|
+
|
|
70
|
+
## License
|
|
71
|
+
|
|
72
|
+
MIT — see [LICENSE](https://github.com/mixedrays/homeostate/blob/main/LICENSE).
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** A key into an object or an index into an array, from the root down. */
|
|
2
|
+
export type Path = (string | number)[];
|
|
3
|
+
/** Where two JSON values first differ; a side is `undefined` where it lacks the key. */
|
|
4
|
+
export interface Difference {
|
|
5
|
+
path: Path;
|
|
6
|
+
left: unknown;
|
|
7
|
+
right: unknown;
|
|
8
|
+
}
|
|
9
|
+
/** `value` as JSON stores it: functions and `undefined` dropped, a Date as a string. */
|
|
10
|
+
export declare const asJson: (value: unknown) => unknown;
|
|
11
|
+
/** The first place where two JSON values differ, or `null` when they are equal. */
|
|
12
|
+
export declare const firstDifference: (left: unknown, right: unknown, path?: Path) => Difference | null;
|
|
13
|
+
/** `todos[0].title`, the way a path reads in code. */
|
|
14
|
+
export declare const formatPath: (path: Path) => string;
|
|
15
|
+
/** A value on one line, shortened; `missing` for `undefined`. */
|
|
16
|
+
export declare const formatValue: (value: unknown) => string;
|
|
17
|
+
//# sourceMappingURL=compare.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compare.d.ts","sourceRoot":"","sources":["../src/compare.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,MAAM,MAAM,IAAI,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;AAEvC,wFAAwF;AACxF,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,IAAI,CAAC;IACX,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EAAE,OAAO,CAAC;CAChB;AAUD,wFAAwF;AACxF,eAAO,MAAM,MAAM,GAAI,OAAO,OAAO,KAAG,OACgB,CAAC;AAEzD,mFAAmF;AACnF,eAAO,MAAM,eAAe,GAC1B,MAAM,OAAO,EACb,OAAO,OAAO,EACd,OAAM,IAAS,KACd,UAAU,GAAG,IAgCf,CAAC;AAEF,sDAAsD;AACtD,eAAO,MAAM,UAAU,GAAI,MAAM,IAAI,KAAG,MAQvC,CAAC;AAIF,iEAAiE;AACjE,eAAO,MAAM,WAAW,GAAI,OAAO,OAAO,KAAG,MAI5C,CAAC"}
|
package/dist/compare.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2
|
+
const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
|
3
|
+
/** `value` as JSON stores it: functions and `undefined` dropped, a Date as a string. */
|
|
4
|
+
export const asJson = (value) => JSON.parse(JSON.stringify(value) ?? "null");
|
|
5
|
+
/** The first place where two JSON values differ, or `null` when they are equal. */
|
|
6
|
+
export const firstDifference = (left, right, path = []) => {
|
|
7
|
+
if (Object.is(left, right))
|
|
8
|
+
return null;
|
|
9
|
+
if (Array.isArray(left) && Array.isArray(right)) {
|
|
10
|
+
const length = Math.max(left.length, right.length);
|
|
11
|
+
for (let index = 0; index < length; index++) {
|
|
12
|
+
const at = [...path, index];
|
|
13
|
+
if (index >= left.length || index >= right.length)
|
|
14
|
+
return { path: at, left: left[index], right: right[index] };
|
|
15
|
+
const difference = firstDifference(left[index], right[index], at);
|
|
16
|
+
if (difference)
|
|
17
|
+
return difference;
|
|
18
|
+
}
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
if (isRecord(left) && isRecord(right)) {
|
|
22
|
+
const keys = [...new Set([...Object.keys(left), ...Object.keys(right)])];
|
|
23
|
+
for (const key of keys.sort()) {
|
|
24
|
+
const at = [...path, key];
|
|
25
|
+
if (!hasOwn(left, key) || !hasOwn(right, key))
|
|
26
|
+
return {
|
|
27
|
+
path: at,
|
|
28
|
+
left: hasOwn(left, key) ? left[key] : undefined,
|
|
29
|
+
right: hasOwn(right, key) ? right[key] : undefined,
|
|
30
|
+
};
|
|
31
|
+
const difference = firstDifference(left[key], right[key], at);
|
|
32
|
+
if (difference)
|
|
33
|
+
return difference;
|
|
34
|
+
}
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
return { path, left, right };
|
|
38
|
+
};
|
|
39
|
+
/** `todos[0].title`, the way a path reads in code. */
|
|
40
|
+
export const formatPath = (path) => {
|
|
41
|
+
if (path.length === 0)
|
|
42
|
+
return "the root";
|
|
43
|
+
return path.reduce((text, key) => {
|
|
44
|
+
if (typeof key === "number")
|
|
45
|
+
return `${text}[${key}]`;
|
|
46
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(key))
|
|
47
|
+
return `${text}[${JSON.stringify(key)}]`;
|
|
48
|
+
return text === "" ? key : `${text}.${key}`;
|
|
49
|
+
}, "");
|
|
50
|
+
};
|
|
51
|
+
const MAX_VALUE = 60;
|
|
52
|
+
/** A value on one line, shortened; `missing` for `undefined`. */
|
|
53
|
+
export const formatValue = (value) => {
|
|
54
|
+
if (value === undefined)
|
|
55
|
+
return "missing";
|
|
56
|
+
const text = JSON.stringify(value);
|
|
57
|
+
return text.length > MAX_VALUE ? `${text.slice(0, MAX_VALUE - 1)}…` : text;
|
|
58
|
+
};
|
|
59
|
+
//# sourceMappingURL=compare.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
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workOptions, NetworkStats, Peer, PeerSetup, } from "./network.js";
|
|
3
|
+
export { randomEdit, runRandomized } from "./randomized.js";
|
|
4
|
+
export type { RandomAction, RandomizedOptions } from "./randomized.js";
|
|
5
|
+
export { createRandom } from "./random.js";
|
|
6
|
+
export type { Random } from "./random.js";
|
|
7
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC/D,YAAY,EACV,OAAO,EACP,cAAc,EACd,YAAY,EACZ,IAAI,EACJ,SAAS,GACV,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC5D,YAAY,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACvE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,YAAY,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAQ/D,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAE5D,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC"}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { type CrdtBackend, type PersistableDoc, type StoreAdapter, type SyncEngine, type SyncEngineConfig } from "@homeostate/core";
|
|
2
|
+
/**
|
|
3
|
+
* What a peer is made of: a store and a backend, as for `createSyncEngine`, and the backend's
|
|
4
|
+
* document as binary updates, which is what the network carries. Use the same document for
|
|
5
|
+
* `backend` and `doc`, e.g. `createYjsBackend(doc, "shared")` and `createYjsPersistable(doc)`.
|
|
6
|
+
*/
|
|
7
|
+
export interface PeerSetup<S extends object = any> {
|
|
8
|
+
adapter: StoreAdapter<S>;
|
|
9
|
+
backend: CrdtBackend;
|
|
10
|
+
doc: PersistableDoc;
|
|
11
|
+
/**
|
|
12
|
+
* Passed to `createSyncEngine`, typed by the adapter's state; its `filter`, `keys` and `omit`
|
|
13
|
+
* also decide what convergence compares.
|
|
14
|
+
*/
|
|
15
|
+
config?: NoInfer<SyncEngineConfig<S>>;
|
|
16
|
+
/** Names the peer in convergence errors. Defaults to `peer-<index>`. */
|
|
17
|
+
name?: string;
|
|
18
|
+
/**
|
|
19
|
+
* Whether to connect the engine as the peer joins, before the network has delivered it the
|
|
20
|
+
* other peers' state. Defaults to `true`. Pass `false` and call `peer.engine.connect()`
|
|
21
|
+
* after `settle()` to model an app that waits for its provider to sync first.
|
|
22
|
+
*/
|
|
23
|
+
connect?: boolean;
|
|
24
|
+
}
|
|
25
|
+
/** A peer on the network: its setup and the sync engine running between its store and backend. */
|
|
26
|
+
export interface Peer<S extends object = any> {
|
|
27
|
+
/** Position in `network.peers`. */
|
|
28
|
+
readonly index: number;
|
|
29
|
+
readonly name: string;
|
|
30
|
+
readonly adapter: StoreAdapter<S>;
|
|
31
|
+
readonly backend: CrdtBackend;
|
|
32
|
+
readonly doc: PersistableDoc;
|
|
33
|
+
readonly engine: SyncEngine;
|
|
34
|
+
/** The store's synced keys, as JSON. */
|
|
35
|
+
syncedState: () => unknown;
|
|
36
|
+
}
|
|
37
|
+
export interface NetworkOptions {
|
|
38
|
+
/** Seed for every random choice, so a run can be replayed. Defaults to a random seed. */
|
|
39
|
+
seed?: number;
|
|
40
|
+
/**
|
|
41
|
+
* Time a message takes, in virtual milliseconds: a number, or `[min, max]` for a random time
|
|
42
|
+
* in that range. Defaults to 0.
|
|
43
|
+
*/
|
|
44
|
+
latency?: number | readonly [number, number];
|
|
45
|
+
/** Probability that an update is lost on its way. Defaults to 0. */
|
|
46
|
+
dropRate?: number;
|
|
47
|
+
/**
|
|
48
|
+
* Whether messages between two peers may overtake each other. Defaults to `false`, as over
|
|
49
|
+
* a WebSocket; with `true`, each takes its own random latency.
|
|
50
|
+
*/
|
|
51
|
+
reorder?: boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Deliveries one `settle()` makes before it gives up on a network that never quiets, such
|
|
54
|
+
* as two peers writing in a loop. Defaults to 100 000.
|
|
55
|
+
*/
|
|
56
|
+
maxDeliveries?: number;
|
|
57
|
+
}
|
|
58
|
+
export interface NetworkStats {
|
|
59
|
+
/** Messages handed to the network, updates and the documents exchanged on connecting. */
|
|
60
|
+
sent: number;
|
|
61
|
+
delivered: number;
|
|
62
|
+
/** Updates lost to `dropRate`. */
|
|
63
|
+
dropped: number;
|
|
64
|
+
/** Messages lost because their link was cut while they were on their way. */
|
|
65
|
+
cut: number;
|
|
66
|
+
/** Messages on their way. */
|
|
67
|
+
inFlight: number;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Peers connected by a simulated network that runs on virtual time. Each change to a peer's
|
|
71
|
+
* document goes to every peer it is linked to, after the latency, unless it is dropped or its
|
|
72
|
+
* link is cut first. Linking two peers, as `connect` and `heal` do, makes them exchange their
|
|
73
|
+
* whole documents, as providers do on reconnecting, so what was lost on the way arrives.
|
|
74
|
+
*/
|
|
75
|
+
export interface Network {
|
|
76
|
+
/** The seed of this network's random choices. */
|
|
77
|
+
readonly seed: number;
|
|
78
|
+
/** Every peer, in the order they joined. */
|
|
79
|
+
readonly peers: readonly Peer[];
|
|
80
|
+
/** Virtual time, in milliseconds. */
|
|
81
|
+
now: () => number;
|
|
82
|
+
/**
|
|
83
|
+
* Add a peer, linked to every peer already on the network, and connect its engine unless
|
|
84
|
+
* `setup.connect` is `false`. It exchanges its document with each of them.
|
|
85
|
+
*/
|
|
86
|
+
addPeer: <S extends object>(setup: PeerSetup<S>) => Peer<S>;
|
|
87
|
+
/** Whether two peers are linked. */
|
|
88
|
+
linked: (a: Peer, b: Peer) => boolean;
|
|
89
|
+
/** Link two peers, and have them exchange their documents. */
|
|
90
|
+
connect: (a: Peer, b: Peer) => void;
|
|
91
|
+
/** Cut the link between two peers; messages on their way between them are lost. */
|
|
92
|
+
disconnect: (a: Peer, b: Peer) => void;
|
|
93
|
+
/** Cut a peer off from every other, as going offline does. */
|
|
94
|
+
isolate: (peer: Peer) => void;
|
|
95
|
+
/**
|
|
96
|
+
* Split the network: peers are linked only to the peers in their own group, and peers in
|
|
97
|
+
* no group to none. Links that come back exchange documents.
|
|
98
|
+
*/
|
|
99
|
+
partition: (...groups: Peer[][]) => void;
|
|
100
|
+
/**
|
|
101
|
+
* Link every pair of peers and have each exchange documents, as if every peer reconnected,
|
|
102
|
+
* so that updates lost to drops and cut links arrive too.
|
|
103
|
+
*/
|
|
104
|
+
heal: () => void;
|
|
105
|
+
/** Deliver the messages due within the next `ms` of virtual time, and move time on. */
|
|
106
|
+
advance: (ms: number) => Promise<void>;
|
|
107
|
+
/** Deliver every message on its way, and those they lead to, until none are left. */
|
|
108
|
+
settle: () => Promise<void>;
|
|
109
|
+
stats: () => NetworkStats;
|
|
110
|
+
/**
|
|
111
|
+
* Where the peers do not agree, one line each: a peer's document against the first peer's,
|
|
112
|
+
* a peer's store against the first peer's, and a connected peer's store against its own
|
|
113
|
+
* document. Empty once the peers have converged.
|
|
114
|
+
*/
|
|
115
|
+
differences: () => string[];
|
|
116
|
+
/** Throws a `ConvergenceError` unless `differences()` is empty. */
|
|
117
|
+
expectConverged: () => void;
|
|
118
|
+
/** Disconnect every engine, stop listening to every document and drop what is on its way. */
|
|
119
|
+
destroy: () => void;
|
|
120
|
+
}
|
|
121
|
+
/** Thrown by `expectConverged`; the message lists the differences. */
|
|
122
|
+
export declare class ConvergenceError extends Error {
|
|
123
|
+
readonly differences: string[];
|
|
124
|
+
readonly seed: number;
|
|
125
|
+
constructor(message: string, differences: string[], seed: number);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Creates an empty network. Add peers with `addPeer`, change their stores, then `settle()` and
|
|
129
|
+
* `expectConverged()`.
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```typescript
|
|
133
|
+
* const network = createNetwork({ latency: [5, 50], seed: 42 });
|
|
134
|
+
* const [alice, bob] = [0, 1].map(() => {
|
|
135
|
+
* const doc = new Y.Doc();
|
|
136
|
+
* const store = createStore(() => ({ todos: [] }));
|
|
137
|
+
* return network.addPeer({
|
|
138
|
+
* adapter: createZustandAdapter(store),
|
|
139
|
+
* backend: createYjsBackend(doc, "shared"),
|
|
140
|
+
* doc: createYjsPersistable(doc),
|
|
141
|
+
* });
|
|
142
|
+
* });
|
|
143
|
+
* network.isolate(alice);
|
|
144
|
+
* // ...edit both stores...
|
|
145
|
+
* network.heal();
|
|
146
|
+
* await network.settle();
|
|
147
|
+
* network.expectConverged();
|
|
148
|
+
* ```
|
|
149
|
+
*/
|
|
150
|
+
export declare function createNetwork(options?: NetworkOptions): Network;
|
|
151
|
+
//# sourceMappingURL=network.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"network.d.ts","sourceRoot":"","sources":["../src/network.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,gBAAgB,EAEtB,MAAM,kBAAkB,CAAC;AAI1B;;;;GAIG;AAGH,MAAM,WAAW,SAAS,CAAC,CAAC,SAAS,MAAM,GAAG,GAAG;IAC/C,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC;IACzB,OAAO,EAAE,WAAW,CAAC;IACrB,GAAG,EAAE,cAAc,CAAC;IACpB;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC;IACtC,wEAAwE;IACxE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;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AM,EAAE,EAAE,IAAI,EAAE,MAAM;CAMjE;AAqBD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,aAAa,CAAC,OAAO,GAAE,cAAmB,GAAG,OAAO,CAgPnE"}
|
package/dist/network.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { createSyncEngine, } from "@homeostate/core";
|
|
2
|
+
import { asJson, firstDifference, formatPath, formatValue } from "./compare.js";
|
|
3
|
+
import { createRandom, randomSeed } from "./random.js";
|
|
4
|
+
/** Thrown by `expectConverged`; the message lists the differences. */
|
|
5
|
+
export class ConvergenceError extends Error {
|
|
6
|
+
constructor(message, differences, seed) {
|
|
7
|
+
super(message);
|
|
8
|
+
Object.defineProperty(this, "differences", {
|
|
9
|
+
enumerable: true,
|
|
10
|
+
configurable: true,
|
|
11
|
+
writable: true,
|
|
12
|
+
value: void 0
|
|
13
|
+
});
|
|
14
|
+
Object.defineProperty(this, "seed", {
|
|
15
|
+
enumerable: true,
|
|
16
|
+
configurable: true,
|
|
17
|
+
writable: true,
|
|
18
|
+
value: void 0
|
|
19
|
+
});
|
|
20
|
+
this.name = "ConvergenceError";
|
|
21
|
+
this.differences = differences;
|
|
22
|
+
this.seed = seed;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
// Taken now, so a test that fakes timers later still lets `settle()` reach the event loop.
|
|
26
|
+
const realSetTimeout = globalThis.setTimeout.bind(globalThis);
|
|
27
|
+
/** Lets work a delivery started, such as a store that notifies asynchronously, finish. */
|
|
28
|
+
const yieldToEventLoop = () => new Promise((resolve) => realSetTimeout(resolve, 0));
|
|
29
|
+
const linkKey = (a, b) => a.index < b.index ? `${a.index}:${b.index}` : `${b.index}:${a.index}`;
|
|
30
|
+
/**
|
|
31
|
+
* Creates an empty network. Add peers with `addPeer`, change their stores, then `settle()` and
|
|
32
|
+
* `expectConverged()`.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```typescript
|
|
36
|
+
* const network = createNetwork({ latency: [5, 50], seed: 42 });
|
|
37
|
+
* const [alice, bob] = [0, 1].map(() => {
|
|
38
|
+
* const doc = new Y.Doc();
|
|
39
|
+
* const store = createStore(() => ({ todos: [] }));
|
|
40
|
+
* return network.addPeer({
|
|
41
|
+
* adapter: createZustandAdapter(store),
|
|
42
|
+
* backend: createYjsBackend(doc, "shared"),
|
|
43
|
+
* doc: createYjsPersistable(doc),
|
|
44
|
+
* });
|
|
45
|
+
* });
|
|
46
|
+
* network.isolate(alice);
|
|
47
|
+
* // ...edit both stores...
|
|
48
|
+
* network.heal();
|
|
49
|
+
* await network.settle();
|
|
50
|
+
* network.expectConverged();
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
export function createNetwork(options = {}) {
|
|
54
|
+
const { seed = randomSeed(), latency = 0, dropRate = 0, reorder = false, maxDeliveries = 100000, } = options;
|
|
55
|
+
const random = createRandom(seed);
|
|
56
|
+
const peers = [];
|
|
57
|
+
const unsubscribers = [];
|
|
58
|
+
/** Pairs of peers whose link is cut; every other pair is linked. */
|
|
59
|
+
const cut = new Set();
|
|
60
|
+
/** When the last message from one peer to another is due, to keep links in order. */
|
|
61
|
+
const lastDue = new Map();
|
|
62
|
+
let queue = [];
|
|
63
|
+
let now = 0;
|
|
64
|
+
let order = 0;
|
|
65
|
+
const stats = { sent: 0, delivered: 0, dropped: 0, cut: 0 };
|
|
66
|
+
const delay = () => {
|
|
67
|
+
if (typeof latency === "number")
|
|
68
|
+
return latency;
|
|
69
|
+
const [min, max] = latency;
|
|
70
|
+
return min + random.next() * (max - min);
|
|
71
|
+
};
|
|
72
|
+
const schedule = (from, to, update) => {
|
|
73
|
+
stats.sent++;
|
|
74
|
+
let at = now + delay();
|
|
75
|
+
if (!reorder) {
|
|
76
|
+
const key = `${from.index}>${to.index}`;
|
|
77
|
+
at = Math.max(at, lastDue.get(key) ?? 0);
|
|
78
|
+
lastDue.set(key, at);
|
|
79
|
+
}
|
|
80
|
+
const message = { from, to, update, at, order: order++ };
|
|
81
|
+
// Keep the queue sorted by due time, then by sending order.
|
|
82
|
+
let index = queue.length;
|
|
83
|
+
while (index > 0 &&
|
|
84
|
+
(queue[index - 1].at > at ||
|
|
85
|
+
(queue[index - 1].at === at && queue[index - 1].order > message.order)))
|
|
86
|
+
index--;
|
|
87
|
+
queue.splice(index, 0, message);
|
|
88
|
+
};
|
|
89
|
+
const linked = (a, b) => a !== b && !cut.has(linkKey(a, b));
|
|
90
|
+
const broadcast = (from, update) => {
|
|
91
|
+
for (const to of peers) {
|
|
92
|
+
if (!linked(from, to))
|
|
93
|
+
continue;
|
|
94
|
+
if (random.chance(dropRate)) {
|
|
95
|
+
stats.sent++;
|
|
96
|
+
stats.dropped++;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
// The document may reuse its buffer for the next update.
|
|
100
|
+
schedule(from, to, update.slice());
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
const link = (a, b) => {
|
|
104
|
+
if (a === b)
|
|
105
|
+
return;
|
|
106
|
+
cut.delete(linkKey(a, b));
|
|
107
|
+
// Never dropped, so linking always lets two peers catch up.
|
|
108
|
+
schedule(a, b, a.doc.encode());
|
|
109
|
+
schedule(b, a, b.doc.encode());
|
|
110
|
+
};
|
|
111
|
+
const unlink = (a, b) => {
|
|
112
|
+
if (a === b)
|
|
113
|
+
return;
|
|
114
|
+
cut.add(linkKey(a, b));
|
|
115
|
+
const before = queue.length;
|
|
116
|
+
queue = queue.filter(({ from, to }) => !((from === a && to === b) || (from === b && to === a)));
|
|
117
|
+
stats.cut += before - queue.length;
|
|
118
|
+
};
|
|
119
|
+
const deliver = (message) => {
|
|
120
|
+
now = Math.max(now, message.at);
|
|
121
|
+
stats.delivered++;
|
|
122
|
+
message.to.doc.apply(message.update);
|
|
123
|
+
};
|
|
124
|
+
/** Deliver messages due by `until`, letting each delivery's work finish before the next. */
|
|
125
|
+
const run = async (until) => {
|
|
126
|
+
let deliveries = 0;
|
|
127
|
+
for (;;) {
|
|
128
|
+
const next = queue[0];
|
|
129
|
+
if (next && next.at <= until) {
|
|
130
|
+
if (++deliveries > maxDeliveries)
|
|
131
|
+
throw new Error(`The network did not settle after ${maxDeliveries} deliveries; is a peer writing in a loop?`);
|
|
132
|
+
queue.shift();
|
|
133
|
+
deliver(next);
|
|
134
|
+
await Promise.resolve();
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
// Asynchronous stores may still send; only stop once a full turn sends nothing.
|
|
138
|
+
await yieldToEventLoop();
|
|
139
|
+
const due = queue[0];
|
|
140
|
+
if (!due || due.at > until)
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
const view = (peer) => ({
|
|
145
|
+
store: peer.syncedState(),
|
|
146
|
+
document: asJson(peer.backend.read()),
|
|
147
|
+
});
|
|
148
|
+
const differences = () => {
|
|
149
|
+
const lines = [];
|
|
150
|
+
const describe = (subject, left, right) => {
|
|
151
|
+
const difference = firstDifference(left, right);
|
|
152
|
+
if (difference)
|
|
153
|
+
lines.push(`${subject} at ${formatPath(difference.path)}: ${formatValue(difference.left)} vs ${formatValue(difference.right)}`);
|
|
154
|
+
};
|
|
155
|
+
const views = peers.map(view);
|
|
156
|
+
peers.forEach((peer, i) => {
|
|
157
|
+
if (peer.engine.isConnected())
|
|
158
|
+
describe(`${peer.name}'s store differs from its document`, views[i].store, views[i].document);
|
|
159
|
+
});
|
|
160
|
+
const [first] = peers;
|
|
161
|
+
for (let i = 1; i < peers.length; i++) {
|
|
162
|
+
describe(`${peers[i].name}'s document differs from ${first.name}'s`, views[i].document, views[0].document);
|
|
163
|
+
describe(`${peers[i].name}'s store differs from ${first.name}'s`, views[i].store, views[0].store);
|
|
164
|
+
}
|
|
165
|
+
return lines;
|
|
166
|
+
};
|
|
167
|
+
return {
|
|
168
|
+
seed,
|
|
169
|
+
peers,
|
|
170
|
+
now: () => now,
|
|
171
|
+
addPeer: (setup) => {
|
|
172
|
+
const index = peers.length;
|
|
173
|
+
const engine = createSyncEngine(setup.backend, setup.adapter, setup.config);
|
|
174
|
+
const peer = {
|
|
175
|
+
index,
|
|
176
|
+
name: setup.name ?? `peer-${index}`,
|
|
177
|
+
adapter: setup.adapter,
|
|
178
|
+
backend: setup.backend,
|
|
179
|
+
doc: setup.doc,
|
|
180
|
+
engine,
|
|
181
|
+
syncedState: () => asJson(engine.getSyncedState()),
|
|
182
|
+
};
|
|
183
|
+
peers.push(peer);
|
|
184
|
+
unsubscribers.push(setup.doc.subscribe((update) => broadcast(peer, update)));
|
|
185
|
+
for (const other of peers)
|
|
186
|
+
link(peer, other);
|
|
187
|
+
if (setup.connect !== false)
|
|
188
|
+
engine.connect();
|
|
189
|
+
return peer;
|
|
190
|
+
},
|
|
191
|
+
linked,
|
|
192
|
+
connect: link,
|
|
193
|
+
disconnect: unlink,
|
|
194
|
+
isolate: (peer) => {
|
|
195
|
+
for (const other of peers)
|
|
196
|
+
unlink(peer, other);
|
|
197
|
+
},
|
|
198
|
+
partition: (...groups) => {
|
|
199
|
+
const groupOf = (peer) => groups.findIndex((group) => group.includes(peer));
|
|
200
|
+
for (const a of peers)
|
|
201
|
+
for (const b of peers) {
|
|
202
|
+
if (a.index >= b.index)
|
|
203
|
+
continue;
|
|
204
|
+
const together = groupOf(a) !== -1 && groupOf(a) === groupOf(b);
|
|
205
|
+
if (!together)
|
|
206
|
+
unlink(a, b);
|
|
207
|
+
else if (!linked(a, b))
|
|
208
|
+
link(a, b);
|
|
209
|
+
}
|
|
210
|
+
},
|
|
211
|
+
heal: () => {
|
|
212
|
+
for (const a of peers)
|
|
213
|
+
for (const b of peers)
|
|
214
|
+
if (a.index < b.index)
|
|
215
|
+
link(a, b);
|
|
216
|
+
},
|
|
217
|
+
advance: async (ms) => {
|
|
218
|
+
const until = now + ms;
|
|
219
|
+
await run(until);
|
|
220
|
+
now = until;
|
|
221
|
+
},
|
|
222
|
+
settle: () => run(Infinity),
|
|
223
|
+
stats: () => ({ ...stats, inFlight: queue.length }),
|
|
224
|
+
differences,
|
|
225
|
+
expectConverged: () => {
|
|
226
|
+
const lines = differences();
|
|
227
|
+
if (lines.length === 0)
|
|
228
|
+
return;
|
|
229
|
+
const inFlight = queue.length > 0
|
|
230
|
+
? `\n${queue.length} messages are still on their way: settle() delivers them.`
|
|
231
|
+
: "";
|
|
232
|
+
throw new ConvergenceError(`${peers.length} peers did not converge (seed ${seed}):\n${lines
|
|
233
|
+
.map((line) => `- ${line}`)
|
|
234
|
+
.join("\n")}${inFlight}`, lines, seed);
|
|
235
|
+
},
|
|
236
|
+
destroy: () => {
|
|
237
|
+
for (const peer of peers)
|
|
238
|
+
peer.engine.disconnect();
|
|
239
|
+
unsubscribers.forEach((unsubscribe) => unsubscribe());
|
|
240
|
+
unsubscribers.length = 0;
|
|
241
|
+
queue = [];
|
|
242
|
+
},
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
//# sourceMappingURL=network.js.map
|