@dxos/messaging 0.8.4-main.ead640a → 0.8.4-main.f466a3d56e

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 (62) hide show
  1. package/LICENSE +102 -5
  2. package/dist/lib/neutral/chunk-EC4H56J5.mjs +497 -0
  3. package/dist/lib/neutral/chunk-EC4H56J5.mjs.map +7 -0
  4. package/dist/lib/neutral/index.mjs +1249 -0
  5. package/dist/lib/neutral/index.mjs.map +7 -0
  6. package/dist/lib/neutral/meta.json +1 -0
  7. package/dist/lib/{browser → neutral}/testing/index.mjs +18 -46
  8. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  9. package/dist/types/src/messenger-monitor.d.ts.map +1 -1
  10. package/dist/types/src/messenger.blueprint-test.d.ts +1 -1
  11. package/dist/types/src/messenger.blueprint-test.d.ts.map +1 -1
  12. package/dist/types/src/messenger.d.ts +3 -2
  13. package/dist/types/src/messenger.d.ts.map +1 -1
  14. package/dist/types/src/signal-client/signal-client-monitor.d.ts.map +1 -1
  15. package/dist/types/src/signal-client/signal-client.d.ts +5 -6
  16. package/dist/types/src/signal-client/signal-client.d.ts.map +1 -1
  17. package/dist/types/src/signal-client/signal-local-state.d.ts.map +1 -1
  18. package/dist/types/src/signal-client/signal-rpc-client-monitor.d.ts.map +1 -1
  19. package/dist/types/src/signal-client/signal-rpc-client.d.ts +3 -3
  20. package/dist/types/src/signal-client/signal-rpc-client.d.ts.map +1 -1
  21. package/dist/types/src/signal-manager/edge-signal-manager.d.ts +5 -5
  22. package/dist/types/src/signal-manager/edge-signal-manager.d.ts.map +1 -1
  23. package/dist/types/src/signal-manager/memory-signal-manager.d.ts +5 -4
  24. package/dist/types/src/signal-manager/memory-signal-manager.d.ts.map +1 -1
  25. package/dist/types/src/signal-manager/utils.d.ts.map +1 -1
  26. package/dist/types/src/signal-manager/websocket-signal-manager-monitor.d.ts.map +1 -1
  27. package/dist/types/src/signal-manager/websocket-signal-manager.d.ts +5 -6
  28. package/dist/types/src/signal-manager/websocket-signal-manager.d.ts.map +1 -1
  29. package/dist/types/src/signal-methods.d.ts +5 -5
  30. package/dist/types/src/signal-methods.d.ts.map +1 -1
  31. package/dist/types/src/testing/test-builder.d.ts.map +1 -1
  32. package/dist/types/src/testing/test-peer.d.ts.map +1 -1
  33. package/dist/types/src/testing/utils.d.ts.map +1 -1
  34. package/dist/types/tsconfig.tsbuildinfo +1 -1
  35. package/package.json +25 -30
  36. package/src/messenger.blueprint-test.ts +13 -12
  37. package/src/messenger.ts +37 -32
  38. package/src/signal-client/signal-client.node.test.ts +9 -9
  39. package/src/signal-client/signal-client.ts +6 -10
  40. package/src/signal-client/signal-local-state.ts +0 -1
  41. package/src/signal-client/signal-rpc-client.ts +4 -6
  42. package/src/signal-manager/edge-signal-manager.ts +10 -7
  43. package/src/signal-manager/memory-signal-manager.ts +17 -15
  44. package/src/signal-manager/websocket-signal-manager.node.test.ts +13 -13
  45. package/src/signal-manager/websocket-signal-manager.ts +9 -16
  46. package/src/signal-methods.ts +5 -5
  47. package/src/testing/test-builder.ts +4 -3
  48. package/src/testing/test-peer.ts +0 -1
  49. package/src/testing/utils.ts +0 -1
  50. package/dist/lib/browser/chunk-CD3GXEDZ.mjs +0 -2433
  51. package/dist/lib/browser/chunk-CD3GXEDZ.mjs.map +0 -7
  52. package/dist/lib/browser/index.mjs +0 -22
  53. package/dist/lib/browser/index.mjs.map +0 -7
  54. package/dist/lib/browser/meta.json +0 -1
  55. package/dist/lib/browser/testing/index.mjs.map +0 -7
  56. package/dist/lib/node-esm/chunk-IVXFEWLW.mjs +0 -2433
  57. package/dist/lib/node-esm/chunk-IVXFEWLW.mjs.map +0 -7
  58. package/dist/lib/node-esm/index.mjs +0 -22
  59. package/dist/lib/node-esm/index.mjs.map +0 -7
  60. package/dist/lib/node-esm/meta.json +0 -1
  61. package/dist/lib/node-esm/testing/index.mjs +0 -172
  62. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
