@mmstack/mesh 21.12.0 → 21.14.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
@@ -261,6 +261,21 @@ Presence is an ephemeral side channel. It is never persisted, never conflicts, a
261
261
  automatically when a peer leaves. The payload is yours to shape: cursors, selection, "who is
262
262
  here", or an agent's current activity.
263
263
 
264
+ ## Directed frames
265
+
266
+ ```ts
267
+ mesh.send(origin, { ask: 'list' }); // to one member, by origin
268
+ const stop = mesh.direct(({ from, data }) => reply(from, data));
269
+ ```
270
+
271
+ `send` and `direct` carry ephemeral payloads to one member only: the relay routes each frame to
272
+ `to` and never persists it. A frame for an origin that is not in the room is lost, and so is one
273
+ that arrives with no listener. A frame that arrives before the welcome is held and handed over
274
+ right after it, unless its sender leaves first; at most 256 are held. The library refuses a foreign
275
+ frame version (`v` other than `MESH_DIRECT_VERSION`) before any listener sees it; payload versions
276
+ live inside `data`, and `data` must be defined. An agent seat has the same pair. Peer links never
277
+ see these frames; `signaling` stays WebRTC negotiation only.
278
+
264
279
  ## Trust
265
280
 
266
281
  Pass a `policy` and (when your policy reads claims) a `ctx`, and the client validates each write
@@ -487,7 +502,9 @@ post-migration by construction, and journal replay stays correct forever.
487
502
  SSR-side room.
488
503
 
489
504
  A transport is a small interface (`send`, `onMessage`, `onClose`, `close`), so wiring a custom
490
- one is a few lines.
505
+ one is a few lines. `onClose` reports the close `code` and `reason` (a 1009 means the relay
506
+ closed because a frame was too big), and `meshSync`'s `onDisconnect` option surfaces them
507
+ when a reconnect is scheduled.
491
508
 
492
509
  ## Peer to peer
493
510
 
@@ -1,9 +1,26 @@
1
1
  import { createWatch } from '@angular/core/primitives/signals';
2
2
  import { createConvergingApply, createStoreContext, store, opSync, forkStore, isStoreReservedKey, OP_PROTO_VERSION, registerResource, throttled } from '@mmstack/primitives/core';
3
- import { MESH_PROTO_VERSION, checkEnvelope } from '@mmstack/mesh-protocol';
4
- import { inject, Injector, signal, computed, isDevMode, runInInjectionContext, DestroyRef, untracked, effect } from '@angular/core';
3
+ import { isDevMode, inject, Injector, signal, computed, runInInjectionContext, DestroyRef, untracked, effect } from '@angular/core';
4
+ import { MESH_PROTO_VERSION, MESH_DIRECT_VERSION, checkEnvelope } from '@mmstack/mesh-protocol';
5
5
 
6
+ /**
7
+ * Hands `msg` to every listener; a throwing listener never interrupts the session or the others.
8
+ * @internal
9
+ */
10
+ const deliverDirect = (listeners, msg) => {
11
+ const out = { from: msg.from, v: msg.v, data: msg.data };
12
+ for (const cb of [...listeners]) {
13
+ try {
14
+ cb(out);
15
+ }
16
+ catch {
17
+ // a consumer's failure stays its own
18
+ }
19
+ }
20
+ };
6
21
  const RECONNECT_BASE_MS = 500;
