@dxos/messaging 0.6.13 → 0.6.14-main.1366248

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.
Files changed (58) hide show
  1. package/dist/lib/browser/chunk-U5OG65N2.mjs +2301 -0
  2. package/dist/lib/browser/chunk-U5OG65N2.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +9 -2286
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +146 -0
  7. package/dist/lib/browser/testing/index.mjs.map +7 -0
  8. package/dist/lib/node/chunk-ZWQVINAC.cjs +2286 -0
  9. package/dist/lib/node/chunk-ZWQVINAC.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +9 -2242
  11. package/dist/lib/node/index.cjs.map +4 -4
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/testing/index.cjs +162 -0
  14. package/dist/lib/node/testing/index.cjs.map +7 -0
  15. package/dist/lib/node-esm/chunk-NCL2P63O.mjs +2301 -0
  16. package/dist/lib/node-esm/chunk-NCL2P63O.mjs.map +7 -0
  17. package/dist/lib/node-esm/index.mjs +22 -0
  18. package/dist/lib/node-esm/index.mjs.map +7 -0
  19. package/dist/lib/node-esm/meta.json +1 -0
  20. package/dist/lib/node-esm/testing/index.mjs +146 -0
  21. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  22. package/dist/types/src/messenger.blueprint-test.d.ts +2 -3
  23. package/dist/types/src/messenger.blueprint-test.d.ts.map +1 -1
  24. package/dist/types/src/messenger.d.ts.map +1 -1
  25. package/dist/types/src/messenger.node.test.d.ts +2 -0
  26. package/dist/types/src/messenger.node.test.d.ts.map +1 -0
  27. package/dist/types/src/signal-client/signal-client.node.test.d.ts +2 -0
  28. package/dist/types/src/signal-client/signal-client.node.test.d.ts.map +1 -0
  29. package/dist/types/src/signal-client/signal-rpc-client.node.test.d.ts +2 -0
  30. package/dist/types/src/signal-client/signal-rpc-client.node.test.d.ts.map +1 -0
  31. package/dist/types/src/signal-manager/edge-signal-manager.d.ts.map +1 -1
  32. package/dist/types/src/signal-manager/websocket-signal-manager.node.test.d.ts +2 -0
  33. package/dist/types/src/signal-manager/websocket-signal-manager.node.test.d.ts.map +1 -0
  34. package/dist/types/src/testing/test-builder.d.ts +3 -4
  35. package/dist/types/src/testing/test-builder.d.ts.map +1 -1
  36. package/dist/types/src/testing/test-peer.d.ts +0 -1
  37. package/dist/types/src/testing/test-peer.d.ts.map +1 -1
  38. package/package.json +29 -24
  39. package/src/messenger.blueprint-test.ts +25 -33
  40. package/src/{messenger.test.ts → messenger.node.test.ts} +6 -19
  41. package/src/messenger.ts +1 -1
  42. package/src/signal-client/{signal-client.test.ts → signal-client.node.test.ts} +9 -8
  43. package/src/signal-client/{signal-rpc-client.test.ts → signal-rpc-client.node.test.ts} +8 -13
  44. package/src/signal-manager/edge-signal-manager.ts +23 -10
  45. package/src/signal-manager/{websocket-signal-manager.test.ts → websocket-signal-manager.node.test.ts} +12 -30
  46. package/src/testing/test-builder.ts +3 -6
  47. package/src/testing/test-peer.ts +5 -7
  48. package/dist/types/src/messenger.test.d.ts +0 -2
  49. package/dist/types/src/messenger.test.d.ts.map +0 -1
  50. package/dist/types/src/signal-client/signal-client.test.d.ts +0 -2
  51. package/dist/types/src/signal-client/signal-client.test.d.ts.map +0 -1
  52. package/dist/types/src/signal-client/signal-rpc-client.test.d.ts +0 -2
  53. package/dist/types/src/signal-client/signal-rpc-client.test.d.ts.map +0 -1
  54. package/dist/types/src/signal-manager/edge-signal-manager.test.d.ts +0 -2
  55. package/dist/types/src/signal-manager/edge-signal-manager.test.d.ts.map +0 -1
  56. package/dist/types/src/signal-manager/websocket-signal-manager.test.d.ts +0 -2
  57. package/dist/types/src/signal-manager/websocket-signal-manager.test.d.ts.map +0 -1
  58. package/src/signal-manager/edge-signal-manager.test.ts +0 -67
