@dxos/messaging 0.8.4-main.a4bbb77 → 0.8.4-main.ae835ea

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.
@@ -30,24 +30,31 @@ var MessengerMonitor = class {
30
30
  var MESSAGE_TIMEOUT = 1e4;
31
31
 
32
32
  // src/messenger.ts
33
- function _define_property(obj, key, value) {
34
- if (key in obj) {
35
- Object.defineProperty(obj, key, {
36
- value,
37
- enumerable: true,
38
- configurable: true,
39
- writable: true
40
- });
41
- } else {
42
- obj[key] = value;
43
- }
44
- return obj;
45
- }
46
33
  var __dxlog_file = "/__w/dxos/dxos/packages/core/mesh/messaging/src/messenger.ts";
47
34
  var ReliablePayload = schema.getCodecForType("dxos.mesh.messaging.ReliablePayload");
48
35
  var Acknowledgement = schema.getCodecForType("dxos.mesh.messaging.Acknowledgement");
49
36
  var RECEIVED_MESSAGES_GC_INTERVAL = 12e4;
50
37
  var Messenger = class {
38
+ _monitor = new MessengerMonitor();
39
+ _signalManager;
40
+ // { peerId, payloadType } => listeners set
41
+ _listeners = new ComplexMap(({ peerId, payloadType }) => peerId + payloadType);
42
+ // peerId => listeners set
43
+ _defaultListeners = /* @__PURE__ */ new Map();
44
+ _onAckCallbacks = new ComplexMap(PublicKey.hash);
45
+ _receivedMessages = new ComplexSet(PublicKey.hash);
46
+ /**
47
+ * Keys scheduled to be cleared from _receivedMessages on the next iteration.
48
+ */
49
+ _toClear = new ComplexSet(PublicKey.hash);
50
+ _ctx;
51
+ _closed = true;
52
+ _retryDelay;
53
+ constructor({ signalManager, retryDelay = 1e3 }) {
54
+ this._signalManager = signalManager;
55
+ this._retryDelay = retryDelay;
56
+ this.open();
57
+ }
51
58
  open() {
52
59
  if (!this._closed) {
53
60
  return;
@@ -403,21 +410,6 @@ var Messenger = class {
403
410
  });
404
411
  }
405
412
  }
406
- constructor({ signalManager, retryDelay = 1e3 }) {
407
- _define_property(this, "_monitor", new MessengerMonitor());
408
- _define_property(this, "_signalManager", void 0);
409
- _define_property(this, "_listeners", new ComplexMap(({ peerId, payloadType }) => peerId + payloadType));
410
- _define_property(this, "_defaultListeners", /* @__PURE__ */ new Map());
411
- _define_property(this, "_onAckCallbacks", new ComplexMap(PublicKey.hash));
412
- _define_property(this, "_receivedMessages", new ComplexSet(PublicKey.hash));
413
- _define_property(this, "_toClear", new ComplexSet(PublicKey.hash));
414
- _define_property(this, "_ctx", void 0);
415
- _define_property(this, "_closed", true);
416
- _define_property(this, "_retryDelay", void 0);
417
- this._signalManager = signalManager;
418
- this._retryDelay = retryDelay;
419
- this.open();
420
- }
421
413
  };
422
414
 
423
415
  // src/signal-client/signal-client.ts
@@ -431,20 +423,22 @@ import { SignalState } from "@dxos/protocols/proto/dxos/mesh/signal";
431
423
 
432
424
  // src/signal-client/signal-client-monitor.ts
433
425
  import { trace as trace3 } from "@dxos/tracing";
434
- function _define_property2(obj, key, value) {
435
- if (key in obj) {
436
- Object.defineProperty(obj, key, {
437
- value,
438
- enumerable: true,
439
- configurable: true,
440
- writable: true
441
- });
442
- } else {
443
- obj[key] = value;
444
- }
445
- return obj;
446
- }
447
426
  var SignalClientMonitor = class {
427
+ _performance = {
428
+ sentMessages: 0,
429
+ receivedMessages: 0,
430
+ reconnectCounter: 0,
431
+ joinCounter: 0,
432
+ leaveCounter: 0
433
+ };
434
+ /**
435
+ * Timestamp of when the connection attempt was began.
436
+ */
437
+ _connectionStarted = /* @__PURE__ */ new Date();
438
+ /**
439
+ * Timestamp of last state change.
440
+ */
441
+ _lastStateChange = /* @__PURE__ */ new Date();
448
442
  getRecordedTimestamps() {
449
443
  return {
450
444
  connectionStarted: this._connectionStarted,
@@ -514,17 +508,6 @@ var SignalClientMonitor = class {
514
508
  }
515
509
  });
516
510
  }
517
- constructor() {
518
- _define_property2(this, "_performance", {
519
- sentMessages: 0,
520
- receivedMessages: 0,
521
- reconnectCounter: 0,
522
- joinCounter: 0,
523
- leaveCounter: 0
524
- });
525
- _define_property2(this, "_connectionStarted", /* @__PURE__ */ new Date());
526
- _define_property2(this, "_lastStateChange", /* @__PURE__ */ new Date());
527
- }
528
511
  };