22
+ /** `direct` frames held before a welcome, per connection: the bound peer links keep for signals. */
23
+ const HELD_DIRECTS = 256;
7
24
  function meshSession(opt) {
8
25
  const { sync, hooks } = opt;
9
26
  const schedule = opt.schedule ?? {
@@ -30,6 +47,11 @@ function meshSession(opt) {
30
47
  let reconnectTimer;
31
48
  let unsubs = [];
32
49
  let closed = false;
50
+ // a `direct` frame waits for the welcome of its connection, as peer links hold signals
51
+ let welcomedHere = false;
52
+ let heldDirects = [];
53
+ let versionWarned = false;
54
+ let heldWarned = false;
33
55
  let ackFailure;
34
56
  const ackWaiters = [];
35
57
  const releaseAckWaiters = (failure) => {
@@ -65,6 +87,7 @@ function meshSession(opt) {
65
87
  releaseAckWaiters();
66
88
  }
67
89
  unacked.clear();
90
+ heldDirects = [];
68
91
  transport?.close();
69
92
  transport = null;
70
93
  peers = new Map();
@@ -199,6 +222,14 @@ function meshSession(opt) {
199
222
  room: opt.room,
200
223
  data: presenceData,
201
224
  });
225
+ welcomedHere = true;
226
+ const replay = heldDirects;
227
+ heldDirects = [];
228
+ for (const held of replay) {
229
+ if (closed)
230
+ return;
231
+ hooks.onDirect?.(held);
232
+ }
202
233
  return;
203
234
  }
204
235
  case 'env':
@@ -215,6 +246,9 @@ function meshSession(opt) {
215
246
  return;
216
247
  }
217
248
  case 'member': {
249
+ // a leave discards what that origin sent before the welcome
250
+ if (msg.gone)
251
+ heldDirects = heldDirects.filter((h) => h.from !== msg.origin);
218
252
  if (members === undefined || msg.origin === sync.origin)
219
253
  return;
220
254
  members = msg.gone
@@ -254,6 +288,24 @@ function meshSession(opt) {
254
288
  }
255
289
  }
256
290
  };
291
+ const receiveDirect = (msg) => {
292
+ // a frame version this side does not speak is refused whole: nothing else of it is read
293
+ if (msg.v !== MESH_DIRECT_VERSION) {
294
+ if (isDevMode() && !versionWarned) {
295
+ versionWarned = true;
296
+ console.warn(`[@mmstack/mesh] dropped a direct frame of version ${String(msg.v)}; this side speaks ${MESH_DIRECT_VERSION}`);
297
+ }
298
+ return;
299
+ }
300
+ if (welcomedHere)
301
+ hooks.onDirect?.(msg);
302
+ else if (heldDirects.length < HELD_DIRECTS)
303
+ heldDirects.push(msg);
304
+ else if (isDevMode() && !heldWarned) {
305
+ heldWarned = true;
306
+ console.warn(`[@mmstack/mesh] more than ${HELD_DIRECTS} direct frames arrived before the welcome; the rest are dropped`);
307
+ }
308
+ };
257
309
  const connect = () => {
258
310
  if (closed)
259
311
  return;
@@ -261,21 +313,30 @@ function meshSession(opt) {
261
313
  unsub();
262
314
  const t = opt.transport();
263
315
  transport = t;
316
+ welcomedHere = false;
317
+ heldDirects = [];
264
318
  unsubs = [
265
319
  t.onMessage((msg) => {
266
320
  if (closed || transport !== t || msg.room !== opt.room)
267
321
  return;
322
+ if (msg.t === 'direct') {
323
+ receiveDirect(msg);
324
+ return;
325
+ }
268
326
  handle(msg);
269
327
  if (!closed || msg.t === 'reject' || msg.t === 'eject')
270
328
  hooks.onMessage?.(msg);
271
329
  }),
272
- t.onClose(() => {
330
+ t.onClose((code, reason) => {
273
331
  if (closed || transport !== t)
274
332
  return;
275
333
  transport = null;
334
+ welcomedHere = false;
335
+ heldDirects = [];
276
336
  members = undefined;
277
337
  hooks.onMembers?.(members);
278
338
  setStatus('reconnecting');
339
+ hooks.onDisconnect?.(code, reason);
279
340
  const delay = Math.min(opt.reconnect?.maxDelayMs ?? 15_000, RECONNECT_BASE_MS * 2 ** attempts++);
280
341
  reconnectTimer = schedule.set(() => {
281
342
  reconnectTimer = undefined;
@@ -322,6 +383,17 @@ function meshSession(opt) {
322
383
  if (!closed && msg.room === opt.room)
323
384
  transport?.send(msg);
324
385
  },
386
+ sendDirect: (to, data) => {
387
+ if (closed)
388
+ return;
389
+ transport?.send({
390
+ t: 'direct',
391
+ room: opt.room,
392
+ to,
393
+ v: MESH_DIRECT_VERSION,
394
+ data,
395
+ });
396
+ },
325
397
  setPresence: (data) => {
326
398
  presenceData = data;
327
399
  hasPresence = true;
@@ -376,6 +448,7 @@ function agentSeat(initial, opt) {
376
448
  },
377
449
  });
378
450
  const listeners = new Set();
451
+ const directListeners = new Set();
379
452
  const emit = (event) => {
380
453
  for (const cb of [...listeners])
381
454
  cb(event);
@@ -410,6 +483,7 @@ function agentSeat(initial, opt) {
410
483
  emit({ kind: 'change', ...batch });
411
484
  },
412
485
  onResync: (seq) => emit({ kind: 'resync', seq }),
486
+ onDirect: (msg) => deliverDirect(directListeners, msg),
413
487
  onRefused: (env, reason) => {
414
488
  diverged = true; // the write stays applied until the rehydrate that follows lands
415
489
  opt.onRefused?.(env, reason);
@@ -486,6 +560,11 @@ function agentSeat(initial, opt) {
486
560
  return session.whenAcked();
487
561
  },
488
562
  setPresence: (data) => session.setPresence(data),
563
+ send: (to, data) => session.sendDirect(to, data),
564
+ direct: (cb) => {
565
+ directListeners.add(cb);
566
+ return () => directListeners.delete(cb);
567
+ },
489
568
  sync: {
490
569
  override: (fn) => sync.override(fn),
491
570
  captureFrontier: () => sync.captureFrontier(),
@@ -603,6 +682,7 @@ function meshSync(source, opt) {
603
682
  // the last roster the links on the port were given; a socket drop blanks the session's, not this
604
683
  let roster = [];
605
684
  const signalingListeners = new Set();
685
+ const directListeners = new Set();
606
686
  let earlySignals = [];
607
687
  // the ICE servers of the last welcome, for peer links that attach after it
608
688
  let welcomeIce;
@@ -799,6 +879,7 @@ function meshSync(source, opt) {
799
879
  }
800
880
  },
801
881
  onMessage: signalMessage,
882
+ onDirect: (msg) => deliverDirect(directListeners, msg),
802
883
  onRefused: (env, reason) => {
803
884
  refused.update((n) => n + 1);
804
885
  opt.onRefused?.(env, reason);
@@ -816,6 +897,7 @@ function meshSync(source, opt) {
816
897
  opt.onEject?.(reason);
817
898
  }
818
899
  },
900
+ onDisconnect: (code, reason) => opt.onDisconnect?.(code, reason),
819
901
  onSynced: () => lastSyncedAt.set(Date.now()),
820
902
  onPeers: (map) => peerMap.set(map),
821
903
  onOutboxChange: () => {
@@ -1024,6 +1106,11 @@ function meshSync(source, opt) {
1024
1106
  else
1025
1107
  pendingPresence = { data };
1026
1108
  },
1109
+ send: (to, data) => session?.sendDirect(to, data),
1110
+ direct: (cb) => {
1111
+ directListeners.add(cb);
1112
+ return () => directListeners.delete(cb);
1113
+ },
1027
1114
  fork: (forkOpt) => {
1028
1115
  const f = forkStore(source, forkOpt);
1029
1116
  let frontier = started ? sync.captureFrontier() : { seq: 0 };
@@ -1081,9 +1168,9 @@ function webSocketTransport(url, protocols) {
1081
1168
  for (const cb of [...messageCbs])
1082
1169
  cb(msg);
1083
1170
  };
1084
- ws.onclose = () => {
1171
+ ws.onclose = (event) => {
1085
1172
  for (const cb of [...closeCbs])
1086
- cb();
1173
+ cb(event.code, event.reason);
1087
1174
  };
1088
1175
  return {
1089
1176
  send: (msg) => {
@@ -1127,7 +1214,7 @@ function directTransport(relay, ctx) {
1127
1214
  open = false;
1128
1215
  connection.disconnect();
1129
1216
  for (const cb of [...closeCbs])
1130
- cb();
1217
+ cb(1000, '');
1131
1218
  },
1132
1219
  }, ctx);
1133
1220
  return {
@@ -1149,7 +1236,7 @@ function directTransport(relay, ctx) {
1149
1236
  open = false;
1150
1237
  connection.disconnect();
1151
1238
  for (const cb of [...closeCbs])
1152
- cb();
1239
+ cb(1000, '');
1153
1240
  },
1154
1241
  };
1155
1242
  };