package/LICENSE CHANGED
@@ -1,8 +1,105 @@
1
- MIT License
2
- Copyright (c) 2022 DXOS
1
+ # Functional Source License, Version 1.1, ALv2 Future License
3
2
 
4
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
3
+ ## Abbreviation
5
4
 
6
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
5
+ FSL-1.1-Apache-2.0
7
6
 
8
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7
+ ## Notice
8
+
9
+ Copyright 2026 DXOS
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following
93
+ will apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
@@ -0,0 +1,497 @@
1
+ import "@dxos/node-std/globals";
2
+
3
+ // src/messenger.ts
4
+ import { TimeoutError, scheduleExponentialBackoffTaskInterval, scheduleTask, scheduleTaskInterval } from "@dxos/async";
5
+ import { Context } from "@dxos/context";
6
+ import { invariant } from "@dxos/invariant";
7
+ import { PublicKey } from "@dxos/keys";
8
+ import { log } from "@dxos/log";
9
+ import { TimeoutError as ProtocolTimeoutError } from "@dxos/protocols";
10
+ import { schema } from "@dxos/protocols/proto";
11
+ import { ComplexMap, ComplexSet } from "@dxos/util";
12
+
13
+ // src/messenger-monitor.ts
14
+ import { trace } from "@dxos/tracing";
15
+ var MessengerMonitor = class {
16
+ recordMessageAckFailed() {
17
+ trace.metrics.increment("dxos.mesh.signal.messenger.failed-ack", 1);
18
+ }
19
+ recordReliableMessage(params) {
20
+ trace.metrics.increment("dxos.mesh.signal.messenger.reliable-send", 1, {
21
+ tags: {
22
+ success: params.sent,
23
+ attempts: params.sendAttempts
24
+ }
25
+ });
26
+ }
27
+ };
28
+
29
+ // src/timeouts.ts
30
+ var MESSAGE_TIMEOUT = 1e4;
31
+
32
+ // src/messenger.ts
33
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/mesh/messaging/src/messenger.ts";
34
+ var ReliablePayload = schema.getCodecForType("dxos.mesh.messaging.ReliablePayload");
35
+ var Acknowledgement = schema.getCodecForType("dxos.mesh.messaging.Acknowledgement");
36
+ var RECEIVED_MESSAGES_GC_INTERVAL = 12e4;
37
+ var Messenger = class {
38
+ _monitor = new MessengerMonitor();
39
+ _signalManager;
40
+ // { peerId, payloadType } => listeners set
41
+ _listeners = new ComplexMap(({ peerId, payloadType }) => peerId + payloadType);
42
+ // peerId => listeners set
43
+ _defaultListeners = /* @__PURE__ */ new Map();
44
+ _onAckCallbacks = new ComplexMap(PublicKey.hash);
45
+ _receivedMessages = new ComplexSet(PublicKey.hash);
46
+ /**
47
+ * Keys scheduled to be cleared from _receivedMessages on the next iteration.
48
+ */
49
+ _toClear = new ComplexSet(PublicKey.hash);
50
+ _ctx;
51
+ _closed = true;
52
+ _retryDelay;
53
+ constructor({ signalManager, retryDelay = 1e3 }) {
54
+ this._signalManager = signalManager;
55
+ this._retryDelay = retryDelay;
56
+ this.open();
57
+ }
58
+ open() {
59
+ if (!this._closed) {
60
+ return;
61
+ }
62
+ log("opening messenger", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 43, S: this });
63
+ this._ctx = new Context({
64
+ onError: (err) => log.catch(err, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 45, S: this })
65
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 44 });
66
+ this._ctx.onDispose(this._signalManager.onMessage.on(async (message) => {
67
+ log("received message", {
68
+ from: message.author
69
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 48, S: this });
70
+ await this._handleMessage(message);
71
+ }));
72
+ scheduleTaskInterval(this._ctx, async () => {
73
+ this._performGc();
74
+ }, RECEIVED_MESSAGES_GC_INTERVAL);
75
+ this._closed = false;
76
+ log("opened messenger", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 58, S: this });
77
+ }
78
+ async close() {
79
+ if (this._closed) {
80
+ return;
81
+ }
82
+ this._closed = true;
83
+ await this._ctx.dispose();
84
+ }
85
+ async sendMessage(ctx, { author, recipient, payload }) {
86
+ invariant(!this._closed, "Closed", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 68, S: this, A: ["!this._closed", "'Closed'"] });
87
+ const messageContext = this._ctx.derive();
88
+ const reliablePayload = {
89
+ messageId: PublicKey.random(),
90
+ payload
91
+ };
92
+ invariant(!this._onAckCallbacks.has(reliablePayload.messageId), void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 74, S: this, A: ["!this._onAckCallbacks.has(reliablePayload.messageId)", ""] });
93
+ log("send message", {
94
+ messageId: reliablePayload.messageId,
95
+ author,
96
+ recipient
97
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 75, S: this });
98
+ let messageReceived;
99
+ let timeoutHit;
100
+ let sendAttempts = 0;
101
+ const promise = new Promise((resolve, reject) => {
102
+ messageReceived = resolve;
103
+ timeoutHit = reject;
104
+ });
105
+ scheduleExponentialBackoffTaskInterval(messageContext, async () => {
106
+ log("retrying message", {
107
+ messageId: reliablePayload.messageId
108
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 89, S: this });
109
+ sendAttempts++;
110
+ await this._encodeAndSend(ctx, {
111
+ author,
112
+ recipient,
113
+ reliablePayload
114
+ }).catch((err) => log("failed to send message", {
115
+ err
116
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 97, S: this }));
117
+ }, this._retryDelay);
118
+ scheduleTask(messageContext, () => {
119
+ log("message not delivered", {
120
+ messageId: reliablePayload.messageId
121
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 102, S: this });
122
+ this._onAckCallbacks.delete(reliablePayload.messageId);
123
+ timeoutHit(new ProtocolTimeoutError({
124
+ message: "signaling message not delivered",
125
+ cause: new TimeoutError(MESSAGE_TIMEOUT, "Message not delivered")
126
+ }));
127
+ void messageContext.dispose();
128
+ this._monitor.recordReliableMessage({
129
+ sendAttempts,
130
+ sent: false
131
+ });
132
+ }, MESSAGE_TIMEOUT);
133
+ this._onAckCallbacks.set(reliablePayload.messageId, () => {
134
+ messageReceived();
135
+ this._onAckCallbacks.delete(reliablePayload.messageId);
136
+ void messageContext.dispose();
137
+ this._monitor.recordReliableMessage({
138
+ sendAttempts,
139
+ sent: true
140
+ });
141
+ });
142
+ await this._encodeAndSend(ctx, {
143
+ author,
144
+ recipient,
145
+ reliablePayload
146
+ });
147
+ return promise;
148
+ }
149
+ /**
150
+ * Subscribes onMessage function to messages that contains payload with payloadType.
151
+ * @param payloadType if not specified, onMessage will be subscribed to all types of messages.
152
+ */
153
+ async listen({ peer, payloadType, onMessage }) {
154
+ invariant(!this._closed, "Closed", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 136, S: this, A: ["!this._closed", "'Closed'"] });
155
+ await this._signalManager.subscribeMessages(peer);
156
+ let listeners;
157
+ invariant(peer.peerKey, "Peer key is required", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 139, S: this, A: ["peer.peerKey", "'Peer key is required'"] });
158
+ if (!payloadType) {
159
+ listeners = this._defaultListeners.get(peer.peerKey);
160
+ if (!listeners) {
161
+ listeners = /* @__PURE__ */ new Set();
162
+ this._defaultListeners.set(peer.peerKey, listeners);
163
+ }
164
+ } else {
165
+ listeners = this._listeners.get({
166
+ peerId: peer.peerKey,
167
+ payloadType
168
+ });
169
+ if (!listeners) {
170
+ listeners = /* @__PURE__ */ new Set();
171
+ this._listeners.set({
172
+ peerId: peer.peerKey,
173
+ payloadType
174
+ }, listeners);
175
+ }
176
+ }
177
+ listeners.add(onMessage);
178
+ return {
179
+ unsubscribe: async () => {
180
+ listeners.delete(onMessage);
181
+ }
182
+ };
183
+ }
184
+ async _encodeAndSend(ctx, { author, recipient, reliablePayload }) {
185
+ await this._signalManager.sendMessage(ctx, {
186
+ author,
187
+ recipient,
188
+ payload: {
189
+ type_url: "dxos.mesh.messaging.ReliablePayload",
190
+ value: ReliablePayload.encode(reliablePayload, {
191
+ preserveAny: true
192
+ })
193
+ }
194
+ });
195
+ }
196
+ async _handleMessage(message) {
197
+ switch (message.payload.type_url) {
198
+ case "dxos.mesh.messaging.ReliablePayload": {
199
+ await this._handleReliablePayload(message);
200
+ break;
201
+ }
202
+ case "dxos.mesh.messaging.Acknowledgement": {
203
+ await this._handleAcknowledgement({
204
+ payload: message.payload
205
+ });
206
+ break;
207
+ }
208
+ }
209
+ }
210
+ async _handleReliablePayload({ author, recipient, payload }) {
211
+ invariant(payload.type_url === "dxos.mesh.messaging.ReliablePayload", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 195, S: this, A: ["payload.type_url === 'dxos.mesh.messaging.ReliablePayload'", ""] });
212
+ const reliablePayload = ReliablePayload.decode(payload.value, {
213
+ preserveAny: true
214
+ });
215
+ log("handling message", {
216
+ messageId: reliablePayload.messageId
217
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 199, S: this });
218
+ try {
219
+ await this._sendAcknowledgement(this._ctx, {
220
+ author,
221
+ recipient,
222
+ messageId: reliablePayload.messageId
223
+ });
224
+ } catch (err) {
225
+ this._monitor.recordMessageAckFailed();
226
+ throw err;
227
+ }
228
+ if (this._receivedMessages.has(reliablePayload.messageId)) {
229
+ return;
230
+ }
231
+ this._receivedMessages.add(reliablePayload.messageId);
232
+ await this._callListeners({
233
+ author,
234
+ recipient,
235
+ payload: reliablePayload.payload
236
+ });
237
+ }
238
+ async _handleAcknowledgement({ payload }) {
239
+ invariant(payload.type_url === "dxos.mesh.messaging.Acknowledgement", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 224, S: this, A: ["payload.type_url === 'dxos.mesh.messaging.Acknowledgement'", ""] });
240
+ this._onAckCallbacks.get(Acknowledgement.decode(payload.value).messageId)?.();
241
+ }
242
+ async _sendAcknowledgement(ctx, { author, recipient, messageId }) {
243
+ log("sending ACK", {
244
+ messageId,
245
+ from: recipient,
246
+ to: author
247
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 228, S: this });
248
+ await this._signalManager.sendMessage(ctx, {
249
+ author: recipient,
250
+ recipient: author,
251
+ payload: {
252
+ type_url: "dxos.mesh.messaging.Acknowledgement",
253
+ value: Acknowledgement.encode({
254
+ messageId
255
+ })
256
+ }
257
+ });
258
+ }
259
+ async _callListeners(message) {
260
+ {
261
+ invariant(message.recipient.peerKey, "Peer key is required", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 246, S: this, A: ["message.recipient.peerKey", "'Peer key is required'"] });
262
+ const defaultListenerMap = this._defaultListeners.get(message.recipient.peerKey);
263
+ if (defaultListenerMap) {
264
+ for (const listener of defaultListenerMap) {
265
+ await listener(message);
266
+ }
267
+ }
268
+ }
269
+ {
270
+ const listenerMap = this._listeners.get({
271
+ peerId: message.recipient.peerKey,
272
+ payloadType: message.payload.type_url
273
+ });
274
+ if (listenerMap) {
275
+ for (const listener of listenerMap) {
276
+ await listener(message);
277
+ }
278
+ }
279
+ }
280
+ }
281
+ _performGc() {
282
+ const start = performance.now();
283
+ for (const key of this._toClear.keys()) {
284
+ this._receivedMessages.delete(key);
285
+ }
286
+ this._toClear.clear();
287
+ for (const key of this._receivedMessages.keys()) {
288
+ this._toClear.add(key);
289
+ }
290
+ const elapsed = performance.now() - start;
291
+ if (elapsed > 100) {
292
+ log.warn("GC took too long", {
293
+ elapsed
294
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 277, S: this });
295
+ }
296
+ }
297
+ };
298
+
299
+ // src/signal-methods.ts
300
+ var PeerInfoHash = ({ peerKey }) => peerKey;
301
+
302
+ // src/signal-manager/memory-signal-manager.ts
303
+ import { Event, Trigger } from "@dxos/async";
304
+ import { Context as Context2 } from "@dxos/context";
305
+ import { invariant as invariant2 } from "@dxos/invariant";
306
+ import { PublicKey as PublicKey2 } from "@dxos/keys";
307
+ import { log as log2 } from "@dxos/log";
308
+ import { schema as schema2 } from "@dxos/protocols/proto";
309
+ import { ComplexMap as ComplexMap2, ComplexSet as ComplexSet2 } from "@dxos/util";
310
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/memory-signal-manager.ts";
311
+ var MemorySignalManagerContext = class {
312
+ // Swarm messages.
313
+ swarmEvent = new Event();
314
+ // Mapping from topic to set of peers.
315
+ swarms = new ComplexMap2(PublicKey2.hash);
316
+ // Map of connections for each peer for signaling.
317
+ connections = new ComplexMap2(PeerInfoHash);
318
+ };
319
+ var MemorySignalManager = class {
320
+ _context;
321
+ statusChanged = new Event();
322
+ swarmEvent = new Event();
323
+ onMessage = new Event();
324
+ /** Will be used to emit SwarmEvents on .open() and .close() */
325
+ _joinedSwarms = new ComplexSet2(({ topic, peer }) => topic.toHex() + peer.peerKey);
326
+ _ctx;
327
+ // TODO(dmaretskyi): Replace with callback.
328
+ _freezeTrigger = new Trigger().wake();
329
+ constructor(_context) {
330
+ this._context = _context;
331
+ this._ctx = new Context2(void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 35 });
332
+ this._ctx.onDispose(this._context.swarmEvent.on((data) => this.swarmEvent.emit(data)));
333
+ }
334
+ async open() {
335
+ if (!this._ctx.disposed) {
336
+ return;
337
+ }
338
+ this._ctx = new Context2(void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 42 });
339
+ this._ctx.onDispose(this._context.swarmEvent.on((data) => this.swarmEvent.emit(data)));
340
+ await Promise.all([
341
+ ...this._joinedSwarms.values()
342
+ ].map((value) => this.join(this._ctx, value)));
343
+ }
344
+ async close() {
345
+ if (this._ctx.disposed) {
346
+ return;
347
+ }
348
+ const joinedSwarmsCopy = new ComplexSet2(({ topic, peer }) => topic.toHex() + peer.peerKey, [
349
+ ...this._joinedSwarms.values()
350
+ ]);
351
+ await Promise.all([
352
+ ...this._joinedSwarms.values()
353
+ ].map((value) => this.leave(this._ctx, value)));
354
+ this._joinedSwarms = joinedSwarmsCopy;
355
+ await this._ctx.dispose();
356
+ }
357
+ getStatus() {
358
+ return [];
359
+ }
360
+ async join(_ctx, { topic, peer }) {
361
+ invariant2(!this._ctx.disposed, "Closed", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 67, S: this, A: ["!this._ctx.disposed", "'Closed'"] });
362
+ this._joinedSwarms.add({
363
+ topic,
364
+ peer
365
+ });
366
+ if (!this._context.swarms.has(topic)) {
367
+ this._context.swarms.set(topic, new ComplexSet2(PeerInfoHash));
368
+ }
369
+ this._context.swarms.get(topic).add(peer);
370
+ this._context.swarmEvent.emit({
371
+ topic,
372
+ peerAvailable: {
373
+ peer,
374
+ since: /* @__PURE__ */ new Date()
375
+ }
376
+ });
377
+ for (const [topic2, peers] of this._context.swarms) {
378
+ Array.from(peers).forEach((peer2) => {
379
+ this.swarmEvent.emit({
380
+ topic: topic2,
381
+ peerAvailable: {
382
+ peer: peer2,
383
+ since: /* @__PURE__ */ new Date()
384
+ }
385
+ });
386
+ });
387
+ }
388
+ }
389
+ async leave(_ctx, { topic, peer }) {
390
+ invariant2(!this._ctx.disposed, "Closed", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 97, S: this, A: ["!this._ctx.disposed", "'Closed'"] });
391
+ this._joinedSwarms.delete({
392
+ topic,
393
+ peer
394
+ });
395
+ if (!this._context.swarms.has(topic)) {
396
+ this._context.swarms.set(topic, new ComplexSet2(PeerInfoHash));
397
+ }
398
+ this._context.swarms.get(topic).delete(peer);
399
+ const swarmEvent = {
400
+ topic,
401
+ peerLeft: {
402
+ peer
403
+ }
404
+ };
405
+ this._context.swarmEvent.emit(swarmEvent);
406
+ }
407
+ async query(_ctx, request) {
408
+ throw new Error("Not implemented");
409
+ }
410
+ async sendMessage(_ctx, { author, recipient, payload }) {
411
+ log2("send message", {
412
+ author,
413
+ recipient,
414
+ ...dec(payload)
415
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 118, S: this });
416
+ invariant2(recipient, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 123, S: this, A: ["recipient", ""] });
417
+ invariant2(!this._ctx.disposed, "Closed", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 124, S: this, A: ["!this._ctx.disposed", "'Closed'"] });
418
+ await this._freezeTrigger.wait();
419
+ const remote = this._context.connections.get(recipient);
420
+ if (!remote) {
421
+ log2.warn("recipient is not subscribed for messages", {
422
+ author,
423
+ recipient
424
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 128, S: this });
425
+ return;
426
+ }
427
+ if (remote._ctx.disposed) {
428
+ log2.warn("recipient is disposed", {
429
+ author,
430
+ recipient
431
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 135, S: this });
432
+ return;
433
+ }
434
+ remote._freezeTrigger.wait().then(() => {
435
+ if (remote._ctx.disposed) {
436
+ log2.warn("recipient is disposed", {
437
+ author,
438
+ recipient
439
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 143, S: this });
440
+ return;
441
+ }
442
+ log2("receive message", {
443
+ author,
444
+ recipient,
445
+ ...dec(payload)
446
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 149, S: this });
447
+ remote.onMessage.emit({
448
+ author,
449
+ recipient,
450
+ payload
451
+ });
452
+ }).catch((err) => {
453
+ log2.error("error while waiting for freeze", {
454
+ err
455
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 160, S: this });
456
+ });
457
+ }
458
+ async subscribeMessages(peerInfo) {
459
+ log2("subscribing", {
460
+ peerInfo
461
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 166, S: this });
462
+ this._context.connections.set(peerInfo, this);
463
+ }
464
+ async unsubscribeMessages(peerInfo) {
465
+ log2("unsubscribing", {
466
+ peerInfo
467
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 172, S: this });
468
+ this._context.connections.delete(peerInfo);
469
+ }
470
+ freeze() {
471
+ this._freezeTrigger.reset();
472
+ }
473
+ unfreeze() {
474
+ this._freezeTrigger.wake();
475
+ }
476
+ };
477
+ var dec = (payload) => {
478
+ if (!payload.type_url.endsWith("ReliablePayload")) {
479
+ return {};
480
+ }
481
+ const relPayload = schema2.getCodecForType("dxos.mesh.messaging.ReliablePayload").decode(payload.value);
482
+ if (typeof relPayload?.payload?.data === "object") {
483
+ return {
484
+ payload: Object.keys(relPayload?.payload?.data)[0],
485
+ sessionId: relPayload?.payload?.sessionId
486
+ };
487
+ }
488
+ return {};
489
+ };
490
+
491
+ export {
492
+ Messenger,
493
+ PeerInfoHash,
494
+ MemorySignalManagerContext,
495
+ MemorySignalManager
496
+ };
497
+ //# sourceMappingURL=chunk-EC4H56J5.mjs.map