529
512
  var getByteCount = (message) => {
530
513
  return message.author.peerKey.length + message.recipient.peerKey.length + message.payload.type_url.length + message.payload.value.length;
@@ -541,21 +524,36 @@ import { cancelWithContext } from "@dxos/context";
541
524
  import { PublicKey as PublicKey2 } from "@dxos/keys";
542
525
  import { log as log2 } from "@dxos/log";
543
526
  import { ComplexMap as ComplexMap2, ComplexSet as ComplexSet2, safeAwaitAll } from "@dxos/util";
544
- function _define_property3(obj, key, value) {
545
- if (key in obj) {
546
- Object.defineProperty(obj, key, {
547
- value,
548
- enumerable: true,
549
- configurable: true,
550
- writable: true
551
- });
552
- } else {
553
- obj[key] = value;
554
- }
555
- return obj;
556
- }
557
527
  var __dxlog_file2 = "/__w/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-local-state.ts";
558
528
  var SignalLocalState = class {
529
+ _onMessage;
530
+ _onSwarmEvent;
531
+ /**
532
+ * Swarm events streams. Keys represent actually joined topic and peerId.
533
+ */
534
+ _swarmStreams = new ComplexMap2(({ topic, peerId }) => topic.toHex() + peerId.toHex());
535
+ /**
536
+ * Represent desired joined topic and peerId.
537
+ */
538
+ _joinedTopics = new ComplexSet2(({ topic, peerId }) => topic.toHex() + peerId.toHex());
539
+ /**
540
+ * Represent desired message subscriptions.
541
+ */
542
+ _subscribedMessages = new ComplexSet2(({ peerId }) => peerId.toHex());
543
+ /**
544
+ * Message streams. Keys represents actually subscribed peers.
545
+ * @internal
546
+ */
547
+ messageStreams = new ComplexMap2((key) => key.toHex());
548
+ /**
549
+ * Event to use in tests to wait till subscription is successfully established.
550
+ * @internal
551
+ */
552
+ reconciled = new Event();
553
+ constructor(_onMessage, _onSwarmEvent) {
554
+ this._onMessage = _onMessage;
555
+ this._onSwarmEvent = _onSwarmEvent;
556
+ }
559
557
  async safeCloseStreams() {
560
558
  const streams = [
561
559
  ...this._swarmStreams.values()
@@ -715,22 +713,6 @@ var SignalLocalState = class {
715
713
  this.messageStreams.set(peerId, messageStream);
716
714
  }
717
715
  }
718
- constructor(_onMessage, _onSwarmEvent) {
719
- _define_property3(this, "_onMessage", void 0);
720
- _define_property3(this, "_onSwarmEvent", void 0);
721
- _define_property3(this, "_swarmStreams", void 0);
722
- _define_property3(this, "_joinedTopics", void 0);
723
- _define_property3(this, "_subscribedMessages", void 0);
724
- _define_property3(this, "messageStreams", void 0);
725
- _define_property3(this, "reconciled", void 0);
726
- this._onMessage = _onMessage;
727
- this._onSwarmEvent = _onSwarmEvent;
728
- this._swarmStreams = new ComplexMap2(({ topic, peerId }) => topic.toHex() + peerId.toHex());
729
- this._joinedTopics = new ComplexSet2(({ topic, peerId }) => topic.toHex() + peerId.toHex());
730
- this._subscribedMessages = new ComplexSet2(({ peerId }) => peerId.toHex());
731
- this.messageStreams = new ComplexMap2((key) => key.toHex());
732
- this.reconciled = new Event();
733
- }
734
716
  };
735
717
 
736
718
  // src/signal-client/signal-rpc-client.ts
@@ -757,22 +739,132 @@ var SignalRpcClientMonitor = class {
757
739
  };
758
740
 
759
741
  // src/signal-client/signal-rpc-client.ts
760
- function _define_property4(obj, key, value) {
761
- if (key in obj) {
762
- Object.defineProperty(obj, key, {
763
- value,
764
- enumerable: true,
765
- configurable: true,
766
- writable: true
767
- });
768
- } else {
769
- obj[key] = value;
770
- }
771
- return obj;
772
- }
773
742
  var __dxlog_file3 = "/__w/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-rpc-client.ts";
774
743
  var SIGNAL_KEEPALIVE_INTERVAL = 1e4;
775
744
  var SignalRPCClient = class {
745
+ _socket;
746
+ _rpc;
747
+ _connectTrigger = new Trigger();
748
+ _keepaliveCtx;
749
+ _closed = false;
750
+ _url;
751
+ _callbacks;
752
+ _closeComplete = new Trigger();
753
+ _monitor = new SignalRpcClientMonitor();
754
+ constructor({ url, callbacks = {} }) {
755
+ const traceId = PublicKey3.random().toHex();
756
+ log3.trace("dxos.mesh.signal-rpc-client.constructor", trace5.begin({
757
+ id: traceId
758
+ }), {
759
+ F: __dxlog_file3,
760
+ L: 66,
761
+ S: this,
762
+ C: (f, a) => f(...a)
763
+ });
764
+ this._url = url;
765
+ this._callbacks = callbacks;
766
+ this._socket = new WebSocket(this._url);
767
+ this._rpc = createProtoRpcPeer({
768
+ requested: {
769
+ Signal: schema2.getService("dxos.mesh.signal.Signal")
770
+ },
771
+ noHandshake: true,
772
+ port: {
773
+ send: (msg) => {
774
+ if (this._closed) {
775
+ return;
776
+ }
777
+ try {
778
+ this._socket.send(msg);
779
+ } catch (err) {
780
+ log3.warn("send error", err, {
781
+ F: __dxlog_file3,
782
+ L: 85,
783
+ S: this,
784
+ C: (f, a) => f(...a)
785
+ });
786
+ }
787
+ },
788
+ subscribe: (cb) => {
789
+ this._socket.onmessage = async (msg) => {
790
+ if (typeof Blob !== "undefined" && msg.data instanceof Blob) {
791
+ cb(Buffer.from(await msg.data.arrayBuffer()));
792
+ } else {
793
+ cb(msg.data);
794
+ }
795
+ };
796
+ }
797
+ },
798
+ encodingOptions: {
799
+ preserveAny: true
800
+ }
801
+ });
802
+ this._socket.onopen = async () => {
803
+ try {
804
+ await this._rpc.open();
805
+ if (this._closed) {
806
+ await this._safeCloseRpc();
807
+ return;
808
+ }
809
+ log3(`RPC open ${this._url}`, void 0, {
810
+ F: __dxlog_file3,
811
+ L: 110,
812
+ S: this,
813
+ C: (f, a) => f(...a)
814
+ });
815
+ this._callbacks.onConnected?.();
816
+ this._connectTrigger.wake();
817
+ this._keepaliveCtx = new Context2(void 0, {
818
+ F: __dxlog_file3,
819
+ L: 113
820
+ });
821
+ scheduleTaskInterval2(this._keepaliveCtx, async () => {
822
+ this._socket?.send("__ping__");
823
+ }, SIGNAL_KEEPALIVE_INTERVAL);
824
+ } catch (err) {
825
+ this._callbacks.onError?.(err);
826
+ this._socket.close();
827
+ this._closed = true;
828
+ }
829
+ };
830
+ this._socket.onclose = async () => {
831
+ log3(`Disconnected ${this._url}`, void 0, {
832
+ F: __dxlog_file3,
833
+ L: 133,
834
+ S: this,
835
+ C: (f, a) => f(...a)
836
+ });
837
+ this._callbacks.onDisconnected?.();
838
+ this._closeComplete.wake();
839
+ await this.close();
840
+ };
841
+ this._socket.onerror = async (event) => {
842
+ if (this._closed) {
843
+ this._socket.close();
844
+ return;
845
+ }
846
+ this._closed = true;
847
+ this._callbacks.onError?.(event.error ?? new Error(event.message));
848
+ await this._safeCloseRpc();
849
+ log3.warn(`Socket ${event.type ?? "unknown"} error`, {
850
+ message: event.message,
851
+ url: this._url
852
+ }, {
853
+ F: __dxlog_file3,
854
+ L: 149,
855
+ S: this,
856
+ C: (f, a) => f(...a)
857
+ });
858
+ };
859
+ log3.trace("dxos.mesh.signal-rpc-client.constructor", trace5.end({
860
+ id: traceId
861
+ }), {
862
+ F: __dxlog_file3,
863
+ L: 152,
864
+ S: this,
865
+ C: (f, a) => f(...a)
866
+ });
867
+ }
776
868
  async close() {
777
869
  if (this._closed) {
778
870
  return;
@@ -890,151 +982,54 @@ var SignalRPCClient = class {
890
982
  });
891
983
  }
892
984
  }
893
- constructor({ url, callbacks = {} }) {
894
- _define_property4(this, "_socket", void 0);
895
- _define_property4(this, "_rpc", void 0);
896
- _define_property4(this, "_connectTrigger", new Trigger());
897
- _define_property4(this, "_keepaliveCtx", void 0);
898
- _define_property4(this, "_closed", false);
899
- _define_property4(this, "_url", void 0);
900
- _define_property4(this, "_callbacks", void 0);
901
- _define_property4(this, "_closeComplete", new Trigger());
902
- _define_property4(this, "_monitor", new SignalRpcClientMonitor());
903
- const traceId = PublicKey3.random().toHex();
904
- log3.trace("dxos.mesh.signal-rpc-client.constructor", trace5.begin({
905
- id: traceId
906
- }), {
907
- F: __dxlog_file3,
908
- L: 66,
909
- S: this,
910
- C: (f, a) => f(...a)
911
- });
912
- this._url = url;
913
- this._callbacks = callbacks;
914
- this._socket = new WebSocket(this._url);
915
- this._rpc = createProtoRpcPeer({
916
- requested: {
917
- Signal: schema2.getService("dxos.mesh.signal.Signal")
918
- },
919
- noHandshake: true,
920
- port: {
921
- send: (msg) => {
922
- if (this._closed) {
923
- return;
924
- }
925
- try {
926
- this._socket.send(msg);
927
- } catch (err) {
928
- log3.warn("send error", err, {
929
- F: __dxlog_file3,
930
- L: 85,
931
- S: this,
932
- C: (f, a) => f(...a)
933
- });
934
- }
935
- },
936
- subscribe: (cb) => {
937
- this._socket.onmessage = async (msg) => {
938
- if (typeof Blob !== "undefined" && msg.data instanceof Blob) {
939
- cb(Buffer.from(await msg.data.arrayBuffer()));
940
- } else {
941
- cb(msg.data);
942
- }
943
- };
944
- }
945
- },
946
- encodingOptions: {
947
- preserveAny: true
948
- }
949
- });
950
- this._socket.onopen = async () => {
951
- try {
952
- await this._rpc.open();
953
- if (this._closed) {
954
- await this._safeCloseRpc();
955
- return;
956
- }
957
- log3(`RPC open ${this._url}`, void 0, {
958
- F: __dxlog_file3,
959
- L: 110,
960
- S: this,
961
- C: (f, a) => f(...a)
962
- });
963
- this._callbacks.onConnected?.();
964
- this._connectTrigger.wake();
965
- this._keepaliveCtx = new Context2(void 0, {
966
- F: __dxlog_file3,
967
- L: 113
968
- });
969
- scheduleTaskInterval2(this._keepaliveCtx, async () => {
970
- this._socket?.send("__ping__");
971
- }, SIGNAL_KEEPALIVE_INTERVAL);
972
- } catch (err) {
973
- this._callbacks.onError?.(err);
974
- this._socket.close();
975
- this._closed = true;
976
- }
977
- };
978
- this._socket.onclose = async () => {
979
- log3(`Disconnected ${this._url}`, void 0, {
980
- F: __dxlog_file3,
981
- L: 133,
982
- S: this,
983
- C: (f, a) => f(...a)
984
- });
985
- this._callbacks.onDisconnected?.();
986
- this._closeComplete.wake();
987
- await this.close();
988
- };
989
- this._socket.onerror = async (event) => {
990
- if (this._closed) {
991
- this._socket.close();
992
- return;
993
- }
994
- this._closed = true;
995
- this._callbacks.onError?.(event.error ?? new Error(event.message));
996
- await this._safeCloseRpc();
997
- log3.warn(`Socket ${event.type ?? "unknown"} error`, {
998
- message: event.message,
999
- url: this._url
1000
- }, {
1001
- F: __dxlog_file3,
1002
- L: 149,
1003
- S: this,
1004
- C: (f, a) => f(...a)
1005
- });
1006
- };
1007
- log3.trace("dxos.mesh.signal-rpc-client.constructor", trace5.end({
1008
- id: traceId
1009
- }), {
1010
- F: __dxlog_file3,
1011
- L: 152,
1012
- S: this,
1013
- C: (f, a) => f(...a)
1014
- });
1015
- }
1016
985
  };
1017
986
 
1018
987
  // src/signal-client/signal-client.ts
1019
- function _define_property5(obj, key, value) {
1020
- if (key in obj) {
1021
- Object.defineProperty(obj, key, {
1022
- value,
1023
- enumerable: true,
1024
- configurable: true,
1025
- writable: true
1026
- });
1027
- } else {
1028
- obj[key] = value;
1029
- }
1030
- return obj;
1031
- }
1032
988
  var __dxlog_file4 = "/__w/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-client.ts";
1033
989
  var DEFAULT_RECONNECT_TIMEOUT = 100;
1034
990
  var MAX_RECONNECT_TIMEOUT = 5e3;
1035
991
  var ERROR_RECONCILE_DELAY = 1e3;
1036
992
  var RECONCILE_INTERVAL = 5e3;
1037
993
  var SignalClient = class extends Resource {
994
+ _host;
995
+ _getMetadata;
996
+ _monitor = new SignalClientMonitor();
997
+ _state = SignalState.CLOSED;
998
+ _lastError;
999
+ _lastReconciliationFailed = false;
1000
+ _clientReady = new Trigger2();
1001
+ _connectionCtx;
1002
+ _client;
1003
+ _reconcileTask;
1004
+ _reconnectTask;
1005
+ /**
1006
+ * Number of milliseconds after which the connection will be attempted again in case of error.
1007
+ */
1008
+ _reconnectAfter = DEFAULT_RECONNECT_TIMEOUT;
1009
+ _instanceId = PublicKey4.random().toHex();
1010
+ /**
1011
+ * @internal
1012
+ */
1013
+ localState;
1014
+ statusChanged = new Event2();
1015
+ onMessage = new Event2();
1016
+ swarmEvent = new Event2();
1017
+ /**
1018
+ * @param _host Signal server websocket URL.
1019
+ * @param onMessage called when a new message is received.
1020
+ * @param onSwarmEvent called when a new swarm event is received.
1021
+ * @param _getMetadata signal-message metadata provider, called for every message.
1022
+ */
1023
+ constructor(_host, _getMetadata) {
1024
+ super(), this._host = _host, this._getMetadata = _getMetadata;
1025
+ if (!this._host.startsWith("wss://") && !this._host.startsWith("ws://")) {
1026
+ throw new Error(`Signal server requires a websocket URL. Provided: ${this._host}`);
1027
+ }
1028
+ this.localState = new SignalLocalState(async (message) => {
1029
+ this._monitor.recordMessageReceived(message);
1030
+ this.onMessage.emit(message);
1031
+ }, async (event) => this.swarmEvent.emit(event));
1032
+ }
1038
1033
  async _open() {
1039
1034
  log4.trace("dxos.mesh.signal-client.open", trace6.begin({
1040
1035
  id: this._instanceId
@@ -1432,28 +1427,6 @@ var SignalClient = class extends Resource {
1432
1427
  });
1433
1428
  this._client = void 0;
1434
1429
  }
1435
- /**
1436
- * @param _host Signal server websocket URL.
1437
- * @param onMessage called when a new message is received.
1438
- * @param onSwarmEvent called when a new swarm event is received.
1439
- * @param _getMetadata signal-message metadata provider, called for every message.
1440
- */
1441
- constructor(_host, _getMetadata) {
1442
- super(), _define_property5(this, "_host", void 0), _define_property5(this, "_getMetadata", void 0), _define_property5(this, "_monitor", void 0), _define_property5(this, "_state", void 0), _define_property5(this, "_lastError", void 0), _define_property5(this, "_lastReconciliationFailed", void 0), _define_property5(this, "_clientReady", void 0), _define_property5(this, "_connectionCtx", void 0), _define_property5(this, "_client", void 0), _define_property5(this, "_reconcileTask", void 0), _define_property5(this, "_reconnectTask", void 0), /**
1443
- * Number of milliseconds after which the connection will be attempted again in case of error.
1444
- */
1445
- _define_property5(this, "_reconnectAfter", void 0), _define_property5(this, "_instanceId", void 0), /**
1446
- * @internal
1447
- */
1448
- _define_property5(this, "localState", void 0), _define_property5(this, "statusChanged", void 0), _define_property5(this, "onMessage", void 0), _define_property5(this, "swarmEvent", void 0), this._host = _host, this._getMetadata = _getMetadata, this._monitor = new SignalClientMonitor(), this._state = SignalState.CLOSED, this._lastReconciliationFailed = false, this._clientReady = new Trigger2(), this._reconnectAfter = DEFAULT_RECONNECT_TIMEOUT, this._instanceId = PublicKey4.random().toHex(), this.statusChanged = new Event2(), this.onMessage = new Event2(), this.swarmEvent = new Event2();
1449
- if (!this._host.startsWith("wss://") && !this._host.startsWith("ws://")) {
1450
- throw new Error(`Signal server requires a websocket URL. Provided: ${this._host}`);
1451
- }
1452
- this.localState = new SignalLocalState(async (message) => {
1453
- this._monitor.recordMessageReceived(message);
1454
- this.onMessage.emit(message);
1455
- }, async (event) => this.swarmEvent.emit(event));
1456
- }
1457
1430
  };
1458
1431
 
1459
1432
  // src/signal-methods.ts
@@ -1467,28 +1440,33 @@ import { PublicKey as PublicKey5 } from "@dxos/keys";
1467
1440
  import { log as log5 } from "@dxos/log";
1468
1441
  import { schema as schema3 } from "@dxos/protocols/proto";
1469
1442
  import { ComplexMap as ComplexMap3, ComplexSet as ComplexSet3 } from "@dxos/util";
1470
- function _define_property6(obj, key, value) {
1471
- if (key in obj) {
1472
- Object.defineProperty(obj, key, {
1473
- value,
1474
- enumerable: true,
1475
- configurable: true,
1476
- writable: true
1477
- });
1478
- } else {
1479
- obj[key] = value;
1480
- }
1481
- return obj;
1482
- }
1483
1443
  var __dxlog_file5 = "/__w/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/memory-signal-manager.ts";
1484
1444
  var MemorySignalManagerContext = class {
1485
- constructor() {
1486
- _define_property6(this, "swarmEvent", new Event3());
1487
- _define_property6(this, "swarms", new ComplexMap3(PublicKey5.hash));
1488
- _define_property6(this, "connections", new ComplexMap3(PeerInfoHash));
1489
- }
1445
+ // Swarm messages.
1446
+ swarmEvent = new Event3();
1447
+ // Mapping from topic to set of peers.
1448
+ swarms = new ComplexMap3(PublicKey5.hash);
1449
+ // Map of connections for each peer for signaling.
1450
+ connections = new ComplexMap3(PeerInfoHash);
1490
1451
  };
1491
1452
  var MemorySignalManager = class {
1453
+ _context;
1454
+ statusChanged = new Event3();
1455
+ swarmEvent = new Event3();
1456
+ onMessage = new Event3();
1457
+ /** Will be used to emit SwarmEvents on .open() and .close() */
1458
+ _joinedSwarms = new ComplexSet3(({ topic, peer }) => topic.toHex() + peer.peerKey);
1459
+ _ctx;
1460
+ // TODO(dmaretskyi): Replace with callback.
1461
+ _freezeTrigger = new Trigger3().wake();
1462
+ constructor(_context) {
1463
+ this._context = _context;
1464
+ this._ctx = new Context3(void 0, {
1465
+ F: __dxlog_file5,
1466
+ L: 54
1467
+ });
1468
+ this._ctx.onDispose(this._context.swarmEvent.on((data) => this.swarmEvent.emit(data)));
1469
+ }
1492
1470
  async open() {
1493
1471
  if (!this._ctx.disposed) {
1494
1472
  return;
@@ -1706,26 +1684,6 @@ var MemorySignalManager = class {
1706
1684
  unfreeze() {
1707
1685
  this._freezeTrigger.wake();
1708
1686
  }
1709
- constructor(_context) {
1710
- _define_property6(this, "_context", void 0);
1711
- _define_property6(this, "statusChanged", void 0);
1712
- _define_property6(this, "swarmEvent", void 0);
1713
- _define_property6(this, "onMessage", void 0);
1714
- _define_property6(this, "_joinedSwarms", void 0);
1715
- _define_property6(this, "_ctx", void 0);
1716
- _define_property6(this, "_freezeTrigger", void 0);
1717
- this._context = _context;
1718
- this.statusChanged = new Event3();
1719
- this.swarmEvent = new Event3();
1720
- this.onMessage = new Event3();
1721
- this._joinedSwarms = new ComplexSet3(({ topic, peer }) => topic.toHex() + peer.peerKey);
1722
- this._freezeTrigger = new Trigger3().wake();
1723
- this._ctx = new Context3(void 0, {
1724
- F: __dxlog_file5,
1725
- L: 54
1726
- });
1727
- this._ctx.onDispose(this._context.swarmEvent.on((data) => this.swarmEvent.emit(data)));
1728
- }
1729
1687
  };
1730
1688
  var dec = (payload) => {
1731
1689
  if (!payload.type_url.endsWith("ReliablePayload")) {
@@ -1767,19 +1725,6 @@ var WebsocketSignalManagerMonitor = class {
1767
1725
  };
1768
1726
 
1769
1727
  // src/signal-manager/websocket-signal-manager.ts
1770
- function _define_property7(obj, key, value) {
1771
- if (key in obj) {
1772
- Object.defineProperty(obj, key, {
1773
- value,
1774
- enumerable: true,
1775
- configurable: true,
1776
- writable: true
1777
- });
1778
- } else {
1779
- obj[key] = value;
1780
- }
1781
- return obj;
1782
- }
1783
1728
  function _ts_decorate(decorators, target, key, desc) {
1784
1729
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1785
1730
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -1790,6 +1735,42 @@ var __dxlog_file6 = "/__w/dxos/dxos/packages/core/mesh/messaging/src/signal-mana
1790
1735
  var MAX_SERVER_FAILURES = 5;
1791
1736
  var WSS_SIGNAL_SERVER_REBOOT_DELAY = 3e3;
1792
1737
  var WebsocketSignalManager = class extends Resource2 {
1738
+ _hosts;
1739
+ _getMetadata;
1740
+ _servers = /* @__PURE__ */ new Map();
1741
+ _monitor = new WebsocketSignalManagerMonitor();
1742
+ /**
1743
+ * Used to avoid logging failed server restarts more than once until the server actually recovers.
1744
+ */
1745
+ _failedServersBitfield;
1746
+ failureCount = /* @__PURE__ */ new Map();
1747
+ statusChanged = new Event4();
1748
+ swarmEvent = new Event4();
1749
+ onMessage = new Event4();
1750
+ _instanceId = PublicKey6.random().toHex();
1751
+ constructor(_hosts, _getMetadata) {
1752
+ super(), this._hosts = _hosts, this._getMetadata = _getMetadata;
1753
+ log6("Created WebsocketSignalManager", {
1754
+ hosts: this._hosts
1755
+ }, {
1756
+ F: __dxlog_file6,
1757
+ L: 59,
1758
+ S: this,
1759
+ C: (f, a) => f(...a)
1760
+ });
1761
+ for (const host of this._hosts) {
1762
+ if (this._servers.has(host.server)) {
1763
+ continue;
1764
+ }
1765
+ const server = new SignalClient(host.server, this._getMetadata);
1766
+ server.swarmEvent.on((data) => this.swarmEvent.emit(data));
1767
+ server.onMessage.on((data) => this.onMessage.emit(data));
1768
+ server.statusChanged.on(() => this.statusChanged.emit(this.getStatus()));
1769
+ this._servers.set(host.server, server);
1770
+ this.failureCount.set(host.server, 0);
1771
+ }
1772
+ this._failedServersBitfield = BitField.zeros(this._hosts.length);
1773
+ }
1793
1774
  async _open() {
1794
1775
  log6("open signal manager", {
1795
1776
  hosts: this._hosts
@@ -2047,32 +2028,6 @@ var WebsocketSignalManager = class extends Resource2 {
2047
2028
  async _forEachServer(fn) {
2048
2029
  return Promise.all(Array.from(this._servers.entries()).map(([serverName, server], idx) => fn(server, serverName, idx)));
2049
2030
  }
2050
- constructor(_hosts, _getMetadata) {
2051
- super(), _define_property7(this, "_hosts", void 0), _define_property7(this, "_getMetadata", void 0), _define_property7(this, "_servers", void 0), _define_property7(this, "_monitor", void 0), /**
2052
- * Used to avoid logging failed server restarts more than once until the server actually recovers.
2053
- */
2054
- _define_property7(this, "_failedServersBitfield", void 0), _define_property7(this, "failureCount", void 0), _define_property7(this, "statusChanged", void 0), _define_property7(this, "swarmEvent", void 0), _define_property7(this, "onMessage", void 0), _define_property7(this, "_instanceId", void 0), this._hosts = _hosts, this._getMetadata = _getMetadata, this._servers = /* @__PURE__ */ new Map(), this._monitor = new WebsocketSignalManagerMonitor(), this.failureCount = /* @__PURE__ */ new Map(), this.statusChanged = new Event4(), this.swarmEvent = new Event4(), this.onMessage = new Event4(), this._instanceId = PublicKey6.random().toHex();
2055
- log6("Created WebsocketSignalManager", {
2056
- hosts: this._hosts
2057
- }, {
2058
- F: __dxlog_file6,
2059
- L: 59,
2060
- S: this,
2061
- C: (f, a) => f(...a)
2062
- });
2063
- for (const host of this._hosts) {
2064
- if (this._servers.has(host.server)) {
2065
- continue;
2066
- }
2067
- const server = new SignalClient(host.server, this._getMetadata);
2068
- server.swarmEvent.on((data) => this.swarmEvent.emit(data));
2069
- server.onMessage.on((data) => this.onMessage.emit(data));
2070
- server.statusChanged.on(() => this.statusChanged.emit(this.getStatus()));
2071
- this._servers.set(host.server, server);
2072
- this.failureCount.set(host.server, 0);
2073
- }
2074
- this._failedServersBitfield = BitField.zeros(this._hosts.length);
2075
- }
2076
2031
  };
2077
2032
  _ts_decorate([
2078
2033
  synchronized
@@ -2087,7 +2042,7 @@ _ts_decorate([
2087
2042
  // src/signal-manager/edge-signal-manager.ts
2088
2043
  import { Event as Event5, scheduleMicroTask } from "@dxos/async";
2089
2044
  import { Resource as Resource3, cancelWithContext as cancelWithContext3 } from "@dxos/context";
2090
- import { protocol } from "@dxos/edge-client";
2045
+ import { EdgeIdentityChangedError, protocol } from "@dxos/edge-client";
2091
2046
  import { invariant as invariant6 } from "@dxos/invariant";
2092
2047
  import { PublicKey as PublicKey7 } from "@dxos/keys";
2093
2048
  import { log as log7 } from "@dxos/log";
@@ -2095,21 +2050,24 @@ import { EdgeService } from "@dxos/protocols";
2095
2050
  import { bufWkt } from "@dxos/protocols/buf";
2096
2051
  import { SwarmRequest_Action as SwarmRequestAction, SwarmRequestSchema, SwarmResponseSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
2097
2052
  import { ComplexMap as ComplexMap4, ComplexSet as ComplexSet4 } from "@dxos/util";
2098
- function _define_property8(obj, key, value) {
2099
- if (key in obj) {
2100
- Object.defineProperty(obj, key, {
2101
- value,
2102
- enumerable: true,
2103
- configurable: true,
2104
- writable: true
2105
- });
2106
- } else {
2107
- obj[key] = value;
2108
- }
2109
- return obj;
2110
- }
2111
2053
  var __dxlog_file7 = "/__w/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/edge-signal-manager.ts";
2112
2054
  var EdgeSignalManager = class extends Resource3 {
2055
+ /**
2056
+ * @deprecated
2057
+ */
2058
+ swarmEvent = new Event5();
2059
+ swarmState = new Event5();
2060
+ onMessage = new Event5();
2061
+ /**
2062
+ * Swarm key -> { peer: <own state payload>, joinedPeers: <state of swarm> }.
2063
+ */
2064
+ // TODO(mykola): This class should not contain swarm state joinedPeers. Temporary before network-manager API changes to accept list of peers.
2065
+ _swarmPeers = new ComplexMap4(PublicKey7.hash);
2066
+ _edgeConnection;
2067
+ constructor({ edgeConnection }) {
2068
+ super();
2069
+ this._edgeConnection = edgeConnection;
2070
+ }
2113
2071
  async _open() {
2114
2072
  this._ctx.onDispose(this._edgeConnection.onMessage((message) => this._onMessage(message)));
2115
2073
  this._ctx.onDispose(this._edgeConnection.onReconnected(() => {
@@ -2153,16 +2111,23 @@ var EdgeSignalManager = class extends Resource3 {
2153
2111
  }
2154
2112
  async leave({ topic, peer }) {
2155
2113
  this._swarmPeers.delete(topic);
2156
- await this._edgeConnection.send(protocol.createMessage(SwarmRequestSchema, {
2157
- serviceId: EdgeService.SWARM,
2158
- source: createMessageSource(topic, peer),
2159
- payload: {
2160
- action: SwarmRequestAction.LEAVE,
2161
- swarmKeys: [
2162
- topic.toHex()
2163
- ]
2114
+ try {
2115
+ await this._edgeConnection.send(protocol.createMessage(SwarmRequestSchema, {
2116
+ serviceId: EdgeService.SWARM,
2117
+ source: createMessageSource(topic, peer),
2118
+ payload: {
2119
+ action: SwarmRequestAction.LEAVE,
2120
+ swarmKeys: [
2121
+ topic.toHex()
2122
+ ]
2123
+ }
2124
+ }));
2125
+ } catch (err) {
2126
+ if (err instanceof EdgeIdentityChangedError) {
2127
+ return;
2164
2128
  }
2165
- }));
2129
+ throw err;
2130
+ }
2166
2131
  }
2167
2132
  async query({ topic }) {
2168
2133
  const response = cancelWithContext3(this._ctx, this.swarmState.waitFor((state) => state.swarmKey === topic.toHex()));
@@ -2191,7 +2156,7 @@ var EdgeSignalManager = class extends Resource3 {
2191
2156
  }
2192
2157
  }, {
2193
2158
  F: __dxlog_file7,
2194
- L: 122,
2159
+ L: 131,
2195
2160
  S: this,
2196
2161
  C: (f, a) => f(...a)
2197
2162
  });
@@ -2226,7 +2191,7 @@ var EdgeSignalManager = class extends Resource3 {
2226
2191
  _processSwarmResponse(message) {
2227
2192
  invariant6(protocol.getPayloadType(message) === SwarmResponseSchema.typeName, "Wrong payload type", {
2228
2193
  F: __dxlog_file7,
2229
- L: 159,
2194
+ L: 168,
2230
2195
  S: this,
2231
2196
  A: [
2232
2197
  "protocol.getPayloadType(message) === SwarmResponseSchema.typeName",
@@ -2270,7 +2235,7 @@ var EdgeSignalManager = class extends Resource3 {
2270
2235
  _processMessage(message) {
2271
2236
  invariant6(protocol.getPayloadType(message) === bufWkt.AnySchema.typeName, "Wrong payload type", {
2272
2237
  F: __dxlog_file7,
2273
- L: 197,
2238
+ L: 206,
2274
2239
  S: this,
2275
2240
  A: [
2276
2241
  "protocol.getPayloadType(message) === bufWkt.AnySchema.typeName",
@@ -2280,7 +2245,7 @@ var EdgeSignalManager = class extends Resource3 {
2280
2245
  const payload = protocol.getPayload(message, bufWkt.AnySchema);
2281
2246
  invariant6(message.source, "source is missing", {
2282
2247
  F: __dxlog_file7,
2283
- L: 199,
2248
+ L: 208,
2284
2249
  S: this,
2285
2250
  A: [
2286
2251
  "message.source",
@@ -2289,7 +2254,7 @@ var EdgeSignalManager = class extends Resource3 {
2289
2254
  });
2290
2255
  invariant6(message.target, "target is missing", {
2291
2256
  F: __dxlog_file7,
2292
- L: 200,
2257
+ L: 209,
2293
2258
  S: this,
2294
2259
  A: [
2295
2260
  "message.target",
@@ -2298,7 +2263,7 @@ var EdgeSignalManager = class extends Resource3 {
2298
2263
  });
2299
2264
  invariant6(message.target.length === 1, "target should have exactly one item", {
2300
2265
  F: __dxlog_file7,
2301
- L: 201,
2266
+ L: 210,
2302
2267
  S: this,
2303
2268
  A: [
2304
2269
  "message.target.length === 1",
@@ -2322,7 +2287,7 @@ var EdgeSignalManager = class extends Resource3 {
2322
2287
  swarms: Array.from(this._swarmPeers.keys())
2323
2288
  }, {
2324
2289
  F: __dxlog_file7,
2325
- L: 220,
2290
+ L: 229,
2326
2291
  S: this,
2327
2292
  C: (f, a) => f(...a)
2328
2293
  });
@@ -2337,17 +2302,6 @@ var EdgeSignalManager = class extends Resource3 {
2337
2302
  });
2338
2303
  }
2339
2304
  }
2340
- constructor({ edgeConnection }) {
2341
- super(), /**
2342
- * @deprecated
2343
- */
2344
- _define_property8(this, "swarmEvent", new Event5()), _define_property8(this, "swarmState", new Event5()), _define_property8(this, "onMessage", new Event5()), /**
2345
- * Swarm key -> { peer: <own state payload>, joinedPeers: <state of swarm> }.
2346
- */
2347
- // TODO(mykola): This class should not contain swarm state joinedPeers. Temporary before network-manager API changes to accept list of peers.
2348
- _define_property8(this, "_swarmPeers", new ComplexMap4(PublicKey7.hash)), _define_property8(this, "_edgeConnection", void 0);
2349
- this._edgeConnection = edgeConnection;
2350
- }
2351
2305
  };
2352
2306
  var createMessageSource = (topic, peerInfo) => {
2353
2307
  return {
@@ -2423,4 +2377,4 @@ export {
2423
2377
  EdgeSignalManager,
2424
2378
  setIdentityTags
2425
2379
  };
2426
- //# sourceMappingURL=chunk-46VUJLOF.mjs.map
2380
+ //# sourceMappingURL=chunk-L7NDSF6K.mjs.map