feat(assembly): add WebRTC partition-and-heal sync with live demo harness

This commit is contained in:
OmO Orchestrator committed 2026-11-17 19:07:43 -05:00
1 parent d795070985
commit 06db1549a0
7 files changed
+748

No files matched your search

@@ -0,0 +1,48 @@
{
"task": "23. ma-assembly partition-heal demo (problem 7, layer 2)",
"qa": "failure/conflict",
"description": "Both sides vote the SAME proposal with the SAME voter differently while partitioned; reconnect yields ONE deterministic resolved vote (CRDT same-key resolution), identical on both sides - no crash, no silent data loss.",
"tool": "Playwright (chromium), two isolated browser contexts over real y-webrtc WebRTC + local signaling server",
"run_command": "node e2e/assemblyPartition.e2e.mjs",
"partition_mechanism": "genuine partition: setOffline(true) on both contexts + signaling WebSocket route blocked + provider.disconnect() tears established RTCDataChannels (peerCount->0); partition proven by asserting votes do NOT propagate across the window",
"timestamp": "2026-11-18T00:06:01.013Z",
"result": {
"scenario": "conflict",
"room": "conflict-bbpzo5jpjvs",
"steps": {
"transportProven": {
"peersA": 1,
"peersB": 1,
"bSawWarmupVote": true
},
"partition": {
"offlineA": true,
"offlineB": true,
"peersA": 0,
"peersB": 0,
"signalingRouteBlocked": true,
"leakedDuringPartition": false
},
"healed": {
"tallyA": {
"proposalId": "prop",
"yes": 2,
"no": 0,
"abstain": 0,
"total": 2
},
"tallyB": {
"proposalId": "prop",
"yes": 2,
"no": 0,
"abstain": 0,
"total": 2
},
"identical": true,
"surviving_dave_choice": "yes"
}
},
"pass": true
},
"pass": true
}
@@ -0,0 +1,47 @@
{
"task": "23. ma-assembly partition-heal demo (problem 7, layer 2)",
"qa": "happy",
"description": "Two non-conflicting votes (one per side) cast while partitioned; reconnect merges to show both.",
"tool": "Playwright (chromium), two isolated browser contexts over real y-webrtc WebRTC + local signaling server",
"run_command": "node e2e/assemblyPartition.e2e.mjs",
"partition_mechanism": "genuine partition: setOffline(true) on both contexts + signaling WebSocket route blocked + provider.disconnect() tears established RTCDataChannels (peerCount->0); partition proven by asserting votes do NOT propagate across the window",
"timestamp": "2026-11-18T00:06:01.013Z",
"result": {
"scenario": "happy",
"room": "happy-j0joyvvrl1",
"steps": {
"transportProven": {
"peersA": 1,
"peersB": 1,
"bSawWarmupVote": true
},
"partition": {
"offlineA": true,
"offlineB": true,
"peersA": 0,
"peersB": 0,
"signalingRouteBlocked": true,
"leakedDuringPartition": false
},
"healed": {
"tallyA": {
"proposalId": "prop",
"yes": 2,
"no": 1,
"abstain": 0,
"total": 3
},
"tallyB": {
"proposalId": "prop",
"yes": 2,
"no": 1,
"abstain": 0,
"total": 3
},
"identical": true
}
},
"pass": true
},
"pass": true
}
+20
View File
@@ -0,0 +1,20 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>ma-assembly partition-heal demo</title>
<style>
body { font: 14px system-ui, sans-serif; margin: 2rem; color: #1f2328; }
h1 { color: #1677ff; font-size: 1.1rem; }
#status { font-variant-numeric: tabular-nums; }
pre { background: #f6f8fa; padding: 1rem; border-radius: 8px; }
</style>
</head>
<body>
<h1>THE COMMONS - ma-assembly P2P sync</h1>
<p id="status">booting…</p>
<pre id="tally">(no tally yet)</pre>
<script type="module" src="/demo/assemblySyncHarness.ts"></script>
</body>
</html>
+90
View File
@@ -0,0 +1,90 @@
import {
castVote,
createAssemblyDoc,
putProposal,
type AssemblyDoc,
type ProposalRecord,
type VoteRecord,
} from "../src/lib/assembly.ts";
import {
connectAssemblySync,
tallyProposal,
type AssemblySync,
type VoteTally,
} from "../src/lib/assemblySync.ts";
interface InitOptions {
room: string;
signaling: string[];
}
interface CommonsHarness {
init(opts: InitOptions): string;
seedProposal(proposal: ProposalRecord): void;
vote(proposalId: string, voterId: string, choice: VoteRecord["choice"]): void;
tally(proposalId: string): VoteTally;
peerCount(): number;
voteCount(): number;
online(): boolean;
setConnected(connected: boolean): void;
}
let assembly: AssemblyDoc | null = null;
let sync: AssemblySync | null = null;
function render(): void {
const statusEl = document.getElementById("status");
const tallyEl = document.getElementById("tally");
if (statusEl && sync) {
statusEl.textContent = `online=${navigator.onLine} peers=${sync.connectedPeerCount()} votes=${assembly?.votes.size ?? 0}`;
}
if (tallyEl && assembly) {
tallyEl.textContent = JSON.stringify([...assembly.votes.values()], null, 2);
}
}
const harness: CommonsHarness = {
init(opts) {
assembly = createAssemblyDoc();
sync = connectAssemblySync(assembly, opts.room, {
signaling: opts.signaling,
peerOpts: { config: { iceServers: [] } },
});
sync.provider.on("peers", render);
sync.provider.on("synced", render);
assembly.doc.on("update", render);
render();
return sync.room;
},
seedProposal(proposal) {
if (!assembly) throw new Error("harness not initialized");
putProposal(assembly, proposal);
},
vote(proposalId, voterId, choice) {
if (!assembly) throw new Error("harness not initialized");
castVote(assembly, { proposalId, voterId, choice, castAt: Date.now() });
},
tally(proposalId) {
if (!assembly) throw new Error("harness not initialized");
return tallyProposal(assembly, proposalId);
},
peerCount() {
return sync?.connectedPeerCount() ?? 0;
},
voteCount() {
return assembly?.votes.size ?? 0;
},
online() {
return navigator.onLine;
},
setConnected(connected) {
if (!sync) throw new Error("harness not initialized");
if (connected) sync.provider.connect();
else sync.provider.disconnect();
render();
},
};
(window as unknown as { commons: CommonsHarness }).commons = harness;
window.addEventListener("online", render);
window.addEventListener("offline", render);
+301
View File
@@ -0,0 +1,301 @@
// ma-assembly WebRTC partition-and-heal acceptance test (plan todo 23).
//
// Self-contained Playwright runner. It starts a local y-webrtc signaling
// server and a Vite dev server, opens TWO isolated browser contexts (the two
// "devices"), and for each QA scenario:
// 1. connects both sides over real WebRTC and proves the live transport
// works (a warmup vote genuinely propagates side->side),
// 2. PARTITIONS the two sides for real - setOffline(true) on both contexts,
// blocks the signaling WebSocket route, AND tears the established
// RTCDataChannels (provider.disconnect) so peerCount drops to 0,
// 3. casts an independent vote on each side and ASSERTS non-propagation for
// a window (this is the genuine-partition proof: if the sides were
// secretly still syncing, the counts would move and the test fails),
// 4. HEALS - setOffline(false), unblocks signaling, reconnects - and asserts
// both sides converge to the identical final tally.
//
// Why not setOffline alone: over loopback, Chromium host candidates
// (127.0.0.1) bypass network emulation, so setOffline(true) does NOT cut an
// already-established data channel (empirically verified). Genuinely severing
// the transport + asserting non-propagation is what makes the partition real
// rather than cosmetic.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import { spawn } from "node:child_process";
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const SIG_PORT = 40000 + Math.floor(Math.random() * 20000);
const VITE_PORT = 41000 + Math.floor(Math.random() * 20000);
const SIG = `ws://127.0.0.1:${SIG_PORT}`;
const PAGE = `http://127.0.0.1:${VITE_PORT}/demo/assembly-sync.html`;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function waitFor(fn, label, timeoutMs = 20000) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (await fn()) return;
await sleep(200);
}
throw new Error(`timeout waiting for: ${label}`);
}
function startSignaling() {
return new Promise((resolvePromise, reject) => {
const child = spawn("node", ["node_modules/y-webrtc/bin/server.js"], {
cwd: ROOT,
env: { ...process.env, PORT: String(SIG_PORT) },
stdio: ["ignore", "pipe", "pipe"],
});
const to = setTimeout(() => reject(new Error("signaling start timeout")), 10000);
child.stdout.on("data", (b) => {
if (String(b).includes("Signaling server running")) {
clearTimeout(to);
resolvePromise(child);
}
});
child.stderr.on("data", (b) => process.stderr.write(`[sig] ${b}`));
child.on("exit", (code) => reject(new Error(`signaling exited early: ${code}`)));
});
}
async function runScenario(browser, { name, partitionVotes, assertConverged }) {
const ctxA = await browser.newContext();
const ctxB = await browser.newContext();
const state = { blockSig: false };
for (const ctx of [ctxA, ctxB]) {
await ctx.routeWebSocket(new RegExp(`127\\.0\\.0\\.1:${SIG_PORT}`), (ws) => {
if (state.blockSig) {
ws.close();
return;
}
ws.connectToServer();
});
}
const a = await ctxA.newPage();
const b = await ctxB.newPage();
const room = `${name}-${Math.random().toString(36).slice(2)}`;
const evidence = { scenario: name, room, steps: {} };
try {
await a.goto(PAGE);
await b.goto(PAGE);
const initArg = { room, signaling: [SIG] };
await a.evaluate((o) => window.commons.init(o), initArg);
await b.evaluate((o) => window.commons.init(o), initArg);
// 1. connect + prove the live transport actually works
await waitFor(() => a.evaluate(() => window.commons.peerCount() > 0), "A connects");
await waitFor(() => b.evaluate(() => window.commons.peerCount() > 0), "B connects");
await a.evaluate(() => window.commons.vote("prop", "warmup-voter", "yes"));
await waitFor(() => b.evaluate(() => window.commons.voteCount() >= 1), "warmup propagates to B");
evidence.steps.transportProven = {
peersA: await a.evaluate(() => window.commons.peerCount()),
peersB: await b.evaluate(() => window.commons.peerCount()),
bSawWarmupVote: (await b.evaluate(() => window.commons.voteCount())) >= 1,
};
// 2. genuine partition
state.blockSig = true;
await ctxA.setOffline(true);
await ctxB.setOffline(true);
await a.evaluate(() => window.commons.setConnected(false));
await b.evaluate(() => window.commons.setConnected(false));
await waitFor(() => a.evaluate(() => window.commons.peerCount() === 0), "A isolated");
await waitFor(() => b.evaluate(() => window.commons.peerCount() === 0), "B isolated");
const countBeforeA = await a.evaluate(() => window.commons.voteCount());
const countBeforeB = await b.evaluate(() => window.commons.voteCount());
// 3. independent votes while partitioned
await a.evaluate((v) => window.commons.vote(v.proposalId, v.voterId, v.choice), partitionVotes.a);
await b.evaluate((v) => window.commons.vote(v.proposalId, v.voterId, v.choice), partitionVotes.b);
// assert non-propagation across the partition window (the genuine-partition proof)
let leaked = false;
for (let i = 0; i < 15; i++) {
const ac = await a.evaluate(() => window.commons.voteCount());
const bc = await b.evaluate(() => window.commons.voteCount());
if (ac > countBeforeA + 1 || bc > countBeforeB + 1) {
leaked = true;
break;
}
await sleep(200);
}
evidence.steps.partition = {
offlineA: await a.evaluate(() => navigator.onLine) === false,
offlineB: await b.evaluate(() => navigator.onLine) === false,
peersA: await a.evaluate(() => window.commons.peerCount()),
peersB: await b.evaluate(() => window.commons.peerCount()),
signalingRouteBlocked: true,
leakedDuringPartition: leaked,
};
if (leaked) throw new Error(`${name}: votes LEAKED during partition - not genuinely partitioned`);
if (evidence.steps.partition.peersA !== 0 || evidence.steps.partition.peersB !== 0) {
throw new Error(`${name}: peers still connected during partition`);
}
// 4. heal + converge
state.blockSig = false;
await ctxA.setOffline(false);
await ctxB.setOffline(false);
await a.evaluate(() => window.commons.setConnected(true));
await b.evaluate(() => window.commons.setConnected(true));
const tally = await assertConverged(a, b, waitFor);
evidence.steps.healed = tally;
evidence.pass = true;
return evidence;
} catch (err) {
evidence.pass = false;
evidence.error = String(err && err.message ? err.message : err);
throw Object.assign(err, { evidence });
} finally {
await ctxA.close();
await ctxB.close();
}
}
async function main() {
const sig = await startSignaling();
const vite = await createViteServer({
root: ROOT,
configFile: resolve(ROOT, "vite.config.ts"),
logLevel: "warn",
server: { host: "127.0.0.1", port: VITE_PORT, strictPort: true },
});
await vite.listen();
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
const results = {};
let failed = false;
try {
// HAPPY: two non-conflicting votes from each side merge to show both.
try {
results.happy = await runScenario(browser, {
name: "happy",
partitionVotes: {
a: { proposalId: "prop", voterId: "bob", choice: "yes" },
b: { proposalId: "prop", voterId: "carol", choice: "no" },
},
assertConverged: async (a, b, wf) => {
await wf(() => a.evaluate(() => window.commons.voteCount() >= 3), "A converges");
await wf(() => b.evaluate(() => window.commons.voteCount() >= 3), "B converges");
const tA = await a.evaluate(() => window.commons.tally("prop"));
const tB = await b.evaluate(() => window.commons.tally("prop"));
if (JSON.stringify(tA) !== JSON.stringify(tB)) {
throw new Error(`happy: tallies differ A=${JSON.stringify(tA)} B=${JSON.stringify(tB)}`);
}
if (tA.total !== 3 || tA.yes !== 2 || tA.no !== 1) {
throw new Error(`happy: expected union tally yes2/no1/total3, got ${JSON.stringify(tA)}`);
}
return { tallyA: tA, tallyB: tB, identical: true };
},
});
} catch (e) {
failed = true;
results.happy = e.evidence ?? { scenario: "happy", pass: false, error: String(e) };
}
// CONFLICT: both sides vote the SAME proposal with the SAME voter
// differently while partitioned -> reconnect yields ONE deterministic
// resolved vote (CRDT same-key resolution), not a crash or data loss.
try {
results.conflict = await runScenario(browser, {
name: "conflict",
partitionVotes: {
a: { proposalId: "prop", voterId: "dave", choice: "yes" },
b: { proposalId: "prop", voterId: "dave", choice: "no" },
},
assertConverged: async (a, b, wf) => {
await wf(() => a.evaluate(() => window.commons.voteCount() >= 2), "A converges");
await wf(() => b.evaluate(() => window.commons.voteCount() >= 2), "B converges");
// let any residual sync settle, then confirm stability + agreement
await sleep(500);
const tA = await a.evaluate(() => window.commons.tally("prop"));
const tB = await b.evaluate(() => window.commons.tally("prop"));
const vcA = await a.evaluate(() => window.commons.voteCount());
const vcB = await b.evaluate(() => window.commons.voteCount());
if (JSON.stringify(tA) !== JSON.stringify(tB)) {
throw new Error(`conflict: non-deterministic resolution A=${JSON.stringify(tA)} B=${JSON.stringify(tB)}`);
}
if (vcA !== vcB || vcA !== 2) {
throw new Error(`conflict: expected exactly 2 surviving votes (warmup+1 resolved dave), got A=${vcA} B=${vcB}`);
}
if (tA.total !== 2 || tA.yes + tA.no + tA.abstain !== 2) {
throw new Error(`conflict: data loss or double-count, tally=${JSON.stringify(tA)}`);
}
const resolvedDave = tA.yes === 2 ? "yes" : "no";
return { tallyA: tA, tallyB: tB, identical: true, surviving_dave_choice: resolvedDave };
},
});
} catch (e) {
failed = true;
results.conflict = e.evidence ?? { scenario: "conflict", pass: false, error: String(e) };
}
} finally {
await browser.close();
await vite.close();
sig.kill("SIGKILL");
}
// Write evidence artifacts
const evDir = resolve(ROOT, ".omo/evidence/the-commons-hollow");
mkdirSync(evDir, { recursive: true });
const now = new Date().toISOString();
const mechanism =
"genuine partition: setOffline(true) on both contexts + signaling WebSocket route blocked + provider.disconnect() tears established RTCDataChannels (peerCount->0); partition proven by asserting votes do NOT propagate across the window";
writeFileSync(
resolve(evDir, "task-23-the-commons-hollow.json"),
JSON.stringify(
{
task: "23. ma-assembly partition-heal demo (problem 7, layer 2)",
qa: "happy",
description: "Two non-conflicting votes (one per side) cast while partitioned; reconnect merges to show both.",
tool: "Playwright (chromium), two isolated browser contexts over real y-webrtc WebRTC + local signaling server",
run_command: "node e2e/assemblyPartition.e2e.mjs",
partition_mechanism: mechanism,
timestamp: now,
result: results.happy,
pass: Boolean(results.happy && results.happy.pass),
},
null,
2,
),
);
writeFileSync(
resolve(evDir, "task-23-the-commons-hollow-conflict.json"),
JSON.stringify(
{
task: "23. ma-assembly partition-heal demo (problem 7, layer 2)",
qa: "failure/conflict",
description:
"Both sides vote the SAME proposal with the SAME voter differently while partitioned; reconnect yields ONE deterministic resolved vote (CRDT same-key resolution), identical on both sides - no crash, no silent data loss.",
tool: "Playwright (chromium), two isolated browser contexts over real y-webrtc WebRTC + local signaling server",
run_command: "node e2e/assemblyPartition.e2e.mjs",
partition_mechanism: mechanism,
timestamp: now,
result: results.conflict,
pass: Boolean(results.conflict && results.conflict.pass),
},
null,
2,
),
);
console.log("\n===== e2e RESULT =====");
console.log(JSON.stringify(results, null, 2));
const happyOk = Boolean(results.happy && results.happy.pass);
const conflictOk = Boolean(results.conflict && results.conflict.pass);
console.log(`\nSUMMARY: happy=${happyOk ? "PASS" : "FAIL"} conflict=${conflictOk ? "PASS" : "FAIL"}`);
if (failed || !happyOk || !conflictOk) {
process.exitCode = 1;
}
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});
+102
View File
@@ -0,0 +1,102 @@
import { describe, expect, it } from "vitest";
import * as Y from "yjs";
import {
castVote,
createAssemblyDoc,
encodeAssemblyState,
type AssemblyDoc,
} from "./assembly.ts";
import {
DEFAULT_SIGNALING_SERVERS,
tallyProposal,
} from "./assemblySync.ts";
function replica(mutate: (a: AssemblyDoc) => void): Uint8Array {
const a = createAssemblyDoc();
mutate(a);
return encodeAssemblyState(a);
}
function mergeInOrder(updates: Uint8Array[]): AssemblyDoc {
const target = createAssemblyDoc();
for (const u of updates) Y.applyUpdate(target.doc, u);
return target;
}
describe("tallyProposal", () => {
it("counts votes per choice and ignores other proposals", () => {
const a = createAssemblyDoc();
castVote(a, { proposalId: "p1", voterId: "alice", choice: "yes", castAt: 1 });
castVote(a, { proposalId: "p1", voterId: "bob", choice: "yes", castAt: 2 });
castVote(a, { proposalId: "p1", voterId: "carol", choice: "no", castAt: 3 });
castVote(a, { proposalId: "p1", voterId: "dave", choice: "abstain", castAt: 4 });
castVote(a, { proposalId: "p2", voterId: "alice", choice: "no", castAt: 5 });
expect(tallyProposal(a, "p1")).toEqual({
proposalId: "p1",
yes: 2,
no: 1,
abstain: 1,
total: 4,
});
expect(tallyProposal(a, "p2")).toEqual({
proposalId: "p2",
yes: 0,
no: 1,
abstain: 0,
total: 1,
});
});
it("is empty for a proposal with no votes", () => {
const a = createAssemblyDoc();
expect(tallyProposal(a, "ghost")).toEqual({
proposalId: "ghost",
yes: 0,
no: 0,
abstain: 0,
total: 0,
});
});
it("merges two non-conflicting partition replicas to the union tally (happy path)", () => {
const left = replica((a) =>
castVote(a, { proposalId: "p1", voterId: "bob", choice: "yes", castAt: 10 }),
);
const right = replica((a) =>
castVote(a, { proposalId: "p1", voterId: "carol", choice: "no", castAt: 11 }),
);
const mergedLR = mergeInOrder([left, right]);
const mergedRL = mergeInOrder([right, left]);
const expected = { proposalId: "p1", yes: 1, no: 1, abstain: 0, total: 2 };
expect(tallyProposal(mergedLR, "p1")).toEqual(expected);
expect(tallyProposal(mergedRL, "p1")).toEqual(expected);
});
it("resolves a same-voter conflict deterministically to one surviving vote (conflict path)", () => {
const left = replica((a) =>
castVote(a, { proposalId: "p1", voterId: "dave", choice: "yes", castAt: 20 }),
);
const right = replica((a) =>
castVote(a, { proposalId: "p1", voterId: "dave", choice: "no", castAt: 21 }),
);
const mergedLR = tallyProposal(mergeInOrder([left, right]), "p1");
const mergedRL = tallyProposal(mergeInOrder([right, left]), "p1");
expect(mergedLR).toEqual(mergedRL);
expect(mergedLR.total).toBe(1);
expect(mergedLR.yes + mergedLR.no).toBe(1);
});
});
describe("DEFAULT_SIGNALING_SERVERS", () => {
it("defaults to a zero-infrastructure public wss signaling server", () => {
expect(DEFAULT_SIGNALING_SERVERS.length).toBeGreaterThan(0);
for (const url of DEFAULT_SIGNALING_SERVERS) {
expect(url.startsWith("wss://")).toBe(true);
}
});
});
+140
View File
@@ -0,0 +1,140 @@
import { WebrtcProvider } from "y-webrtc";
import { listVotes, type AssemblyDoc } from "./assembly.ts";
/**
* ma-assembly peer-to-peer sync (todo 23, problem 7 layer 2).
*
* This module is the one place that wires a real WebRTC transport to the
* local-first `AssemblyDoc` CRDT from `./assembly.ts`. It does nothing to
* the conflict-resolution story - that is entirely `Y.Doc`'s - it only
* carries Yjs update bytes between replicas over `y-webrtc`'s
* `WebrtcProvider` (signaling to discover peers, then direct RTCDataChannel
* traffic). There is still no server-side source of truth: the signaling
* server only brokers the initial handshake and never sees document state.
*
* Transport policy (matches the plan's todo 23):
* - Default signaling is y-webrtc's bundled public server - zero
* infrastructure, works between two real devices on the open internet.
* - For a controlled demo or an automated partition test (or whenever the
* public server is unreachable), callers inject their own signaling URL
* (e.g. a `y-webrtc-signaling` server on localhost). Nothing else about
* the wiring changes.
*
* The provider is a genuine network client: when the browsing context goes
* offline the signaling socket drops and every RTCDataChannel fails its ICE
* connectivity checks, so no update bytes cross the partition - which is
* exactly what the acceptance test proves rather than assumes.
*/
/** y-webrtc's bundled public signaling server (the project default). */
export const DEFAULT_SIGNALING_SERVERS: readonly string[] = [
"wss://y-webrtc-eu.fly.dev",
];
export interface AssemblySyncOptions {
/**
* Signaling server URLs used only to discover peers. Defaults to
* {@link DEFAULT_SIGNALING_SERVERS} (zero-infrastructure public server).
* Inject a local URL for a reliable demo or test.
*/
signaling?: string[];
/** Optional room password - when set, y-webrtc encrypts all traffic. */
password?: string;
/**
* Options forwarded to the underlying simple-peer connections (e.g. an
* `{ config: { iceServers: [] } }` for loopback-only peers that need no
* STUN/TURN).
*/
peerOpts?: Record<string, unknown>;
/** Cap on simultaneous WebRTC peer connections (y-webrtc default: 20). */
maxConns?: number;
}
/** A live sync session bound to one `AssemblyDoc` and one room. */
export interface AssemblySync {
readonly provider: WebrtcProvider;
readonly room: string;
/** Number of WebRTC peers this replica is currently connected to. Drops
* to 0 while partitioned, which is how the test observes the partition. */
connectedPeerCount(): number;
/** True while at least one WebRTC peer connection is established. */
hasPeers(): boolean;
/** Tears the signaling socket and every peer connection down. */
destroy(): void;
}
/**
* Binds a `WebrtcProvider` to an Assembly document's `Y.Doc` and starts
* looking for peers in `room`. The provider syncs the full document both
* ways for as long as it stays connected; callers merge nothing by hand.
*/
export function connectAssemblySync(
assembly: AssemblyDoc,
room: string,
options: AssemblySyncOptions = {},
): AssemblySync {
const provider = new WebrtcProvider(room, assembly.doc, {
signaling: options.signaling ?? [...DEFAULT_SIGNALING_SERVERS],
...(options.password !== undefined ? { password: options.password } : {}),
...(options.maxConns !== undefined ? { maxConns: options.maxConns } : {}),
peerOpts: options.peerOpts ?? {},
});
const connectedPeerCount = (): number => {
const conns = provider.room?.webrtcConns;
if (!conns) return 0;
let n = 0;
for (const conn of conns.values()) {
if (conn.connected) n += 1;
}
return n;
};
return {
provider,
room,
connectedPeerCount,
hasPeers: () => connectedPeerCount() > 0,
destroy: () => provider.destroy(),
};
}
/**
* A per-proposal vote tally. Computed by a pure reduction over the CRDT's
* current votes, so every replica that has converged derives an identical
* tally - this is the value the partition-heal acceptance test compares
* across the two sides.
*/
export interface VoteTally {
proposalId: string;
yes: number;
no: number;
abstain: number;
total: number;
}
/**
* Counts the current votes for `proposalId` by choice. Because the vote map
* is keyed by `(proposalId, voterId)` (see `assembly.ts`), a resident who
* votes twice - even concurrently on two partitioned replicas - contributes
* exactly one vote once the replicas merge, resolved to the CRDT's
* deterministic winner.
*/
export function tallyProposal(
assembly: AssemblyDoc,
proposalId: string,
): VoteTally {
const tally: VoteTally = {
proposalId,
yes: 0,
no: 0,
abstain: 0,
total: 0,
};
for (const vote of listVotes(assembly)) {
if (vote.proposalId !== proposalId) continue;
tally[vote.choice] += 1;
tally.total += 1;
}
return tally;
}