@dxos/messaging 0.8.4-main.fd6878d → 0.8.4-staging.60fe92afc8

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