@dxos/messaging 0.6.12 → 0.6.13-main.548ca8d

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