@dxos/messaging 0.6.11 → 0.6.12-main.5cc132e

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 (32) hide show
  1. package/dist/lib/browser/meta.json +1 -1
  2. package/dist/lib/node-esm/index.mjs +2290 -0
  3. package/dist/lib/node-esm/index.mjs.map +7 -0
  4. package/dist/lib/node-esm/meta.json +1 -0
  5. package/dist/types/src/messenger.blueprint-test.d.ts.map +1 -1
  6. package/dist/types/src/messenger.node.test.d.ts +2 -0
  7. package/dist/types/src/messenger.node.test.d.ts.map +1 -0
  8. package/dist/types/src/signal-client/signal-client.node.test.d.ts +2 -0
  9. package/dist/types/src/signal-client/signal-client.node.test.d.ts.map +1 -0
  10. package/dist/types/src/signal-client/signal-rpc-client.node.test.d.ts +2 -0
  11. package/dist/types/src/signal-client/signal-rpc-client.node.test.d.ts.map +1 -0
  12. package/dist/types/src/signal-manager/edge-signal-manager.node.test.d.ts +2 -0
  13. package/dist/types/src/signal-manager/edge-signal-manager.node.test.d.ts.map +1 -0
  14. package/dist/types/src/signal-manager/websocket-signal-manager.node.test.d.ts +2 -0
  15. package/dist/types/src/signal-manager/websocket-signal-manager.node.test.d.ts.map +1 -0
  16. package/package.json +18 -19
  17. package/src/messenger.blueprint-test.ts +23 -28
  18. package/src/{messenger.test.ts → messenger.node.test.ts} +6 -4
  19. package/src/signal-client/{signal-client.test.ts → signal-client.node.test.ts} +9 -8
  20. package/src/signal-client/{signal-rpc-client.test.ts → signal-rpc-client.node.test.ts} +8 -13
  21. package/src/signal-manager/{edge-signal-manager.test.ts → edge-signal-manager.node.test.ts} +7 -4
  22. package/src/signal-manager/{websocket-signal-manager.test.ts → websocket-signal-manager.node.test.ts} +12 -30
  23. package/dist/types/src/messenger.test.d.ts +0 -2
  24. package/dist/types/src/messenger.test.d.ts.map +0 -1
  25. package/dist/types/src/signal-client/signal-client.test.d.ts +0 -2
  26. package/dist/types/src/signal-client/signal-client.test.d.ts.map +0 -1
  27. package/dist/types/src/signal-client/signal-rpc-client.test.d.ts +0 -2
  28. package/dist/types/src/signal-client/signal-rpc-client.test.d.ts.map +0 -1
  29. package/dist/types/src/signal-manager/edge-signal-manager.test.d.ts +0 -2
  30. package/dist/types/src/signal-manager/edge-signal-manager.test.d.ts.map +0 -1
  31. package/dist/types/src/signal-manager/websocket-signal-manager.test.d.ts +0 -2
  32. package/dist/types/src/signal-manager/websocket-signal-manager.test.d.ts.map +0 -1
