@mmstack/mesh 21.9.0 → 21.10.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/README.md CHANGED
@@ -41,6 +41,33 @@ delta when possible, and re-applies any writes made while offline on top of what
41
41
  moved to in the meantime. A relay restart is detected through a room instance nonce, so a stale
42
42
  sequence number never corrupts state.
43
43
 
44
+ `mesh.origin()` is `null` until the session sends hello, then reflects the origin that hello
45
+ used. It stays stable across socket reconnects and follows the current op engine when a session
46
+ is rebuilt; an outbox restore publishes the new boot's origin, not the origins of replayed writes.
47
+ The last announced origin remains available after close. `mesh.members()` lists other relay
48
+ origins, including peers that have never published presence. It is empty before welcome and
49
+ while disconnected, and updates on welcomes, joins, and departures.
50
+
51
+ Peer links can share the session's connection directly, without wrapping its transport:
52
+
53
+ ```ts
54
+ const origin = mesh.origin();
55
+ if (origin !== null && mesh.status() === 'live') {
56
+ const links = peerLinks({
57
+ room: 'board-42',
58
+ origin,
59
+ signaling: mesh.signaling,
60
+ });
61
+ }
62
+ ```
63
+
64
+ Create links in an injection context (or pass their `injector` option). In a reactive consumer,
65
+ create them once per origin and close the previous links if that origin changes. The signaling
66
+ port follows socket reconnects without sending a second hello. It buffers up to 256 early
67
+ signaling frames for its first listener, clears stale frames on welcome or disconnect, and
68
+ retires peer links only when the session ends: a socket drop leaves them up, and the next welcome
69
+ says who is still there. Closing the links leaves the mesh session open.
70
+
44
71
  ## Conflict resolution
45
72
 
46
73
  By default the latest write to a path wins, decided by a hybrid logical clock so every peer
