@dxos/edge-client 0.8.4-main.a4bbb77 → 0.8.4-main.ae835ea

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 (33) hide show
  1. package/dist/lib/browser/{chunk-IKP53CBQ.mjs → chunk-VESGVCLQ.mjs} +15 -44
  2. package/dist/lib/browser/{chunk-IKP53CBQ.mjs.map → chunk-VESGVCLQ.mjs.map} +2 -2
  3. package/dist/lib/browser/edge-ws-muxer.mjs +1 -1
  4. package/dist/lib/browser/index.mjs +247 -156
  5. package/dist/lib/browser/index.mjs.map +3 -3
  6. package/dist/lib/browser/meta.json +1 -1
  7. package/dist/lib/browser/testing/index.mjs +1 -1
  8. package/dist/lib/browser/testing/index.mjs.map +2 -2
  9. package/dist/lib/node-esm/{chunk-DR5YNW5K.mjs → chunk-JTBFRYNM.mjs} +15 -44
  10. package/dist/lib/node-esm/{chunk-DR5YNW5K.mjs.map → chunk-JTBFRYNM.mjs.map} +2 -2
  11. package/dist/lib/node-esm/edge-ws-muxer.mjs +1 -1
  12. package/dist/lib/node-esm/index.mjs +247 -156
  13. package/dist/lib/node-esm/index.mjs.map +3 -3
  14. package/dist/lib/node-esm/meta.json +1 -1
  15. package/dist/lib/node-esm/testing/index.mjs +1 -1
  16. package/dist/lib/node-esm/testing/index.mjs.map +2 -2
  17. package/dist/types/src/edge-client.d.ts.map +1 -1
  18. package/dist/types/src/edge-http-client.d.ts +1 -0
  19. package/dist/types/src/edge-http-client.d.ts.map +1 -1
  20. package/dist/types/src/edge-ws-connection.d.ts +19 -0
  21. package/dist/types/src/edge-ws-connection.d.ts.map +1 -1
  22. package/dist/types/src/http-client.d.ts +10 -7
  23. package/dist/types/src/http-client.d.ts.map +1 -1
  24. package/dist/types/src/testing/test-utils.d.ts +1 -1
  25. package/dist/types/tsconfig.tsbuildinfo +1 -1
  26. package/package.json +14 -14
  27. package/src/edge-client.test.ts +4 -4
  28. package/src/edge-client.ts +36 -5
  29. package/src/edge-http-client.ts +24 -20
  30. package/src/edge-ws-connection.ts +118 -5
  31. package/src/http-client.test.ts +6 -4
  32. package/src/http-client.ts +13 -7
  33. package/src/testing/test-utils.ts +3 -3
@@ -6,7 +6,7 @@ import {
6
6
  getTypename,
7
7
  protocol,
8
8
  toUint8Array
9
- } from "./chunk-IKP53CBQ.mjs";
9
+ } from "./chunk-VESGVCLQ.mjs";
10
10
 
11
11
  // src/index.ts
12
12
  export * from "@dxos/protocols/buf/dxos/edge/messenger_pb";
@@ -123,7 +123,7 @@ var createStubEdgeIdentity = () => {
123
123
  };
124
124
 
125
125
  // src/edge-client.ts
126
- import { Event, PersistentLifecycle, Trigger, TriggerState, scheduleMicroTask } from "@dxos/async";
126
+ import { Event, PersistentLifecycle, Trigger, TriggerState, scheduleMicroTask, scheduleTaskInterval as scheduleTaskInterval2 } from "@dxos/async";
127
127
  import { Resource as Resource2 } from "@dxos/context";
128
128
  import { log as log2, logInfo as logInfo2 } from "@dxos/log";
129
129
  import { EdgeStatus } from "@dxos/protocols/proto/dxos/client/services";
@@ -177,19 +177,6 @@ import { log, logInfo } from "@dxos/log";
177
177
  import { EdgeWebsocketProtocol } from "@dxos/protocols";
178
178
  import { buf } from "@dxos/protocols/buf";
179
179
  import { MessageSchema } from "@dxos/protocols/buf/dxos/edge/messenger_pb";
