@dxos/messaging 0.8.3 → 0.8.4-main.28f8d3d

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 (67) hide show
  1. package/dist/lib/browser/{chunk-ISA3S2ZX.mjs → chunk-TPBTNKLU.mjs} +228 -154
  2. package/dist/lib/browser/chunk-TPBTNKLU.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +1 -1
  4. package/dist/lib/browser/meta.json +1 -1
  5. package/dist/lib/browser/testing/index.mjs +17 -9
  6. package/dist/lib/browser/testing/index.mjs.map +3 -3
  7. package/dist/lib/node-esm/{chunk-SO4RY3ON.mjs → chunk-SHJNQUOF.mjs} +228 -154
  8. package/dist/lib/node-esm/chunk-SHJNQUOF.mjs.map +7 -0
  9. package/dist/lib/node-esm/index.mjs +1 -1
  10. package/dist/lib/node-esm/meta.json +1 -1
  11. package/dist/lib/node-esm/testing/index.mjs +17 -9
  12. package/dist/lib/node-esm/testing/index.mjs.map +3 -3
  13. package/dist/types/src/messenger.blueprint-test.d.ts.map +1 -1
  14. package/dist/types/src/messenger.d.ts +1 -1
  15. package/dist/types/src/messenger.d.ts.map +1 -1
  16. package/dist/types/src/signal-client/signal-client.d.ts +2 -2
  17. package/dist/types/src/signal-client/signal-client.d.ts.map +1 -1
  18. package/dist/types/src/signal-client/signal-local-state.d.ts +1 -1
  19. package/dist/types/src/signal-client/signal-local-state.d.ts.map +1 -1
  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 +1 -1
  22. package/dist/types/src/signal-manager/edge-signal-manager.d.ts.map +1 -1
  23. package/dist/types/src/signal-manager/index.d.ts +1 -1
  24. package/dist/types/src/signal-manager/index.d.ts.map +1 -1
  25. package/dist/types/src/signal-manager/memory-signal-manager.d.ts +1 -1
  26. package/dist/types/src/signal-manager/memory-signal-manager.d.ts.map +1 -1
  27. package/dist/types/src/signal-manager/signal-manager.d.ts +1 -1
  28. package/dist/types/src/signal-manager/signal-manager.d.ts.map +1 -1
  29. package/dist/types/src/signal-manager/websocket-signal-manager.d.ts +1 -1
  30. package/dist/types/src/signal-manager/websocket-signal-manager.d.ts.map +1 -1
  31. package/dist/types/src/signal-methods.d.ts +2 -2
  32. package/dist/types/src/signal-methods.d.ts.map +1 -1
  33. package/dist/types/src/testing/test-builder.d.ts +1 -1
  34. package/dist/types/src/testing/test-builder.d.ts.map +1 -1
  35. package/dist/types/src/testing/test-peer.d.ts +1 -1
  36. package/dist/types/src/testing/test-peer.d.ts.map +1 -1
  37. package/dist/types/src/testing/utils.d.ts +1 -1
  38. package/dist/types/src/testing/utils.d.ts.map +1 -1
  39. package/dist/types/tsconfig.tsbuildinfo +1 -1
  40. package/package.json +18 -16
  41. package/src/messenger.blueprint-test.ts +2 -2
  42. package/src/messenger.node.test.ts +2 -2
  43. package/src/messenger.ts +1 -1
  44. package/src/signal-client/signal-client.node.test.ts +4 -3
  45. package/src/signal-client/signal-client.ts +7 -6
  46. package/src/signal-client/signal-local-state.ts +4 -3
  47. package/src/signal-client/signal-rpc-client.node.test.ts +1 -1
  48. package/src/signal-client/signal-rpc-client.ts +4 -4
  49. package/src/signal-manager/edge-signal-manager.ts +6 -5
  50. package/src/signal-manager/index.ts +1 -1
  51. package/src/signal-manager/memory-signal-manager.ts +2 -1
  52. package/src/signal-manager/signal-manager.ts +1 -1
  53. package/src/signal-manager/websocket-signal-manager.node.test.ts +3 -2
  54. package/src/signal-manager/websocket-signal-manager.ts +4 -3
  55. package/src/signal-methods.ts +3 -3
  56. package/src/testing/test-builder.ts +3 -2
  57. package/src/testing/test-peer.ts +3 -2
  58. package/src/testing/utils.ts +3 -2
  59. package/dist/lib/browser/chunk-ISA3S2ZX.mjs.map +0 -7
  60. package/dist/lib/node/chunk-GMND65DN.cjs +0 -2291
  61. package/dist/lib/node/chunk-GMND65DN.cjs.map +0 -7
  62. package/dist/lib/node/index.cjs +0 -43
  63. package/dist/lib/node/index.cjs.map +0 -7
  64. package/dist/lib/node/meta.json +0 -1
  65. package/dist/lib/node/testing/index.cjs +0 -159
  66. package/dist/lib/node/testing/index.cjs.map +0 -7
  67. package/dist/lib/node-esm/chunk-SO4RY3ON.mjs.map +0 -7