@@ -124,21 +151,24 @@ meshSync(board, {
124
151
  ```
125
152
 
126
153
  `store` is any `AsyncStore` (`get`, `set`, `del`), the same interface `persist` takes. On boot the
127
- client restores the saved queue, adopts the origin it used before the reload, and resends the
128
- unacknowledged writes when it reconnects. Those offline edits then rebase onto whatever the room
154
+ client restores the saved queue and resends the unacknowledged writes when it reconnects, each under
155
+ the origin it was recorded with. New writes go out under a fresh origin: every boot mints its own. Those offline edits then rebase onto whatever the room
129
156
  moved to while the tab was gone. The queue is saved on a 300ms debounce; set `debounceMs` to change
130
157
  it, or `0` to write on every change.
131
158
 
132
- One origin is driven by one tab at a time. `crossTab` sets what a second tab on the same key does:
159
+ The saved queue is a single-writer slot, and a Web Lock on the key elects its writer. `crossTab` sets
160
+ what a second tab on the same key does:
133
161
 
134
- - `'queue'` (default) takes a Web Lock on the key. The second tab waits, with `status()` reading
135
- `'connecting'`, until the first tab closes, then takes over. Exactly one durable writer holds the
136
- key at a time.
162
+ - `'queue'` (default): the second tab waits, with `status()` reading `'waiting'`, until the first
163
+ tab closes, then takes over.
164
+ - `'ephemeral'`: the second tab is live at once on its own origin. It never reads or writes the saved
165
+ queue, so its unacknowledged writes are lost if it closes before the room acknowledges them. When
166
+ the lock is free, it takes the lock and behaves like `'queue'`.
137
167
  - `'off'` skips the lock. Use it when you coordinate ownership yourself, for example a distinct key
138
168
  per tab, or leader election over `tabSync`.
139
169
 
140
- When the Web Locks API is unavailable, `'queue'` logs a development warning and runs without the
141
- lock.
170
+ When the Web Locks API is unavailable, `'queue'` and `'ephemeral'` log a development warning and run
171
+ without the lock, as the owner of the saved queue.
142
172
 
143
173
  The outbox persists your unacknowledged writes, not a full snapshot. For a meshed store, use it in
144
174
  place of wrapping the store in `persist`. The two race on boot, and the outbox is the one that
@@ -467,3 +497,118 @@ const mesh = webRtcMesh(store, {
467
497
  signaling: webSocketTransport('wss://sync.example.com'), // data flows peer to peer
468
498
  });
469
499
  ```
500
+
501
+ ### Pointers and other frame-rate values
502
+
503
+ `rtcPresence` is for values that change many times a second and only matter while they are
504
+ fresh: pointer positions, viewports. Each peer publishes one value; every other peer sees the
505
+ latest one per sender. Frames go peer to peer over a lossy, unordered data channel, because a
506
+ pointer that waits for a retransmit is already stale. Nothing is persisted and nothing is caught
507
+ up: a peer that connects sees a sender's value when that sender next moves.
508
+
509
+ It rides on `peerLinks`, the link layer `webRtcMesh` is built on: one peer connection per remote,
510
+ set up from the relay's membership and negotiated over its `signal` frames, carrying the labelled
511
+ channels you ask for. Put `presenceChannel` in the links' channels.
512
+
513
+ ```ts
514
+ import {
515
+ peerLinks,
516
+ presenceChannel,
517
+ rtcPresence,
518
+ webSocketTransport,
519
+ } from '@mmstack/mesh';
520
+
521
+ const links = peerLinks({
522
+ room: 'call-7',
523
+ origin: tabId, // one origin is one seat; give every tab its own
524
+ signaling: webSocketTransport('wss://sync.example.com'),
525
+ channels: [presenceChannel],
526
+ });
527
+ const pointers = rtcPresence<{ x: number; y: number }>(links, {
528
+ roster: links.onMembers,
529
+ });
530
+
531
+ pointers.set({ x, y }); // throttled; the first value of a burst goes out at once, the last one lands
532
+ pointers.peers(); // Map of origin to its latest value
533
+ ```
534
+
535
+ A document mesh and pointers can share one peer connection: ask `webRtcMesh` for the extra
536
+ channel and hand its links to the presence.
537
+
538
+ ```ts
539
+ const mesh = webRtcMesh(doc, {
540
+ room: 'call-7',
541
+ writer: userId,
542
+ signaling: webSocketTransport('wss://sync.example.com'),
543
+ channels: [presenceChannel],
544
+ });
545
+ const pointers = rtcPresence<Point>(mesh.links, {
546
+ roster: mesh.links.onMembers,
547
+ });
548
+ ```
549
+
550
+ The mesh picks a random replica origin per instance unless you pass `origin`; either way
551
+ `mesh.origin` is the key other peers see this side under, and the seat rule below applies.
552
+
553
+ A receiver takes its order only from causality it can observe, never from clocks or from
554
+ numbers chosen by different senders. It holds a value only for an origin in the roster, the
555
+ relay's list of who is in the room, and drops that value as soon as the origin leaves: a peer
556
+ link can outlive a dead socket for a while, so the link is not proof that anyone is there.
557
+ Within one link the highest `seq` wins and anything at or below it is dropped: one counter
558
+ stamps every frame sent on that link in send order, so a lower `seq` was sent earlier. The link
559
+ is the epoch: a link that opens or closes starts its origin fresh, and a frame of an old link
560
+ cannot arrive on a new one. The counter belongs to the links and the channel, not to the sender,
561
+ so a sender closed and recreated on the same links carries on where the last one stopped and is
562
+ heard at once. A new tab or device is a new link, which every receiver already treats as fresh.
563
+
564
+ One origin is one seat. When a second connection arrives with the same origin the relay hands it
565
+ the seat and tells the room about a plain join, so the links tell seats apart by instance: every
566
+ link announces a random instance id in its signals and, once it knows the instance across,
567
+ addresses its signals to it. A signal addressed to an instance a side no longer has is dropped as
568
+ a retired link's leftovers. An unaddressed signal from an instance other than the linked one is a
569
+ new seat, and the receiving side rebuilds its end, addressed, which settles it: only unaddressed
570
+ signals cause a rebuild, and a rebuilt end never sends one. Two tabs sharing an origin still take
571
+ the seat from each other every time one reconnects, so give each tab its own origin.
572
+
573
+ To share a connection someone else already holds, such as a `meshSync` session, pass a
574
+ `SignalingPort` (`send`, `onMessage`, and `members()` over that connection) as `signaling`.
575
+ `members()` returns the current relay roster for the room, or `undefined` until welcomed;
576
+ the owner must keep it current even before the links subscribe. This lets links negotiate with
577
+ existing members when attached after the welcome. Pass the connection's origin to the links;
578
+ they never send a hello of their own.
579
+
580
+ For an external presence roster, pass a subscription function as `roster`. It must synchronously
581
+ emit the current origins and every subsequent membership transition, and return an unsubscribe
582
+ function. Do not adapt a signal using an effect: a leave and rejoin can be coalesced into one
583
+ snapshot, losing the evidence that the previous value must be forgotten.
584
+
585
+ ### Reachability
586
+
587
+ The library ships no ICE servers: it contacts no third party unless you tell it to. Without any,
588
+ browsers hide host addresses behind mDNS names, so links only form between peers on the same
589
+ network segment. Give them servers in one of two ways: a static `RTCConfiguration` passed to
590
+ `rtcPeerConnector(config)`, or a list the relay issues in every welcome through its
591
+ `iceServers` option, which replaces the static list for every link built after that welcome.
592
+ TURN credentials are short-lived and belong to the operator, so the option also takes a function
593
+ of the room and the origin, called at each welcome to mint fresh ones. A link rebuilt long after
594
+ its welcome still uses that welcome's credentials, so choose a lifetime longer than a session.
595
+
596
+ ```ts
597
+ const relay = createRelay({
598
+ iceServers: (room, origin) => [
599
+ { urls: 'turn:turn.example.com', ...mintTurn(room, origin) },
600
+ ],
601
+ });
602
+ ```
603
+
604
+ ### Recovery
605
+
606
+ A link that does not open every channel within `openTimeoutMs` (15 s), loses a channel, or is
607
+ reported gone by its connector is dropped and rebuilt, for as long as the relay lists its origin.
608
+ The WebRTC connector first tries one ICE restart when ICE fails, or stays disconnected for
609
+ `disconnectGraceMs` (5 s). Rebuilds wait a jittered backoff that doubles from `retry.minMs` (1 s)
610
+ to `retry.maxMs` (30 s) and never gives up; a welcome or a join rebuilds at once. Either side may
611
+ rebuild: its new instance announces itself, and the other side rebuilds its end to match, as for
612
+ a new seat. Links are built only after the welcome of the connection they signal over, so every
613
+ link carries that welcome's ICE servers. `links.stalled()` lists the members whose link was lost and has not opened again; with
614
+ `peers()` it tells an open link, a first attempt, and one that keeps failing apart.