180
- function _define_property(obj, key, value) {
181
- if (key in obj) {
182
- Object.defineProperty(obj, key, {
183
- value,
184
- enumerable: true,
185
- configurable: true,
186
- writable: true
187
- });
188
- } else {
189
- obj[key] = value;
190
- }
191
- return obj;
192
- }
193
180
  function _ts_decorate(decorators, target, key, desc) {
194
181
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
195
182
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -200,6 +187,28 @@ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-ws-c
200
187
  var SIGNAL_KEEPALIVE_INTERVAL = 4e3;
201
188
  var SIGNAL_KEEPALIVE_TIMEOUT = 12e3;
202
189
  var EdgeWsConnection = class extends Resource {
190
+ _identity;
191
+ _connectionInfo;
192
+ _callbacks;
193
+ _inactivityTimeoutCtx;
194
+ _ws;
195
+ _wsMuxer;
196
+ _lastReceivedMessageTimestamp = Date.now();
197
+ _openTimestamp;
198
+ // Latency tracking.
199
+ _pingTimestamp;
200
+ _rtt = 0;
201
+ // Rate tracking with sliding window.
202
+ _uploadRate = 0;
203
+ _downloadRate = 0;
204
+ _rateWindow = 1e4;
205
+ _rateUpdateInterval = 1e3;
206
+ _bytesSamples = [];
207
+ _messagesSent = 0;
208
+ _messagesReceived = 0;
209
+ constructor(_identity, _connectionInfo, _callbacks) {
210
+ super(), this._identity = _identity, this._connectionInfo = _connectionInfo, this._callbacks = _callbacks;
211
+ }
203
212
  get info() {
204
213
  return {
205
214
  open: this.isOpen,
@@ -207,10 +216,28 @@ var EdgeWsConnection = class extends Resource {
207
216
  device: this._identity.peerKey
208
217
  };
209
218
  }
219
+ get rtt() {
220
+ return this._rtt;
221
+ }
222
+ get uptime() {
223
+ return this._openTimestamp ? (Date.now() - this._openTimestamp) / 1e3 : 0;
224
+ }
225
+ get uploadRate() {
226
+ return this._uploadRate;
227
+ }
228
+ get downloadRate() {
229
+ return this._downloadRate;
230
+ }
231
+ get messagesSent() {
232
+ return this._messagesSent;
233
+ }
234
+ get messagesReceived() {
235
+ return this._messagesReceived;
236
+ }
210
237
  send(message) {
211
238
  invariant3(this._ws, void 0, {
212
239
  F: __dxlog_file3,
213
- L: 53,
240
+ L: 93,
214
241
  S: this,
215
242
  A: [
216
243
  "this._ws",
@@ -219,7 +246,7 @@ var EdgeWsConnection = class extends Resource {
219
246
  });
220
247
  invariant3(this._wsMuxer, void 0, {
221
248
  F: __dxlog_file3,
222
- L: 54,
249
+ L: 94,
223
250
  S: this,
224
251
  A: [
225
252
  "this._wsMuxer",
@@ -231,10 +258,11 @@ var EdgeWsConnection = class extends Resource {
231
258
  payload: protocol.getPayloadType(message)
232
259
  }, {
233
260
  F: __dxlog_file3,
234
- L: 55,
261
+ L: 95,
235
262
  S: this,
236
263
  C: (f, a) => f(...a)
237
264
  });
265
+ this._messagesSent++;
238
266
  if (this._ws?.protocol.includes(EdgeWebsocketProtocol.V0)) {
239
267
  const binary = buf.toBinary(MessageSchema, message);
240
268
  if (binary.length > CLOUDFLARE_MESSAGE_MAX_BYTES) {
@@ -244,17 +272,20 @@ var EdgeWsConnection = class extends Resource {
244
272
  payload: protocol.getPayloadType(message)
245
273
  }, {
246
274
  F: __dxlog_file3,
247
- L: 59,
275
+ L: 100,
248
276
  S: this,
249
277
  C: (f, a) => f(...a)
250
278
  });
251
279
  return;
252
280
  }
281
+ this._recordBytes(binary.byteLength, 0);
253
282
  this._ws.send(binary);
254
283
  } else {
284
+ const binary = buf.toBinary(MessageSchema, message);
285
+ this._recordBytes(binary.byteLength, 0);
255
286
  this._wsMuxer.send(message).catch((e) => log.catch(e, void 0, {
256
287
  F: __dxlog_file3,
257
- L: 68,
288
+ L: 113,
258
289
  S: this,
259
290
  C: (f, a) => f(...a)
260
291
  }));
@@ -276,18 +307,20 @@ var EdgeWsConnection = class extends Resource {
276
307
  if (this.isOpen) {
277
308
  log("connected", void 0, {
278
309
  F: __dxlog_file3,
279
- L: 85,
310
+ L: 130,
280
311
  S: this,
281
312
  C: (f, a) => f(...a)
282
313
  });
314
+ this._openTimestamp = Date.now();
283
315
  this._callbacks.onConnected();
284
316
  this._scheduleHeartbeats();
317
+ this._scheduleRateCalculation();
285
318
  } else {
286
319
  log.verbose("connected after becoming inactive", {
287
320
  currentIdentity: this._identity
288
321
  }, {
289
322
  F: __dxlog_file3,
290
- L: 89,
323
+ L: 136,
291
324
  S: this,
292
325
  C: (f, a) => f(...a)
293
326
  });
@@ -295,12 +328,12 @@ var EdgeWsConnection = class extends Resource {
295
328
  };
296
329
  this._ws.onclose = (event) => {
297
330
  if (this.isOpen) {
298
- log.warn("disconnected while being open", {
331
+ log.warn("server disconnected", {
299
332
  code: event.code,
300
333
  reason: event.reason
301
334
  }, {
302
335
  F: __dxlog_file3,
303
- L: 94,
336
+ L: 141,
304
337
  S: this,
305
338
  C: (f, a) => f(...a)
306
339
  });
@@ -315,7 +348,7 @@ var EdgeWsConnection = class extends Resource {
315
348
  info: event.message
316
349
  }, {
317
350
  F: __dxlog_file3,
318
- L: 101,
351
+ L: 148,
319
352
  S: this,
320
353
  C: (f, a) => f(...a)
321
354
  });
@@ -325,7 +358,7 @@ var EdgeWsConnection = class extends Resource {
325
358
  error: event.error
326
359
  }, {
327
360
  F: __dxlog_file3,
328
- L: 104,
361
+ L: 151,
329
362
  S: this,
330
363
  C: (f, a) => f(...a)
331
364
  });
@@ -337,7 +370,7 @@ var EdgeWsConnection = class extends Resource {
337
370
  event: event.type
338
371
  }, {
339
372
  F: __dxlog_file3,
340
- L: 112,
373
+ L: 159,
341
374
  S: this,
342
375
  C: (f, a) => f(...a)
343
376
  });
@@ -345,13 +378,19 @@ var EdgeWsConnection = class extends Resource {
345
378
  }
346
379
  this._lastReceivedMessageTimestamp = Date.now();
347
380
  if (event.data === "__pong__") {
381
+ if (this._pingTimestamp) {
382
+ this._rtt = Date.now() - this._pingTimestamp;
383
+ this._pingTimestamp = void 0;
384
+ }
348
385
  this._rescheduleHeartbeatTimeout();
349
386
  return;
350
387
  }
351
388
  const bytes = await toUint8Array(event.data);
389
+ this._recordBytes(0, bytes.byteLength);
352
390
  if (!this.isOpen) {
353
391
  return;
354
392
  }
393
+ this._messagesReceived++;
355
394
  const message = this._ws?.protocol?.includes(EdgeWebsocketProtocol.V0) ? buf.fromBinary(MessageSchema, bytes) : muxer.receiveData(bytes);
356
395
  if (message) {
357
396
  log("received", {
@@ -359,7 +398,7 @@ var EdgeWsConnection = class extends Resource {
359
398
  payload: protocol.getPayloadType(message)
360
399
  }, {
361
400
  F: __dxlog_file3,
362
- L: 130,
401
+ L: 185,
363
402
  S: this,
364
403
  C: (f, a) => f(...a)
365
404
  });
@@ -379,11 +418,11 @@ var EdgeWsConnection = class extends Resource {
379
418
  if (err instanceof Error && err.message.includes("WebSocket is closed before the connection is established.")) {
380
419
  return;
381
420
  }
382
- log.warn("Error closing websocket", {
421
+ log.warn("error closing websocket", {
383
422
  err
384
423
  }, {
385
424
  F: __dxlog_file3,
386
- L: 148,
425
+ L: 203,
387
426
  S: this,
388
427
  C: (f, a) => f(...a)
389
428
  });
@@ -392,7 +431,7 @@ var EdgeWsConnection = class extends Resource {
392
431
  _scheduleHeartbeats() {
393
432
  invariant3(this._ws, void 0, {
394
433
  F: __dxlog_file3,
395
- L: 153,
434
+ L: 208,
396
435
  S: this,
397
436
  A: [
398
437
  "this._ws",
@@ -400,8 +439,10 @@ var EdgeWsConnection = class extends Resource {
400
439
  ]
401
440
  });
402
441
  scheduleTaskInterval(this._ctx, async () => {
442
+ this._pingTimestamp = Date.now();
403
443
  this._ws?.send("__ping__");
404
444
  }, SIGNAL_KEEPALIVE_INTERVAL);
445
+ this._pingTimestamp = Date.now();
405
446
  this._ws.send("__ping__");
406
447
  this._rescheduleHeartbeatTimeout();
407
448
  }
@@ -412,7 +453,7 @@ var EdgeWsConnection = class extends Resource {
412
453
  void this._inactivityTimeoutCtx?.dispose();
413
454
  this._inactivityTimeoutCtx = new Context(void 0, {
414
455
  F: __dxlog_file3,
415
- L: 172
456
+ L: 229
416
457
  });
417
458
  scheduleTask(this._inactivityTimeoutCtx, () => {
418
459
  if (this.isOpen) {
@@ -421,7 +462,7 @@ var EdgeWsConnection = class extends Resource {
421
462
  lastReceivedMessageTimestamp: this._lastReceivedMessageTimestamp
422
463
  }, {
423
464
  F: __dxlog_file3,
424
- L: 178,
465
+ L: 235,
425
466
  S: this,
426
467
  C: (f, a) => f(...a)
427
468
  });
@@ -432,8 +473,46 @@ var EdgeWsConnection = class extends Resource {
432
473
  }
433
474
  }, SIGNAL_KEEPALIVE_TIMEOUT);
434
475
  }
435
- constructor(_identity, _connectionInfo, _callbacks) {
436
- super(), _define_property(this, "_identity", void 0), _define_property(this, "_connectionInfo", void 0), _define_property(this, "_callbacks", void 0), _define_property(this, "_inactivityTimeoutCtx", void 0), _define_property(this, "_ws", void 0), _define_property(this, "_wsMuxer", void 0), _define_property(this, "_lastReceivedMessageTimestamp", void 0), this._identity = _identity, this._connectionInfo = _connectionInfo, this._callbacks = _callbacks, this._lastReceivedMessageTimestamp = Date.now();
476
+ _recordBytes(sent, received) {
477
+ const now = Date.now();
478
+ const currentSecond = Math.floor(now / 1e3) * 1e3;
479
+ const existingSample = this._bytesSamples.find((s) => Math.floor(s.timestamp / 1e3) * 1e3 === currentSecond);
480
+ if (existingSample) {
481
+ existingSample.sent += sent;
482
+ existingSample.received += received;
483
+ } else {
484
+ this._bytesSamples.push({
485
+ timestamp: now,
486
+ sent,
487
+ received
488
+ });
489
+ }
490
+ }
491
+ _scheduleRateCalculation() {
492
+ scheduleTaskInterval(this._ctx, async () => {
493
+ this._calculateRates();
494
+ }, this._rateUpdateInterval);
495
+ this._calculateRates();
496
+ }
497
+ _calculateRates() {
498
+ const now = Date.now();
499
+ const cutoff = now - this._rateWindow;
500
+ this._bytesSamples = this._bytesSamples.filter((s) => s.timestamp > cutoff);
501
+ if (this._bytesSamples.length === 0) {
502
+ this._uploadRate = 0;
503
+ this._downloadRate = 0;
504
+ return;
505
+ }
506
+ let totalSent = 0;
507
+ let totalReceived = 0;
508
+ const oldestTimestamp = Math.min(...this._bytesSamples.map((s) => s.timestamp));
509
+ const timeSpan = (now - oldestTimestamp) / 1e3;
510
+ for (const sample of this._bytesSamples) {
511
+ totalSent += sample.sent;
512
+ totalReceived += sample.received;
513
+ }
514
+ this._uploadRate = timeSpan > 0 ? Math.round(totalSent / timeSpan) : 0;
515
+ this._downloadRate = timeSpan > 0 ? Math.round(totalReceived / timeSpan) : 0;
437
516
  }
438
517
  };
439
518
  _ts_decorate([
@@ -461,19 +540,6 @@ var getEdgeUrlWithProtocol = (baseUrl, protocol2) => {
461
540
  };
462
541
 
463
542
  // src/edge-client.ts
464
- function _define_property2(obj, key, value) {
465
- if (key in obj) {
466
- Object.defineProperty(obj, key, {
467
- value,
468
- enumerable: true,
469
- configurable: true,
470
- writable: true
471
- });
472
- } else {
473
- obj[key] = value;
474
- }
475
- return obj;
476
- }
477
543
  function _ts_decorate2(decorators, target, key, desc) {
478
544
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
479
545
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -482,7 +548,26 @@ function _ts_decorate2(decorators, target, key, desc) {
482
548
  }
483
549
  var __dxlog_file4 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-client.ts";
484
550
  var DEFAULT_TIMEOUT = 1e4;
551
+ var STATUS_REFRESH_INTERVAL = 1e3;
485
552
  var EdgeClient = class extends Resource2 {
553
+ _identity;
554
+ _config;
555
+ statusChanged = new Event();
556
+ _persistentLifecycle = new PersistentLifecycle({
557
+ start: async () => this._connect(),
558
+ stop: async (state) => this._disconnect(state)
559
+ });
560
+ _messageListeners = /* @__PURE__ */ new Set();
561
+ _reconnectListeners = /* @__PURE__ */ new Set();
562
+ _baseWsUrl;
563
+ _baseHttpUrl;
564
+ _currentConnection = void 0;
565
+ _ready = new Trigger();
566
+ constructor(_identity, _config) {
567
+ super(), this._identity = _identity, this._config = _config;
568
+ this._baseWsUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "ws");
569
+ this._baseHttpUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "http");
570
+ }
486
571
  get info() {
487
572
  return {
488
573
  open: this.isOpen,
@@ -492,7 +577,15 @@ var EdgeClient = class extends Resource2 {
492
577
  };
493
578
  }
494
579
  get status() {
495
- return Boolean(this._currentConnection) && this._ready.state === TriggerState.RESOLVED ? EdgeStatus.CONNECTED : EdgeStatus.NOT_CONNECTED;
580
+ return {
581
+ state: Boolean(this._currentConnection) && this._ready.state === TriggerState.RESOLVED ? EdgeStatus.ConnectionState.CONNECTED : EdgeStatus.ConnectionState.NOT_CONNECTED,
582
+ uptime: this._currentConnection?.uptime ?? 0,
583
+ rtt: this._currentConnection?.rtt ?? 0,
584
+ rateBytesUp: this._currentConnection?.uploadRate ?? 0,
585
+ rateBytesDown: this._currentConnection?.downloadRate ?? 0,
586
+ messagesSent: this._currentConnection?.messagesSent ?? 0,
587
+ messagesReceived: this._currentConnection?.messagesReceived ?? 0
588
+ };
496
589
  }
497
590
  get identityKey() {
498
591
  return this._identity.identityKey;
@@ -507,7 +600,7 @@ var EdgeClient = class extends Resource2 {
507
600
  oldIdentity: this._identity
508
601
  }, {
509
602
  F: __dxlog_file4,
510
- L: 99,
603
+ L: 118,
511
604
  S: this,
512
605
  C: (f, a) => f(...a)
513
606
  });
@@ -524,7 +617,7 @@ var EdgeClient = class extends Resource2 {
524
617
  if (this._ready.state !== TriggerState.RESOLVED) {
525
618
  log2("waiting for websocket", void 0, {
526
619
  F: __dxlog_file4,
527
- L: 112,
620
+ L: 131,
528
621
  S: this,
529
622
  C: (f, a) => f(...a)
530
623
  });
@@ -554,7 +647,7 @@ var EdgeClient = class extends Resource2 {
554
647
  } catch (error) {
555
648
  log2.catch(error, void 0, {
556
649
  F: __dxlog_file4,
557
- L: 145,
650
+ L: 164,
558
651
  S: this,
559
652
  C: (f, a) => f(...a)
560
653
  });
@@ -572,7 +665,7 @@ var EdgeClient = class extends Resource2 {
572
665
  info: this.info
573
666
  }, {
574
667
  F: __dxlog_file4,
575
- L: 158,
668
+ L: 177,
576
669
  S: this,
577
670
  C: (f, a) => f(...a)
578
671
  });
@@ -581,11 +674,17 @@ var EdgeClient = class extends Resource2 {
581
674
  err
582
675
  }, {
583
676
  F: __dxlog_file4,
584
- L: 160,
677
+ L: 179,
585
678
  S: this,
586
679
  C: (f, a) => f(...a)
587
680
  });
588
681
  });
682
+ scheduleTaskInterval2(this._ctx, async () => {
683
+ if (!this._currentConnection) {
684
+ return;
685
+ }
686
+ this.statusChanged.emit(this.status);
687
+ }, STATUS_REFRESH_INTERVAL);
589
688
  }
590
689
  /**
591
690
  * Close connection and free resources.
@@ -595,7 +694,7 @@ var EdgeClient = class extends Resource2 {
595
694
  peerKey: this._identity.peerKey
596
695
  }, {
597
696
  F: __dxlog_file4,
598
- L: 168,
697
+ L: 199,
599
698
  S: this,
600
699
  C: (f, a) => f(...a)
601
700
  });
@@ -612,7 +711,7 @@ var EdgeClient = class extends Resource2 {
612
711
  if (this._identity !== identity) {
613
712
  log2("identity changed during auth header request", void 0, {
614
713
  F: __dxlog_file4,
615
- L: 182,
714
+ L: 213,
616
715
  S: this,
617
716
  C: (f, a) => f(...a)
618
717
  });
@@ -625,7 +724,7 @@ var EdgeClient = class extends Resource2 {
625
724
  protocolHeader
626
725
  }, {
627
726
  F: __dxlog_file4,
628
- L: 188,
727
+ L: 219,
629
728
  S: this,
630
729
  C: (f, a) => f(...a)
631
730
  });
@@ -640,7 +739,7 @@ var EdgeClient = class extends Resource2 {
640
739
  } else {
641
740
  log2.verbose("connected callback ignored, because connection is not active", void 0, {
642
741
  F: __dxlog_file4,
643
- L: 198,
742
+ L: 229,
644
743
  S: this,
645
744
  C: (f, a) => f(...a)
646
745
  });
@@ -653,7 +752,7 @@ var EdgeClient = class extends Resource2 {
653
752
  } else {
654
753
  log2.verbose("restart requested by inactive connection", void 0, {
655
754
  F: __dxlog_file4,
656
- L: 206,
755
+ L: 237,
657
756
  S: this,
658
757
  C: (f, a) => f(...a)
659
758
  });
@@ -669,7 +768,7 @@ var EdgeClient = class extends Resource2 {
669
768
  type: message.payload?.typeUrl
670
769
  }, {
671
770
  F: __dxlog_file4,
672
- L: 214,
771
+ L: 245,
673
772
  S: this,
674
773
  C: (f, a) => f(...a)
675
774
  });
@@ -706,7 +805,7 @@ var EdgeClient = class extends Resource2 {
706
805
  err
707
806
  }, {
708
807
  F: __dxlog_file4,
709
- L: 249,
808
+ L: 280,
710
809
  S: this,
711
810
  C: (f, a) => f(...a)
712
811
  });
@@ -723,7 +822,7 @@ var EdgeClient = class extends Resource2 {
723
822
  payload: protocol.getPayloadType(message)
724
823
  }, {
725
824
  F: __dxlog_file4,
726
- L: 259,
825
+ L: 290,
727
826
  S: this,
728
827
  C: (f, a) => f(...a)
729
828
  });
@@ -744,21 +843,14 @@ var EdgeClient = class extends Resource2 {
744
843
  statusText: response.statusText
745
844
  }, {
746
845
  F: __dxlog_file4,
747
- L: 271,
846
+ L: 302,
748
847
  S: this,
749
848
  C: (f, a) => f(...a)
750
849
  });
751
850
  return void 0;
752
851
  }
753
852
  }
754
- constructor(_identity, _config) {
755
- super(), _define_property2(this, "_identity", void 0), _define_property2(this, "_config", void 0), _define_property2(this, "statusChanged", void 0), _define_property2(this, "_persistentLifecycle", void 0), _define_property2(this, "_messageListeners", void 0), _define_property2(this, "_reconnectListeners", void 0), _define_property2(this, "_baseWsUrl", void 0), _define_property2(this, "_baseHttpUrl", void 0), _define_property2(this, "_currentConnection", void 0), _define_property2(this, "_ready", void 0), _define_property2(this, "_isActive", void 0), this._identity = _identity, this._config = _config, this.statusChanged = new Event(), this._persistentLifecycle = new PersistentLifecycle({
756
- start: async () => this._connect(),
757
- stop: async (state) => this._disconnect(state)
758
- }), this._messageListeners = /* @__PURE__ */ new Set(), this._reconnectListeners = /* @__PURE__ */ new Set(), this._currentConnection = void 0, this._ready = new Trigger(), this._isActive = (connection) => connection === this._currentConnection;
759
- this._baseWsUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "ws");
760
- this._baseHttpUrl = getEdgeUrlWithProtocol(_config.socketEndpoint, "http");
761
- }
853
+ _isActive = (connection) => connection === this._currentConnection;
762
854
  };
763
855
  _ts_decorate2([
764
856
  logInfo2
@@ -769,44 +861,37 @@ var encodePresentationWsAuthHeader = (encodedPresentation) => {
769
861
  };
770
862
 
771
863
  // src/edge-http-client.ts
772
- import { FetchHttpClient, HttpClient } from "@effect/platform";
773
- import { Effect as Effect2, pipe } from "effect";
864
+ import * as FetchHttpClient from "@effect/platform/FetchHttpClient";
865
+ import * as HttpClient from "@effect/platform/HttpClient";
866
+ import * as Effect2 from "effect/Effect";
867
+ import * as Function from "effect/Function";
774
868
  import { sleep } from "@dxos/async";
775
869
  import { Context as Context3 } from "@dxos/context";
870
+ import { invariant as invariant4 } from "@dxos/invariant";
776
871
  import { log as log4 } from "@dxos/log";
777
872
  import { EdgeAuthChallengeError, EdgeCallFailedError } from "@dxos/protocols";
778
873
  import { createUrl } from "@dxos/util";
779
874
 
780
875
  // src/http-client.ts
781
- import { Context as Context2, Duration, Effect, Layer, Schedule } from "effect";
876
+ import * as Context2 from "effect/Context";
877
+ import * as Duration from "effect/Duration";
878
+ import * as Effect from "effect/Effect";
879
+ import * as Layer from "effect/Layer";
880
+ import * as Schedule from "effect/Schedule";
782
881
  import { log as log3 } from "@dxos/log";
783
- function _define_property3(obj, key, value) {
784
- if (key in obj) {
785
- Object.defineProperty(obj, key, {
786
- value,
787
- enumerable: true,
788
- configurable: true,
789
- writable: true
790
- });
791
- } else {
792
- obj[key] = value;
793
- }
794
- return obj;
795
- }
796
882
  var __dxlog_file5 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/http-client.ts";
797
- var _Context_Tag;
798
- var HttpConfig = class extends (_Context_Tag = Context2.Tag("HttpConfig")()) {
883
+ var HttpConfig = class _HttpConfig extends Context2.Tag("HttpConfig")() {
884
+ static default = Layer.succeed(_HttpConfig, {
885
+ timeout: Duration.millis(1e3),
886
+ retryTimes: 3,
887
+ retryBaseDelay: Duration.millis(1e3)
888
+ });
799
889
  };
800
- _define_property3(HttpConfig, "default", Layer.succeed(HttpConfig, {
801
- timeout: Duration.millis(1e3),
802
- retryTimes: 3,
803
- retryBaseDelay: Duration.millis(1e3)
804
- }));
805
- var withRetry = (effect, { timeout = Duration.millis(1e3), retryBaseDelay = Duration.millis(1e3), retryTimes = 3 } = {}) => {
890
+ var withRetry = (effect, { timeout: timeout2 = Duration.millis(1e3), retryBaseDelay = Duration.millis(1e3), retryTimes = 3 } = {}) => {
806
891
  return effect.pipe(Effect.flatMap((res) => (
807
892
  // Treat 500 errors as retryable?
808
893
  res.status === 500 ? Effect.fail(new Error(res.status.toString())) : res.json
809
- )), Effect.timeout(timeout), Effect.retry({
894
+ )), Effect.timeout(timeout2), Effect.retry({
810
895
  schedule: Schedule.exponential(retryBaseDelay).pipe(Schedule.jittered),
811
896
  times: retryTimes
812
897
  }));
@@ -819,7 +904,7 @@ var withLogging = (effect) => effect.pipe(Effect.tap((res) => log3.info("respons
819
904
  status: res.status
820
905
  }, {
821
906
  F: __dxlog_file5,
822
- L: 58,
907
+ L: 64,
823
908
  S: void 0,
824
909
  C: (f, a) => f(...a)
825
910
  })));
@@ -829,25 +914,29 @@ var encodeAuthHeader = (challenge) => {
829
914
  };
830
915
 
831
916
  // src/edge-http-client.ts
832
- function _define_property4(obj, key, value) {
833
- if (key in obj) {
834
- Object.defineProperty(obj, key, {
835
- value,
836
- enumerable: true,
837
- configurable: true,
838
- writable: true
839
- });
840
- } else {
841
- obj[key] = value;
842
- }
843
- return obj;
844
- }
845
917
  var __dxlog_file6 = "/__w/dxos/dxos/packages/core/mesh/edge-client/src/edge-http-client.ts";
846
918
  var DEFAULT_RETRY_TIMEOUT = 1500;
847
919
  var DEFAULT_RETRY_JITTER = 500;
848
920
  var DEFAULT_MAX_RETRIES_COUNT = 3;
849
921
  var WARNING_BODY_SIZE = 10 * 1024 * 1024;
850
922
  var EdgeHttpClient = class {
923
+ _baseUrl;
924
+ _edgeIdentity;
925
+ /**
926
+ * Auth header is cached until receiving the next 401 from EDGE, at which point it gets refreshed.
927
+ */
928
+ _authHeader;
929
+ constructor(baseUrl) {
930
+ this._baseUrl = getEdgeUrlWithProtocol(baseUrl, "http");
931
+ log4("created", {
932
+ url: this._baseUrl
933
+ }, {
934
+ F: __dxlog_file6,
935
+ L: 101,
936
+ S: this,
937
+ C: (f, a) => f(...a)
938
+ });
939
+ }
851
940
  get baseUrl() {
852
941
  return this._baseUrl;
853
942
  }
@@ -1066,74 +1155,90 @@ var EdgeHttpClient = class {
1066
1155
  // Internal
1067
1156
  //
1068
1157
  async _fetch(url, args) {
1069
- return pipe(HttpClient.get(url), withLogging, withRetryConfig, Effect2.provide(FetchHttpClient.layer), Effect2.provide(HttpConfig.default), Effect2.withSpan("EdgeHttpClient"), Effect2.runPromise);
1158
+ return Function.pipe(HttpClient.get(url), withLogging, withRetryConfig, Effect2.provide(FetchHttpClient.layer), Effect2.provide(HttpConfig.default), Effect2.withSpan("EdgeHttpClient"), Effect2.runPromise);
1070
1159
  }
1071
1160
  // TODO(burdon): Refactor with effect (see edge-http-client.test.ts).
1072
1161
  async _call(url, args) {
1073
1162
  const shouldRetry = createRetryHandler(args);
1074
- const requestContext = args.context ?? new Context3(void 0, {
1163
+ const requestContext = args.context ?? Context3.default(void 0, {
1075
1164
  F: __dxlog_file6,
1076
- L: 389
1165
+ L: 393
1077
1166
  });
1078
1167
  log4("fetch", {
1079
1168
  url,
1080
1169
  request: args.body
1081
1170
  }, {
1082
1171
  F: __dxlog_file6,
1083
- L: 390,
1172
+ L: 394,
1084
1173
  S: this,
1085
1174
  C: (f, a) => f(...a)
1086
1175
  });
1087
1176
  let handledAuth = false;
1088
1177
  while (true) {
1089
1178
  let processingError = void 0;
1090
- let retryAfterHeaderValue = Number.NaN;
1091
1179
  try {
1092
1180
  const request = createRequest(args, this._authHeader);
1093
1181
  const response = await fetch(url, request);
1094
- retryAfterHeaderValue = Number(response.headers.get("Retry-After"));
1182
+ const body = response.headers.get("Content-Type") === "application/json" ? await response.clone().json() : void 0;
1095
1183
  if (response.ok) {
1096
- const body = await response.json();
1097
1184
  if (args.rawResponse) {
1098
1185
  return body;
1099
1186
  }
1187
+ invariant4(body, "Expected body to be present", {
1188
+ F: __dxlog_file6,
1189
+ L: 409,
1190
+ S: this,
1191
+ A: [
1192
+ "body",
1193
+ "'Expected body to be present'"
1194
+ ]
1195
+ });
1100
1196
  if (!("success" in body)) {
1101
1197
  return body;
1102
1198
  }
1103
1199
  if (body.success) {
1104
1200
  return body.data;
1105
1201
  }
1106
- log4.warn("unsuccessful edge response", {
1107
- url,
1108
- body
1109
- }, {
1110
- F: __dxlog_file6,
1111
- L: 415,
1112
- S: this,
1113
- C: (f, a) => f(...a)
1114
- });
1115
- if (body.errorData?.type === "auth_challenge" && typeof body.errorData?.challenge === "string") {
1116
- processingError = new EdgeAuthChallengeError(body.errorData.challenge, body.errorData);
1117
- } else if (body.errorData) {
1118
- processingError = EdgeCallFailedError.fromUnsuccessfulResponse(response, body);
1119
- }
1120
1202
  } else if (response.status === 401 && !handledAuth) {
1121
1203
  this._authHeader = await this._handleUnauthorized(response);
1122
1204
  handledAuth = true;
1123
1205
  continue;
1206
+ }
1207
+ invariant4(!body?.success, "Expected body to not be a failure response or undefined.", {
1208
+ F: __dxlog_file6,
1209
+ L: 422,
1210
+ S: this,
1211
+ A: [
1212
+ "!body?.success",
1213
+ "'Expected body to not be a failure response or undefined.'"
1214
+ ]
1215
+ });
1216
+ if (body?.errorData?.type === "auth_challenge" && typeof body?.errorData?.challenge === "string") {
1217
+ processingError = new EdgeAuthChallengeError(body.errorData.challenge, body.errorData);
1218
+ } else if (body?.success === false) {
1219
+ processingError = EdgeCallFailedError.fromUnsuccessfulResponse(response, body);
1124
1220
  } else {
1221
+ invariant4(!response.ok, "Expected response to not be ok.", {
1222
+ F: __dxlog_file6,
1223
+ L: 429,
1224
+ S: this,
1225
+ A: [
1226
+ "!response.ok",
1227
+ "'Expected response to not be ok.'"
1228
+ ]
1229
+ });
1125
1230
  processingError = await EdgeCallFailedError.fromHttpFailure(response);
1126
1231
  }
1127
1232
  } catch (error) {
1128
1233
  processingError = EdgeCallFailedError.fromProcessingFailureCause(error);
1129
1234
  }
1130
- if (processingError?.isRetryable && await shouldRetry(requestContext, retryAfterHeaderValue)) {
1235
+ if (processingError?.isRetryable && await shouldRetry(requestContext, processingError.retryAfterMs)) {
1131
1236
  log4("retrying edge request", {
1132
1237
  url,
1133
1238
  processingError
1134
1239
  }, {
1135
1240
  F: __dxlog_file6,
1136
- L: 433,
1241
+ L: 437,
1137
1242
  S: this,
1138
1243
  C: (f, a) => f(...a)
1139
1244
  });
@@ -1146,7 +1251,7 @@ var EdgeHttpClient = class {
1146
1251
  if (!this._edgeIdentity) {
1147
1252
  log4.warn("unauthorized response received before identity was set", void 0, {
1148
1253
  F: __dxlog_file6,
1149
- L: 442,
1254
+ L: 446,
1150
1255
  S: this,
1151
1256
  C: (f, a) => f(...a)
1152
1257
  });
@@ -1155,20 +1260,6 @@ var EdgeHttpClient = class {
1155
1260
  const challenge = await handleAuthChallenge(response, this._edgeIdentity);
1156
1261
  return encodeAuthHeader(challenge);
1157
1262
  }
1158
- constructor(baseUrl) {
1159
- _define_property4(this, "_baseUrl", void 0);
1160
- _define_property4(this, "_edgeIdentity", void 0);
1161
- _define_property4(this, "_authHeader", void 0);
1162
- this._baseUrl = getEdgeUrlWithProtocol(baseUrl, "http");
1163
- log4("created", {
1164
- url: this._baseUrl
1165
- }, {
1166
- F: __dxlog_file6,
1167
- L: 97,
1168
- S: this,
1169
- C: (f, a) => f(...a)
1170
- });
1171
- }
1172
1263
  };
1173
1264
  var createRequest = ({ method, body, json = true }, authHeader) => {
1174
1265
  let requestBody;
@@ -1184,7 +1275,7 @@ var createRequest = ({ method, body, json = true }, authHeader) => {
1184
1275
  bodySize: requestBody.length
1185
1276
  }, {
1186
1277
  F: __dxlog_file6,
1187
- L: 466,
1278
+ L: 470,
1188
1279
  S: void 0,
1189
1280
  C: (f, a) => f(...a)
1190
1281
  });
@@ -1198,14 +1289,14 @@ var createRequest = ({ method, body, json = true }, authHeader) => {
1198
1289
  headers
1199
1290
  };
1200
1291
  };
1201
- var createRetryHandler = ({ retry }) => {
1202
- if (!retry || retry.count < 1) {
1292
+ var createRetryHandler = ({ retry: retry2 }) => {
1293
+ if (!retry2 || retry2.count < 1) {
1203
1294
  return async () => false;
1204
1295
  }
1205
1296
  let retries = 0;
1206
- const maxRetries = retry.count ?? DEFAULT_MAX_RETRIES_COUNT;
1207
- const baseTimeout = retry.timeout ?? DEFAULT_RETRY_TIMEOUT;
1208
- const jitter = retry.jitter ?? DEFAULT_RETRY_JITTER;
1297
+ const maxRetries = retry2.count ?? DEFAULT_MAX_RETRIES_COUNT;
1298
+ const baseTimeout = retry2.timeout ?? DEFAULT_RETRY_TIMEOUT;
1299
+ const jitter = retry2.jitter ?? DEFAULT_RETRY_JITTER;
1209
1300
  return async (ctx, retryAfter) => {
1210
1301
  if (++retries > maxRetries || ctx.disposed) {
1211
1302
  return false;
@@ -1213,8 +1304,8 @@ var createRetryHandler = ({ retry }) => {
1213
1304
  if (retryAfter) {
1214
1305
  await sleep(retryAfter);
1215
1306
  } else {
1216
- const timeout = baseTimeout + Math.random() * jitter;
1217
- await sleep(timeout);
1307
+ const timeout2 = baseTimeout + Math.random() * jitter;
1308
+ await sleep(timeout2);
1218
1309
  }
1219
1310
  return true;
1220
1311
  };