@@ -0,0 +1,2301 @@
1
+ import "@dxos/node-std/globals";
2
+
3
+ // packages/core/mesh/messaging/src/messenger.ts
4
+ import { TimeoutError, scheduleExponentialBackoffTaskInterval, scheduleTask, scheduleTaskInterval } from "@dxos/async";
5
+ import { Context } from "@dxos/context";
6
+ import { invariant } from "@dxos/invariant";
7
+ import { PublicKey } from "@dxos/keys";
8
+ import { log } from "@dxos/log";
9
+ import { TimeoutError as ProtocolTimeoutError, trace as trace2 } from "@dxos/protocols";
10
+ import { schema } from "@dxos/protocols/proto";
11
+ import { ComplexMap, ComplexSet } from "@dxos/util";
12
+
13
+ // packages/core/mesh/messaging/src/messenger-monitor.ts
14
+ import { trace } from "@dxos/tracing";
15
+ var MessengerMonitor = class {
16
+ recordMessageAckFailed() {
17
+ trace.metrics.increment("dxos.mesh.signal.messenger.failed-ack", 1);
18
+ }
19
+ recordReliableMessage(params) {
20
+ trace.metrics.increment("dxos.mesh.signal.messenger.reliable-send", 1, {
21
+ tags: {
22
+ success: params.sent,
23
+ attempts: params.sendAttempts
24
+ }
25
+ });
26
+ }
27
+ };
28
+
29
+ // packages/core/mesh/messaging/src/timeouts.ts
30
+ var MESSAGE_TIMEOUT = 1e4;
31
+
32
+ // packages/core/mesh/messaging/src/messenger.ts
33
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/messenger.ts";
34
+ var ReliablePayload = schema.getCodecForType("dxos.mesh.messaging.ReliablePayload");
35
+ var Acknowledgement = schema.getCodecForType("dxos.mesh.messaging.Acknowledgement");
36
+ var RECEIVED_MESSAGES_GC_INTERVAL = 12e4;
37
+ var Messenger = class {
38
+ constructor({ signalManager, retryDelay = 1e3 }) {
39
+ this._monitor = new MessengerMonitor();
40
+ // { peerId, payloadType } => listeners set
41
+ this._listeners = new ComplexMap(({ peerId, payloadType }) => peerId + payloadType);
42
+ // peerId => listeners set
43
+ this._defaultListeners = /* @__PURE__ */ new Map();
44
+ this._onAckCallbacks = new ComplexMap(PublicKey.hash);
45
+ this._receivedMessages = new ComplexSet(PublicKey.hash);
46
+ /**
47
+ * Keys scheduled to be cleared from _receivedMessages on the next iteration.
48
+ */
49
+ this._toClear = new ComplexSet(PublicKey.hash);
50
+ this._closed = true;
51
+ this._signalManager = signalManager;
52
+ this._retryDelay = retryDelay;
53
+ this.open();
54
+ }
55
+ open() {
56
+ if (!this._closed) {
57
+ return;
58
+ }
59
+ const traceId = PublicKey.random().toHex();
60
+ log.trace("dxos.mesh.messenger.open", trace2.begin({
61
+ id: traceId
62
+ }), {
63
+ F: __dxlog_file,
64
+ L: 72,
65
+ S: this,
66
+ C: (f, a) => f(...a)
67
+ });
68
+ this._ctx = new Context({
69
+ onError: (err) => log.catch(err, void 0, {
70
+ F: __dxlog_file,
71
+ L: 74,
72
+ S: this,
73
+ C: (f, a) => f(...a)
74
+ })
75
+ }, {
76
+ F: __dxlog_file,
77
+ L: 73
78
+ });
79
+ this._ctx.onDispose(this._signalManager.onMessage.on(async (message) => {
80
+ log("received message", {
81
+ from: message.author
82
+ }, {
83
+ F: __dxlog_file,
84
+ L: 78,
85
+ S: this,
86
+ C: (f, a) => f(...a)
87
+ });
88
+ await this._handleMessage(message);
89
+ }));
90
+ scheduleTaskInterval(this._ctx, async () => {
91
+ this._performGc();
92
+ }, RECEIVED_MESSAGES_GC_INTERVAL);
93
+ this._closed = false;
94
+ log.trace("dxos.mesh.messenger.open", trace2.end({
95
+ id: traceId
96
+ }), {
97
+ F: __dxlog_file,
98
+ L: 93,
99
+ S: this,
100
+ C: (f, a) => f(...a)
101
+ });
102
+ }
103
+ async close() {
104
+ if (this._closed) {
105
+ return;
106
+ }
107
+ this._closed = true;
108
+ await this._ctx.dispose();
109
+ }
110
+ async sendMessage({ author, recipient, payload }) {
111
+ invariant(!this._closed, "Closed", {
112
+ F: __dxlog_file,
113
+ L: 105,
114
+ S: this,
115
+ A: [
116
+ "!this._closed",
117
+ "'Closed'"
118
+ ]
119
+ });
120
+ const messageContext = this._ctx.derive();
121
+ const reliablePayload = {
122
+ messageId: PublicKey.random(),
123
+ payload
124
+ };
125
+ invariant(!this._onAckCallbacks.has(reliablePayload.messageId), void 0, {
126
+ F: __dxlog_file,
127
+ L: 112,
128
+ S: this,
129
+ A: [
130
+ "!this._onAckCallbacks.has(reliablePayload.messageId!)",
131
+ ""
132
+ ]
133
+ });
134
+ log("send message", {
135
+ messageId: reliablePayload.messageId,
136
+ author,
137
+ recipient
138
+ }, {
139
+ F: __dxlog_file,
140
+ L: 113,
141
+ S: this,
142
+ C: (f, a) => f(...a)
143
+ });
144
+ let messageReceived;
145
+ let timeoutHit;
146
+ let sendAttempts = 0;
147
+ const promise = new Promise((resolve, reject) => {
148
+ messageReceived = resolve;
149
+ timeoutHit = reject;
150
+ });
151
+ scheduleExponentialBackoffTaskInterval(messageContext, async () => {
152
+ log("retrying message", {
153
+ messageId: reliablePayload.messageId
154
+ }, {
155
+ F: __dxlog_file,
156
+ L: 128,
157
+ S: this,
158
+ C: (f, a) => f(...a)
159
+ });
160
+ sendAttempts++;
161
+ await this._encodeAndSend({
162
+ author,
163
+ recipient,
164
+ reliablePayload
165
+ }).catch((err) => log("failed to send message", {
166
+ err
167
+ }, {
168
+ F: __dxlog_file,
169
+ L: 131,
170
+ S: this,
171
+ C: (f, a) => f(...a)
172
+ }));
173
+ }, this._retryDelay);
174
+ scheduleTask(messageContext, () => {
175
+ log("message not delivered", {
176
+ messageId: reliablePayload.messageId
177
+ }, {
178
+ F: __dxlog_file,
179
+ L: 140,
180
+ S: this,
181
+ C: (f, a) => f(...a)
182
+ });
183
+ this._onAckCallbacks.delete(reliablePayload.messageId);
184
+ timeoutHit(new ProtocolTimeoutError("signaling message not delivered", new TimeoutError(MESSAGE_TIMEOUT, "Message not delivered")));
185
+ void messageContext.dispose();
186
+ this._monitor.recordReliableMessage({
187
+ sendAttempts,
188
+ sent: false
189
+ });
190
+ }, MESSAGE_TIMEOUT);
191
+ this._onAckCallbacks.set(reliablePayload.messageId, () => {
192
+ messageReceived();
193
+ this._onAckCallbacks.delete(reliablePayload.messageId);
194
+ void messageContext.dispose();
195
+ this._monitor.recordReliableMessage({
196
+ sendAttempts,
197
+ sent: true
198
+ });
199
+ });
200
+ await this._encodeAndSend({
201
+ author,
202
+ recipient,
203
+ reliablePayload
204
+ });
205
+ return promise;
206
+ }
207
+ /**
208
+ * Subscribes onMessage function to messages that contains payload with payloadType.
209
+ * @param payloadType if not specified, onMessage will be subscribed to all types of messages.
210
+ */
211
+ async listen({ peer, payloadType, onMessage }) {
212
+ invariant(!this._closed, "Closed", {
213
+ F: __dxlog_file,
214
+ L: 178,
215
+ S: this,
216
+ A: [
217
+ "!this._closed",
218
+ "'Closed'"
219
+ ]
220
+ });
221
+ await this._signalManager.subscribeMessages(peer);
222
+ let listeners;
223
+ invariant(peer.peerKey, "Peer key is required", {
224
+ F: __dxlog_file,
225
+ L: 182,
226
+ S: this,
227
+ A: [
228
+ "peer.peerKey",
229
+ "'Peer key is required'"
230
+ ]
231
+ });
232
+ if (!payloadType) {
233
+ listeners = this._defaultListeners.get(peer.peerKey);
234
+ if (!listeners) {
235
+ listeners = /* @__PURE__ */ new Set();
236
+ this._defaultListeners.set(peer.peerKey, listeners);
237
+ }
238
+ } else {
239
+ listeners = this._listeners.get({
240
+ peerId: peer.peerKey,
241
+ payloadType
242
+ });
243
+ if (!listeners) {
244
+ listeners = /* @__PURE__ */ new Set();
245
+ this._listeners.set({
246
+ peerId: peer.peerKey,
247
+ payloadType
248
+ }, listeners);
249
+ }
250
+ }
251
+ listeners.add(onMessage);
252
+ return {
253
+ unsubscribe: async () => {
254
+ listeners.delete(onMessage);
255
+ }
256
+ };
257
+ }
258
+ async _encodeAndSend({ author, recipient, reliablePayload }) {
259
+ await this._signalManager.sendMessage({
260
+ author,
261
+ recipient,
262
+ payload: {
263
+ type_url: "dxos.mesh.messaging.ReliablePayload",
264
+ value: ReliablePayload.encode(reliablePayload, {
265
+ preserveAny: true
266
+ })
267
+ }
268
+ });
269
+ }
270
+ async _handleMessage(message) {
271
+ switch (message.payload.type_url) {
272
+ case "dxos.mesh.messaging.ReliablePayload": {
273
+ await this._handleReliablePayload(message);
274
+ break;
275
+ }
276
+ case "dxos.mesh.messaging.Acknowledgement": {
277
+ await this._handleAcknowledgement({
278
+ payload: message.payload
279
+ });
280
+ break;
281
+ }
282
+ }
283
+ }
284
+ async _handleReliablePayload({ author, recipient, payload }) {
285
+ invariant(payload.type_url === "dxos.mesh.messaging.ReliablePayload", void 0, {
286
+ F: __dxlog_file,
287
+ L: 240,
288
+ S: this,
289
+ A: [
290
+ "payload.type_url === 'dxos.mesh.messaging.ReliablePayload'",
291
+ ""
292
+ ]
293
+ });
294
+ const reliablePayload = ReliablePayload.decode(payload.value, {
295
+ preserveAny: true
296
+ });
297
+ log("handling message", {
298
+ messageId: reliablePayload.messageId
299
+ }, {
300
+ F: __dxlog_file,
301
+ L: 243,
302
+ S: this,
303
+ C: (f, a) => f(...a)
304
+ });
305
+ try {
306
+ await this._sendAcknowledgement({
307
+ author,
308
+ recipient,
309
+ messageId: reliablePayload.messageId
310
+ });
311
+ } catch (err) {
312
+ this._monitor.recordMessageAckFailed();
313
+ throw err;
314
+ }
315
+ if (this._receivedMessages.has(reliablePayload.messageId)) {
316
+ return;
317
+ }
318
+ this._receivedMessages.add(reliablePayload.messageId);
319
+ await this._callListeners({
320
+ author,
321
+ recipient,
322
+ payload: reliablePayload.payload
323
+ });
324
+ }
325
+ async _handleAcknowledgement({ payload }) {
326
+ invariant(payload.type_url === "dxos.mesh.messaging.Acknowledgement", void 0, {
327
+ F: __dxlog_file,
328
+ L: 271,
329
+ S: this,
330
+ A: [
331
+ "payload.type_url === 'dxos.mesh.messaging.Acknowledgement'",
332
+ ""
333
+ ]
334
+ });
335
+ this._onAckCallbacks.get(Acknowledgement.decode(payload.value).messageId)?.();
336
+ }
337
+ async _sendAcknowledgement({ author, recipient, messageId }) {
338
+ log("sending ACK", {
339
+ messageId,
340
+ from: recipient,
341
+ to: author
342
+ }, {
343
+ F: __dxlog_file,
344
+ L: 284,
345
+ S: this,
346
+ C: (f, a) => f(...a)
347
+ });
348
+ await this._signalManager.sendMessage({
349
+ author: recipient,
350
+ recipient: author,
351
+ payload: {
352
+ type_url: "dxos.mesh.messaging.Acknowledgement",
353
+ value: Acknowledgement.encode({
354
+ messageId
355
+ })
356
+ }
357
+ });
358
+ }
359
+ async _callListeners(message) {
360
+ {
361
+ invariant(message.recipient.peerKey, "Peer key is required", {
362
+ F: __dxlog_file,
363
+ L: 298,
364
+ S: this,
365
+ A: [
366
+ "message.recipient.peerKey",
367
+ "'Peer key is required'"
368
+ ]
369
+ });
370
+ const defaultListenerMap = this._defaultListeners.get(message.recipient.peerKey);
371
+ if (defaultListenerMap) {
372
+ for (const listener of defaultListenerMap) {
373
+ await listener(message);
374
+ }
375
+ }
376
+ }
377
+ {
378
+ const listenerMap = this._listeners.get({
379
+ peerId: message.recipient.peerKey,
380
+ payloadType: message.payload.type_url
381
+ });
382
+ if (listenerMap) {
383
+ for (const listener of listenerMap) {
384
+ await listener(message);
385
+ }
386
+ }
387
+ }
388
+ }
389
+ _performGc() {
390
+ const start = performance.now();
391
+ for (const key of this._toClear.keys()) {
392
+ this._receivedMessages.delete(key);
393
+ }
394
+ this._toClear.clear();
395
+ for (const key of this._receivedMessages.keys()) {
396
+ this._toClear.add(key);
397
+ }
398
+ const elapsed = performance.now() - start;
399
+ if (elapsed > 100) {
400
+ log.warn("GC took too long", {
401
+ elapsed
402
+ }, {
403
+ F: __dxlog_file,
404
+ L: 333,
405
+ S: this,
406
+ C: (f, a) => f(...a)
407
+ });
408
+ }
409
+ }
410
+ };
411
+
412
+ // packages/core/mesh/messaging/src/signal-client/signal-client.ts
413
+ import { DeferredTask, Event as Event2, Trigger as Trigger2, scheduleTask as scheduleTask2, scheduleTaskInterval as scheduleTaskInterval3, sleep } from "@dxos/async";
414
+ import { cancelWithContext as cancelWithContext2, Resource } from "@dxos/context";
415
+ import { invariant as invariant3 } from "@dxos/invariant";
416
+ import { PublicKey as PublicKey4 } from "@dxos/keys";
417
+ import { log as log4 } from "@dxos/log";
418
+ import { trace as trace6 } from "@dxos/protocols";
419
+ import { SignalState } from "@dxos/protocols/proto/dxos/mesh/signal";
420
+
421
+ // packages/core/mesh/messaging/src/signal-client/signal-client-monitor.ts
422
+ import { trace as trace3 } from "@dxos/tracing";
423
+ var SignalClientMonitor = class {
424
+ constructor() {
425
+ this._performance = {
426
+ sentMessages: 0,
427
+ receivedMessages: 0,
428
+ reconnectCounter: 0,
429
+ joinCounter: 0,
430
+ leaveCounter: 0
431
+ };
432
+ /**
433
+ * Timestamp of when the connection attempt was began.
434
+ */
435
+ this._connectionStarted = /* @__PURE__ */ new Date();
436
+ /**
437
+ * Timestamp of last state change.
438
+ */
439
+ this._lastStateChange = /* @__PURE__ */ new Date();
440
+ }
441
+ getRecordedTimestamps() {
442
+ return {
443
+ connectionStarted: this._connectionStarted,
444
+ lastStateChange: this._lastStateChange
445
+ };
446
+ }
447
+ recordStateChangeTime() {
448
+ this._lastStateChange = /* @__PURE__ */ new Date();
449
+ }
450
+ recordConnectionStartTime() {
451
+ this._connectionStarted = /* @__PURE__ */ new Date();
452
+ }
453
+ recordReconnect(params) {
454
+ this._performance.reconnectCounter++;
455
+ trace3.metrics.increment("dxos.mesh.signal.signal-client.reconnect", 1, {
456
+ tags: {
457
+ success: params.success
458
+ }
459
+ });
460
+ }
461
+ recordJoin() {
462
+ this._performance.joinCounter++;
463
+ }
464
+ recordLeave() {
465
+ this._performance.leaveCounter++;
466
+ }
467
+ recordMessageReceived(message) {
468
+ this._performance.receivedMessages++;
469
+ trace3.metrics.increment("dxos.mesh.signal.signal-client.received-total", 1, {
470
+ tags: createIdentityTags(message)
471
+ });
472
+ trace3.metrics.distribution("dxos.mesh.signal.signal-client.bytes-in", getByteCount(message), {
473
+ tags: createIdentityTags(message)
474
+ });
475
+ }
476
+ async recordMessageSending(message, sendMessage) {
477
+ this._performance.sentMessages++;
478
+ const tags = createIdentityTags(message);
479
+ let success = true;
480
+ try {
481
+ const reqStart = Date.now();
482
+ await sendMessage();
483
+ const reqDuration = Date.now() - reqStart;
484
+ trace3.metrics.distribution("dxos.mesh.signal.signal-client.send-duration", reqDuration, {
485
+ tags
486
+ });
487
+ trace3.metrics.distribution("dxos.mesh.signal.signal-client.bytes-out", getByteCount(message), {
488
+ tags
489
+ });
490
+ } catch (err) {
491
+ success = false;
492
+ }
493
+ trace3.metrics.increment("dxos.mesh.signal.signal-client.sent-total", 1, {
494
+ tags: {
495
+ ...tags,
496
+ success
497
+ }
498
+ });
499
+ }
500
+ recordStreamCloseErrors(count) {
501
+ trace3.metrics.increment("dxos.mesh.signal.signal-client.stream-close-errors", count);
502
+ }
503
+ recordReconciliation(params) {
504
+ trace3.metrics.increment("dxos.mesh.signal.signal-client.reconciliation", 1, {
505
+ tags: {
506
+ success: params.success
507
+ }
508
+ });
509
+ }
510
+ };
511
+ var getByteCount = (message) => {
512
+ return message.author.peerKey.length + message.recipient.peerKey.length + message.payload.type_url.length + message.payload.value.length;
513
+ };
514
+ var createIdentityTags = (message) => {
515
+ return {
516
+ peer: message.author.peerKey
517
+ };
518
+ };
519
+
520
+ // packages/core/mesh/messaging/src/signal-client/signal-local-state.ts
521
+ import { asyncTimeout, Event } from "@dxos/async";
522
+ import { cancelWithContext } from "@dxos/context";
523
+ import { PublicKey as PublicKey2 } from "@dxos/keys";
524
+ import { log as log2 } from "@dxos/log";
525
+ import { ComplexMap as ComplexMap2, ComplexSet as ComplexSet2, safeAwaitAll } from "@dxos/util";
526
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-local-state.ts";
527
+ var SignalLocalState = class {
528
+ constructor(_onMessage, _onSwarmEvent) {
529
+ this._onMessage = _onMessage;
530
+ this._onSwarmEvent = _onSwarmEvent;
531
+ this._swarmStreams = new ComplexMap2(({ topic, peerId }) => topic.toHex() + peerId.toHex());
532
+ this._joinedTopics = new ComplexSet2(({ topic, peerId }) => topic.toHex() + peerId.toHex());
533
+ this._subscribedMessages = new ComplexSet2(({ peerId }) => peerId.toHex());
534
+ this.messageStreams = new ComplexMap2((key) => key.toHex());
535
+ this.reconciled = new Event();
536
+ }
537
+ async safeCloseStreams() {
538
+ const streams = [
539
+ ...this._swarmStreams.values()
540
+ ].concat([
541
+ ...this.messageStreams.values()
542
+ ]);
543
+ this._swarmStreams.clear();
544
+ this.messageStreams.clear();
545
+ const failureCount = (await safeAwaitAll(streams, (s) => s.close())).length;
546
+ return {
547
+ failureCount
548
+ };
549
+ }
550
+ join({ topic, peerId }) {
551
+ this._joinedTopics.add({
552
+ topic,
553
+ peerId
554
+ });
555
+ }
556
+ leave({ topic, peerId }) {
557
+ void this._swarmStreams.get({
558
+ topic,
559
+ peerId
560
+ })?.close();
561
+ this._swarmStreams.delete({
562
+ topic,
563
+ peerId
564
+ });
565
+ this._joinedTopics.delete({
566
+ topic,
567
+ peerId
568
+ });
569
+ }
570
+ subscribeMessages(peerId) {
571
+ this._subscribedMessages.add({
572
+ peerId
573
+ });
574
+ }
575
+ unsubscribeMessages(peerId) {
576
+ log2("unsubscribing from messages", {
577
+ peerId
578
+ }, {
579
+ F: __dxlog_file2,
580
+ L: 79,
581
+ S: this,
582
+ C: (f, a) => f(...a)
583
+ });
584
+ this._subscribedMessages.delete({
585
+ peerId
586
+ });
587
+ void this.messageStreams.get(peerId)?.close();
588
+ this.messageStreams.delete(peerId);
589
+ }
590
+ async reconcile(ctx, client) {
591
+ await this._reconcileSwarmSubscriptions(ctx, client);
592
+ await this._reconcileMessageSubscriptions(ctx, client);
593
+ this.reconciled.emit();
594
+ }
595
+ async _reconcileSwarmSubscriptions(ctx, client) {
596
+ for (const { topic, peerId } of this._swarmStreams.keys()) {
597
+ if (this._joinedTopics.has({
598
+ topic,
599
+ peerId
600
+ })) {
601
+ continue;
602
+ }
603
+ void this._swarmStreams.get({
604
+ topic,
605
+ peerId
606
+ })?.close();
607
+ this._swarmStreams.delete({
608
+ topic,
609
+ peerId
610
+ });
611
+ }
612
+ for (const { topic, peerId } of this._joinedTopics.values()) {
613
+ if (this._swarmStreams.has({
614
+ topic,
615
+ peerId
616
+ })) {
617
+ continue;
618
+ }
619
+ const swarmStream = await asyncTimeout(cancelWithContext(ctx, client.join({
620
+ topic,
621
+ peerId
622
+ })), 5e3);
623
+ swarmStream.subscribe(async (swarmEvent) => {
624
+ if (this._joinedTopics.has({
625
+ topic,
626
+ peerId
627
+ })) {
628
+ log2("swarm event", {
629
+ swarmEvent
630
+ }, {
631
+ F: __dxlog_file2,
632
+ L: 115,
633
+ S: this,
634
+ C: (f, a) => f(...a)
635
+ });
636
+ const event = swarmEvent.peerAvailable ? {
637
+ topic,
638
+ peerAvailable: {
639
+ ...swarmEvent.peerAvailable,
640
+ peer: {
641
+ peerKey: PublicKey2.from(swarmEvent.peerAvailable.peer).toHex()
642
+ }
643
+ }
644
+ } : {
645
+ topic,
646
+ peerLeft: {
647
+ ...swarmEvent.peerLeft,
648
+ peer: {
649
+ peerKey: PublicKey2.from(swarmEvent.peerLeft.peer).toHex()
650
+ }
651
+ }
652
+ };
653
+ await this._onSwarmEvent(event);
654
+ }
655
+ });
656
+ this._swarmStreams.set({
657
+ topic,
658
+ peerId
659
+ }, swarmStream);
660
+ }
661
+ }
662
+ async _reconcileMessageSubscriptions(ctx, client) {
663
+ for (const peerId of this.messageStreams.keys()) {
664
+ if (this._subscribedMessages.has({
665
+ peerId
666
+ })) {
667
+ continue;
668
+ }
669
+ void this.messageStreams.get(peerId)?.close();
670
+ this.messageStreams.delete(peerId);
671
+ }
672
+ for (const { peerId } of this._subscribedMessages.values()) {
673
+ if (this.messageStreams.has(peerId)) {
674
+ continue;
675
+ }
676
+ const messageStream = await asyncTimeout(cancelWithContext(ctx, client.receiveMessages(peerId)), 5e3);
677
+ messageStream.subscribe(async (signalMessage) => {
678
+ if (this._subscribedMessages.has({
679
+ peerId
680
+ })) {
681
+ const message = {
682
+ author: {
683
+ peerKey: PublicKey2.from(signalMessage.author).toHex()
684
+ },
685
+ recipient: {
686
+ peerKey: PublicKey2.from(signalMessage.recipient).toHex()
687
+ },
688
+ payload: signalMessage.payload
689
+ };
690
+ await this._onMessage(message);
691
+ }
692
+ });
693
+ this.messageStreams.set(peerId, messageStream);
694
+ }
695
+ }
696
+ };
697
+
698
+ // packages/core/mesh/messaging/src/signal-client/signal-rpc-client.ts
699
+ import WebSocket from "isomorphic-ws";
700
+ import { scheduleTaskInterval as scheduleTaskInterval2, TimeoutError as TimeoutError2, Trigger } from "@dxos/async";
701
+ import { Context as Context2 } from "@dxos/context";
702
+ import { invariant as invariant2 } from "@dxos/invariant";
703
+ import { PublicKey as PublicKey3 } from "@dxos/keys";
704
+ import { log as log3 } from "@dxos/log";
705
+ import { trace as trace5 } from "@dxos/protocols";
706
+ import { schema as schema2 } from "@dxos/protocols/proto";
707
+ import { createProtoRpcPeer } from "@dxos/rpc";
708
+
709
+ // packages/core/mesh/messaging/src/signal-client/signal-rpc-client-monitor.ts
710
+ import { trace as trace4 } from "@dxos/tracing";
711
+ var SignalRpcClientMonitor = class {
712
+ recordClientCloseFailure(params) {
713
+ trace4.metrics.increment("dxos.mesh.signal.signal-rpc-client.close-failure", 1, {
714
+ tags: {
715
+ reason: params.failureReason
716
+ }
717
+ });
718
+ }
719
+ };
720
+
721
+ // packages/core/mesh/messaging/src/signal-client/signal-rpc-client.ts
722
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-rpc-client.ts";
723
+ var SIGNAL_KEEPALIVE_INTERVAL = 1e4;
724
+ var SignalRPCClient = class {
725
+ constructor({ url, callbacks = {} }) {
726
+ this._connectTrigger = new Trigger();
727
+ this._closed = false;
728
+ this._closeComplete = new Trigger();
729
+ this._monitor = new SignalRpcClientMonitor();
730
+ const traceId = PublicKey3.random().toHex();
731
+ log3.trace("dxos.mesh.signal-rpc-client.constructor", trace5.begin({
732
+ id: traceId
733
+ }), {
734
+ F: __dxlog_file3,
735
+ L: 61,
736
+ S: this,
737
+ C: (f, a) => f(...a)
738
+ });
739
+ this._url = url;
740
+ this._callbacks = callbacks;
741
+ this._socket = new WebSocket(this._url);
742
+ this._rpc = createProtoRpcPeer({
743
+ requested: {
744
+ Signal: schema2.getService("dxos.mesh.signal.Signal")
745
+ },
746
+ noHandshake: true,
747
+ port: {
748
+ send: (msg) => {
749
+ if (this._closed) {
750
+ return;
751
+ }
752
+ try {
753
+ this._socket.send(msg);
754
+ } catch (err) {
755
+ log3.warn("send error", err, {
756
+ F: __dxlog_file3,
757
+ L: 80,
758
+ S: this,
759
+ C: (f, a) => f(...a)
760
+ });
761
+ }
762
+ },
763
+ subscribe: (cb) => {
764
+ this._socket.onmessage = async (msg) => {
765
+ if (typeof Blob !== "undefined" && msg.data instanceof Blob) {
766
+ cb(Buffer.from(await msg.data.arrayBuffer()));
767
+ } else {
768
+ cb(msg.data);
769
+ }
770
+ };
771
+ }
772
+ },
773
+ encodingOptions: {
774
+ preserveAny: true
775
+ }
776
+ });
777
+ this._socket.onopen = async () => {
778
+ try {
779
+ await this._rpc.open();
780
+ if (this._closed) {
781
+ await this._safeCloseRpc();
782
+ return;
783
+ }
784
+ log3(`RPC open ${this._url}`, void 0, {
785
+ F: __dxlog_file3,
786
+ L: 105,
787
+ S: this,
788
+ C: (f, a) => f(...a)
789
+ });
790
+ this._callbacks.onConnected?.();
791
+ this._connectTrigger.wake();
792
+ this._keepaliveCtx = new Context2(void 0, {
793
+ F: __dxlog_file3,
794
+ L: 108
795
+ });
796
+ scheduleTaskInterval2(this._keepaliveCtx, async () => {
797
+ this._socket?.send("__ping__");
798
+ }, SIGNAL_KEEPALIVE_INTERVAL);
799
+ } catch (err) {
800
+ this._callbacks.onError?.(err);
801
+ this._socket.close();
802
+ this._closed = true;
803
+ }
804
+ };
805
+ this._socket.onclose = async () => {
806
+ log3(`Disconnected ${this._url}`, void 0, {
807
+ F: __dxlog_file3,
808
+ L: 128,
809
+ S: this,
810
+ C: (f, a) => f(...a)
811
+ });
812
+ this._callbacks.onDisconnected?.();
813
+ this._closeComplete.wake();
814
+ await this.close();
815
+ };
816
+ this._socket.onerror = async (event) => {
817
+ if (this._closed) {
818
+ this._socket.close();
819
+ return;
820
+ }
821
+ this._closed = true;
822
+ this._callbacks.onError?.(event.error ?? new Error(event.message));
823
+ await this._safeCloseRpc();
824
+ log3.warn(`Socket ${event.type ?? "unknown"} error`, {
825
+ message: event.message,
826
+ url: this._url
827
+ }, {
828
+ F: __dxlog_file3,
829
+ L: 144,
830
+ S: this,
831
+ C: (f, a) => f(...a)
832
+ });
833
+ };
834
+ log3.trace("dxos.mesh.signal-rpc-client.constructor", trace5.end({
835
+ id: traceId
836
+ }), {
837
+ F: __dxlog_file3,
838
+ L: 147,
839
+ S: this,
840
+ C: (f, a) => f(...a)
841
+ });
842
+ }
843
+ async close() {
844
+ if (this._closed) {
845
+ return;
846
+ }
847
+ this._closed = true;
848
+ await this._keepaliveCtx?.dispose();
849
+ try {
850
+ await this._safeCloseRpc();
851
+ if (this._socket.readyState === WebSocket.OPEN || this._socket.readyState === WebSocket.CONNECTING) {
852
+ this._socket.close();
853
+ }
854
+ await this._closeComplete.wait({
855
+ timeout: 1e3
856
+ });
857
+ } catch (err) {
858
+ const failureReason = err instanceof TimeoutError2 ? "timeout" : err?.constructor?.name ?? "unknown";
859
+ this._monitor.recordClientCloseFailure({
860
+ failureReason
861
+ });
862
+ }
863
+ }
864
+ async join({ topic, peerId }) {
865
+ log3("join", {
866
+ topic,
867
+ peerId,
868
+ metadata: this._callbacks?.getMetadata?.()
869
+ }, {
870
+ F: __dxlog_file3,
871
+ L: 173,
872
+ S: this,
873
+ C: (f, a) => f(...a)
874
+ });
875
+ invariant2(!this._closed, "SignalRPCClient is closed", {
876
+ F: __dxlog_file3,
877
+ L: 174,
878
+ S: this,
879
+ A: [
880
+ "!this._closed",
881
+ "'SignalRPCClient is closed'"
882
+ ]
883
+ });
884
+ await this._connectTrigger.wait();
885
+ const swarmStream = this._rpc.rpc.Signal.join({
886
+ swarm: topic.asUint8Array(),
887
+ peer: peerId.asUint8Array(),
888
+ metadata: this._callbacks?.getMetadata?.()
889
+ });
890
+ await swarmStream.waitUntilReady();
891
+ return swarmStream;
892
+ }
893
+ async receiveMessages(peerId) {
894
+ log3("receiveMessages", {
895
+ peerId
896
+ }, {
897
+ F: __dxlog_file3,
898
+ L: 186,
899
+ S: this,
900
+ C: (f, a) => f(...a)
901
+ });
902
+ invariant2(!this._closed, "SignalRPCClient is closed", {
903
+ F: __dxlog_file3,
904
+ L: 187,
905
+ S: this,
906
+ A: [
907
+ "!this._closed",
908
+ "'SignalRPCClient is closed'"
909
+ ]
910
+ });
911
+ await this._connectTrigger.wait();
912
+ const messageStream = this._rpc.rpc.Signal.receiveMessages({
913
+ peer: peerId.asUint8Array()
914
+ });
915
+ await messageStream.waitUntilReady();
916
+ return messageStream;
917
+ }
918
+ async sendMessage({ author, recipient, payload }) {
919
+ log3("sendMessage", {
920
+ author,
921
+ recipient,
922
+ payload,
923
+ metadata: this._callbacks?.getMetadata?.()
924
+ }, {
925
+ F: __dxlog_file3,
926
+ L: 197,
927
+ S: this,
928
+ C: (f, a) => f(...a)
929
+ });
930
+ invariant2(!this._closed, "SignalRPCClient is closed", {
931
+ F: __dxlog_file3,
932
+ L: 198,
933
+ S: this,
934
+ A: [
935
+ "!this._closed",
936
+ "'SignalRPCClient is closed'"
937
+ ]
938
+ });
939
+ await this._connectTrigger.wait();
940
+ await this._rpc.rpc.Signal.sendMessage({
941
+ author: author.asUint8Array(),
942
+ recipient: recipient.asUint8Array(),
943
+ payload,
944
+ metadata: this._callbacks?.getMetadata?.()
945
+ });
946
+ }
947
+ async _safeCloseRpc() {
948
+ try {
949
+ this._connectTrigger.reset();
950
+ await this._rpc.close();
951
+ } catch (err) {
952
+ log3.catch(err, void 0, {
953
+ F: __dxlog_file3,
954
+ L: 213,
955
+ S: this,
956
+ C: (f, a) => f(...a)
957
+ });
958
+ }
959
+ }
960
+ };
961
+
962
+ // packages/core/mesh/messaging/src/signal-client/signal-client.ts
963
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-client.ts";
964
+ var DEFAULT_RECONNECT_TIMEOUT = 100;
965
+ var MAX_RECONNECT_TIMEOUT = 5e3;
966
+ var ERROR_RECONCILE_DELAY = 1e3;
967
+ var RECONCILE_INTERVAL = 5e3;
968
+ var SignalClient = class extends Resource {
969
+ /**
970
+ * @param _host Signal server websocket URL.
971
+ * @param onMessage called when a new message is received.
972
+ * @param onSwarmEvent called when a new swarm event is received.
973
+ * @param _getMetadata signal-message metadata provider, called for every message.
974
+ */
975
+ constructor(_host, _getMetadata) {
976
+ super();
977
+ this._host = _host;
978
+ this._getMetadata = _getMetadata;
979
+ this._monitor = new SignalClientMonitor();
980
+ this._state = SignalState.CLOSED;
981
+ this._lastReconciliationFailed = false;
982
+ this._clientReady = new Trigger2();
983
+ this._reconnectAfter = DEFAULT_RECONNECT_TIMEOUT;
984
+ this._instanceId = PublicKey4.random().toHex();
985
+ this.statusChanged = new Event2();
986
+ this.onMessage = new Event2();
987
+ this.swarmEvent = new Event2();
988
+ if (!this._host.startsWith("wss://") && !this._host.startsWith("ws://")) {
989
+ throw new Error(`Signal server requires a websocket URL. Provided: ${this._host}`);
990
+ }
991
+ this.localState = new SignalLocalState(async (message) => {
992
+ this._monitor.recordMessageReceived(message);
993
+ this.onMessage.emit(message);
994
+ }, async (event) => this.swarmEvent.emit(event));
995
+ }
996
+ async _open() {
997
+ log4.trace("dxos.mesh.signal-client.open", trace6.begin({
998
+ id: this._instanceId
999
+ }), {
1000
+ F: __dxlog_file4,
1001
+ L: 92,
1002
+ S: this,
1003
+ C: (f, a) => f(...a)
1004
+ });
1005
+ if ([
1006
+ SignalState.CONNECTED,
1007
+ SignalState.CONNECTING
1008
+ ].includes(this._state)) {
1009
+ return;
1010
+ }
1011
+ this._setState(SignalState.CONNECTING);
1012
+ this._reconcileTask = new DeferredTask(this._ctx, async () => {
1013
+ try {
1014
+ await cancelWithContext2(this._connectionCtx, this._clientReady.wait({
1015
+ timeout: 5e3
1016
+ }));
1017
+ invariant3(this._state === SignalState.CONNECTED, "Not connected to Signal Server", {
1018
+ F: __dxlog_file4,
1019
+ L: 102,
1020
+ S: this,
1021
+ A: [
1022
+ "this._state === SignalState.CONNECTED",
1023
+ "'Not connected to Signal Server'"
1024
+ ]
1025
+ });
1026
+ await this.localState.reconcile(this._connectionCtx, this._client);
1027
+ this._monitor.recordReconciliation({
1028
+ success: true
1029
+ });
1030
+ this._lastReconciliationFailed = false;
1031
+ } catch (err) {
1032
+ this._lastReconciliationFailed = true;
1033
+ this._monitor.recordReconciliation({
1034
+ success: false
1035
+ });
1036
+ throw err;
1037
+ }
1038
+ });
1039
+ scheduleTaskInterval3(this._ctx, async () => {
1040
+ if (this._state === SignalState.CONNECTED) {
1041
+ this._reconcileTask.schedule();
1042
+ }
1043
+ }, RECONCILE_INTERVAL);
1044
+ this._reconnectTask = new DeferredTask(this._ctx, async () => {
1045
+ try {
1046
+ await this._reconnect();
1047
+ this._monitor.recordReconnect({
1048
+ success: true
1049
+ });
1050
+ } catch (err) {
1051
+ this._monitor.recordReconnect({
1052
+ success: false
1053
+ });
1054
+ throw err;
1055
+ }
1056
+ });
1057
+ this._createClient();
1058
+ log4.trace("dxos.mesh.signal-client.open", trace6.end({
1059
+ id: this._instanceId
1060
+ }), {
1061
+ F: __dxlog_file4,
1062
+ L: 135,
1063
+ S: this,
1064
+ C: (f, a) => f(...a)
1065
+ });
1066
+ }
1067
+ async _catch(err) {
1068
+ if (this._state === SignalState.CLOSED || this._ctx.disposed) {
1069
+ return;
1070
+ }
1071
+ if (this._state === SignalState.CONNECTED && !this._lastReconciliationFailed) {
1072
+ log4.warn("SignalClient error:", err, {
1073
+ F: __dxlog_file4,
1074
+ L: 144,
1075
+ S: this,
1076
+ C: (f, a) => f(...a)
1077
+ });
1078
+ }
1079
+ this._scheduleReconcileAfterError();
1080
+ }
1081
+ async _close() {
1082
+ log4("closing...", void 0, {
1083
+ F: __dxlog_file4,
1084
+ L: 150,
1085
+ S: this,
1086
+ C: (f, a) => f(...a)
1087
+ });
1088
+ if ([
1089
+ SignalState.CLOSED
1090
+ ].includes(this._state)) {
1091
+ return;
1092
+ }
1093
+ this._setState(SignalState.CLOSED);
1094
+ await this._safeResetClient();
1095
+ log4("closed", void 0, {
1096
+ F: __dxlog_file4,
1097
+ L: 158,
1098
+ S: this,
1099
+ C: (f, a) => f(...a)
1100
+ });
1101
+ }
1102
+ getStatus() {
1103
+ return {
1104
+ host: this._host,
1105
+ state: this._state,
1106
+ error: this._lastError?.message,
1107
+ reconnectIn: this._reconnectAfter,
1108
+ ...this._monitor.getRecordedTimestamps()
1109
+ };
1110
+ }
1111
+ async join(args) {
1112
+ log4("joining", {
1113
+ topic: args.topic,
1114
+ peerId: args.peer.peerKey
1115
+ }, {
1116
+ F: __dxlog_file4,
1117
+ L: 172,
1118
+ S: this,
1119
+ C: (f, a) => f(...a)
1120
+ });
1121
+ this._monitor.recordJoin();
1122
+ this.localState.join({
1123
+ topic: args.topic,
1124
+ peerId: PublicKey4.from(args.peer.peerKey)
1125
+ });
1126
+ this._reconcileTask?.schedule();
1127
+ }
1128
+ async leave(args) {
1129
+ log4("leaving", {
1130
+ topic: args.topic,
1131
+ peerId: args.peer.peerKey
1132
+ }, {
1133
+ F: __dxlog_file4,
1134
+ L: 179,
1135
+ S: this,
1136
+ C: (f, a) => f(...a)
1137
+ });
1138
+ this._monitor.recordLeave();
1139
+ this.localState.leave({
1140
+ topic: args.topic,
1141
+ peerId: PublicKey4.from(args.peer.peerKey)
1142
+ });
1143
+ }
1144
+ async sendMessage(msg) {
1145
+ return this._monitor.recordMessageSending(msg, async () => {
1146
+ await this._clientReady.wait();
1147
+ invariant3(this._state === SignalState.CONNECTED, "Not connected to Signal Server", {
1148
+ F: __dxlog_file4,
1149
+ L: 187,
1150
+ S: this,
1151
+ A: [
1152
+ "this._state === SignalState.CONNECTED",
1153
+ "'Not connected to Signal Server'"
1154
+ ]
1155
+ });
1156
+ invariant3(msg.author.peerKey, "Author key required", {
1157
+ F: __dxlog_file4,
1158
+ L: 188,
1159
+ S: this,
1160
+ A: [
1161
+ "msg.author.peerKey",
1162
+ "'Author key required'"
1163
+ ]
1164
+ });
1165
+ invariant3(msg.recipient.peerKey, "Recipient key required", {
1166
+ F: __dxlog_file4,
1167
+ L: 189,
1168
+ S: this,
1169
+ A: [
1170
+ "msg.recipient.peerKey",
1171
+ "'Recipient key required'"
1172
+ ]
1173
+ });
1174
+ await this._client.sendMessage({
1175
+ author: PublicKey4.from(msg.author.peerKey),
1176
+ recipient: PublicKey4.from(msg.recipient.peerKey),
1177
+ payload: msg.payload
1178
+ });
1179
+ });
1180
+ }
1181
+ async subscribeMessages(peer) {
1182
+ invariant3(peer.peerKey, "Peer key required", {
1183
+ F: __dxlog_file4,
1184
+ L: 199,
1185
+ S: this,
1186
+ A: [
1187
+ "peer.peerKey",
1188
+ "'Peer key required'"
1189
+ ]
1190
+ });
1191
+ log4("subscribing to messages", {
1192
+ peer
1193
+ }, {
1194
+ F: __dxlog_file4,
1195
+ L: 200,
1196
+ S: this,
1197
+ C: (f, a) => f(...a)
1198
+ });
1199
+ this.localState.subscribeMessages(PublicKey4.from(peer.peerKey));
1200
+ this._reconcileTask?.schedule();
1201
+ }
1202
+ async unsubscribeMessages(peer) {
1203
+ invariant3(peer.peerKey, "Peer key required", {
1204
+ F: __dxlog_file4,
1205
+ L: 206,
1206
+ S: this,
1207
+ A: [
1208
+ "peer.peerKey",
1209
+ "'Peer key required'"
1210
+ ]
1211
+ });
1212
+ log4("unsubscribing from messages", {
1213
+ peer
1214
+ }, {
1215
+ F: __dxlog_file4,
1216
+ L: 207,
1217
+ S: this,
1218
+ C: (f, a) => f(...a)
1219
+ });
1220
+ this.localState.unsubscribeMessages(PublicKey4.from(peer.peerKey));
1221
+ }
1222
+ _scheduleReconcileAfterError() {
1223
+ scheduleTask2(this._ctx, () => this._reconcileTask.schedule(), ERROR_RECONCILE_DELAY);
1224
+ }
1225
+ _createClient() {
1226
+ log4("creating client", {
1227
+ host: this._host,
1228
+ state: this._state
1229
+ }, {
1230
+ F: __dxlog_file4,
1231
+ L: 216,
1232
+ S: this,
1233
+ C: (f, a) => f(...a)
1234
+ });
1235
+ invariant3(!this._client, "Client already created", {
1236
+ F: __dxlog_file4,
1237
+ L: 217,
1238
+ S: this,
1239
+ A: [
1240
+ "!this._client",
1241
+ "'Client already created'"
1242
+ ]
1243
+ });
1244
+ this._monitor.recordConnectionStartTime();
1245
+ this._connectionCtx = this._ctx.derive();
1246
+ this._connectionCtx.onDispose(async () => {
1247
+ log4("connection context disposed", void 0, {
1248
+ F: __dxlog_file4,
1249
+ L: 224,
1250
+ S: this,
1251
+ C: (f, a) => f(...a)
1252
+ });
1253
+ const { failureCount } = await this.localState.safeCloseStreams();
1254
+ this._monitor.recordStreamCloseErrors(failureCount);
1255
+ });
1256
+ try {
1257
+ const client = new SignalRPCClient({
1258
+ url: this._host,
1259
+ callbacks: {
1260
+ onConnected: () => {
1261
+ if (client === this._client) {
1262
+ log4("socket connected", void 0, {
1263
+ F: __dxlog_file4,
1264
+ L: 235,
1265
+ S: this,
1266
+ C: (f, a) => f(...a)
1267
+ });
1268
+ this._onConnected();
1269
+ }
1270
+ },
1271
+ onDisconnected: () => {
1272
+ if (client !== this._client) {
1273
+ return;
1274
+ }
1275
+ log4("socket disconnected", {
1276
+ state: this._state
1277
+ }, {
1278
+ F: __dxlog_file4,
1279
+ L: 244,
1280
+ S: this,
1281
+ C: (f, a) => f(...a)
1282
+ });
1283
+ if (this._state === SignalState.ERROR) {
1284
+ this._setState(SignalState.DISCONNECTED);
1285
+ } else {
1286
+ this._onDisconnected();
1287
+ }
1288
+ },
1289
+ onError: (error) => {
1290
+ if (client === this._client) {
1291
+ log4("socket error", {
1292
+ error,
1293
+ state: this._state
1294
+ }, {
1295
+ F: __dxlog_file4,
1296
+ L: 256,
1297
+ S: this,
1298
+ C: (f, a) => f(...a)
1299
+ });
1300
+ this._onDisconnected({
1301
+ error
1302
+ });
1303
+ }
1304
+ },
1305
+ getMetadata: this._getMetadata
1306
+ }
1307
+ });
1308
+ this._client = client;
1309
+ } catch (error) {
1310
+ this._client = void 0;
1311
+ this._onDisconnected({
1312
+ error
1313
+ });
1314
+ }
1315
+ }
1316
+ async _reconnect() {
1317
+ log4(`reconnecting in ${this._reconnectAfter}ms`, {
1318
+ state: this._state
1319
+ }, {
1320
+ F: __dxlog_file4,
1321
+ L: 271,
1322
+ S: this,
1323
+ C: (f, a) => f(...a)
1324
+ });
1325
+ if (this._state === SignalState.RECONNECTING) {
1326
+ log4.info("Signal api already reconnecting.", void 0, {
1327
+ F: __dxlog_file4,
1328
+ L: 274,
1329
+ S: this,
1330
+ C: (f, a) => f(...a)
1331
+ });
1332
+ return;
1333
+ }
1334
+ if (this._state === SignalState.CLOSED) {
1335
+ return;
1336
+ }
1337
+ this._setState(SignalState.RECONNECTING);
1338
+ await this._safeResetClient();
1339
+ await cancelWithContext2(this._ctx, sleep(this._reconnectAfter));
1340
+ this._createClient();
1341
+ }
1342
+ _onConnected() {
1343
+ this._lastError = void 0;
1344
+ this._lastReconciliationFailed = false;
1345
+ this._reconnectAfter = DEFAULT_RECONNECT_TIMEOUT;
1346
+ this._setState(SignalState.CONNECTED);
1347
+ this._clientReady.wake();
1348
+ this._reconcileTask.schedule();
1349
+ }
1350
+ _onDisconnected(options) {
1351
+ this._updateReconnectTimeout();
1352
+ if (this._state === SignalState.CLOSED) {
1353
+ return;
1354
+ }
1355
+ if (options?.error) {
1356
+ this._lastError = options.error;
1357
+ this._setState(SignalState.ERROR);
1358
+ } else {
1359
+ this._setState(SignalState.DISCONNECTED);
1360
+ }
1361
+ this._reconnectTask.schedule();
1362
+ }
1363
+ _setState(newState) {
1364
+ this._state = newState;
1365
+ this._monitor.recordStateChangeTime();
1366
+ log4("signal state changed", {
1367
+ status: this.getStatus()
1368
+ }, {
1369
+ F: __dxlog_file4,
1370
+ L: 315,
1371
+ S: this,
1372
+ C: (f, a) => f(...a)
1373
+ });
1374
+ this.statusChanged.emit(this.getStatus());
1375
+ }
1376
+ _updateReconnectTimeout() {
1377
+ if (this._state !== SignalState.CONNECTED && this._state !== SignalState.CONNECTING) {
1378
+ this._reconnectAfter *= 2;
1379
+ this._reconnectAfter = Math.min(this._reconnectAfter, MAX_RECONNECT_TIMEOUT);
1380
+ }
1381
+ }
1382
+ async _safeResetClient() {
1383
+ await this._connectionCtx?.dispose();
1384
+ this._connectionCtx = void 0;
1385
+ this._clientReady.reset();
1386
+ await this._client?.close().catch(() => {
1387
+ });
1388
+ this._client = void 0;
1389
+ }
1390
+ };
1391
+
1392
+ // packages/core/mesh/messaging/src/signal-methods.ts
1393
+ var PeerInfoHash = ({ peerKey }) => peerKey;
1394
+
1395
+ // packages/core/mesh/messaging/src/signal-manager/memory-signal-manager.ts
1396
+ import { Event as Event3, Trigger as Trigger3 } from "@dxos/async";
1397
+ import { Context as Context3 } from "@dxos/context";
1398
+ import { invariant as invariant4 } from "@dxos/invariant";
1399
+ import { PublicKey as PublicKey5 } from "@dxos/keys";
1400
+ import { log as log5 } from "@dxos/log";
1401
+ import { schema as schema3 } from "@dxos/protocols/proto";
1402
+ import { ComplexMap as ComplexMap3, ComplexSet as ComplexSet3 } from "@dxos/util";
1403
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/memory-signal-manager.ts";
1404
+ var MemorySignalManagerContext = class {
1405
+ constructor() {
1406
+ // Swarm messages.
1407
+ this.swarmEvent = new Event3();
1408
+ // Mapping from topic to set of peers.
1409
+ this.swarms = new ComplexMap3(PublicKey5.hash);
1410
+ // Map of connections for each peer for signaling.
1411
+ this.connections = new ComplexMap3(PeerInfoHash);
1412
+ }
1413
+ };
1414
+ var MemorySignalManager = class {
1415
+ constructor(_context) {
1416
+ this._context = _context;
1417
+ this.statusChanged = new Event3();
1418
+ this.swarmEvent = new Event3();
1419
+ this.onMessage = new Event3();
1420
+ this._joinedSwarms = new ComplexSet3(({ topic, peer }) => topic.toHex() + peer.peerKey);
1421
+ this._freezeTrigger = new Trigger3().wake();
1422
+ this._ctx = new Context3(void 0, {
1423
+ F: __dxlog_file5,
1424
+ L: 51
1425
+ });
1426
+ this._ctx.onDispose(this._context.swarmEvent.on((data) => this.swarmEvent.emit(data)));
1427
+ }
1428
+ async open() {
1429
+ if (!this._ctx.disposed) {
1430
+ return;
1431
+ }
1432
+ this._ctx = new Context3(void 0, {
1433
+ F: __dxlog_file5,
1434
+ L: 60
1435
+ });
1436
+ this._ctx.onDispose(this._context.swarmEvent.on((data) => this.swarmEvent.emit(data)));
1437
+ await Promise.all([
1438
+ ...this._joinedSwarms.values()
1439
+ ].map((value) => this.join(value)));
1440
+ }
1441
+ async close() {
1442
+ if (this._ctx.disposed) {
1443
+ return;
1444
+ }
1445
+ const joinedSwarmsCopy = new ComplexSet3(({ topic, peer }) => topic.toHex() + peer.peerKey, [
1446
+ ...this._joinedSwarms.values()
1447
+ ]);
1448
+ await Promise.all([
1449
+ ...this._joinedSwarms.values()
1450
+ ].map((value) => this.leave(value)));
1451
+ this._joinedSwarms = joinedSwarmsCopy;
1452
+ await this._ctx.dispose();
1453
+ }
1454
+ getStatus() {
1455
+ return [];
1456
+ }
1457
+ async join({ topic, peer }) {
1458
+ invariant4(!this._ctx.disposed, "Closed", {
1459
+ F: __dxlog_file5,
1460
+ L: 89,
1461
+ S: this,
1462
+ A: [
1463
+ "!this._ctx.disposed",
1464
+ "'Closed'"
1465
+ ]
1466
+ });
1467
+ this._joinedSwarms.add({
1468
+ topic,
1469
+ peer
1470
+ });
1471
+ if (!this._context.swarms.has(topic)) {
1472
+ this._context.swarms.set(topic, new ComplexSet3(PeerInfoHash));
1473
+ }
1474
+ this._context.swarms.get(topic).add(peer);
1475
+ this._context.swarmEvent.emit({
1476
+ topic,
1477
+ peerAvailable: {
1478
+ peer,
1479
+ since: /* @__PURE__ */ new Date()
1480
+ }
1481
+ });
1482
+ for (const [topic2, peers] of this._context.swarms) {
1483
+ Array.from(peers).forEach((peer2) => {
1484
+ this.swarmEvent.emit({
1485
+ topic: topic2,
1486
+ peerAvailable: {
1487
+ peer: peer2,
1488
+ since: /* @__PURE__ */ new Date()
1489
+ }
1490
+ });
1491
+ });
1492
+ }
1493
+ }
1494
+ async leave({ topic, peer }) {
1495
+ invariant4(!this._ctx.disposed, "Closed", {
1496
+ F: __dxlog_file5,
1497
+ L: 121,
1498
+ S: this,
1499
+ A: [
1500
+ "!this._ctx.disposed",
1501
+ "'Closed'"
1502
+ ]
1503
+ });
1504
+ this._joinedSwarms.delete({
1505
+ topic,
1506
+ peer
1507
+ });
1508
+ if (!this._context.swarms.has(topic)) {
1509
+ this._context.swarms.set(topic, new ComplexSet3(PeerInfoHash));
1510
+ }
1511
+ this._context.swarms.get(topic).delete(peer);
1512
+ const swarmEvent = {
1513
+ topic,
1514
+ peerLeft: {
1515
+ peer
1516
+ }
1517
+ };
1518
+ this._context.swarmEvent.emit(swarmEvent);
1519
+ }
1520
+ async sendMessage({ author, recipient, payload }) {
1521
+ log5("send message", {
1522
+ author,
1523
+ recipient,
1524
+ ...dec(payload)
1525
+ }, {
1526
+ F: __dxlog_file5,
1527
+ L: 142,
1528
+ S: this,
1529
+ C: (f, a) => f(...a)
1530
+ });
1531
+ invariant4(recipient, void 0, {
1532
+ F: __dxlog_file5,
1533
+ L: 144,
1534
+ S: this,
1535
+ A: [
1536
+ "recipient",
1537
+ ""
1538
+ ]
1539
+ });
1540
+ invariant4(!this._ctx.disposed, "Closed", {
1541
+ F: __dxlog_file5,
1542
+ L: 145,
1543
+ S: this,
1544
+ A: [
1545
+ "!this._ctx.disposed",
1546
+ "'Closed'"
1547
+ ]
1548
+ });
1549
+ await this._freezeTrigger.wait();
1550
+ const remote = this._context.connections.get(recipient);
1551
+ if (!remote) {
1552
+ log5.warn("recipient is not subscribed for messages", {
1553
+ author,
1554
+ recipient
1555
+ }, {
1556
+ F: __dxlog_file5,
1557
+ L: 151,
1558
+ S: this,
1559
+ C: (f, a) => f(...a)
1560
+ });
1561
+ return;
1562
+ }
1563
+ if (remote._ctx.disposed) {
1564
+ log5.warn("recipient is disposed", {
1565
+ author,
1566
+ recipient
1567
+ }, {
1568
+ F: __dxlog_file5,
1569
+ L: 156,
1570
+ S: this,
1571
+ C: (f, a) => f(...a)
1572
+ });
1573
+ return;
1574
+ }
1575
+ remote._freezeTrigger.wait().then(() => {
1576
+ if (remote._ctx.disposed) {
1577
+ log5.warn("recipient is disposed", {
1578
+ author,
1579
+ recipient
1580
+ }, {
1581
+ F: __dxlog_file5,
1582
+ L: 164,
1583
+ S: this,
1584
+ C: (f, a) => f(...a)
1585
+ });
1586
+ return;
1587
+ }
1588
+ log5("receive message", {
1589
+ author,
1590
+ recipient,
1591
+ ...dec(payload)
1592
+ }, {
1593
+ F: __dxlog_file5,
1594
+ L: 168,
1595
+ S: this,
1596
+ C: (f, a) => f(...a)
1597
+ });
1598
+ remote.onMessage.emit({
1599
+ author,
1600
+ recipient,
1601
+ payload
1602
+ });
1603
+ }).catch((err) => {
1604
+ log5.error("error while waiting for freeze", {
1605
+ err
1606
+ }, {
1607
+ F: __dxlog_file5,
1608
+ L: 173,
1609
+ S: this,
1610
+ C: (f, a) => f(...a)
1611
+ });
1612
+ });
1613
+ }
1614
+ async subscribeMessages(peerInfo) {
1615
+ log5("subscribing", {
1616
+ peerInfo
1617
+ }, {
1618
+ F: __dxlog_file5,
1619
+ L: 178,
1620
+ S: this,
1621
+ C: (f, a) => f(...a)
1622
+ });
1623
+ this._context.connections.set(peerInfo, this);
1624
+ }
1625
+ async unsubscribeMessages(peerInfo) {
1626
+ log5("unsubscribing", {
1627
+ peerInfo
1628
+ }, {
1629
+ F: __dxlog_file5,
1630
+ L: 183,
1631
+ S: this,
1632
+ C: (f, a) => f(...a)
1633
+ });
1634
+ this._context.connections.delete(peerInfo);
1635
+ }
1636
+ freeze() {
1637
+ this._freezeTrigger.reset();
1638
+ }
1639
+ unfreeze() {
1640
+ this._freezeTrigger.wake();
1641
+ }
1642
+ };
1643
+ var dec = (payload) => {
1644
+ if (!payload.type_url.endsWith("ReliablePayload")) {
1645
+ return {};
1646
+ }
1647
+ const relPayload = schema3.getCodecForType("dxos.mesh.messaging.ReliablePayload").decode(payload.value);
1648
+ if (typeof relPayload?.payload?.data === "object") {
1649
+ return {
1650
+ payload: Object.keys(relPayload?.payload?.data)[0],
1651
+ sessionId: relPayload?.payload?.sessionId
1652
+ };
1653
+ }
1654
+ return {};
1655
+ };
1656
+
1657
+ // packages/core/mesh/messaging/src/signal-manager/websocket-signal-manager.ts
1658
+ import { Event as Event4, sleep as sleep2, synchronized } from "@dxos/async";
1659
+ import { LifecycleState, Resource as Resource2 } from "@dxos/context";
1660
+ import { invariant as invariant5 } from "@dxos/invariant";
1661
+ import { PublicKey as PublicKey6 } from "@dxos/keys";
1662
+ import { log as log6 } from "@dxos/log";
1663
+ import { RateLimitExceededError, TimeoutError as TimeoutError3, trace as trace8 } from "@dxos/protocols";
1664
+ import { BitField, safeAwaitAll as safeAwaitAll2 } from "@dxos/util";
1665
+
1666
+ // packages/core/mesh/messaging/src/signal-manager/websocket-signal-manager-monitor.ts
1667
+ import { trace as trace7 } from "@dxos/tracing";
1668
+ var WebsocketSignalManagerMonitor = class {
1669
+ recordRateLimitExceeded() {
1670
+ trace7.metrics.increment("dxos.mesh.signal.signal-manager.rate-limit-hit", 1);
1671
+ }
1672
+ recordServerFailure(params) {
1673
+ trace7.metrics.increment("dxos.mesh.signal.signal-manager.server-failure", 1, {
1674
+ tags: {
1675
+ server: params.serverName,
1676
+ restarted: params.willRestart
1677
+ }
1678
+ });
1679
+ }
1680
+ };
1681
+
1682
+ // packages/core/mesh/messaging/src/signal-manager/websocket-signal-manager.ts
1683
+ function _ts_decorate(decorators, target, key, desc) {
1684
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1685
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1686
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1687
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1688
+ }
1689
+ var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/websocket-signal-manager.ts";
1690
+ var MAX_SERVER_FAILURES = 5;
1691
+ var WSS_SIGNAL_SERVER_REBOOT_DELAY = 3e3;
1692
+ var WebsocketSignalManager = class extends Resource2 {
1693
+ constructor(_hosts, _getMetadata) {
1694
+ super();
1695
+ this._hosts = _hosts;
1696
+ this._getMetadata = _getMetadata;
1697
+ this._servers = /* @__PURE__ */ new Map();
1698
+ this._monitor = new WebsocketSignalManagerMonitor();
1699
+ this.failureCount = /* @__PURE__ */ new Map();
1700
+ this.statusChanged = new Event4();
1701
+ this.swarmEvent = new Event4();
1702
+ this.onMessage = new Event4();
1703
+ this._instanceId = PublicKey6.random().toHex();
1704
+ log6("Created WebsocketSignalManager", {
1705
+ hosts: this._hosts
1706
+ }, {
1707
+ F: __dxlog_file6,
1708
+ L: 54,
1709
+ S: this,
1710
+ C: (f, a) => f(...a)
1711
+ });
1712
+ for (const host of this._hosts) {
1713
+ if (this._servers.has(host.server)) {
1714
+ continue;
1715
+ }
1716
+ const server = new SignalClient(host.server, this._getMetadata);
1717
+ server.swarmEvent.on((data) => this.swarmEvent.emit(data));
1718
+ server.onMessage.on((data) => this.onMessage.emit(data));
1719
+ server.statusChanged.on(() => this.statusChanged.emit(this.getStatus()));
1720
+ this._servers.set(host.server, server);
1721
+ this.failureCount.set(host.server, 0);
1722
+ }
1723
+ this._failedServersBitfield = BitField.zeros(this._hosts.length);
1724
+ }
1725
+ async _open() {
1726
+ log6("open signal manager", {
1727
+ hosts: this._hosts
1728
+ }, {
1729
+ F: __dxlog_file6,
1730
+ L: 74,
1731
+ S: this,
1732
+ C: (f, a) => f(...a)
1733
+ });
1734
+ log6.trace("dxos.mesh.websocket-signal-manager.open", trace8.begin({
1735
+ id: this._instanceId
1736
+ }), {
1737
+ F: __dxlog_file6,
1738
+ L: 75,
1739
+ S: this,
1740
+ C: (f, a) => f(...a)
1741
+ });
1742
+ await safeAwaitAll2(this._servers.values(), (server) => server.open());
1743
+ log6.trace("dxos.mesh.websocket-signal-manager.open", trace8.end({
1744
+ id: this._instanceId
1745
+ }), {
1746
+ F: __dxlog_file6,
1747
+ L: 79,
1748
+ S: this,
1749
+ C: (f, a) => f(...a)
1750
+ });
1751
+ }
1752
+ async _close() {
1753
+ await safeAwaitAll2(this._servers.values(), (server) => server.close());
1754
+ }
1755
+ async restartServer(serverName) {
1756
+ log6("restarting server", {
1757
+ serverName
1758
+ }, {
1759
+ F: __dxlog_file6,
1760
+ L: 87,
1761
+ S: this,
1762
+ C: (f, a) => f(...a)
1763
+ });
1764
+ invariant5(this._lifecycleState === LifecycleState.OPEN, void 0, {
1765
+ F: __dxlog_file6,
1766
+ L: 88,
1767
+ S: this,
1768
+ A: [
1769
+ "this._lifecycleState === LifecycleState.OPEN",
1770
+ ""
1771
+ ]
1772
+ });
1773
+ const server = this._servers.get(serverName);
1774
+ invariant5(server, "server not found", {
1775
+ F: __dxlog_file6,
1776
+ L: 91,
1777
+ S: this,
1778
+ A: [
1779
+ "server",
1780
+ "'server not found'"
1781
+ ]
1782
+ });
1783
+ await server.close();
1784
+ await sleep2(WSS_SIGNAL_SERVER_REBOOT_DELAY);
1785
+ await server.open();
1786
+ }
1787
+ getStatus() {
1788
+ return Array.from(this._servers.values()).map((server) => server.getStatus());
1789
+ }
1790
+ async join({ topic, peer }) {
1791
+ log6("join", {
1792
+ topic,
1793
+ peer
1794
+ }, {
1795
+ F: __dxlog_file6,
1796
+ L: 104,
1797
+ S: this,
1798
+ C: (f, a) => f(...a)
1799
+ });
1800
+ invariant5(this._lifecycleState === LifecycleState.OPEN, void 0, {
1801
+ F: __dxlog_file6,
1802
+ L: 105,
1803
+ S: this,
1804
+ A: [
1805
+ "this._lifecycleState === LifecycleState.OPEN",
1806
+ ""
1807
+ ]
1808
+ });
1809
+ await this._forEachServer((server) => server.join({
1810
+ topic,
1811
+ peer
1812
+ }));
1813
+ }
1814
+ async leave({ topic, peer }) {
1815
+ log6("leaving", {
1816
+ topic,
1817
+ peer
1818
+ }, {
1819
+ F: __dxlog_file6,
1820
+ L: 111,
1821
+ S: this,
1822
+ C: (f, a) => f(...a)
1823
+ });
1824
+ invariant5(this._lifecycleState === LifecycleState.OPEN, void 0, {
1825
+ F: __dxlog_file6,
1826
+ L: 112,
1827
+ S: this,
1828
+ A: [
1829
+ "this._lifecycleState === LifecycleState.OPEN",
1830
+ ""
1831
+ ]
1832
+ });
1833
+ await this._forEachServer((server) => server.leave({
1834
+ topic,
1835
+ peer
1836
+ }));
1837
+ }
1838
+ async sendMessage({ author, recipient, payload }) {
1839
+ log6("signal", {
1840
+ recipient
1841
+ }, {
1842
+ F: __dxlog_file6,
1843
+ L: 117,
1844
+ S: this,
1845
+ C: (f, a) => f(...a)
1846
+ });
1847
+ invariant5(this._lifecycleState === LifecycleState.OPEN, void 0, {
1848
+ F: __dxlog_file6,
1849
+ L: 118,
1850
+ S: this,
1851
+ A: [
1852
+ "this._lifecycleState === LifecycleState.OPEN",
1853
+ ""
1854
+ ]
1855
+ });
1856
+ void this._forEachServer(async (server, serverName, index) => {
1857
+ void server.sendMessage({
1858
+ author,
1859
+ recipient,
1860
+ payload
1861
+ }).then(() => this._clearServerFailedFlag(serverName, index)).catch((err) => {
1862
+ if (err instanceof RateLimitExceededError) {
1863
+ log6.info("WSS rate limit exceeded", {
1864
+ err
1865
+ }, {
1866
+ F: __dxlog_file6,
1867
+ L: 126,
1868
+ S: this,
1869
+ C: (f, a) => f(...a)
1870
+ });
1871
+ this._monitor.recordRateLimitExceeded();
1872
+ } else if (err instanceof TimeoutError3 || err.constructor.name === "TimeoutError") {
1873
+ log6.info("WSS sendMessage timeout", {
1874
+ err
1875
+ }, {
1876
+ F: __dxlog_file6,
1877
+ L: 129,
1878
+ S: this,
1879
+ C: (f, a) => f(...a)
1880
+ });
1881
+ void this.checkServerFailure(serverName, index);
1882
+ } else {
1883
+ log6.warn(`error sending to ${serverName}`, {
1884
+ err
1885
+ }, {
1886
+ F: __dxlog_file6,
1887
+ L: 132,
1888
+ S: this,
1889
+ C: (f, a) => f(...a)
1890
+ });
1891
+ void this.checkServerFailure(serverName, index);
1892
+ }
1893
+ });
1894
+ });
1895
+ }
1896
+ async checkServerFailure(serverName, index) {
1897
+ const failureCount = this.failureCount.get(serverName) ?? 0;
1898
+ const isRestartRequired = failureCount > MAX_SERVER_FAILURES;
1899
+ this._monitor.recordServerFailure({
1900
+ serverName,
1901
+ willRestart: isRestartRequired
1902
+ });
1903
+ if (isRestartRequired) {
1904
+ if (!BitField.get(this._failedServersBitfield, index)) {
1905
+ log6.warn("too many failures for ws-server, restarting", {
1906
+ serverName,
1907
+ failureCount
1908
+ }, {
1909
+ F: __dxlog_file6,
1910
+ L: 146,
1911
+ S: this,
1912
+ C: (f, a) => f(...a)
1913
+ });
1914
+ BitField.set(this._failedServersBitfield, index, true);
1915
+ }
1916
+ await this.restartServer(serverName);
1917
+ this.failureCount.set(serverName, 0);
1918
+ return;
1919
+ }
1920
+ this.failureCount.set(serverName, (this.failureCount.get(serverName) ?? 0) + 1);
1921
+ }
1922
+ _clearServerFailedFlag(serverName, index) {
1923
+ if (BitField.get(this._failedServersBitfield, index)) {
1924
+ log6.info("server connection restored", {
1925
+ serverName
1926
+ }, {
1927
+ F: __dxlog_file6,
1928
+ L: 159,
1929
+ S: this,
1930
+ C: (f, a) => f(...a)
1931
+ });
1932
+ BitField.set(this._failedServersBitfield, index, false);
1933
+ this.failureCount.set(serverName, 0);
1934
+ }
1935
+ }
1936
+ async subscribeMessages(peer) {
1937
+ log6("subscribed for message stream", {
1938
+ peer
1939
+ }, {
1940
+ F: __dxlog_file6,
1941
+ L: 166,
1942
+ S: this,
1943
+ C: (f, a) => f(...a)
1944
+ });
1945
+ invariant5(this._lifecycleState === LifecycleState.OPEN, void 0, {
1946
+ F: __dxlog_file6,
1947
+ L: 167,
1948
+ S: this,
1949
+ A: [
1950
+ "this._lifecycleState === LifecycleState.OPEN",
1951
+ ""
1952
+ ]
1953
+ });
1954
+ await this._forEachServer(async (server) => server.subscribeMessages(peer));
1955
+ }
1956
+ async unsubscribeMessages(peer) {
1957
+ log6("subscribed for message stream", {
1958
+ peer
1959
+ }, {
1960
+ F: __dxlog_file6,
1961
+ L: 173,
1962
+ S: this,
1963
+ C: (f, a) => f(...a)
1964
+ });
1965
+ invariant5(this._lifecycleState === LifecycleState.OPEN, void 0, {
1966
+ F: __dxlog_file6,
1967
+ L: 174,
1968
+ S: this,
1969
+ A: [
1970
+ "this._lifecycleState === LifecycleState.OPEN",
1971
+ ""
1972
+ ]
1973
+ });
1974
+ await this._forEachServer(async (server) => server.unsubscribeMessages(peer));
1975
+ }
1976
+ async _forEachServer(fn) {
1977
+ return Promise.all(Array.from(this._servers.entries()).map(([serverName, server], idx) => fn(server, serverName, idx)));
1978
+ }
1979
+ };
1980
+ _ts_decorate([
1981
+ synchronized
1982
+ ], WebsocketSignalManager.prototype, "join", null);
1983
+ _ts_decorate([
1984
+ synchronized
1985
+ ], WebsocketSignalManager.prototype, "leave", null);
1986
+ _ts_decorate([
1987
+ synchronized
1988
+ ], WebsocketSignalManager.prototype, "checkServerFailure", null);
1989
+
1990
+ // packages/core/mesh/messaging/src/signal-manager/edge-signal-manager.ts
1991
+ import { Event as Event5, scheduleMicroTask } from "@dxos/async";
1992
+ import { Resource as Resource3 } from "@dxos/context";
1993
+ import { protocol } from "@dxos/edge-client";
1994
+ import { invariant as invariant6 } from "@dxos/invariant";
1995
+ import { PublicKey as PublicKey7 } from "@dxos/keys";
1996
+ import { log as log7 } from "@dxos/log";
1997
+ import { EdgeService } from "@dxos/protocols";
1998
+ import { bufWkt } from "@dxos/protocols/buf";
1999
+ import { SwarmRequestSchema, SwarmRequest_Action as SwarmRequestAction, SwarmResponseSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
2000
+ import { ComplexMap as ComplexMap4, ComplexSet as ComplexSet4 } from "@dxos/util";
2001
+ var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/edge-signal-manager.ts";
2002
+ var EdgeSignalManager = class extends Resource3 {
2003
+ constructor({ edgeConnection }) {
2004
+ super();
2005
+ this.swarmEvent = new Event5();
2006
+ this.onMessage = new Event5();
2007
+ /**
2008
+ * swarm key -> peerKeys in the swarm
2009
+ */
2010
+ // TODO(mykola): This class should not contain swarm state. Temporary before network-manager API changes to accept list of peers.
2011
+ this._swarmPeers = new ComplexMap4(PublicKey7.hash);
2012
+ this._edgeConnection = edgeConnection;
2013
+ }
2014
+ async _open() {
2015
+ this._ctx.onDispose(this._edgeConnection.onMessage((message) => this._onMessage(message)));
2016
+ this._ctx.onDispose(this._edgeConnection.onReconnected(() => {
2017
+ scheduleMicroTask(this._ctx, () => this._rejoinAllSwarms());
2018
+ }));
2019
+ }
2020
+ /**
2021
+ * Warning: PeerInfo is inferred from edgeConnection.
2022
+ */
2023
+ async join({ topic, peer }) {
2024
+ if (!this._matchSelfPeerInfo(peer)) {
2025
+ log7.warn("ignoring peer info on join request", {
2026
+ peer,
2027
+ expected: {
2028
+ peerKey: this._edgeConnection.peerKey,
2029
+ identityKey: this._edgeConnection.identityKey
2030
+ }
2031
+ }, {
2032
+ F: __dxlog_file7,
2033
+ L: 56,
2034
+ S: this,
2035
+ C: (f, a) => f(...a)
2036
+ });
2037
+ }
2038
+ this._swarmPeers.set(topic, new ComplexSet4(PeerInfoHash));
2039
+ await this._edgeConnection.send(protocol.createMessage(SwarmRequestSchema, {
2040
+ serviceId: EdgeService.SWARM_SERVICE_ID,
2041
+ source: createMessageSource(topic, peer),
2042
+ payload: {
2043
+ action: SwarmRequestAction.JOIN,
2044
+ swarmKeys: [
2045
+ topic.toHex()
2046
+ ]
2047
+ }
2048
+ }));
2049
+ }
2050
+ async leave({ topic, peer }) {
2051
+ this._swarmPeers.delete(topic);
2052
+ await this._edgeConnection.send(protocol.createMessage(SwarmRequestSchema, {
2053
+ serviceId: EdgeService.SWARM_SERVICE_ID,
2054
+ source: createMessageSource(topic, peer),
2055
+ payload: {
2056
+ action: SwarmRequestAction.LEAVE,
2057
+ swarmKeys: [
2058
+ topic.toHex()
2059
+ ]
2060
+ }
2061
+ }));
2062
+ }
2063
+ async sendMessage(message) {
2064
+ if (!this._matchSelfPeerInfo(message.author)) {
2065
+ log7.warn("ignoring author on send request", {
2066
+ author: message.author,
2067
+ expected: {
2068
+ peerKey: this._edgeConnection.peerKey,
2069
+ identityKey: this._edgeConnection.identityKey
2070
+ }
2071
+ }, {
2072
+ F: __dxlog_file7,
2073
+ L: 89,
2074
+ S: this,
2075
+ C: (f, a) => f(...a)
2076
+ });
2077
+ }
2078
+ await this._edgeConnection.send(protocol.createMessage(bufWkt.AnySchema, {
2079
+ serviceId: EdgeService.SIGNAL_SERVICE_ID,
2080
+ source: message.author,
2081
+ target: [
2082
+ message.recipient
2083
+ ],
2084
+ payload: {
2085
+ typeUrl: message.payload.type_url,
2086
+ value: message.payload.value
2087
+ }
2088
+ }));
2089
+ }
2090
+ async subscribeMessages(peerInfo) {
2091
+ }
2092
+ async unsubscribeMessages(peerInfo) {
2093
+ }
2094
+ _onMessage(message) {
2095
+ switch (message.serviceId) {
2096
+ case EdgeService.SWARM_SERVICE_ID: {
2097
+ this._processSwarmResponse(message);
2098
+ break;
2099
+ }
2100
+ case EdgeService.SIGNAL_SERVICE_ID: {
2101
+ this._processMessage(message);
2102
+ }
2103
+ }
2104
+ }
2105
+ _processSwarmResponse(message) {
2106
+ invariant6(protocol.getPayloadType(message) === SwarmResponseSchema.typeName, "Wrong payload type", {
2107
+ F: __dxlog_file7,
2108
+ L: 126,
2109
+ S: this,
2110
+ A: [
2111
+ "protocol.getPayloadType(message) === SwarmResponseSchema.typeName",
2112
+ "'Wrong payload type'"
2113
+ ]
2114
+ });
2115
+ const payload = protocol.getPayload(message, SwarmResponseSchema);
2116
+ const topic = PublicKey7.from(payload.swarmKey);
2117
+ if (!this._swarmPeers.has(topic)) {
2118
+ log7.warn("Received message from wrong topic", {
2119
+ topic
2120
+ }, {
2121
+ F: __dxlog_file7,
2122
+ L: 130,
2123
+ S: this,
2124
+ C: (f, a) => f(...a)
2125
+ });
2126
+ return;
2127
+ }
2128
+ const oldPeers = this._swarmPeers.get(topic);
2129
+ const timestamp = message.timestamp ? new Date(Date.parse(message.timestamp)) : /* @__PURE__ */ new Date();
2130
+ const newPeers = new ComplexSet4(PeerInfoHash, payload.peers);
2131
+ for (const peer of newPeers) {
2132
+ if (oldPeers.has(peer)) {
2133
+ continue;
2134
+ }
2135
+ this.swarmEvent.emit({
2136
+ topic,
2137
+ peerAvailable: {
2138
+ peer,
2139
+ since: timestamp
2140
+ }
2141
+ });
2142
+ }
2143
+ for (const peer of oldPeers) {
2144
+ if (newPeers.has(peer)) {
2145
+ continue;
2146
+ }
2147
+ this.swarmEvent.emit({
2148
+ topic,
2149
+ peerLeft: {
2150
+ peer
2151
+ }
2152
+ });
2153
+ }
2154
+ this._swarmPeers.set(topic, newPeers);
2155
+ }
2156
+ _processMessage(message) {
2157
+ invariant6(protocol.getPayloadType(message) === bufWkt.AnySchema.typeName, "Wrong payload type", {
2158
+ F: __dxlog_file7,
2159
+ L: 163,
2160
+ S: this,
2161
+ A: [
2162
+ "protocol.getPayloadType(message) === bufWkt.AnySchema.typeName",
2163
+ "'Wrong payload type'"
2164
+ ]
2165
+ });
2166
+ const payload = protocol.getPayload(message, bufWkt.AnySchema);
2167
+ invariant6(message.source, "source is missing", {
2168
+ F: __dxlog_file7,
2169
+ L: 165,
2170
+ S: this,
2171
+ A: [
2172
+ "message.source",
2173
+ "'source is missing'"
2174
+ ]
2175
+ });
2176
+ invariant6(message.target, "target is missing", {
2177
+ F: __dxlog_file7,
2178
+ L: 166,
2179
+ S: this,
2180
+ A: [
2181
+ "message.target",
2182
+ "'target is missing'"
2183
+ ]
2184
+ });
2185
+ invariant6(message.target.length === 1, "target should have exactly one item", {
2186
+ F: __dxlog_file7,
2187
+ L: 167,
2188
+ S: this,
2189
+ A: [
2190
+ "message.target.length === 1",
2191
+ "'target should have exactly one item'"
2192
+ ]
2193
+ });
2194
+ this.onMessage.emit({
2195
+ author: message.source,
2196
+ recipient: message.target[0],
2197
+ payload: {
2198
+ type_url: payload.typeUrl,
2199
+ value: payload.value
2200
+ }
2201
+ });
2202
+ }
2203
+ _matchSelfPeerInfo(peer) {
2204
+ return peer && (peer.peerKey === this._edgeConnection.peerKey || peer.identityKey === this._edgeConnection.identityKey);
2205
+ }
2206
+ async _rejoinAllSwarms() {
2207
+ log7("rejoin swarms", {
2208
+ swarms: Array.from(this._swarmPeers.keys())
2209
+ }, {
2210
+ F: __dxlog_file7,
2211
+ L: 186,
2212
+ S: this,
2213
+ C: (f, a) => f(...a)
2214
+ });
2215
+ for (const topic of this._swarmPeers.keys()) {
2216
+ await this.join({
2217
+ topic,
2218
+ peer: {
2219
+ peerKey: this._edgeConnection.peerKey,
2220
+ identityKey: this._edgeConnection.identityKey
2221
+ }
2222
+ });
2223
+ }
2224
+ }
2225
+ };
2226
+ var createMessageSource = (topic, peerInfo) => {
2227
+ return {
2228
+ swarmKey: topic.toHex(),
2229
+ identityKey: peerInfo.identityKey,
2230
+ peerKey: peerInfo.peerKey
2231
+ };
2232
+ };
2233
+
2234
+ // packages/core/mesh/messaging/src/signal-manager/utils.ts
2235
+ import { invariant as invariant7 } from "@dxos/invariant";
2236
+ import { log as log8 } from "@dxos/log";
2237
+ import { DeviceKind } from "@dxos/protocols/proto/dxos/client/services";
2238
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/utils.ts";
2239
+ var setIdentityTags = ({ identityService, devicesService, setTag }) => {
2240
+ identityService.queryIdentity().subscribe((idqr) => {
2241
+ if (!idqr?.identity?.identityKey) {
2242
+ log8("empty response from identity service", {
2243
+ idqr
2244
+ }, {
2245
+ F: __dxlog_file8,
2246
+ L: 21,
2247
+ S: void 0,
2248
+ C: (f, a) => f(...a)
2249
+ });
2250
+ return;
2251
+ }
2252
+ setTag("identityKey", idqr.identity.identityKey.truncate());
2253
+ });
2254
+ devicesService.queryDevices().subscribe((dqr) => {
2255
+ if (!dqr || !dqr.devices || dqr.devices.length === 0) {
2256
+ log8("empty response from device service", {
2257
+ device: dqr
2258
+ }, {
2259
+ F: __dxlog_file8,
2260
+ L: 30,
2261
+ S: void 0,
2262
+ C: (f, a) => f(...a)
2263
+ });
2264
+ return;
2265
+ }
2266
+ invariant7(dqr, "empty response from device service", {
2267
+ F: __dxlog_file8,
2268
+ L: 33,
2269
+ S: void 0,
2270
+ A: [
2271
+ "dqr",
2272
+ "'empty response from device service'"
2273
+ ]
2274
+ });
2275
+ const thisDevice = dqr.devices.find((device) => device.kind === DeviceKind.CURRENT);
2276
+ if (!thisDevice) {
2277
+ log8("no current device", {
2278
+ device: dqr
2279
+ }, {
2280
+ F: __dxlog_file8,
2281
+ L: 37,
2282
+ S: void 0,
2283
+ C: (f, a) => f(...a)
2284
+ });
2285
+ return;
2286
+ }
2287
+ setTag("deviceKey", thisDevice.deviceKey.truncate());
2288
+ });
2289
+ };
2290
+
2291
+ export {
2292
+ Messenger,
2293
+ SignalClient,
2294
+ PeerInfoHash,
2295
+ MemorySignalManagerContext,
2296
+ MemorySignalManager,
2297
+ WebsocketSignalManager,
2298
+ EdgeSignalManager,
2299
+ setIdentityTags
2300
+ };
2301
+ //# sourceMappingURL=chunk-U5OG65N2.mjs.map