@dxos/messaging 0.8.4-main.7ace549 → 0.8.4-main.937b3ca

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