@@ -0,0 +1,2290 @@
1
+ // packages/core/mesh/messaging/src/messenger.ts
2
+ import { TimeoutError, scheduleExponentialBackoffTaskInterval, scheduleTask, scheduleTaskInterval } from "@dxos/async";
3
+ import { Context } from "@dxos/context";
4
+ import { invariant } from "@dxos/invariant";
5
+ import { PublicKey } from "@dxos/keys";
6
+ import { log } from "@dxos/log";
7
+ import { TimeoutError as ProtocolTimeoutError, trace as trace2 } from "@dxos/protocols";
8
+ import { schema } from "@dxos/protocols/proto";
9
+ import { ComplexMap, ComplexSet } from "@dxos/util";
10
+
11
+ // packages/core/mesh/messaging/src/messenger-monitor.ts
12
+ import { trace } from "@dxos/tracing";
13
+ var MessengerMonitor = class {
14
+ recordMessageAckFailed() {
15
+ trace.metrics.increment("dxos.mesh.signal.messenger.failed-ack", 1);
16
+ }
17
+ recordReliableMessage(params) {
18
+ trace.metrics.increment("dxos.mesh.signal.messenger.reliable-send", 1, {
19
+ tags: {
20
+ success: params.sent,
21
+ attempts: params.sendAttempts
22
+ }
23
+ });
24
+ }
25
+ };
26
+
27
+ // packages/core/mesh/messaging/src/timeouts.ts
28
+ var MESSAGE_TIMEOUT = 1e4;
29
+
30
+ // packages/core/mesh/messaging/src/messenger.ts
31
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/messenger.ts";
32
+ var ReliablePayload = schema.getCodecForType("dxos.mesh.messaging.ReliablePayload");
33
+ var Acknowledgement = schema.getCodecForType("dxos.mesh.messaging.Acknowledgement");
34
+ var RECEIVED_MESSAGES_GC_INTERVAL = 12e4;
35
+ var Messenger = class {
36
+ constructor({ signalManager, retryDelay = 300 }) {
37
+ this._monitor = new MessengerMonitor();
38
+ // { peerId, payloadType } => listeners set
39
+ this._listeners = new ComplexMap(({ peerId, payloadType }) => peerId + payloadType);
40
+ // peerId => listeners set
41
+ this._defaultListeners = /* @__PURE__ */ new Map();
42
+ this._onAckCallbacks = new ComplexMap(PublicKey.hash);
43
+ this._receivedMessages = new ComplexSet(PublicKey.hash);
44
+ /**
45
+ * Keys scheduled to be cleared from _receivedMessages on the next iteration.
46
+ */
47
+ this._toClear = new ComplexSet(PublicKey.hash);
48
+ this._closed = true;
49
+ this._signalManager = signalManager;
50
+ this._retryDelay = retryDelay;
51
+ this.open();
52
+ }
53
+ open() {
54
+ if (!this._closed) {
55
+ return;
56
+ }
57
+ const traceId = PublicKey.random().toHex();
58
+ log.trace("dxos.mesh.messenger.open", trace2.begin({
59
+ id: traceId
60
+ }), {
61
+ F: __dxlog_file,
62
+ L: 72,
63
+ S: this,
64
+ C: (f, a) => f(...a)
65
+ });
66
+ this._ctx = new Context({
67
+ onError: (err) => log.catch(err, void 0, {
68
+ F: __dxlog_file,
69
+ L: 74,
70
+ S: this,
71
+ C: (f, a) => f(...a)
72
+ })
73
+ }, {
74
+ F: __dxlog_file,
75
+ L: 73
76
+ });
77
+ this._ctx.onDispose(this._signalManager.onMessage.on(async (message) => {
78
+ log("received message", {
79
+ from: message.author
80
+ }, {
81
+ F: __dxlog_file,
82
+ L: 78,
83
+ S: this,
84
+ C: (f, a) => f(...a)
85
+ });
86
+ await this._handleMessage(message);
87
+ }));
88
+ scheduleTaskInterval(this._ctx, async () => {
89
+ this._performGc();
90
+ }, RECEIVED_MESSAGES_GC_INTERVAL);
91
+ this._closed = false;
92
+ log.trace("dxos.mesh.messenger.open", trace2.end({
93
+ id: traceId
94
+ }), {
95
+ F: __dxlog_file,
96
+ L: 93,
97
+ S: this,
98
+ C: (f, a) => f(...a)
99
+ });
100
+ }
101
+ async close() {
102
+ if (this._closed) {
103
+ return;
104
+ }
105
+ this._closed = true;
106
+ await this._ctx.dispose();
107
+ }
108
+ async sendMessage({ author, recipient, payload }) {
109
+ invariant(!this._closed, "Closed", {
110
+ F: __dxlog_file,
111
+ L: 105,
112
+ S: this,
113
+ A: [
114
+ "!this._closed",
115
+ "'Closed'"
116
+ ]
117
+ });
118
+ const messageContext = this._ctx.derive();
119
+ const reliablePayload = {
120
+ messageId: PublicKey.random(),
121
+ payload
122
+ };
123
+ invariant(!this._onAckCallbacks.has(reliablePayload.messageId), void 0, {
124
+ F: __dxlog_file,
125
+ L: 112,
126
+ S: this,
127
+ A: [
128
+ "!this._onAckCallbacks.has(reliablePayload.messageId!)",
129
+ ""
130
+ ]
131
+ });
132
+ log("send message", {
133
+ messageId: reliablePayload.messageId,
134
+ author,
135
+ recipient
136
+ }, {
137
+ F: __dxlog_file,
138
+ L: 113,
139
+ S: this,
140
+ C: (f, a) => f(...a)
141
+ });
142
+ let messageReceived;
143
+ let timeoutHit;
144
+ let sendAttempts = 0;
145
+ const promise = new Promise((resolve, reject) => {
146
+ messageReceived = resolve;
147
+ timeoutHit = reject;
148
+ });
149
+ scheduleExponentialBackoffTaskInterval(messageContext, async () => {
150
+ log("retrying message", {
151
+ messageId: reliablePayload.messageId
152
+ }, {
153
+ F: __dxlog_file,
154
+ L: 128,
155
+ S: this,
156
+ C: (f, a) => f(...a)
157
+ });
158
+ sendAttempts++;
159
+ await this._encodeAndSend({
160
+ author,
161
+ recipient,
162
+ reliablePayload
163
+ }).catch((err) => log("failed to send message", {
164
+ err
165
+ }, {
166
+ F: __dxlog_file,
167
+ L: 131,
168
+ S: this,
169
+ C: (f, a) => f(...a)
170
+ }));
171
+ }, this._retryDelay);
172
+ scheduleTask(messageContext, () => {
173
+ log("message not delivered", {
174
+ messageId: reliablePayload.messageId
175
+ }, {
176
+ F: __dxlog_file,
177
+ L: 140,
178
+ S: this,
179
+ C: (f, a) => f(...a)
180
+ });
181
+ this._onAckCallbacks.delete(reliablePayload.messageId);
182
+ timeoutHit(new ProtocolTimeoutError("signaling message not delivered", new TimeoutError(MESSAGE_TIMEOUT, "Message not delivered")));
183
+ void messageContext.dispose();
184
+ this._monitor.recordReliableMessage({
185
+ sendAttempts,
186
+ sent: false
187
+ });
188
+ }, MESSAGE_TIMEOUT);
189
+ this._onAckCallbacks.set(reliablePayload.messageId, () => {
190
+ messageReceived();
191
+ this._onAckCallbacks.delete(reliablePayload.messageId);
192
+ void messageContext.dispose();
193
+ this._monitor.recordReliableMessage({
194
+ sendAttempts,
195
+ sent: true
196
+ });
197
+ });
198
+ await this._encodeAndSend({
199
+ author,
200
+ recipient,
201
+ reliablePayload
202
+ });
203
+ return promise;
204
+ }
205
+ /**
206
+ * Subscribes onMessage function to messages that contains payload with payloadType.
207
+ * @param payloadType if not specified, onMessage will be subscribed to all types of messages.
208
+ */
209
+ async listen({ peer, payloadType, onMessage }) {
210
+ invariant(!this._closed, "Closed", {
211
+ F: __dxlog_file,
212
+ L: 178,
213
+ S: this,
214
+ A: [
215
+ "!this._closed",
216
+ "'Closed'"
217
+ ]
218
+ });
219
+ await this._signalManager.subscribeMessages(peer);
220
+ let listeners;
221
+ invariant(peer.peerKey, "Peer key is required", {
222
+ F: __dxlog_file,
223
+ L: 182,
224
+ S: this,
225
+ A: [
226
+ "peer.peerKey",
227
+ "'Peer key is required'"
228
+ ]
229
+ });
230
+ if (!payloadType) {
231
+ listeners = this._defaultListeners.get(peer.peerKey);
232
+ if (!listeners) {
233
+ listeners = /* @__PURE__ */ new Set();
234
+ this._defaultListeners.set(peer.peerKey, listeners);
235
+ }
236
+ } else {
237
+ listeners = this._listeners.get({
238
+ peerId: peer.peerKey,
239
+ payloadType
240
+ });
241
+ if (!listeners) {
242
+ listeners = /* @__PURE__ */ new Set();
243
+ this._listeners.set({
244
+ peerId: peer.peerKey,
245
+ payloadType
246
+ }, listeners);
247
+ }
248
+ }
249
+ listeners.add(onMessage);
250
+ return {
251
+ unsubscribe: async () => {
252
+ listeners.delete(onMessage);
253
+ }
254
+ };
255
+ }
256
+ async _encodeAndSend({ author, recipient, reliablePayload }) {
257
+ await this._signalManager.sendMessage({
258
+ author,
259
+ recipient,
260
+ payload: {
261
+ type_url: "dxos.mesh.messaging.ReliablePayload",
262
+ value: ReliablePayload.encode(reliablePayload, {
263
+ preserveAny: true
264
+ })
265
+ }
266
+ });
267
+ }
268
+ async _handleMessage(message) {
269
+ switch (message.payload.type_url) {
270
+ case "dxos.mesh.messaging.ReliablePayload": {
271
+ await this._handleReliablePayload(message);
272
+ break;
273
+ }
274
+ case "dxos.mesh.messaging.Acknowledgement": {
275
+ await this._handleAcknowledgement({
276
+ payload: message.payload
277
+ });
278
+ break;
279
+ }
280
+ }
281
+ }
282
+ async _handleReliablePayload({ author, recipient, payload }) {
283
+ invariant(payload.type_url === "dxos.mesh.messaging.ReliablePayload", void 0, {
284
+ F: __dxlog_file,
285
+ L: 240,
286
+ S: this,
287
+ A: [
288
+ "payload.type_url === 'dxos.mesh.messaging.ReliablePayload'",
289
+ ""
290
+ ]
291
+ });
292
+ const reliablePayload = ReliablePayload.decode(payload.value, {
293
+ preserveAny: true
294
+ });
295
+ log("handling message", {
296
+ messageId: reliablePayload.messageId
297
+ }, {
298
+ F: __dxlog_file,
299
+ L: 243,
300
+ S: this,
301
+ C: (f, a) => f(...a)
302
+ });
303
+ try {
304
+ await this._sendAcknowledgement({
305
+ author,
306
+ recipient,
307
+ messageId: reliablePayload.messageId
308
+ });
309
+ } catch (err) {
310
+ this._monitor.recordMessageAckFailed();
311
+ throw err;
312
+ }
313
+ if (this._receivedMessages.has(reliablePayload.messageId)) {
314
+ return;
315
+ }
316
+ this._receivedMessages.add(reliablePayload.messageId);
317
+ await this._callListeners({
318
+ author,
319
+ recipient,
320
+ payload: reliablePayload.payload
321
+ });
322
+ }
323
+ async _handleAcknowledgement({ payload }) {
324
+ invariant(payload.type_url === "dxos.mesh.messaging.Acknowledgement", void 0, {
325
+ F: __dxlog_file,
326
+ L: 271,
327
+ S: this,
328
+ A: [
329
+ "payload.type_url === 'dxos.mesh.messaging.Acknowledgement'",
330
+ ""
331
+ ]
332
+ });
333
+ this._onAckCallbacks.get(Acknowledgement.decode(payload.value).messageId)?.();
334
+ }
335
+ async _sendAcknowledgement({ author, recipient, messageId }) {
336
+ log("sending ACK", {
337
+ messageId,
338
+ from: recipient,
339
+ to: author
340
+ }, {
341
+ F: __dxlog_file,
342
+ L: 284,
343
+ S: this,
344
+ C: (f, a) => f(...a)
345
+ });
346
+ await this._signalManager.sendMessage({
347
+ author: recipient,
348
+ recipient: author,
349
+ payload: {
350
+ type_url: "dxos.mesh.messaging.Acknowledgement",
351
+ value: Acknowledgement.encode({
352
+ messageId
353
+ })
354
+ }
355
+ });
356
+ }
357
+ async _callListeners(message) {
358
+ {
359
+ invariant(message.recipient.peerKey, "Peer key is required", {
360
+ F: __dxlog_file,
361
+ L: 298,
362
+ S: this,
363
+ A: [
364
+ "message.recipient.peerKey",
365
+ "'Peer key is required'"
366
+ ]
367
+ });
368
+ const defaultListenerMap = this._defaultListeners.get(message.recipient.peerKey);
369
+ if (defaultListenerMap) {
370
+ for (const listener of defaultListenerMap) {
371
+ await listener(message);
372
+ }
373
+ }
374
+ }
375
+ {
376
+ const listenerMap = this._listeners.get({
377
+ peerId: message.recipient.peerKey,
378
+ payloadType: message.payload.type_url
379
+ });
380
+ if (listenerMap) {
381
+ for (const listener of listenerMap) {
382
+ await listener(message);
383
+ }
384
+ }
385
+ }
386
+ }
387
+ _performGc() {
388
+ const start = performance.now();
389
+ for (const key of this._toClear.keys()) {
390
+ this._receivedMessages.delete(key);
391
+ }
392
+ this._toClear.clear();
393
+ for (const key of this._receivedMessages.keys()) {
394
+ this._toClear.add(key);
395
+ }
396
+ const elapsed = performance.now() - start;
397
+ if (elapsed > 100) {
398
+ log.warn("GC took too long", {
399
+ elapsed
400
+ }, {
401
+ F: __dxlog_file,
402
+ L: 333,
403
+ S: this,
404
+ C: (f, a) => f(...a)
405
+ });
406
+ }
407
+ }
408
+ };
409
+
410
+ // packages/core/mesh/messaging/src/signal-client/signal-client.ts
411
+ import { DeferredTask, Event as Event2, Trigger as Trigger2, scheduleTask as scheduleTask2, scheduleTaskInterval as scheduleTaskInterval3, sleep } from "@dxos/async";
412
+ import { cancelWithContext as cancelWithContext2, Resource } from "@dxos/context";
413
+ import { invariant as invariant3 } from "@dxos/invariant";
414
+ import { PublicKey as PublicKey4 } from "@dxos/keys";
415
+ import { log as log4 } from "@dxos/log";
416
+ import { trace as trace6 } from "@dxos/protocols";
417
+ import { SignalState } from "@dxos/protocols/proto/dxos/mesh/signal";
418
+
419
+ // packages/core/mesh/messaging/src/signal-client/signal-client-monitor.ts
420
+ import { trace as trace3 } from "@dxos/tracing";
421
+ var SignalClientMonitor = class {
422
+ constructor() {
423
+ this._performance = {
424
+ sentMessages: 0,
425
+ receivedMessages: 0,
426
+ reconnectCounter: 0,
427
+ joinCounter: 0,
428
+ leaveCounter: 0
429
+ };
430
+ /**
431
+ * Timestamp of when the connection attempt was began.
432
+ */
433
+ this._connectionStarted = /* @__PURE__ */ new Date();
434
+ /**
435
+ * Timestamp of last state change.
436
+ */
437
+ this._lastStateChange = /* @__PURE__ */ new Date();
438
+ }
439
+ getRecordedTimestamps() {
440
+ return {
441
+ connectionStarted: this._connectionStarted,
442
+ lastStateChange: this._lastStateChange
443
+ };
444
+ }
445
+ recordStateChangeTime() {
446
+ this._lastStateChange = /* @__PURE__ */ new Date();
447
+ }
448
+ recordConnectionStartTime() {
449
+ this._connectionStarted = /* @__PURE__ */ new Date();
450
+ }
451
+ recordReconnect(params) {
452
+ this._performance.reconnectCounter++;
453
+ trace3.metrics.increment("dxos.mesh.signal.signal-client.reconnect", 1, {
454
+ tags: {
455
+ success: params.success
456
+ }
457
+ });
458
+ }
459
+ recordJoin() {
460
+ this._performance.joinCounter++;
461
+ }
462
+ recordLeave() {
463
+ this._performance.leaveCounter++;
464
+ }
465
+ recordMessageReceived(message) {
466
+ this._performance.receivedMessages++;
467
+ trace3.metrics.increment("dxos.mesh.signal.signal-client.received-total", 1, {
468
+ tags: createIdentityTags(message)
469
+ });
470
+ trace3.metrics.distribution("dxos.mesh.signal.signal-client.bytes-in", getByteCount(message), {
471
+ tags: createIdentityTags(message)
472
+ });
473
+ }
474
+ async recordMessageSending(message, sendMessage) {
475
+ this._performance.sentMessages++;
476
+ const tags = createIdentityTags(message);
477
+ let success = true;
478
+ try {
479
+ const reqStart = Date.now();
480
+ await sendMessage();
481
+ const reqDuration = Date.now() - reqStart;
482
+ trace3.metrics.distribution("dxos.mesh.signal.signal-client.send-duration", reqDuration, {
483
+ tags
484
+ });
485
+ trace3.metrics.distribution("dxos.mesh.signal.signal-client.bytes-out", getByteCount(message), {
486
+ tags
487
+ });
488
+ } catch (err) {
489
+ success = false;
490
+ }
491
+ trace3.metrics.increment("dxos.mesh.signal.signal-client.sent-total", 1, {
492
+ tags: {
493
+ ...tags,
494
+ success
495
+ }
496
+ });
497
+ }
498
+ recordStreamCloseErrors(count) {
499
+ trace3.metrics.increment("dxos.mesh.signal.signal-client.stream-close-errors", count);
500
+ }
501
+ recordReconciliation(params) {
502
+ trace3.metrics.increment("dxos.mesh.signal.signal-client.reconciliation", 1, {
503
+ tags: {
504
+ success: params.success
505
+ }
506
+ });
507
+ }
508
+ };
509
+ var getByteCount = (message) => {
510
+ return message.author.peerKey.length + message.recipient.peerKey.length + message.payload.type_url.length + message.payload.value.length;
511
+ };
512
+ var createIdentityTags = (message) => {
513
+ return {
514
+ peer: message.author.peerKey
515
+ };
516
+ };
517
+
518
+ // packages/core/mesh/messaging/src/signal-client/signal-local-state.ts
519
+ import { asyncTimeout, Event } from "@dxos/async";
520
+ import { cancelWithContext } from "@dxos/context";
521
+ import { PublicKey as PublicKey2 } from "@dxos/keys";
522
+ import { log as log2 } from "@dxos/log";
523
+ import { ComplexMap as ComplexMap2, ComplexSet as ComplexSet2, safeAwaitAll } from "@dxos/util";
524
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-local-state.ts";
525
+ var SignalLocalState = class {
526
+ constructor(_onMessage, _onSwarmEvent) {
527
+ this._onMessage = _onMessage;
528
+ this._onSwarmEvent = _onSwarmEvent;
529
+ this._swarmStreams = new ComplexMap2(({ topic, peerId }) => topic.toHex() + peerId.toHex());
530
+ this._joinedTopics = new ComplexSet2(({ topic, peerId }) => topic.toHex() + peerId.toHex());
531
+ this._subscribedMessages = new ComplexSet2(({ peerId }) => peerId.toHex());
532
+ this.messageStreams = new ComplexMap2((key) => key.toHex());
533
+ this.reconciled = new Event();
534
+ }
535
+ async safeCloseStreams() {
536
+ const streams = [
537
+ ...this._swarmStreams.values()
538
+ ].concat([
539
+ ...this.messageStreams.values()
540
+ ]);
541
+ this._swarmStreams.clear();
542
+ this.messageStreams.clear();
543
+ const failureCount = (await safeAwaitAll(streams, (s) => s.close())).length;
544
+ return {
545
+ failureCount
546
+ };
547
+ }
548
+ join({ topic, peerId }) {
549
+ this._joinedTopics.add({
550
+ topic,
551
+ peerId
552
+ });
553
+ }
554
+ leave({ topic, peerId }) {
555
+ void this._swarmStreams.get({
556
+ topic,
557
+ peerId
558
+ })?.close();
559
+ this._swarmStreams.delete({
560
+ topic,
561
+ peerId
562
+ });
563
+ this._joinedTopics.delete({
564
+ topic,
565
+ peerId
566
+ });
567
+ }
568
+ subscribeMessages(peerId) {
569
+ this._subscribedMessages.add({
570
+ peerId
571
+ });
572
+ }
573
+ unsubscribeMessages(peerId) {
574
+ log2("unsubscribing from messages", {
575
+ peerId
576
+ }, {
577
+ F: __dxlog_file2,
578
+ L: 79,
579
+ S: this,
580
+ C: (f, a) => f(...a)
581
+ });
582
+ this._subscribedMessages.delete({
583
+ peerId
584
+ });
585
+ void this.messageStreams.get(peerId)?.close();
586
+ this.messageStreams.delete(peerId);
587
+ }
588
+ async reconcile(ctx, client) {
589
+ await this._reconcileSwarmSubscriptions(ctx, client);
590
+ await this._reconcileMessageSubscriptions(ctx, client);
591
+ this.reconciled.emit();
592
+ }
593
+ async _reconcileSwarmSubscriptions(ctx, client) {
594
+ for (const { topic, peerId } of this._swarmStreams.keys()) {
595
+ if (this._joinedTopics.has({
596
+ topic,
597
+ peerId
598
+ })) {
599
+ continue;
600
+ }
601
+ void this._swarmStreams.get({
602
+ topic,
603
+ peerId
604
+ })?.close();
605
+ this._swarmStreams.delete({
606
+ topic,
607
+ peerId
608
+ });
609
+ }
610
+ for (const { topic, peerId } of this._joinedTopics.values()) {
611
+ if (this._swarmStreams.has({
612
+ topic,
613
+ peerId
614
+ })) {
615
+ continue;
616
+ }
617
+ const swarmStream = await asyncTimeout(cancelWithContext(ctx, client.join({
618
+ topic,
619
+ peerId
620
+ })), 5e3);
621
+ swarmStream.subscribe(async (swarmEvent) => {
622
+ if (this._joinedTopics.has({
623
+ topic,
624
+ peerId
625
+ })) {
626
+ log2("swarm event", {
627
+ swarmEvent
628
+ }, {
629
+ F: __dxlog_file2,
630
+ L: 115,
631
+ S: this,
632
+ C: (f, a) => f(...a)
633
+ });
634
+ const event = swarmEvent.peerAvailable ? {
635
+ topic,
636
+ peerAvailable: {
637
+ ...swarmEvent.peerAvailable,
638
+ peer: {
639
+ peerKey: PublicKey2.from(swarmEvent.peerAvailable.peer).toHex()
640
+ }
641
+ }
642
+ } : {
643
+ topic,
644
+ peerLeft: {
645
+ ...swarmEvent.peerLeft,
646
+ peer: {
647
+ peerKey: PublicKey2.from(swarmEvent.peerLeft.peer).toHex()
648
+ }
649
+ }
650
+ };
651
+ await this._onSwarmEvent(event);
652
+ }
653
+ });
654
+ this._swarmStreams.set({
655
+ topic,
656
+ peerId
657
+ }, swarmStream);
658
+ }
659
+ }
660
+ async _reconcileMessageSubscriptions(ctx, client) {
661
+ for (const peerId of this.messageStreams.keys()) {
662
+ if (this._subscribedMessages.has({
663
+ peerId
664
+ })) {
665
+ continue;
666
+ }
667
+ void this.messageStreams.get(peerId)?.close();
668
+ this.messageStreams.delete(peerId);
669
+ }
670
+ for (const { peerId } of this._subscribedMessages.values()) {
671
+ if (this.messageStreams.has(peerId)) {
672
+ continue;
673
+ }
674
+ const messageStream = await asyncTimeout(cancelWithContext(ctx, client.receiveMessages(peerId)), 5e3);
675
+ messageStream.subscribe(async (signalMessage) => {
676
+ if (this._subscribedMessages.has({
677
+ peerId
678
+ })) {
679
+ const message = {
680
+ author: {
681
+ peerKey: PublicKey2.from(signalMessage.author).toHex()
682
+ },
683
+ recipient: {
684
+ peerKey: PublicKey2.from(signalMessage.recipient).toHex()
685
+ },
686
+ payload: signalMessage.payload
687
+ };
688
+ await this._onMessage(message);
689
+ }
690
+ });
691
+ this.messageStreams.set(peerId, messageStream);
692
+ }
693
+ }
694
+ };
695
+
696
+ // packages/core/mesh/messaging/src/signal-client/signal-rpc-client.ts
697
+ import WebSocket from "isomorphic-ws";
698
+ import { scheduleTaskInterval as scheduleTaskInterval2, TimeoutError as TimeoutError2, Trigger } from "@dxos/async";
699
+ import { Context as Context2 } from "@dxos/context";
700
+ import { invariant as invariant2 } from "@dxos/invariant";
701
+ import { PublicKey as PublicKey3 } from "@dxos/keys";
702
+ import { log as log3 } from "@dxos/log";
703
+ import { trace as trace5 } from "@dxos/protocols";
704
+ import { schema as schema2 } from "@dxos/protocols/proto";
705
+ import { createProtoRpcPeer } from "@dxos/rpc";
706
+
707
+ // packages/core/mesh/messaging/src/signal-client/signal-rpc-client-monitor.ts
708
+ import { trace as trace4 } from "@dxos/tracing";
709
+ var SignalRpcClientMonitor = class {
710
+ recordClientCloseFailure(params) {
711
+ trace4.metrics.increment("dxos.mesh.signal.signal-rpc-client.close-failure", 1, {
712
+ tags: {
713
+ reason: params.failureReason
714
+ }
715
+ });
716
+ }
717
+ };
718
+
719
+ // packages/core/mesh/messaging/src/signal-client/signal-rpc-client.ts
720
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-rpc-client.ts";
721
+ var SIGNAL_KEEPALIVE_INTERVAL = 1e4;
722
+ var SignalRPCClient = class {
723
+ constructor({ url, callbacks = {} }) {
724
+ this._connectTrigger = new Trigger();
725
+ this._closed = false;
726
+ this._closeComplete = new Trigger();
727
+ this._monitor = new SignalRpcClientMonitor();
728
+ const traceId = PublicKey3.random().toHex();
729
+ log3.trace("dxos.mesh.signal-rpc-client.constructor", trace5.begin({
730
+ id: traceId
731
+ }), {
732
+ F: __dxlog_file3,
733
+ L: 61,
734
+ S: this,
735
+ C: (f, a) => f(...a)
736
+ });
737
+ this._url = url;
738
+ this._callbacks = callbacks;
739
+ this._socket = new WebSocket(this._url);
740
+ this._rpc = createProtoRpcPeer({
741
+ requested: {
742
+ Signal: schema2.getService("dxos.mesh.signal.Signal")
743
+ },
744
+ noHandshake: true,
745
+ port: {
746
+ send: (msg) => {
747
+ if (this._closed) {
748
+ return;
749
+ }
750
+ try {
751
+ this._socket.send(msg);
752
+ } catch (err) {
753
+ log3.warn("send error", err, {
754
+ F: __dxlog_file3,
755
+ L: 80,
756
+ S: this,
757
+ C: (f, a) => f(...a)
758
+ });
759
+ }
760
+ },
761
+ subscribe: (cb) => {
762
+ this._socket.onmessage = async (msg) => {
763
+ if (typeof Blob !== "undefined" && msg.data instanceof Blob) {
764
+ cb(Buffer.from(await msg.data.arrayBuffer()));
765
+ } else {
766
+ cb(msg.data);
767
+ }
768
+ };
769
+ }
770
+ },
771
+ encodingOptions: {
772
+ preserveAny: true
773
+ }
774
+ });
775
+ this._socket.onopen = async () => {
776
+ try {
777
+ await this._rpc.open();
778
+ if (this._closed) {
779
+ await this._safeCloseRpc();
780
+ return;
781
+ }
782
+ log3(`RPC open ${this._url}`, void 0, {
783
+ F: __dxlog_file3,
784
+ L: 105,
785
+ S: this,
786
+ C: (f, a) => f(...a)
787
+ });
788
+ this._callbacks.onConnected?.();
789
+ this._connectTrigger.wake();
790
+ this._keepaliveCtx = new Context2(void 0, {
791
+ F: __dxlog_file3,
792
+ L: 108
793
+ });
794
+ scheduleTaskInterval2(this._keepaliveCtx, async () => {
795
+ this._socket?.send("__ping__");
796
+ }, SIGNAL_KEEPALIVE_INTERVAL);
797
+ } catch (err) {
798
+ this._callbacks.onError?.(err);
799
+ this._socket.close();
800
+ this._closed = true;
801
+ }
802
+ };
803
+ this._socket.onclose = async () => {
804
+ log3(`Disconnected ${this._url}`, void 0, {
805
+ F: __dxlog_file3,
806
+ L: 128,
807
+ S: this,
808
+ C: (f, a) => f(...a)
809
+ });
810
+ this._callbacks.onDisconnected?.();
811
+ this._closeComplete.wake();
812
+ await this.close();
813
+ };
814
+ this._socket.onerror = async (event) => {
815
+ if (this._closed) {
816
+ this._socket.close();
817
+ return;
818
+ }
819
+ this._closed = true;
820
+ this._callbacks.onError?.(event.error ?? new Error(event.message));
821
+ await this._safeCloseRpc();
822
+ log3.warn(`Socket ${event.type ?? "unknown"} error`, {
823
+ message: event.message,
824
+ url: this._url
825
+ }, {
826
+ F: __dxlog_file3,
827
+ L: 144,
828
+ S: this,
829
+ C: (f, a) => f(...a)
830
+ });
831
+ };
832
+ log3.trace("dxos.mesh.signal-rpc-client.constructor", trace5.end({
833
+ id: traceId
834
+ }), {
835
+ F: __dxlog_file3,
836
+ L: 147,
837
+ S: this,
838
+ C: (f, a) => f(...a)
839
+ });
840
+ }
841
+ async close() {
842
+ if (this._closed) {
843
+ return;
844
+ }
845
+ this._closed = true;
846
+ await this._keepaliveCtx?.dispose();
847
+ try {
848
+ await this._safeCloseRpc();
849
+ if (this._socket.readyState === WebSocket.OPEN || this._socket.readyState === WebSocket.CONNECTING) {
850
+ this._socket.close();
851
+ }
852
+ await this._closeComplete.wait({
853
+ timeout: 1e3
854
+ });
855
+ } catch (err) {
856
+ const failureReason = err instanceof TimeoutError2 ? "timeout" : err?.constructor?.name ?? "unknown";
857
+ this._monitor.recordClientCloseFailure({
858
+ failureReason
859
+ });
860
+ }
861
+ }
862
+ async join({ topic, peerId }) {
863
+ log3("join", {
864
+ topic,
865
+ peerId,
866
+ metadata: this._callbacks?.getMetadata?.()
867
+ }, {
868
+ F: __dxlog_file3,
869
+ L: 173,
870
+ S: this,
871
+ C: (f, a) => f(...a)
872
+ });
873
+ invariant2(!this._closed, "SignalRPCClient is closed", {
874
+ F: __dxlog_file3,
875
+ L: 174,
876
+ S: this,
877
+ A: [
878
+ "!this._closed",
879
+ "'SignalRPCClient is closed'"
880
+ ]
881
+ });
882
+ await this._connectTrigger.wait();
883
+ const swarmStream = this._rpc.rpc.Signal.join({
884
+ swarm: topic.asUint8Array(),
885
+ peer: peerId.asUint8Array(),
886
+ metadata: this._callbacks?.getMetadata?.()
887
+ });
888
+ await swarmStream.waitUntilReady();
889
+ return swarmStream;
890
+ }
891
+ async receiveMessages(peerId) {
892
+ log3("receiveMessages", {
893
+ peerId
894
+ }, {
895
+ F: __dxlog_file3,
896
+ L: 186,
897
+ S: this,
898
+ C: (f, a) => f(...a)
899
+ });
900
+ invariant2(!this._closed, "SignalRPCClient is closed", {
901
+ F: __dxlog_file3,
902
+ L: 187,
903
+ S: this,
904
+ A: [
905
+ "!this._closed",
906
+ "'SignalRPCClient is closed'"
907
+ ]
908
+ });
909
+ await this._connectTrigger.wait();
910
+ const messageStream = this._rpc.rpc.Signal.receiveMessages({
911
+ peer: peerId.asUint8Array()
912
+ });
913
+ await messageStream.waitUntilReady();
914
+ return messageStream;
915
+ }
916
+ async sendMessage({ author, recipient, payload }) {
917
+ log3("sendMessage", {
918
+ author,
919
+ recipient,
920
+ payload,
921
+ metadata: this._callbacks?.getMetadata?.()
922
+ }, {
923
+ F: __dxlog_file3,
924
+ L: 197,
925
+ S: this,
926
+ C: (f, a) => f(...a)
927
+ });
928
+ invariant2(!this._closed, "SignalRPCClient is closed", {
929
+ F: __dxlog_file3,
930
+ L: 198,
931
+ S: this,
932
+ A: [
933
+ "!this._closed",
934
+ "'SignalRPCClient is closed'"
935
+ ]
936
+ });
937
+ await this._connectTrigger.wait();
938
+ await this._rpc.rpc.Signal.sendMessage({
939
+ author: author.asUint8Array(),
940
+ recipient: recipient.asUint8Array(),
941
+ payload,
942
+ metadata: this._callbacks?.getMetadata?.()
943
+ });
944
+ }
945
+ async _safeCloseRpc() {
946
+ try {
947
+ this._connectTrigger.reset();
948
+ await this._rpc.close();
949
+ } catch (err) {
950
+ log3.catch(err, void 0, {
951
+ F: __dxlog_file3,
952
+ L: 213,
953
+ S: this,
954
+ C: (f, a) => f(...a)
955
+ });
956
+ }
957
+ }
958
+ };
959
+
960
+ // packages/core/mesh/messaging/src/signal-client/signal-client.ts
961
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-client.ts";
962
+ var DEFAULT_RECONNECT_TIMEOUT = 100;
963
+ var MAX_RECONNECT_TIMEOUT = 5e3;
964
+ var ERROR_RECONCILE_DELAY = 1e3;
965
+ var RECONCILE_INTERVAL = 5e3;
966
+ var SignalClient = class extends Resource {
967
+ /**
968
+ * @param _host Signal server websocket URL.
969
+ * @param onMessage called when a new message is received.
970
+ * @param onSwarmEvent called when a new swarm event is received.
971
+ * @param _getMetadata signal-message metadata provider, called for every message.
972
+ */
973
+ constructor(_host, _getMetadata) {
974
+ super();
975
+ this._host = _host;
976
+ this._getMetadata = _getMetadata;
977
+ this._monitor = new SignalClientMonitor();
978
+ this._state = SignalState.CLOSED;
979
+ this._lastReconciliationFailed = false;
980
+ this._clientReady = new Trigger2();
981
+ this._reconnectAfter = DEFAULT_RECONNECT_TIMEOUT;
982
+ this._instanceId = PublicKey4.random().toHex();
983
+ this.statusChanged = new Event2();
984
+ this.onMessage = new Event2();
985
+ this.swarmEvent = new Event2();
986
+ if (!this._host.startsWith("wss://") && !this._host.startsWith("ws://")) {
987
+ throw new Error(`Signal server requires a websocket URL. Provided: ${this._host}`);
988
+ }
989
+ this.localState = new SignalLocalState(async (message) => {
990
+ this._monitor.recordMessageReceived(message);
991
+ this.onMessage.emit(message);
992
+ }, async (event) => this.swarmEvent.emit(event));
993
+ }
994
+ async _open() {
995
+ log4.trace("dxos.mesh.signal-client.open", trace6.begin({
996
+ id: this._instanceId
997
+ }), {
998
+ F: __dxlog_file4,
999
+ L: 92,
1000
+ S: this,
1001
+ C: (f, a) => f(...a)
1002
+ });
1003
+ if ([
1004
+ SignalState.CONNECTED,
1005
+ SignalState.CONNECTING
1006
+ ].includes(this._state)) {
1007
+ return;
1008
+ }
1009
+ this._setState(SignalState.CONNECTING);
1010
+ this._reconcileTask = new DeferredTask(this._ctx, async () => {
1011
+ try {
1012
+ await cancelWithContext2(this._connectionCtx, this._clientReady.wait({
1013
+ timeout: 5e3
1014
+ }));
1015
+ invariant3(this._state === SignalState.CONNECTED, "Not connected to Signal Server", {
1016
+ F: __dxlog_file4,
1017
+ L: 102,
1018
+ S: this,
1019
+ A: [
1020
+ "this._state === SignalState.CONNECTED",
1021
+ "'Not connected to Signal Server'"
1022
+ ]
1023
+ });
1024
+ await this.localState.reconcile(this._connectionCtx, this._client);
1025
+ this._monitor.recordReconciliation({
1026
+ success: true
1027
+ });
1028
+ this._lastReconciliationFailed = false;
1029
+ } catch (err) {
1030
+ this._lastReconciliationFailed = true;
1031
+ this._monitor.recordReconciliation({
1032
+ success: false
1033
+ });
1034
+ throw err;
1035
+ }
1036
+ });
1037
+ scheduleTaskInterval3(this._ctx, async () => {
1038
+ if (this._state === SignalState.CONNECTED) {
1039
+ this._reconcileTask.schedule();
1040
+ }
1041
+ }, RECONCILE_INTERVAL);
1042
+ this._reconnectTask = new DeferredTask(this._ctx, async () => {
1043
+ try {
1044
+ await this._reconnect();
1045
+ this._monitor.recordReconnect({
1046
+ success: true
1047
+ });
1048
+ } catch (err) {
1049
+ this._monitor.recordReconnect({
1050
+ success: false
1051
+ });
1052
+ throw err;
1053
+ }
1054
+ });
1055
+ this._createClient();
1056
+ log4.trace("dxos.mesh.signal-client.open", trace6.end({
1057
+ id: this._instanceId
1058
+ }), {
1059
+ F: __dxlog_file4,
1060
+ L: 135,
1061
+ S: this,
1062
+ C: (f, a) => f(...a)
1063
+ });
1064
+ }
1065
+ async _catch(err) {
1066
+ if (this._state === SignalState.CLOSED || this._ctx.disposed) {
1067
+ return;
1068
+ }
1069
+ if (this._state === SignalState.CONNECTED && !this._lastReconciliationFailed) {
1070
+ log4.warn("SignalClient error:", err, {
1071
+ F: __dxlog_file4,
1072
+ L: 144,
1073
+ S: this,
1074
+ C: (f, a) => f(...a)
1075
+ });
1076
+ }
1077
+ this._scheduleReconcileAfterError();
1078
+ }
1079
+ async _close() {
1080
+ log4("closing...", void 0, {
1081
+ F: __dxlog_file4,
1082
+ L: 150,
1083
+ S: this,
1084
+ C: (f, a) => f(...a)
1085
+ });
1086
+ if ([
1087
+ SignalState.CLOSED
1088
+ ].includes(this._state)) {
1089
+ return;
1090
+ }
1091
+ this._setState(SignalState.CLOSED);
1092
+ await this._safeResetClient();
1093
+ log4("closed", void 0, {
1094
+ F: __dxlog_file4,
1095
+ L: 158,
1096
+ S: this,
1097
+ C: (f, a) => f(...a)
1098
+ });
1099
+ }
1100
+ getStatus() {
1101
+ return {
1102
+ host: this._host,
1103
+ state: this._state,
1104
+ error: this._lastError?.message,
1105
+ reconnectIn: this._reconnectAfter,
1106
+ ...this._monitor.getRecordedTimestamps()
1107
+ };
1108
+ }
1109
+ async join(args) {
1110
+ log4("joining", {
1111
+ topic: args.topic,
1112
+ peerId: args.peer.peerKey
1113
+ }, {
1114
+ F: __dxlog_file4,
1115
+ L: 172,
1116
+ S: this,
1117
+ C: (f, a) => f(...a)
1118
+ });
1119
+ this._monitor.recordJoin();
1120
+ this.localState.join({
1121
+ topic: args.topic,
1122
+ peerId: PublicKey4.from(args.peer.peerKey)
1123
+ });
1124
+ this._reconcileTask?.schedule();
1125
+ }
1126
+ async leave(args) {
1127
+ log4("leaving", {
1128
+ topic: args.topic,
1129
+ peerId: args.peer.peerKey
1130
+ }, {
1131
+ F: __dxlog_file4,
1132
+ L: 179,
1133
+ S: this,
1134
+ C: (f, a) => f(...a)
1135
+ });
1136
+ this._monitor.recordLeave();
1137
+ this.localState.leave({
1138
+ topic: args.topic,
1139
+ peerId: PublicKey4.from(args.peer.peerKey)
1140
+ });
1141
+ }
1142
+ async sendMessage(msg) {
1143
+ return this._monitor.recordMessageSending(msg, async () => {
1144
+ await this._clientReady.wait();
1145
+ invariant3(this._state === SignalState.CONNECTED, "Not connected to Signal Server", {
1146
+ F: __dxlog_file4,
1147
+ L: 187,
1148
+ S: this,
1149
+ A: [
1150
+ "this._state === SignalState.CONNECTED",
1151
+ "'Not connected to Signal Server'"
1152
+ ]
1153
+ });
1154
+ invariant3(msg.author.peerKey, "Author key required", {
1155
+ F: __dxlog_file4,
1156
+ L: 188,
1157
+ S: this,
1158
+ A: [
1159
+ "msg.author.peerKey",
1160
+ "'Author key required'"
1161
+ ]
1162
+ });
1163
+ invariant3(msg.recipient.peerKey, "Recipient key required", {
1164
+ F: __dxlog_file4,
1165
+ L: 189,
1166
+ S: this,
1167
+ A: [
1168
+ "msg.recipient.peerKey",
1169
+ "'Recipient key required'"
1170
+ ]
1171
+ });
1172
+ await this._client.sendMessage({
1173
+ author: PublicKey4.from(msg.author.peerKey),
1174
+ recipient: PublicKey4.from(msg.recipient.peerKey),
1175
+ payload: msg.payload
1176
+ });
1177
+ });
1178
+ }
1179
+ async subscribeMessages(peer) {
1180
+ invariant3(peer.peerKey, "Peer key required", {
1181
+ F: __dxlog_file4,
1182
+ L: 199,
1183
+ S: this,
1184
+ A: [
1185
+ "peer.peerKey",
1186
+ "'Peer key required'"
1187
+ ]
1188
+ });
1189
+ log4("subscribing to messages", {
1190
+ peer
1191
+ }, {
1192
+ F: __dxlog_file4,
1193
+ L: 200,
1194
+ S: this,
1195
+ C: (f, a) => f(...a)
1196
+ });
1197
+ this.localState.subscribeMessages(PublicKey4.from(peer.peerKey));
1198
+ this._reconcileTask?.schedule();
1199
+ }
1200
+ async unsubscribeMessages(peer) {
1201
+ invariant3(peer.peerKey, "Peer key required", {
1202
+ F: __dxlog_file4,
1203
+ L: 206,
1204
+ S: this,
1205
+ A: [
1206
+ "peer.peerKey",
1207
+ "'Peer key required'"
1208
+ ]
1209
+ });
1210
+ log4("unsubscribing from messages", {
1211
+ peer
1212
+ }, {
1213
+ F: __dxlog_file4,
1214
+ L: 207,
1215
+ S: this,
1216
+ C: (f, a) => f(...a)
1217
+ });
1218
+ this.localState.unsubscribeMessages(PublicKey4.from(peer.peerKey));
1219
+ }
1220
+ _scheduleReconcileAfterError() {
1221
+ scheduleTask2(this._ctx, () => this._reconcileTask.schedule(), ERROR_RECONCILE_DELAY);
1222
+ }
1223
+ _createClient() {
1224
+ log4("creating client", {
1225
+ host: this._host,
1226
+ state: this._state
1227
+ }, {
1228
+ F: __dxlog_file4,
1229
+ L: 216,
1230
+ S: this,
1231
+ C: (f, a) => f(...a)
1232
+ });
1233
+ invariant3(!this._client, "Client already created", {
1234
+ F: __dxlog_file4,
1235
+ L: 217,
1236
+ S: this,
1237
+ A: [
1238
+ "!this._client",
1239
+ "'Client already created'"
1240
+ ]
1241
+ });
1242
+ this._monitor.recordConnectionStartTime();
1243
+ this._connectionCtx = this._ctx.derive();
1244
+ this._connectionCtx.onDispose(async () => {
1245
+ log4("connection context disposed", void 0, {
1246
+ F: __dxlog_file4,
1247
+ L: 224,
1248
+ S: this,
1249
+ C: (f, a) => f(...a)
1250
+ });
1251
+ const { failureCount } = await this.localState.safeCloseStreams();
1252
+ this._monitor.recordStreamCloseErrors(failureCount);
1253
+ });
1254
+ try {
1255
+ const client = new SignalRPCClient({
1256
+ url: this._host,
1257
+ callbacks: {
1258
+ onConnected: () => {
1259
+ if (client === this._client) {
1260
+ log4("socket connected", void 0, {
1261
+ F: __dxlog_file4,
1262
+ L: 235,
1263
+ S: this,
1264
+ C: (f, a) => f(...a)
1265
+ });
1266
+ this._onConnected();
1267
+ }
1268
+ },
1269
+ onDisconnected: () => {
1270
+ if (client !== this._client) {
1271
+ return;
1272
+ }
1273
+ log4("socket disconnected", {
1274
+ state: this._state
1275
+ }, {
1276
+ F: __dxlog_file4,
1277
+ L: 244,
1278
+ S: this,
1279
+ C: (f, a) => f(...a)
1280
+ });
1281
+ if (this._state === SignalState.ERROR) {
1282
+ this._setState(SignalState.DISCONNECTED);
1283
+ } else {
1284
+ this._onDisconnected();
1285
+ }
1286
+ },
1287
+ onError: (error) => {
1288
+ if (client === this._client) {
1289
+ log4("socket error", {
1290
+ error,
1291
+ state: this._state
1292
+ }, {
1293
+ F: __dxlog_file4,
1294
+ L: 256,
1295
+ S: this,
1296
+ C: (f, a) => f(...a)
1297
+ });
1298
+ this._onDisconnected({
1299
+ error
1300
+ });
1301
+ }
1302
+ },
1303
+ getMetadata: this._getMetadata
1304
+ }
1305
+ });
1306
+ this._client = client;
1307
+ } catch (error) {
1308
+ this._client = void 0;
1309
+ this._onDisconnected({
1310
+ error
1311
+ });
1312
+ }
1313
+ }
1314
+ async _reconnect() {
1315
+ log4(`reconnecting in ${this._reconnectAfter}ms`, {
1316
+ state: this._state
1317
+ }, {
1318
+ F: __dxlog_file4,
1319
+ L: 271,
1320
+ S: this,
1321
+ C: (f, a) => f(...a)
1322
+ });
1323
+ if (this._state === SignalState.RECONNECTING) {
1324
+ log4.info("Signal api already reconnecting.", void 0, {
1325
+ F: __dxlog_file4,
1326
+ L: 274,
1327
+ S: this,
1328
+ C: (f, a) => f(...a)
1329
+ });
1330
+ return;
1331
+ }
1332
+ if (this._state === SignalState.CLOSED) {
1333
+ return;
1334
+ }
1335
+ this._setState(SignalState.RECONNECTING);
1336
+ await this._safeResetClient();
1337
+ await cancelWithContext2(this._ctx, sleep(this._reconnectAfter));
1338
+ this._createClient();
1339
+ }
1340
+ _onConnected() {
1341
+ this._lastError = void 0;
1342
+ this._lastReconciliationFailed = false;
1343
+ this._reconnectAfter = DEFAULT_RECONNECT_TIMEOUT;
1344
+ this._setState(SignalState.CONNECTED);
1345
+ this._clientReady.wake();
1346
+ this._reconcileTask.schedule();
1347
+ }
1348
+ _onDisconnected(options) {
1349
+ this._updateReconnectTimeout();
1350
+ if (this._state === SignalState.CLOSED) {
1351
+ return;
1352
+ }
1353
+ if (options?.error) {
1354
+ this._lastError = options.error;
1355
+ this._setState(SignalState.ERROR);
1356
+ } else {
1357
+ this._setState(SignalState.DISCONNECTED);
1358
+ }
1359
+ this._reconnectTask.schedule();
1360
+ }
1361
+ _setState(newState) {
1362
+ this._state = newState;
1363
+ this._monitor.recordStateChangeTime();
1364
+ log4("signal state changed", {
1365
+ status: this.getStatus()
1366
+ }, {
1367
+ F: __dxlog_file4,
1368
+ L: 315,
1369
+ S: this,
1370
+ C: (f, a) => f(...a)
1371
+ });
1372
+ this.statusChanged.emit(this.getStatus());
1373
+ }
1374
+ _updateReconnectTimeout() {
1375
+ if (this._state !== SignalState.CONNECTED && this._state !== SignalState.CONNECTING) {
1376
+ this._reconnectAfter *= 2;
1377
+ this._reconnectAfter = Math.min(this._reconnectAfter, MAX_RECONNECT_TIMEOUT);
1378
+ }
1379
+ }
1380
+ async _safeResetClient() {
1381
+ await this._connectionCtx?.dispose();
1382
+ this._connectionCtx = void 0;
1383
+ this._clientReady.reset();
1384
+ await this._client?.close().catch(() => {
1385
+ });
1386
+ this._client = void 0;
1387
+ }
1388
+ };
1389
+
1390
+ // packages/core/mesh/messaging/src/signal-manager/memory-signal-manager.ts
1391
+ import { Event as Event3, Trigger as Trigger3 } from "@dxos/async";
1392
+ import { Context as Context3 } from "@dxos/context";
1393
+ import { invariant as invariant4 } from "@dxos/invariant";
1394
+ import { PublicKey as PublicKey5 } from "@dxos/keys";
1395
+ import { log as log5 } from "@dxos/log";
1396
+ import { schema as schema3 } from "@dxos/protocols/proto";
1397
+ import { ComplexMap as ComplexMap3, ComplexSet as ComplexSet3 } from "@dxos/util";
1398
+
1399
+ // packages/core/mesh/messaging/src/signal-methods.ts
1400
+ var PeerInfoHash = ({ peerKey }) => peerKey;
1401
+
1402
+ // packages/core/mesh/messaging/src/signal-manager/memory-signal-manager.ts
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 { AnySchema } from "@bufbuild/protobuf/wkt";
1992
+ import { Event as Event5 } from "@dxos/async";
1993
+ import { Resource as Resource3 } from "@dxos/context";
1994
+ import { protocol } from "@dxos/edge-client";
1995
+ import { invariant as invariant6 } from "@dxos/invariant";
1996
+ import { PublicKey as PublicKey7 } from "@dxos/keys";
1997
+ import { log as log7 } from "@dxos/log";
1998
+ import { EdgeService } from "@dxos/protocols";
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.addListener((message) => this._onMessage(message)));
2016
+ this._edgeConnection.reconnect.on(this._ctx, () => this._rejoinAllSwarms());
2017
+ await this._rejoinAllSwarms();
2018
+ }
2019
+ /**
2020
+ * Warning: PeerInfo is inferred from edgeConnection.
2021
+ */
2022
+ async join({ topic, peer }) {
2023
+ if (!this._matchSelfPeerInfo(peer)) {
2024
+ log7.warn("ignoring peer info on join request", {
2025
+ peer,
2026
+ expected: {
2027
+ peerKey: this._edgeConnection.peerKey,
2028
+ identityKey: this._edgeConnection.identityKey
2029
+ }
2030
+ }, {
2031
+ F: __dxlog_file7,
2032
+ L: 53,
2033
+ S: this,
2034
+ C: (f, a) => f(...a)
2035
+ });
2036
+ }
2037
+ this._swarmPeers.set(topic, new ComplexSet4(PeerInfoHash));
2038
+ await this._edgeConnection.send(protocol.createMessage(SwarmRequestSchema, {
2039
+ serviceId: EdgeService.SWARM_SERVICE_ID,
2040
+ payload: {
2041
+ action: SwarmRequestAction.JOIN,
2042
+ swarmKeys: [
2043
+ topic.toHex()
2044
+ ]
2045
+ }
2046
+ }));
2047
+ }
2048
+ async leave({ topic, peer }) {
2049
+ this._swarmPeers.delete(topic);
2050
+ await this._edgeConnection.send(protocol.createMessage(SwarmRequestSchema, {
2051
+ serviceId: EdgeService.SWARM_SERVICE_ID,
2052
+ payload: {
2053
+ action: SwarmRequestAction.LEAVE,
2054
+ swarmKeys: [
2055
+ topic.toHex()
2056
+ ]
2057
+ }
2058
+ }));
2059
+ }
2060
+ async sendMessage(message) {
2061
+ if (!this._matchSelfPeerInfo(message.author)) {
2062
+ log7.warn("ignoring author on send request", {
2063
+ author: message.author,
2064
+ expected: {
2065
+ peerKey: this._edgeConnection.peerKey,
2066
+ identityKey: this._edgeConnection.identityKey
2067
+ }
2068
+ }, {
2069
+ F: __dxlog_file7,
2070
+ L: 84,
2071
+ S: this,
2072
+ C: (f, a) => f(...a)
2073
+ });
2074
+ }
2075
+ await this._edgeConnection.send(protocol.createMessage(AnySchema, {
2076
+ serviceId: EdgeService.SIGNAL_SERVICE_ID,
2077
+ source: message.author,
2078
+ target: [
2079
+ message.recipient
2080
+ ],
2081
+ payload: {
2082
+ typeUrl: message.payload.type_url,
2083
+ value: message.payload.value
2084
+ }
2085
+ }));
2086
+ }
2087
+ async subscribeMessages(peerInfo) {
2088
+ }
2089
+ async unsubscribeMessages(peerInfo) {
2090
+ }
2091
+ _onMessage(message) {
2092
+ switch (message.serviceId) {
2093
+ case EdgeService.SWARM_SERVICE_ID: {
2094
+ this._processSwarmResponse(message);
2095
+ break;
2096
+ }
2097
+ case EdgeService.SIGNAL_SERVICE_ID: {
2098
+ this._processMessage(message);
2099
+ }
2100
+ }
2101
+ }
2102
+ _processSwarmResponse(message) {
2103
+ invariant6(protocol.getPayloadType(message) === SwarmResponseSchema.typeName, "Wrong payload type", {
2104
+ F: __dxlog_file7,
2105
+ L: 121,
2106
+ S: this,
2107
+ A: [
2108
+ "protocol.getPayloadType(message) === SwarmResponseSchema.typeName",
2109
+ "'Wrong payload type'"
2110
+ ]
2111
+ });
2112
+ const payload = protocol.getPayload(message, SwarmResponseSchema);
2113
+ const topic = PublicKey7.from(payload.swarmKey);
2114
+ if (!this._swarmPeers.has(topic)) {
2115
+ log7.warn("Received message from wrong topic", {
2116
+ topic
2117
+ }, {
2118
+ F: __dxlog_file7,
2119
+ L: 125,
2120
+ S: this,
2121
+ C: (f, a) => f(...a)
2122
+ });
2123
+ return;
2124
+ }
2125
+ const oldPeers = this._swarmPeers.get(topic);
2126
+ const timestamp = new Date(Date.parse(message.timestamp));
2127
+ const newPeers = new ComplexSet4(PeerInfoHash, payload.peers);
2128
+ for (const peer of newPeers) {
2129
+ if (oldPeers.has(peer)) {
2130
+ continue;
2131
+ }
2132
+ this.swarmEvent.emit({
2133
+ topic,
2134
+ peerAvailable: {
2135
+ peer,
2136
+ since: timestamp
2137
+ }
2138
+ });
2139
+ }
2140
+ for (const peer of oldPeers) {
2141
+ if (newPeers.has(peer)) {
2142
+ continue;
2143
+ }
2144
+ this.swarmEvent.emit({
2145
+ topic,
2146
+ peerLeft: {
2147
+ peer
2148
+ }
2149
+ });
2150
+ }
2151
+ this._swarmPeers.set(topic, newPeers);
2152
+ }
2153
+ _processMessage(message) {
2154
+ invariant6(protocol.getPayloadType(message) === AnySchema.typeName, "Wrong payload type", {
2155
+ F: __dxlog_file7,
2156
+ L: 158,
2157
+ S: this,
2158
+ A: [
2159
+ "protocol.getPayloadType(message) === AnySchema.typeName",
2160
+ "'Wrong payload type'"
2161
+ ]
2162
+ });
2163
+ const payload = protocol.getPayload(message, AnySchema);
2164
+ invariant6(message.source, "source is missing", {
2165
+ F: __dxlog_file7,
2166
+ L: 160,
2167
+ S: this,
2168
+ A: [
2169
+ "message.source",
2170
+ "'source is missing'"
2171
+ ]
2172
+ });
2173
+ invariant6(message.target, "target is missing", {
2174
+ F: __dxlog_file7,
2175
+ L: 161,
2176
+ S: this,
2177
+ A: [
2178
+ "message.target",
2179
+ "'target is missing'"
2180
+ ]
2181
+ });
2182
+ invariant6(message.target.length === 1, "target should have exactly one item", {
2183
+ F: __dxlog_file7,
2184
+ L: 162,
2185
+ S: this,
2186
+ A: [
2187
+ "message.target.length === 1",
2188
+ "'target should have exactly one item'"
2189
+ ]
2190
+ });
2191
+ this.onMessage.emit({
2192
+ author: message.source,
2193
+ recipient: message.target[0],
2194
+ payload: {
2195
+ type_url: payload.typeUrl,
2196
+ value: payload.value
2197
+ }
2198
+ });
2199
+ }
2200
+ _matchSelfPeerInfo(peer) {
2201
+ return peer && (peer.peerKey === this._edgeConnection.peerKey || peer.identityKey === this._edgeConnection.identityKey);
2202
+ }
2203
+ async _rejoinAllSwarms() {
2204
+ log7("rejoin swarms", {
2205
+ swarms: Array.from(this._swarmPeers.keys())
2206
+ }, {
2207
+ F: __dxlog_file7,
2208
+ L: 181,
2209
+ S: this,
2210
+ C: (f, a) => f(...a)
2211
+ });
2212
+ for (const topic of this._swarmPeers.keys()) {
2213
+ await this.join({
2214
+ topic,
2215
+ peer: {
2216
+ peerKey: this._edgeConnection.peerKey,
2217
+ identityKey: this._edgeConnection.identityKey
2218
+ }
2219
+ });
2220
+ }
2221
+ }
2222
+ };
2223
+
2224
+ // packages/core/mesh/messaging/src/signal-manager/utils.ts
2225
+ import { invariant as invariant7 } from "@dxos/invariant";
2226
+ import { log as log8 } from "@dxos/log";
2227
+ import { DeviceKind } from "@dxos/protocols/proto/dxos/client/services";
2228
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/utils.ts";
2229
+ var setIdentityTags = ({ identityService, devicesService, setTag }) => {
2230
+ identityService.queryIdentity().subscribe((idqr) => {
2231
+ if (!idqr?.identity?.identityKey) {
2232
+ log8("empty response from identity service", {
2233
+ idqr
2234
+ }, {
2235
+ F: __dxlog_file8,
2236
+ L: 21,
2237
+ S: void 0,
2238
+ C: (f, a) => f(...a)
2239
+ });
2240
+ return;
2241
+ }
2242
+ setTag("identityKey", idqr.identity.identityKey.truncate());
2243
+ });
2244
+ devicesService.queryDevices().subscribe((dqr) => {
2245
+ if (!dqr || !dqr.devices || dqr.devices.length === 0) {
2246
+ log8("empty response from device service", {
2247
+ device: dqr
2248
+ }, {
2249
+ F: __dxlog_file8,
2250
+ L: 30,
2251
+ S: void 0,
2252
+ C: (f, a) => f(...a)
2253
+ });
2254
+ return;
2255
+ }
2256
+ invariant7(dqr, "empty response from device service", {
2257
+ F: __dxlog_file8,
2258
+ L: 33,
2259
+ S: void 0,
2260
+ A: [
2261
+ "dqr",
2262
+ "'empty response from device service'"
2263
+ ]
2264
+ });
2265
+ const thisDevice = dqr.devices.find((device) => device.kind === DeviceKind.CURRENT);
2266
+ if (!thisDevice) {
2267
+ log8("no current device", {
2268
+ device: dqr
2269
+ }, {
2270
+ F: __dxlog_file8,
2271
+ L: 37,
2272
+ S: void 0,
2273
+ C: (f, a) => f(...a)
2274
+ });
2275
+ return;
2276
+ }
2277
+ setTag("deviceKey", thisDevice.deviceKey.truncate());
2278
+ });
2279
+ };
2280
+ export {
2281
+ EdgeSignalManager,
2282
+ MemorySignalManager,
2283
+ MemorySignalManagerContext,
2284
+ Messenger,
2285
+ PeerInfoHash,
2286
+ SignalClient,
2287
+ WebsocketSignalManager,
2288
+ setIdentityTags
2289
+ };
2290
+ //# sourceMappingURL=index.mjs.map