@@ -1,2291 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
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
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var chunk_GMND65DN_exports = {};
30
- __export(chunk_GMND65DN_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
39
- });
40
- module.exports = __toCommonJS(chunk_GMND65DN_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_async7 = require("@dxos/async");
89
- var import_context7 = require("@dxos/context");
90
- var import_edge_client = require("@dxos/edge-client");
91
- var import_invariant6 = require("@dxos/invariant");
92
- var import_keys7 = require("@dxos/keys");
93
- var import_log7 = require("@dxos/log");
94
- var import_protocols5 = require("@dxos/protocols");
95
- var import_buf = require("@dxos/protocols/buf");
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 = 1e3 }) {
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: 66,
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: 85,
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: 110,
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: 113
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: 133,
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: 149,
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: 152,
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: 178,
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: 179,
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: 191,
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: 192,
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: 210,
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: 211,
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: 226,
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(), this._host = _host, this._getMetadata = _getMetadata, this._monitor = new SignalClientMonitor(), this._state = import_signal.SignalState.CLOSED, this._lastReconciliationFailed = false, this._clientReady = new import_async2.Trigger(), this._reconnectAfter = DEFAULT_RECONNECT_TIMEOUT, this._instanceId = import_keys2.PublicKey.random().toHex(), this.statusChanged = new import_async2.Event(), this.onMessage = new import_async2.Event(), this.swarmEvent = new import_async2.Event();
1011
- if (!this._host.startsWith("wss://") && !this._host.startsWith("ws://")) {
1012
- throw new Error(`Signal server requires a websocket URL. Provided: ${this._host}`);
1013
- }
1014
- this.localState = new SignalLocalState(async (message) => {
1015
- this._monitor.recordMessageReceived(message);
1016
- this.onMessage.emit(message);
1017
- }, async (event) => this.swarmEvent.emit(event));
1018
- }
1019
- async _open() {
1020
- import_log2.log.trace("dxos.mesh.signal-client.open", import_protocols2.trace.begin({
1021
- id: this._instanceId
1022
- }), {
1023
- F: __dxlog_file4,
1024
- L: 96,
1025
- S: this,
1026
- C: (f, a) => f(...a)
1027
- });
1028
- if ([
1029
- import_signal.SignalState.CONNECTED,
1030
- import_signal.SignalState.CONNECTING
1031
- ].includes(this._state)) {
1032
- return;
1033
- }
1034
- this._setState(import_signal.SignalState.CONNECTING);
1035
- this._reconcileTask = new import_async2.DeferredTask(this._ctx, async () => {
1036
- try {
1037
- await (0, import_context2.cancelWithContext)(this._connectionCtx, this._clientReady.wait({
1038
- timeout: 5e3
1039
- }));
1040
- (0, import_invariant2.invariant)(this._state === import_signal.SignalState.CONNECTED, "Not connected to Signal Server", {
1041
- F: __dxlog_file4,
1042
- L: 106,
1043
- S: this,
1044
- A: [
1045
- "this._state === SignalState.CONNECTED",
1046
- "'Not connected to Signal Server'"
1047
- ]
1048
- });
1049
- await this.localState.reconcile(this._connectionCtx, this._client);
1050
- this._monitor.recordReconciliation({
1051
- success: true
1052
- });
1053
- this._lastReconciliationFailed = false;
1054
- } catch (err) {
1055
- this._lastReconciliationFailed = true;
1056
- this._monitor.recordReconciliation({
1057
- success: false
1058
- });
1059
- throw err;
1060
- }
1061
- });
1062
- (0, import_async2.scheduleTaskInterval)(this._ctx, async () => {
1063
- if (this._state === import_signal.SignalState.CONNECTED) {
1064
- this._reconcileTask.schedule();
1065
- }
1066
- }, RECONCILE_INTERVAL);
1067
- this._reconnectTask = new import_async2.DeferredTask(this._ctx, async () => {
1068
- try {
1069
- await this._reconnect();
1070
- this._monitor.recordReconnect({
1071
- success: true
1072
- });
1073
- } catch (err) {
1074
- this._monitor.recordReconnect({
1075
- success: false
1076
- });
1077
- throw err;
1078
- }
1079
- });
1080
- this._createClient();
1081
- import_log2.log.trace("dxos.mesh.signal-client.open", import_protocols2.trace.end({
1082
- id: this._instanceId
1083
- }), {
1084
- F: __dxlog_file4,
1085
- L: 139,
1086
- S: this,
1087
- C: (f, a) => f(...a)
1088
- });
1089
- }
1090
- async _catch(err) {
1091
- if (this._state === import_signal.SignalState.CLOSED || this._ctx.disposed) {
1092
- return;
1093
- }
1094
- if (this._state === import_signal.SignalState.CONNECTED && !this._lastReconciliationFailed) {
1095
- import_log2.log.warn("SignalClient error:", err, {
1096
- F: __dxlog_file4,
1097
- L: 148,
1098
- S: this,
1099
- C: (f, a) => f(...a)
1100
- });
1101
- }
1102
- this._scheduleReconcileAfterError();
1103
- }
1104
- async _close() {
1105
- (0, import_log2.log)("closing...", void 0, {
1106
- F: __dxlog_file4,
1107
- L: 154,
1108
- S: this,
1109
- C: (f, a) => f(...a)
1110
- });
1111
- if ([
1112
- import_signal.SignalState.CLOSED
1113
- ].includes(this._state)) {
1114
- return;
1115
- }
1116
- this._setState(import_signal.SignalState.CLOSED);
1117
- await this._safeResetClient();
1118
- (0, import_log2.log)("closed", void 0, {
1119
- F: __dxlog_file4,
1120
- L: 162,
1121
- S: this,
1122
- C: (f, a) => f(...a)
1123
- });
1124
- }
1125
- getStatus() {
1126
- return {
1127
- host: this._host,
1128
- state: this._state,
1129
- error: this._lastError?.message,
1130
- reconnectIn: this._reconnectAfter,
1131
- ...this._monitor.getRecordedTimestamps()
1132
- };
1133
- }
1134
- async join(args) {
1135
- (0, import_log2.log)("joining", {
1136
- topic: args.topic,
1137
- peerId: args.peer.peerKey
1138
- }, {
1139
- F: __dxlog_file4,
1140
- L: 176,
1141
- S: this,
1142
- C: (f, a) => f(...a)
1143
- });
1144
- this._monitor.recordJoin();
1145
- this.localState.join({
1146
- topic: args.topic,
1147
- peerId: import_keys2.PublicKey.from(args.peer.peerKey)
1148
- });
1149
- this._reconcileTask?.schedule();
1150
- }
1151
- async leave(args) {
1152
- (0, import_log2.log)("leaving", {
1153
- topic: args.topic,
1154
- peerId: args.peer.peerKey
1155
- }, {
1156
- F: __dxlog_file4,
1157
- L: 183,
1158
- S: this,
1159
- C: (f, a) => f(...a)
1160
- });
1161
- this._monitor.recordLeave();
1162
- this.localState.leave({
1163
- topic: args.topic,
1164
- peerId: import_keys2.PublicKey.from(args.peer.peerKey)
1165
- });
1166
- }
1167
- async query(params) {
1168
- throw new Error("Not implemented");
1169
- }
1170
- async sendMessage(msg) {
1171
- return this._monitor.recordMessageSending(msg, async () => {
1172
- await this._clientReady.wait();
1173
- (0, import_invariant2.invariant)(this._state === import_signal.SignalState.CONNECTED, "Not connected to Signal Server", {
1174
- F: __dxlog_file4,
1175
- L: 195,
1176
- S: this,
1177
- A: [
1178
- "this._state === SignalState.CONNECTED",
1179
- "'Not connected to Signal Server'"
1180
- ]
1181
- });
1182
- (0, import_invariant2.invariant)(msg.author.peerKey, "Author key required", {
1183
- F: __dxlog_file4,
1184
- L: 196,
1185
- S: this,
1186
- A: [
1187
- "msg.author.peerKey",
1188
- "'Author key required'"
1189
- ]
1190
- });
1191
- (0, import_invariant2.invariant)(msg.recipient.peerKey, "Recipient key required", {
1192
- F: __dxlog_file4,
1193
- L: 197,
1194
- S: this,
1195
- A: [
1196
- "msg.recipient.peerKey",
1197
- "'Recipient key required'"
1198
- ]
1199
- });
1200
- await this._client.sendMessage({
1201
- author: import_keys2.PublicKey.from(msg.author.peerKey),
1202
- recipient: import_keys2.PublicKey.from(msg.recipient.peerKey),
1203
- payload: msg.payload
1204
- });
1205
- });
1206
- }
1207
- async subscribeMessages(peer) {
1208
- (0, import_invariant2.invariant)(peer.peerKey, "Peer key required", {
1209
- F: __dxlog_file4,
1210
- L: 207,
1211
- S: this,
1212
- A: [
1213
- "peer.peerKey",
1214
- "'Peer key required'"
1215
- ]
1216
- });
1217
- (0, import_log2.log)("subscribing to messages", {
1218
- peer
1219
- }, {
1220
- F: __dxlog_file4,
1221
- L: 208,
1222
- S: this,
1223
- C: (f, a) => f(...a)
1224
- });
1225
- this.localState.subscribeMessages(import_keys2.PublicKey.from(peer.peerKey));
1226
- this._reconcileTask?.schedule();
1227
- }
1228
- async unsubscribeMessages(peer) {
1229
- (0, import_invariant2.invariant)(peer.peerKey, "Peer key required", {
1230
- F: __dxlog_file4,
1231
- L: 214,
1232
- S: this,
1233
- A: [
1234
- "peer.peerKey",
1235
- "'Peer key required'"
1236
- ]
1237
- });
1238
- (0, import_log2.log)("unsubscribing from messages", {
1239
- peer
1240
- }, {
1241
- F: __dxlog_file4,
1242
- L: 215,
1243
- S: this,
1244
- C: (f, a) => f(...a)
1245
- });
1246
- this.localState.unsubscribeMessages(import_keys2.PublicKey.from(peer.peerKey));
1247
- }
1248
- _scheduleReconcileAfterError() {
1249
- (0, import_async2.scheduleTask)(this._ctx, () => this._reconcileTask.schedule(), ERROR_RECONCILE_DELAY);
1250
- }
1251
- _createClient() {
1252
- (0, import_log2.log)("creating client", {
1253
- host: this._host,
1254
- state: this._state
1255
- }, {
1256
- F: __dxlog_file4,
1257
- L: 224,
1258
- S: this,
1259
- C: (f, a) => f(...a)
1260
- });
1261
- (0, import_invariant2.invariant)(!this._client, "Client already created", {
1262
- F: __dxlog_file4,
1263
- L: 225,
1264
- S: this,
1265
- A: [
1266
- "!this._client",
1267
- "'Client already created'"
1268
- ]
1269
- });
1270
- this._monitor.recordConnectionStartTime();
1271
- this._connectionCtx = this._ctx.derive();
1272
- this._connectionCtx.onDispose(async () => {
1273
- (0, import_log2.log)("connection context disposed", void 0, {
1274
- F: __dxlog_file4,
1275
- L: 232,
1276
- S: this,
1277
- C: (f, a) => f(...a)
1278
- });
1279
- const { failureCount } = await this.localState.safeCloseStreams();
1280
- this._monitor.recordStreamCloseErrors(failureCount);
1281
- });
1282
- try {
1283
- const client = new SignalRPCClient({
1284
- url: this._host,
1285
- callbacks: {
1286
- onConnected: () => {
1287
- if (client === this._client) {
1288
- (0, import_log2.log)("socket connected", void 0, {
1289
- F: __dxlog_file4,
1290
- L: 243,
1291
- S: this,
1292
- C: (f, a) => f(...a)
1293
- });
1294
- this._onConnected();
1295
- }
1296
- },
1297
- onDisconnected: () => {
1298
- if (client !== this._client) {
1299
- return;
1300
- }
1301
- (0, import_log2.log)("socket disconnected", {
1302
- state: this._state
1303
- }, {
1304
- F: __dxlog_file4,
1305
- L: 252,
1306
- S: this,
1307
- C: (f, a) => f(...a)
1308
- });
1309
- if (this._state === import_signal.SignalState.ERROR) {
1310
- this._setState(import_signal.SignalState.DISCONNECTED);
1311
- } else {
1312
- this._onDisconnected();
1313
- }
1314
- },
1315
- onError: (error) => {
1316
- if (client === this._client) {
1317
- (0, import_log2.log)("socket error", {
1318
- error,
1319
- state: this._state
1320
- }, {
1321
- F: __dxlog_file4,
1322
- L: 264,
1323
- S: this,
1324
- C: (f, a) => f(...a)
1325
- });
1326
- this._onDisconnected({
1327
- error
1328
- });
1329
- }
1330
- },
1331
- getMetadata: this._getMetadata
1332
- }
1333
- });
1334
- this._client = client;
1335
- } catch (error) {
1336
- this._client = void 0;
1337
- this._onDisconnected({
1338
- error
1339
- });
1340
- }
1341
- }
1342
- async _reconnect() {
1343
- (0, import_log2.log)(`reconnecting in ${this._reconnectAfter}ms`, {
1344
- state: this._state
1345
- }, {
1346
- F: __dxlog_file4,
1347
- L: 279,
1348
- S: this,
1349
- C: (f, a) => f(...a)
1350
- });
1351
- if (this._state === import_signal.SignalState.RECONNECTING) {
1352
- import_log2.log.info("Signal api already reconnecting.", void 0, {
1353
- F: __dxlog_file4,
1354
- L: 282,
1355
- S: this,
1356
- C: (f, a) => f(...a)
1357
- });
1358
- return;
1359
- }
1360
- if (this._state === import_signal.SignalState.CLOSED) {
1361
- return;
1362
- }
1363
- this._setState(import_signal.SignalState.RECONNECTING);
1364
- await this._safeResetClient();
1365
- await (0, import_context2.cancelWithContext)(this._ctx, (0, import_async2.sleep)(this._reconnectAfter));
1366
- this._createClient();
1367
- }
1368
- _onConnected() {
1369
- this._lastError = void 0;
1370
- this._lastReconciliationFailed = false;
1371
- this._reconnectAfter = DEFAULT_RECONNECT_TIMEOUT;
1372
- this._setState(import_signal.SignalState.CONNECTED);
1373
- this._clientReady.wake();
1374
- this._reconcileTask.schedule();
1375
- }
1376
- _onDisconnected(options) {
1377
- this._updateReconnectTimeout();
1378
- if (this._state === import_signal.SignalState.CLOSED) {
1379
- return;
1380
- }
1381
- if (options?.error) {
1382
- this._lastError = options.error;
1383
- this._setState(import_signal.SignalState.ERROR);
1384
- } else {
1385
- this._setState(import_signal.SignalState.DISCONNECTED);
1386
- }
1387
- this._reconnectTask.schedule();
1388
- }
1389
- _setState(newState) {
1390
- this._state = newState;
1391
- this._monitor.recordStateChangeTime();
1392
- (0, import_log2.log)("signal state changed", {
1393
- status: this.getStatus()
1394
- }, {
1395
- F: __dxlog_file4,
1396
- L: 323,
1397
- S: this,
1398
- C: (f, a) => f(...a)
1399
- });
1400
- this.statusChanged.emit(this.getStatus());
1401
- }
1402
- _updateReconnectTimeout() {
1403
- if (this._state !== import_signal.SignalState.CONNECTED && this._state !== import_signal.SignalState.CONNECTING) {
1404
- this._reconnectAfter *= 2;
1405
- this._reconnectAfter = Math.min(this._reconnectAfter, MAX_RECONNECT_TIMEOUT);
1406
- }
1407
- }
1408
- async _safeResetClient() {
1409
- await this._connectionCtx?.dispose();
1410
- this._connectionCtx = void 0;
1411
- this._clientReady.reset();
1412
- await this._client?.close().catch(() => {
1413
- });
1414
- this._client = void 0;
1415
- }
1416
- };
1417
- var PeerInfoHash = ({ peerKey }) => peerKey;
1418
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/memory-signal-manager.ts";
1419
- var MemorySignalManagerContext = class {
1420
- constructor() {
1421
- this.swarmEvent = new import_async5.Event();
1422
- this.swarms = new import_util3.ComplexMap(import_keys5.PublicKey.hash);
1423
- this.connections = new import_util3.ComplexMap(PeerInfoHash);
1424
- }
1425
- };
1426
- var MemorySignalManager = class {
1427
- constructor(_context) {
1428
- this._context = _context;
1429
- this.statusChanged = new import_async5.Event();
1430
- this.swarmEvent = new import_async5.Event();
1431
- this.onMessage = new import_async5.Event();
1432
- this._joinedSwarms = new import_util3.ComplexSet(({ topic, peer }) => topic.toHex() + peer.peerKey);
1433
- this._freezeTrigger = new import_async5.Trigger().wake();
1434
- this._ctx = new import_context5.Context(void 0, {
1435
- F: __dxlog_file5,
1436
- L: 53
1437
- });
1438
- this._ctx.onDispose(this._context.swarmEvent.on((data) => this.swarmEvent.emit(data)));
1439
- }
1440
- async open() {
1441
- if (!this._ctx.disposed) {
1442
- return;
1443
- }
1444
- this._ctx = new import_context5.Context(void 0, {
1445
- F: __dxlog_file5,
1446
- L: 62
1447
- });
1448
- this._ctx.onDispose(this._context.swarmEvent.on((data) => this.swarmEvent.emit(data)));
1449
- await Promise.all([
1450
- ...this._joinedSwarms.values()
1451
- ].map((value) => this.join(value)));
1452
- }
1453
- async close() {
1454
- if (this._ctx.disposed) {
1455
- return;
1456
- }
1457
- const joinedSwarmsCopy = new import_util3.ComplexSet(({ topic, peer }) => topic.toHex() + peer.peerKey, [
1458
- ...this._joinedSwarms.values()
1459
- ]);
1460
- await Promise.all([
1461
- ...this._joinedSwarms.values()
1462
- ].map((value) => this.leave(value)));
1463
- this._joinedSwarms = joinedSwarmsCopy;
1464
- await this._ctx.dispose();
1465
- }
1466
- getStatus() {
1467
- return [];
1468
- }
1469
- async join({ topic, peer }) {
1470
- (0, import_invariant4.invariant)(!this._ctx.disposed, "Closed", {
1471
- F: __dxlog_file5,
1472
- L: 91,
1473
- S: this,
1474
- A: [
1475
- "!this._ctx.disposed",
1476
- "'Closed'"
1477
- ]
1478
- });
1479
- this._joinedSwarms.add({
1480
- topic,
1481
- peer
1482
- });
1483
- if (!this._context.swarms.has(topic)) {
1484
- this._context.swarms.set(topic, new import_util3.ComplexSet(PeerInfoHash));
1485
- }
1486
- this._context.swarms.get(topic).add(peer);
1487
- this._context.swarmEvent.emit({
1488
- topic,
1489
- peerAvailable: {
1490
- peer,
1491
- since: /* @__PURE__ */ new Date()
1492
- }
1493
- });
1494
- for (const [topic2, peers] of this._context.swarms) {
1495
- Array.from(peers).forEach((peer2) => {
1496
- this.swarmEvent.emit({
1497
- topic: topic2,
1498
- peerAvailable: {
1499
- peer: peer2,
1500
- since: /* @__PURE__ */ new Date()
1501
- }
1502
- });
1503
- });
1504
- }
1505
- }
1506
- async leave({ topic, peer }) {
1507
- (0, import_invariant4.invariant)(!this._ctx.disposed, "Closed", {
1508
- F: __dxlog_file5,
1509
- L: 123,
1510
- S: this,
1511
- A: [
1512
- "!this._ctx.disposed",
1513
- "'Closed'"
1514
- ]
1515
- });
1516
- this._joinedSwarms.delete({
1517
- topic,
1518
- peer
1519
- });
1520
- if (!this._context.swarms.has(topic)) {
1521
- this._context.swarms.set(topic, new import_util3.ComplexSet(PeerInfoHash));
1522
- }
1523
- this._context.swarms.get(topic).delete(peer);
1524
- const swarmEvent = {
1525
- topic,
1526
- peerLeft: {
1527
- peer
1528
- }
1529
- };
1530
- this._context.swarmEvent.emit(swarmEvent);
1531
- }
1532
- async query(request) {
1533
- throw new Error("Not implemented");
1534
- }
1535
- async sendMessage({ author, recipient, payload }) {
1536
- (0, import_log5.log)("send message", {
1537
- author,
1538
- recipient,
1539
- ...dec(payload)
1540
- }, {
1541
- F: __dxlog_file5,
1542
- L: 156,
1543
- S: this,
1544
- C: (f, a) => f(...a)
1545
- });
1546
- (0, import_invariant4.invariant)(recipient, void 0, {
1547
- F: __dxlog_file5,
1548
- L: 158,
1549
- S: this,
1550
- A: [
1551
- "recipient",
1552
- ""
1553
- ]
1554
- });
1555
- (0, import_invariant4.invariant)(!this._ctx.disposed, "Closed", {
1556
- F: __dxlog_file5,
1557
- L: 159,
1558
- S: this,
1559
- A: [
1560
- "!this._ctx.disposed",
1561
- "'Closed'"
1562
- ]
1563
- });
1564
- await this._freezeTrigger.wait();
1565
- const remote = this._context.connections.get(recipient);
1566
- if (!remote) {
1567
- import_log5.log.warn("recipient is not subscribed for messages", {
1568
- author,
1569
- recipient
1570
- }, {
1571
- F: __dxlog_file5,
1572
- L: 165,
1573
- S: this,
1574
- C: (f, a) => f(...a)
1575
- });
1576
- return;
1577
- }
1578
- if (remote._ctx.disposed) {
1579
- import_log5.log.warn("recipient is disposed", {
1580
- author,
1581
- recipient
1582
- }, {
1583
- F: __dxlog_file5,
1584
- L: 170,
1585
- S: this,
1586
- C: (f, a) => f(...a)
1587
- });
1588
- return;
1589
- }
1590
- remote._freezeTrigger.wait().then(() => {
1591
- if (remote._ctx.disposed) {
1592
- import_log5.log.warn("recipient is disposed", {
1593
- author,
1594
- recipient
1595
- }, {
1596
- F: __dxlog_file5,
1597
- L: 178,
1598
- S: this,
1599
- C: (f, a) => f(...a)
1600
- });
1601
- return;
1602
- }
1603
- (0, import_log5.log)("receive message", {
1604
- author,
1605
- recipient,
1606
- ...dec(payload)
1607
- }, {
1608
- F: __dxlog_file5,
1609
- L: 182,
1610
- S: this,
1611
- C: (f, a) => f(...a)
1612
- });
1613
- remote.onMessage.emit({
1614
- author,
1615
- recipient,
1616
- payload
1617
- });
1618
- }).catch((err) => {
1619
- import_log5.log.error("error while waiting for freeze", {
1620
- err
1621
- }, {
1622
- F: __dxlog_file5,
1623
- L: 187,
1624
- S: this,
1625
- C: (f, a) => f(...a)
1626
- });
1627
- });
1628
- }
1629
- async subscribeMessages(peerInfo) {
1630
- (0, import_log5.log)("subscribing", {
1631
- peerInfo
1632
- }, {
1633
- F: __dxlog_file5,
1634
- L: 192,
1635
- S: this,
1636
- C: (f, a) => f(...a)
1637
- });
1638
- this._context.connections.set(peerInfo, this);
1639
- }
1640
- async unsubscribeMessages(peerInfo) {
1641
- (0, import_log5.log)("unsubscribing", {
1642
- peerInfo
1643
- }, {
1644
- F: __dxlog_file5,
1645
- L: 197,
1646
- S: this,
1647
- C: (f, a) => f(...a)
1648
- });
1649
- this._context.connections.delete(peerInfo);
1650
- }
1651
- freeze() {
1652
- this._freezeTrigger.reset();
1653
- }
1654
- unfreeze() {
1655
- this._freezeTrigger.wake();
1656
- }
1657
- };
1658
- var dec = (payload) => {
1659
- if (!payload.type_url.endsWith("ReliablePayload")) {
1660
- return {};
1661
- }
1662
- const relPayload = import_proto3.schema.getCodecForType("dxos.mesh.messaging.ReliablePayload").decode(payload.value);
1663
- if (typeof relPayload?.payload?.data === "object") {
1664
- return {
1665
- payload: Object.keys(relPayload?.payload?.data)[0],
1666
- sessionId: relPayload?.payload?.sessionId
1667
- };
1668
- }
1669
- return {};
1670
- };
1671
- var WebsocketSignalManagerMonitor = class {
1672
- recordRateLimitExceeded() {
1673
- import_tracing4.trace.metrics.increment("dxos.mesh.signal.signal-manager.rate-limit-hit", 1);
1674
- }
1675
- recordServerFailure(params) {
1676
- import_tracing4.trace.metrics.increment("dxos.mesh.signal.signal-manager.server-failure", 1, {
1677
- tags: {
1678
- server: params.serverName,
1679
- restarted: params.willRestart
1680
- }
1681
- });
1682
- }
1683
- };
1684
- function _ts_decorate(decorators, target, key, desc) {
1685
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1686
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1687
- 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;
1688
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1689
- }
1690
- var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/websocket-signal-manager.ts";
1691
- var MAX_SERVER_FAILURES = 5;
1692
- var WSS_SIGNAL_SERVER_REBOOT_DELAY = 3e3;
1693
- var WebsocketSignalManager = class extends import_context6.Resource {
1694
- constructor(_hosts, _getMetadata) {
1695
- super(), this._hosts = _hosts, this._getMetadata = _getMetadata, this._servers = /* @__PURE__ */ new Map(), this._monitor = new WebsocketSignalManagerMonitor(), this.failureCount = /* @__PURE__ */ new Map(), this.statusChanged = new import_async6.Event(), this.swarmEvent = new import_async6.Event(), this.onMessage = new import_async6.Event(), this._instanceId = import_keys6.PublicKey.random().toHex();
1696
- (0, import_log6.log)("Created WebsocketSignalManager", {
1697
- hosts: this._hosts
1698
- }, {
1699
- F: __dxlog_file6,
1700
- L: 58,
1701
- S: this,
1702
- C: (f, a) => f(...a)
1703
- });
1704
- for (const host of this._hosts) {
1705
- if (this._servers.has(host.server)) {
1706
- continue;
1707
- }
1708
- const server = new SignalClient(host.server, this._getMetadata);
1709
- server.swarmEvent.on((data) => this.swarmEvent.emit(data));
1710
- server.onMessage.on((data) => this.onMessage.emit(data));
1711
- server.statusChanged.on(() => this.statusChanged.emit(this.getStatus()));
1712
- this._servers.set(host.server, server);
1713
- this.failureCount.set(host.server, 0);
1714
- }
1715
- this._failedServersBitfield = import_util4.BitField.zeros(this._hosts.length);
1716
- }
1717
- async _open() {
1718
- (0, import_log6.log)("open signal manager", {
1719
- hosts: this._hosts
1720
- }, {
1721
- F: __dxlog_file6,
1722
- L: 78,
1723
- S: this,
1724
- C: (f, a) => f(...a)
1725
- });
1726
- import_log6.log.trace("dxos.mesh.websocket-signal-manager.open", import_protocols4.trace.begin({
1727
- id: this._instanceId
1728
- }), {
1729
- F: __dxlog_file6,
1730
- L: 79,
1731
- S: this,
1732
- C: (f, a) => f(...a)
1733
- });
1734
- await (0, import_util4.safeAwaitAll)(this._servers.values(), (server) => server.open());
1735
- import_log6.log.trace("dxos.mesh.websocket-signal-manager.open", import_protocols4.trace.end({
1736
- id: this._instanceId
1737
- }), {
1738
- F: __dxlog_file6,
1739
- L: 83,
1740
- S: this,
1741
- C: (f, a) => f(...a)
1742
- });
1743
- }
1744
- async _close() {
1745
- await (0, import_util4.safeAwaitAll)(this._servers.values(), (server) => server.close());
1746
- }
1747
- async restartServer(serverName) {
1748
- (0, import_log6.log)("restarting server", {
1749
- serverName
1750
- }, {
1751
- F: __dxlog_file6,
1752
- L: 91,
1753
- S: this,
1754
- C: (f, a) => f(...a)
1755
- });
1756
- (0, import_invariant5.invariant)(this._lifecycleState === import_context6.LifecycleState.OPEN, void 0, {
1757
- F: __dxlog_file6,
1758
- L: 92,
1759
- S: this,
1760
- A: [
1761
- "this._lifecycleState === LifecycleState.OPEN",
1762
- ""
1763
- ]
1764
- });
1765
- const server = this._servers.get(serverName);
1766
- (0, import_invariant5.invariant)(server, "server not found", {
1767
- F: __dxlog_file6,
1768
- L: 95,
1769
- S: this,
1770
- A: [
1771
- "server",
1772
- "'server not found'"
1773
- ]
1774
- });
1775
- await server.close();
1776
- await (0, import_async6.sleep)(WSS_SIGNAL_SERVER_REBOOT_DELAY);
1777
- await server.open();
1778
- }
1779
- getStatus() {
1780
- return Array.from(this._servers.values()).map((server) => server.getStatus());
1781
- }
1782
- async join({ topic, peer }) {
1783
- (0, import_log6.log)("join", {
1784
- topic,
1785
- peer
1786
- }, {
1787
- F: __dxlog_file6,
1788
- L: 108,
1789
- S: this,
1790
- C: (f, a) => f(...a)
1791
- });
1792
- (0, import_invariant5.invariant)(this._lifecycleState === import_context6.LifecycleState.OPEN, void 0, {
1793
- F: __dxlog_file6,
1794
- L: 109,
1795
- S: this,
1796
- A: [
1797
- "this._lifecycleState === LifecycleState.OPEN",
1798
- ""
1799
- ]
1800
- });
1801
- await this._forEachServer((server) => server.join({
1802
- topic,
1803
- peer
1804
- }));
1805
- }
1806
- async leave({ topic, peer }) {
1807
- (0, import_log6.log)("leaving", {
1808
- topic,
1809
- peer
1810
- }, {
1811
- F: __dxlog_file6,
1812
- L: 115,
1813
- S: this,
1814
- C: (f, a) => f(...a)
1815
- });
1816
- (0, import_invariant5.invariant)(this._lifecycleState === import_context6.LifecycleState.OPEN, void 0, {
1817
- F: __dxlog_file6,
1818
- L: 116,
1819
- S: this,
1820
- A: [
1821
- "this._lifecycleState === LifecycleState.OPEN",
1822
- ""
1823
- ]
1824
- });
1825
- await this._forEachServer((server) => server.leave({
1826
- topic,
1827
- peer
1828
- }));
1829
- }
1830
- async query({ topic }) {
1831
- throw new Error("Not implemented");
1832
- }
1833
- async sendMessage({ author, recipient, payload }) {
1834
- (0, import_log6.log)("signal", {
1835
- recipient
1836
- }, {
1837
- F: __dxlog_file6,
1838
- L: 125,
1839
- S: this,
1840
- C: (f, a) => f(...a)
1841
- });
1842
- (0, import_invariant5.invariant)(this._lifecycleState === import_context6.LifecycleState.OPEN, void 0, {
1843
- F: __dxlog_file6,
1844
- L: 126,
1845
- S: this,
1846
- A: [
1847
- "this._lifecycleState === LifecycleState.OPEN",
1848
- ""
1849
- ]
1850
- });
1851
- void this._forEachServer(async (server, serverName, index) => {
1852
- void server.sendMessage({
1853
- author,
1854
- recipient,
1855
- payload
1856
- }).then(() => this._clearServerFailedFlag(serverName, index)).catch((err) => {
1857
- if (err instanceof import_protocols4.RateLimitExceededError) {
1858
- import_log6.log.info("WSS rate limit exceeded", {
1859
- err
1860
- }, {
1861
- F: __dxlog_file6,
1862
- L: 134,
1863
- S: this,
1864
- C: (f, a) => f(...a)
1865
- });
1866
- this._monitor.recordRateLimitExceeded();
1867
- } else if (err instanceof import_protocols4.TimeoutError || err.constructor.name === "TimeoutError") {
1868
- import_log6.log.info("WSS sendMessage timeout", {
1869
- err
1870
- }, {
1871
- F: __dxlog_file6,
1872
- L: 137,
1873
- S: this,
1874
- C: (f, a) => f(...a)
1875
- });
1876
- void this.checkServerFailure(serverName, index);
1877
- } else {
1878
- import_log6.log.warn(`error sending to ${serverName}`, {
1879
- err
1880
- }, {
1881
- F: __dxlog_file6,
1882
- L: 140,
1883
- S: this,
1884
- C: (f, a) => f(...a)
1885
- });
1886
- void this.checkServerFailure(serverName, index);
1887
- }
1888
- });
1889
- });
1890
- }
1891
- async checkServerFailure(serverName, index) {
1892
- const failureCount = this.failureCount.get(serverName) ?? 0;
1893
- const isRestartRequired = failureCount > MAX_SERVER_FAILURES;
1894
- this._monitor.recordServerFailure({
1895
- serverName,
1896
- willRestart: isRestartRequired
1897
- });
1898
- if (isRestartRequired) {
1899
- if (!import_util4.BitField.get(this._failedServersBitfield, index)) {
1900
- import_log6.log.warn("too many failures for ws-server, restarting", {
1901
- serverName,
1902
- failureCount
1903
- }, {
1904
- F: __dxlog_file6,
1905
- L: 154,
1906
- S: this,
1907
- C: (f, a) => f(...a)
1908
- });
1909
- import_util4.BitField.set(this._failedServersBitfield, index, true);
1910
- }
1911
- await this.restartServer(serverName);
1912
- this.failureCount.set(serverName, 0);
1913
- return;
1914
- }
1915
- this.failureCount.set(serverName, (this.failureCount.get(serverName) ?? 0) + 1);
1916
- }
1917
- _clearServerFailedFlag(serverName, index) {
1918
- if (import_util4.BitField.get(this._failedServersBitfield, index)) {
1919
- import_log6.log.info("server connection restored", {
1920
- serverName
1921
- }, {
1922
- F: __dxlog_file6,
1923
- L: 167,
1924
- S: this,
1925
- C: (f, a) => f(...a)
1926
- });
1927
- import_util4.BitField.set(this._failedServersBitfield, index, false);
1928
- this.failureCount.set(serverName, 0);
1929
- }
1930
- }
1931
- async subscribeMessages(peer) {
1932
- (0, import_log6.log)("subscribed for message stream", {
1933
- peer
1934
- }, {
1935
- F: __dxlog_file6,
1936
- L: 174,
1937
- S: this,
1938
- C: (f, a) => f(...a)
1939
- });
1940
- (0, import_invariant5.invariant)(this._lifecycleState === import_context6.LifecycleState.OPEN, void 0, {
1941
- F: __dxlog_file6,
1942
- L: 175,
1943
- S: this,
1944
- A: [
1945
- "this._lifecycleState === LifecycleState.OPEN",
1946
- ""
1947
- ]
1948
- });
1949
- await this._forEachServer(async (server) => server.subscribeMessages(peer));
1950
- }
1951
- async unsubscribeMessages(peer) {
1952
- (0, import_log6.log)("subscribed for message stream", {
1953
- peer
1954
- }, {
1955
- F: __dxlog_file6,
1956
- L: 181,
1957
- S: this,
1958
- C: (f, a) => f(...a)
1959
- });
1960
- (0, import_invariant5.invariant)(this._lifecycleState === import_context6.LifecycleState.OPEN, void 0, {
1961
- F: __dxlog_file6,
1962
- L: 182,
1963
- S: this,
1964
- A: [
1965
- "this._lifecycleState === LifecycleState.OPEN",
1966
- ""
1967
- ]
1968
- });
1969
- await this._forEachServer(async (server) => server.unsubscribeMessages(peer));
1970
- }
1971
- async _forEachServer(fn) {
1972
- return Promise.all(Array.from(this._servers.entries()).map(([serverName, server], idx) => fn(server, serverName, idx)));
1973
- }
1974
- };
1975
- _ts_decorate([
1976
- import_async6.synchronized
1977
- ], WebsocketSignalManager.prototype, "join", null);
1978
- _ts_decorate([
1979
- import_async6.synchronized
1980
- ], WebsocketSignalManager.prototype, "leave", null);
1981
- _ts_decorate([
1982
- import_async6.synchronized
1983
- ], WebsocketSignalManager.prototype, "checkServerFailure", null);
1984
- var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/edge-signal-manager.ts";
1985
- var EdgeSignalManager = class extends import_context7.Resource {
1986
- constructor({ edgeConnection }) {
1987
- super();
1988
- this.swarmEvent = new import_async7.Event();
1989
- this.swarmState = new import_async7.Event();
1990
- this.onMessage = new import_async7.Event();
1991
- this._swarmPeers = new import_util5.ComplexMap(import_keys7.PublicKey.hash);
1992
- this._edgeConnection = edgeConnection;
1993
- }
1994
- async _open() {
1995
- this._ctx.onDispose(this._edgeConnection.onMessage((message) => this._onMessage(message)));
1996
- this._ctx.onDispose(this._edgeConnection.onReconnected(() => {
1997
- (0, import_async7.scheduleMicroTask)(this._ctx, () => this._rejoinAllSwarms());
1998
- }));
1999
- }
2000
- /**
2001
- * Warning: PeerInfo is inferred from edgeConnection.
2002
- */
2003
- async join({ topic, peer }) {
2004
- if (!this._matchSelfPeerInfo(peer)) {
2005
- import_log7.log.warn("ignoring peer info on join request", {
2006
- peer,
2007
- expected: {
2008
- peerKey: this._edgeConnection.peerKey,
2009
- identityKey: this._edgeConnection.identityKey
2010
- }
2011
- }, {
2012
- F: __dxlog_file7,
2013
- L: 65,
2014
- S: this,
2015
- C: (f, a) => f(...a)
2016
- });
2017
- peer.identityKey = this._edgeConnection.identityKey;
2018
- peer.peerKey = this._edgeConnection.peerKey;
2019
- }
2020
- this._swarmPeers.set(topic, {
2021
- lastState: peer.state,
2022
- joinedPeers: new import_util5.ComplexSet(PeerInfoHash)
2023
- });
2024
- await this._edgeConnection.send(import_edge_client.protocol.createMessage(import_messenger_pb.SwarmRequestSchema, {
2025
- serviceId: import_protocols5.EdgeService.SWARM,
2026
- source: createMessageSource(topic, peer),
2027
- payload: {
2028
- action: import_messenger_pb.SwarmRequest_Action.JOIN,
2029
- swarmKeys: [
2030
- topic.toHex()
2031
- ]
2032
- }
2033
- }));
2034
- }
2035
- async leave({ topic, peer }) {
2036
- this._swarmPeers.delete(topic);
2037
- await this._edgeConnection.send(import_edge_client.protocol.createMessage(import_messenger_pb.SwarmRequestSchema, {
2038
- serviceId: import_protocols5.EdgeService.SWARM,
2039
- source: createMessageSource(topic, peer),
2040
- payload: {
2041
- action: import_messenger_pb.SwarmRequest_Action.LEAVE,
2042
- swarmKeys: [
2043
- topic.toHex()
2044
- ]
2045
- }
2046
- }));
2047
- }
2048
- async query({ topic }) {
2049
- const response = (0, import_context7.cancelWithContext)(this._ctx, this.swarmState.waitFor((state) => state.swarmKey === topic.toHex()));
2050
- await this._edgeConnection.send(import_edge_client.protocol.createMessage(import_messenger_pb.SwarmRequestSchema, {
2051
- serviceId: import_protocols5.EdgeService.SWARM,
2052
- source: createMessageSource(topic, {
2053
- peerKey: this._edgeConnection.peerKey,
2054
- identityKey: this._edgeConnection.identityKey
2055
- }),
2056
- payload: {
2057
- action: import_messenger_pb.SwarmRequest_Action.INFO,
2058
- swarmKeys: [
2059
- topic.toHex()
2060
- ]
2061
- }
2062
- }));
2063
- return response;
2064
- }
2065
- async sendMessage(message) {
2066
- if (!this._matchSelfPeerInfo(message.author)) {
2067
- import_log7.log.warn("ignoring author on send request", {
2068
- author: message.author,
2069
- expected: {
2070
- peerKey: this._edgeConnection.peerKey,
2071
- identityKey: this._edgeConnection.identityKey
2072
- }
2073
- }, {
2074
- F: __dxlog_file7,
2075
- L: 121,
2076
- S: this,
2077
- C: (f, a) => f(...a)
2078
- });
2079
- }
2080
- await this._edgeConnection.send(import_edge_client.protocol.createMessage(import_buf.bufWkt.AnySchema, {
2081
- serviceId: import_protocols5.EdgeService.SIGNAL,
2082
- source: message.author,
2083
- target: [
2084
- message.recipient
2085
- ],
2086
- payload: {
2087
- typeUrl: message.payload.type_url,
2088
- value: message.payload.value
2089
- }
2090
- }));
2091
- }
2092
- async subscribeMessages(peerInfo) {
2093
- }
2094
- async unsubscribeMessages(peerInfo) {
2095
- }
2096
- _onMessage(message) {
2097
- switch (message.serviceId) {
2098
- case import_protocols5.EdgeService.SWARM: {
2099
- this._processSwarmResponse(message);
2100
- break;
2101
- }
2102
- case import_protocols5.EdgeService.SIGNAL: {
2103
- this._processMessage(message);
2104
- }
2105
- }
2106
- }
2107
- _processSwarmResponse(message) {
2108
- (0, import_invariant6.invariant)(import_edge_client.protocol.getPayloadType(message) === import_messenger_pb.SwarmResponseSchema.typeName, "Wrong payload type", {
2109
- F: __dxlog_file7,
2110
- L: 158,
2111
- S: this,
2112
- A: [
2113
- "protocol.getPayloadType(message) === SwarmResponseSchema.typeName",
2114
- "'Wrong payload type'"
2115
- ]
2116
- });
2117
- const payload = import_edge_client.protocol.getPayload(message, import_messenger_pb.SwarmResponseSchema);
2118
- this.swarmState.emit(payload);
2119
- const topic = import_keys7.PublicKey.from(payload.swarmKey);
2120
- if (!this._swarmPeers.has(topic)) {
2121
- return;
2122
- }
2123
- const { joinedPeers: oldPeers } = this._swarmPeers.get(topic);
2124
- const timestamp = message.timestamp ? new Date(Date.parse(message.timestamp)) : /* @__PURE__ */ new Date();
2125
- const newPeers = new import_util5.ComplexSet(PeerInfoHash, payload.peers);
2126
- for (const peer of newPeers) {
2127
- if (oldPeers.has(peer)) {
2128
- continue;
2129
- }
2130
- this.swarmEvent.emit({
2131
- topic,
2132
- peerAvailable: {
2133
- peer,
2134
- since: timestamp
2135
- }
2136
- });
2137
- }
2138
- for (const peer of oldPeers) {
2139
- if (newPeers.has(peer)) {
2140
- continue;
2141
- }
2142
- this.swarmEvent.emit({
2143
- topic,
2144
- peerLeft: {
2145
- peer
2146
- }
2147
- });
2148
- }
2149
- this._swarmPeers.get(topic).joinedPeers = newPeers;
2150
- }
2151
- _processMessage(message) {
2152
- (0, import_invariant6.invariant)(import_edge_client.protocol.getPayloadType(message) === import_buf.bufWkt.AnySchema.typeName, "Wrong payload type", {
2153
- F: __dxlog_file7,
2154
- L: 196,
2155
- S: this,
2156
- A: [
2157
- "protocol.getPayloadType(message) === bufWkt.AnySchema.typeName",
2158
- "'Wrong payload type'"
2159
- ]
2160
- });
2161
- const payload = import_edge_client.protocol.getPayload(message, import_buf.bufWkt.AnySchema);
2162
- (0, import_invariant6.invariant)(message.source, "source is missing", {
2163
- F: __dxlog_file7,
2164
- L: 198,
2165
- S: this,
2166
- A: [
2167
- "message.source",
2168
- "'source is missing'"
2169
- ]
2170
- });
2171
- (0, import_invariant6.invariant)(message.target, "target is missing", {
2172
- F: __dxlog_file7,
2173
- L: 199,
2174
- S: this,
2175
- A: [
2176
- "message.target",
2177
- "'target is missing'"
2178
- ]
2179
- });
2180
- (0, import_invariant6.invariant)(message.target.length === 1, "target should have exactly one item", {
2181
- F: __dxlog_file7,
2182
- L: 200,
2183
- S: this,
2184
- A: [
2185
- "message.target.length === 1",
2186
- "'target should have exactly one item'"
2187
- ]
2188
- });
2189
- this.onMessage.emit({
2190
- author: message.source,
2191
- recipient: message.target[0],
2192
- payload: {
2193
- type_url: payload.typeUrl,
2194
- value: payload.value
2195
- }
2196
- });
2197
- }
2198
- _matchSelfPeerInfo(peer) {
2199
- return peer && (peer.peerKey === this._edgeConnection.peerKey || peer.identityKey === this._edgeConnection.identityKey);
2200
- }
2201
- async _rejoinAllSwarms() {
2202
- (0, import_log7.log)("rejoin swarms", {
2203
- swarms: Array.from(this._swarmPeers.keys())
2204
- }, {
2205
- F: __dxlog_file7,
2206
- L: 219,
2207
- S: this,
2208
- C: (f, a) => f(...a)
2209
- });
2210
- for (const [topic, { lastState }] of this._swarmPeers.entries()) {
2211
- await this.join({
2212
- topic,
2213
- peer: {
2214
- peerKey: this._edgeConnection.peerKey,
2215
- identityKey: this._edgeConnection.identityKey,
2216
- state: lastState
2217
- }
2218
- });
2219
- }
2220
- }
2221
- };
2222
- var createMessageSource = (topic, peerInfo) => {
2223
- return {
2224
- swarmKey: topic.toHex(),
2225
- ...peerInfo
2226
- };
2227
- };
2228
- var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/utils.ts";
2229
- var setIdentityTags = ({ identityService, devicesService, setTag }) => {
2230
- identityService.queryIdentity().subscribe((idqr) => {
2231
- if (!idqr?.identity?.identityKey) {
2232
- (0, import_log8.log)("empty response from identity service", {
2233
- idqr
2234
- }, {
2235
- F: __dxlog_file8,
2236
- L: 21,
2237
- S: void 0,
2238
- C: (f, a) => f(...a)
2239
- });
2240
- return;
2241
- }
2242
- setTag("identityKey", idqr.identity.identityKey.truncate());
2243
- });
2244
- devicesService.queryDevices().subscribe((dqr) => {
2245
- if (!dqr || !dqr.devices || dqr.devices.length === 0) {
2246
- (0, import_log8.log)("empty response from device service", {
2247
- device: dqr
2248
- }, {
2249
- F: __dxlog_file8,
2250
- L: 30,
2251
- S: void 0,
2252
- C: (f, a) => f(...a)
2253
- });
2254
- return;
2255
- }
2256
- (0, import_invariant7.invariant)(dqr, "empty response from device service", {
2257
- F: __dxlog_file8,
2258
- L: 33,
2259
- S: void 0,
2260
- A: [
2261
- "dqr",
2262
- "'empty response from device service'"
2263
- ]
2264
- });
2265
- const thisDevice = dqr.devices.find((device) => device.kind === import_services.DeviceKind.CURRENT);
2266
- if (!thisDevice) {
2267
- (0, import_log8.log)("no current device", {
2268
- device: dqr
2269
- }, {
2270
- F: __dxlog_file8,
2271
- L: 37,
2272
- S: void 0,
2273
- C: (f, a) => f(...a)
2274
- });
2275
- return;
2276
- }
2277
- setTag("deviceKey", thisDevice.deviceKey.truncate());
2278
- });
2279
- };
2280
- // Annotate the CommonJS export names for ESM import in node:
2281
- 0 && (module.exports = {
2282
- EdgeSignalManager,
2283
- MemorySignalManager,
2284
- MemorySignalManagerContext,
2285
- Messenger,
2286
- PeerInfoHash,
2287
- SignalClient,
2288
- WebsocketSignalManager,
2289
- setIdentityTags
2290
- });
2291
- //# sourceMappingURL=chunk-GMND65DN.cjs.map