@matter/protocol 0.12.4-alpha.0-20250224-e0964a795 → 0.12.4-alpha.0-20250225-52ac4166b

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 (103) hide show
  1. package/dist/cjs/interaction/InteractionClient.d.ts +6 -2
  2. package/dist/cjs/interaction/InteractionClient.d.ts.map +1 -1
  3. package/dist/cjs/interaction/InteractionClient.js +3 -2
  4. package/dist/cjs/interaction/InteractionClient.js.map +1 -1
  5. package/dist/cjs/interaction/InteractionMessenger.d.ts +1 -1
  6. package/dist/cjs/interaction/InteractionMessenger.d.ts.map +1 -1
  7. package/dist/cjs/interaction/InteractionServer.d.ts +19 -2
  8. package/dist/cjs/interaction/InteractionServer.d.ts.map +1 -1
  9. package/dist/cjs/interaction/InteractionServer.js +123 -45
  10. package/dist/cjs/interaction/InteractionServer.js.map +1 -1
  11. package/dist/cjs/interaction/ServerSubscription.d.ts +8 -16
  12. package/dist/cjs/interaction/ServerSubscription.d.ts.map +1 -1
  13. package/dist/cjs/interaction/ServerSubscription.js +78 -55
  14. package/dist/cjs/interaction/ServerSubscription.js.map +1 -1
  15. package/dist/cjs/interaction/Subscription.d.ts +7 -1
  16. package/dist/cjs/interaction/Subscription.d.ts.map +1 -1
  17. package/dist/cjs/interaction/Subscription.js +25 -2
  18. package/dist/cjs/interaction/Subscription.js.map +1 -1
  19. package/dist/cjs/peer/ControllerCommissioner.d.ts.map +1 -1
  20. package/dist/cjs/peer/ControllerCommissioner.js +4 -5
  21. package/dist/cjs/peer/ControllerCommissioner.js.map +1 -1
  22. package/dist/cjs/peer/PeerAddress.d.ts +5 -0
  23. package/dist/cjs/peer/PeerAddress.d.ts.map +1 -1
  24. package/dist/cjs/peer/PeerAddress.js +13 -1
  25. package/dist/cjs/peer/PeerAddress.js.map +1 -1
  26. package/dist/cjs/peer/PeerSet.d.ts +6 -2
  27. package/dist/cjs/peer/PeerSet.d.ts.map +1 -1
  28. package/dist/cjs/peer/PeerSet.js +18 -8
  29. package/dist/cjs/peer/PeerSet.js.map +1 -1
  30. package/dist/cjs/securechannel/SecureChannelMessenger.d.ts +1 -0
  31. package/dist/cjs/securechannel/SecureChannelMessenger.d.ts.map +1 -1
  32. package/dist/cjs/securechannel/SecureChannelMessenger.js +3 -0
  33. package/dist/cjs/securechannel/SecureChannelMessenger.js.map +1 -1
  34. package/dist/cjs/session/SecureSession.d.ts +1 -1
  35. package/dist/cjs/session/SecureSession.d.ts.map +1 -1
  36. package/dist/cjs/session/SecureSession.js +3 -2
  37. package/dist/cjs/session/SecureSession.js.map +1 -1
  38. package/dist/cjs/session/Session.d.ts +1 -0
  39. package/dist/cjs/session/Session.d.ts.map +1 -1
  40. package/dist/cjs/session/Session.js +1 -0
  41. package/dist/cjs/session/Session.js.map +1 -1
  42. package/dist/cjs/session/SessionManager.d.ts +2 -2
  43. package/dist/cjs/session/SessionManager.d.ts.map +1 -1
  44. package/dist/cjs/session/SessionManager.js +5 -9
  45. package/dist/cjs/session/SessionManager.js.map +1 -1
  46. package/dist/esm/interaction/InteractionClient.d.ts +6 -2
  47. package/dist/esm/interaction/InteractionClient.d.ts.map +1 -1
  48. package/dist/esm/interaction/InteractionClient.js +3 -2
  49. package/dist/esm/interaction/InteractionClient.js.map +1 -1
  50. package/dist/esm/interaction/InteractionMessenger.d.ts +1 -1
  51. package/dist/esm/interaction/InteractionMessenger.d.ts.map +1 -1
  52. package/dist/esm/interaction/InteractionServer.d.ts +19 -2
  53. package/dist/esm/interaction/InteractionServer.d.ts.map +1 -1
  54. package/dist/esm/interaction/InteractionServer.js +124 -46
  55. package/dist/esm/interaction/InteractionServer.js.map +1 -1
  56. package/dist/esm/interaction/ServerSubscription.d.ts +8 -16
  57. package/dist/esm/interaction/ServerSubscription.d.ts.map +1 -1
  58. package/dist/esm/interaction/ServerSubscription.js +78 -55
  59. package/dist/esm/interaction/ServerSubscription.js.map +1 -1
  60. package/dist/esm/interaction/Subscription.d.ts +7 -1
  61. package/dist/esm/interaction/Subscription.d.ts.map +1 -1
  62. package/dist/esm/interaction/Subscription.js +26 -3
  63. package/dist/esm/interaction/Subscription.js.map +1 -1
  64. package/dist/esm/peer/ControllerCommissioner.d.ts.map +1 -1
  65. package/dist/esm/peer/ControllerCommissioner.js +4 -5
  66. package/dist/esm/peer/ControllerCommissioner.js.map +1 -1
  67. package/dist/esm/peer/PeerAddress.d.ts +5 -0
  68. package/dist/esm/peer/PeerAddress.d.ts.map +1 -1
  69. package/dist/esm/peer/PeerAddress.js +13 -1
  70. package/dist/esm/peer/PeerAddress.js.map +1 -1
  71. package/dist/esm/peer/PeerSet.d.ts +6 -2
  72. package/dist/esm/peer/PeerSet.d.ts.map +1 -1
  73. package/dist/esm/peer/PeerSet.js +18 -8
  74. package/dist/esm/peer/PeerSet.js.map +1 -1
  75. package/dist/esm/securechannel/SecureChannelMessenger.d.ts +1 -0
  76. package/dist/esm/securechannel/SecureChannelMessenger.d.ts.map +1 -1
  77. package/dist/esm/securechannel/SecureChannelMessenger.js +3 -0
  78. package/dist/esm/securechannel/SecureChannelMessenger.js.map +1 -1
  79. package/dist/esm/session/SecureSession.d.ts +1 -1
  80. package/dist/esm/session/SecureSession.d.ts.map +1 -1
  81. package/dist/esm/session/SecureSession.js +3 -2
  82. package/dist/esm/session/SecureSession.js.map +1 -1
  83. package/dist/esm/session/Session.d.ts +1 -0
  84. package/dist/esm/session/Session.d.ts.map +1 -1
  85. package/dist/esm/session/Session.js +1 -0
  86. package/dist/esm/session/Session.js.map +1 -1
  87. package/dist/esm/session/SessionManager.d.ts +2 -2
  88. package/dist/esm/session/SessionManager.d.ts.map +1 -1
  89. package/dist/esm/session/SessionManager.js +6 -10
  90. package/dist/esm/session/SessionManager.js.map +1 -1
  91. package/package.json +6 -6
  92. package/src/interaction/InteractionClient.ts +8 -3
  93. package/src/interaction/InteractionMessenger.ts +1 -1
  94. package/src/interaction/InteractionServer.ts +165 -50
  95. package/src/interaction/ServerSubscription.ts +87 -63
  96. package/src/interaction/Subscription.ts +34 -6
  97. package/src/peer/ControllerCommissioner.ts +4 -5
  98. package/src/peer/PeerAddress.ts +14 -0
  99. package/src/peer/PeerSet.ts +31 -9
  100. package/src/securechannel/SecureChannelMessenger.ts +4 -0
  101. package/src/session/SecureSession.ts +3 -2
  102. package/src/session/Session.ts +1 -0
  103. package/src/session/SessionManager.ts +5 -9
@@ -175,41 +175,58 @@ export class ServerSubscription extends Subscription {
175
175
  }
176
176
  >();
177
177
  #sendUpdatesActivated = false;
178
- readonly #maxIntervalMs: number;
179
178
  readonly #sendIntervalMs: number;
180
- private readonly minIntervalFloorMs: number;
181
- private readonly maxIntervalCeilingMs: number;
182
- private readonly peerAddress: PeerAddress;
179
+ readonly #minIntervalFloorMs: number;
180
+ readonly #maxIntervalCeilingMs: number;
181
+ readonly #peerAddress: PeerAddress;
183
182
 
184
- private sendNextUpdateImmediately = false;
185
- private sendUpdateErrorCounter = 0;
186
- private attributeUpdatePromises = new Set<PromiseLike<void>>();
187
- private currentUpdatePromise?: Promise<void>;
183
+ #sendNextUpdateImmediately = false;
184
+ #sendUpdateErrorCounter = 0;
185
+ readonly #attributeUpdatePromises = new Set<PromiseLike<void>>();
186
+ #currentUpdatePromise?: Promise<void>;
188
187
 
189
188
  constructor(options: {
190
189
  id: number;
191
190
  context: ServerSubscriptionContext;
192
191
  criteria: SubscriptionCriteria;
193
- minIntervalFloor: number;
194
- maxIntervalCeiling: number;
192
+ minIntervalFloorSeconds: number;
193
+ maxIntervalCeilingSeconds: number;
195
194
  subscriptionOptions: ServerSubscriptionConfig;
195
+ useAsMaxInterval?: number;
196
+ useAsSendInterval?: number;
196
197
  }) {
197
- const { id, context, criteria, minIntervalFloor, maxIntervalCeiling, subscriptionOptions } = options;
198
+ const {
199
+ id,
200
+ context,
201
+ criteria,
202
+ minIntervalFloorSeconds,
203
+ maxIntervalCeilingSeconds,
204
+ subscriptionOptions,
205
+ useAsMaxInterval,
206
+ useAsSendInterval,
207
+ } = options;
198
208
 
199
209
  super(context.session, id, criteria);
200
210
  this.#context = context;
201
211
  this.#structure = context.structure;
202
212
 
203
- this.peerAddress = this.session.peerAddress;
204
- this.minIntervalFloorMs = minIntervalFloor * 1000;
205
- this.maxIntervalCeilingMs = maxIntervalCeiling * 1000;
206
-
207
- const { maxInterval, sendInterval } = this.determineSendingIntervals(
208
- subscriptionOptions.minIntervalSeconds * 1000,
209
- subscriptionOptions.maxIntervalSeconds * 1000,
210
- subscriptionOptions.randomizationWindowSeconds * 1000,
211
- );
212
- this.#maxIntervalMs = maxInterval;
213
+ this.#peerAddress = this.session.peerAddress;
214
+ this.#minIntervalFloorMs = minIntervalFloorSeconds * 1000;
215
+ this.#maxIntervalCeilingMs = maxIntervalCeilingSeconds * 1000;
216
+
217
+ let maxInterval: number;
218
+ let sendInterval: number;
219
+ if (useAsMaxInterval !== undefined && useAsSendInterval !== undefined) {
220
+ maxInterval = useAsMaxInterval * 1000;
221
+ sendInterval = useAsSendInterval * 1000;
222
+ } else {
223
+ ({ maxInterval, sendInterval } = this.#determineSendingIntervals(
224
+ subscriptionOptions.minIntervalSeconds * 1000,
225
+ subscriptionOptions.maxIntervalSeconds * 1000,
226
+ subscriptionOptions.randomizationWindowSeconds * 1000,
227
+ ));
228
+ }
229
+ this.maxIntervalMs = maxInterval;
213
230
  this.#sendIntervalMs = sendInterval;
214
231
 
215
232
  this.#updateTimer = Time.getTimer(`Subscription ${this.id} update`, this.#sendIntervalMs, () =>
@@ -217,7 +234,7 @@ export class ServerSubscription extends Subscription {
217
234
  ); // will be started later
218
235
  }
219
236
 
220
- private determineSendingIntervals(
237
+ #determineSendingIntervals(
221
238
  subscriptionMinIntervalMs: number,
222
239
  subscriptionMaxIntervalMs: number,
223
240
  subscriptionRandomizationWindowMs: number,
@@ -230,7 +247,7 @@ export class ServerSubscription extends Subscription {
230
247
  const maxInterval = Math.min(
231
248
  Math.max(
232
249
  subscriptionMinIntervalMs,
233
- Math.max(this.minIntervalFloorMs, Math.min(subscriptionMaxIntervalMs, this.maxIntervalCeilingMs)),
250
+ Math.max(this.#minIntervalFloorMs, Math.min(subscriptionMaxIntervalMs, this.#maxIntervalCeilingMs)),
234
251
  ) + Math.floor(subscriptionRandomizationWindowMs * Math.random()),
235
252
  MAX_INTERVAL_PUBLISHER_LIMIT_S * 1000,
236
253
  );
@@ -239,7 +256,7 @@ export class ServerSubscription extends Subscription {
239
256
  // But if we have no chance of at least one full resubmission process we do like chip-tool.
240
257
  // One full resubmission process takes 33-45 seconds. So 60s means we reach at least first 2 retries of a
241
258
  // second subscription report after first failed.
242
- sendInterval = Math.max(this.minIntervalFloorMs, Math.floor(maxInterval * 0.8));
259
+ sendInterval = Math.max(this.#minIntervalFloorMs, Math.floor(maxInterval * 0.8));
243
260
  }
244
261
  if (sendInterval < subscriptionMinIntervalMs) {
245
262
  // But not faster than once every 2s
@@ -251,7 +268,7 @@ export class ServerSubscription extends Subscription {
251
268
  return { maxInterval, sendInterval };
252
269
  }
253
270
 
254
- private registerNewAttributes() {
271
+ #registerNewAttributes() {
255
272
  const newAttributes = new Array<AttributeWithPath>();
256
273
  const attributeErrors = new Array<TypeFromSchema<typeof TlvAttributeStatus>>();
257
274
  const formerAttributes = new Set<string>(this.#attributeListeners.keys());
@@ -426,7 +443,7 @@ export class ServerSubscription extends Subscription {
426
443
  * controller. The data of newly added events are not sent automatically.
427
444
  */
428
445
  async updateSubscription() {
429
- const { newAttributes } = this.registerNewAttributes();
446
+ const { newAttributes } = this.#registerNewAttributes();
430
447
 
431
448
  for (const { path, attribute } of newAttributes) {
432
449
  const { version, value } = this.#context.readAttribute(path, attribute);
@@ -485,15 +502,21 @@ export class ServerSubscription extends Subscription {
485
502
  this.#prepareDataUpdate();
486
503
  }
487
504
 
488
- get maxInterval(): number {
489
- return Math.ceil(this.#maxIntervalMs / 1000);
490
- }
491
-
492
505
  get sendInterval(): number {
493
506
  return Math.ceil(this.#sendIntervalMs / 1000);
494
507
  }
495
508
 
496
- activateSendingUpdates() {
509
+ get minIntervalFloorSeconds(): number {
510
+ return Math.ceil(this.#minIntervalFloorMs / 1000);
511
+ }
512
+
513
+ get maxIntervalCeilingSeconds(): number {
514
+ return Math.ceil(this.#maxIntervalCeilingMs / 1000);
515
+ }
516
+
517
+ override activate() {
518
+ super.activate();
519
+
497
520
  // We do not need these data anymore, so we can free some memory
498
521
  if (this.criteria.eventFilters !== undefined) this.criteria.eventFilters.length = 0;
499
522
  if (this.criteria.dataVersionFilters !== undefined) this.criteria.dataVersionFilters.length = 0;
@@ -533,11 +556,11 @@ export class ServerSubscription extends Subscription {
533
556
  this.#updateTimer.stop();
534
557
  const now = Time.nowMs();
535
558
  const timeSinceLastUpdateMs = now - this.#lastUpdateTimeMs;
536
- if (timeSinceLastUpdateMs < this.minIntervalFloorMs) {
559
+ if (timeSinceLastUpdateMs < this.#minIntervalFloorMs) {
537
560
  // Respect minimum delay time between updates
538
561
  this.#updateTimer = Time.getTimer(
539
562
  "Subscription update",
540
- this.minIntervalFloorMs - timeSinceLastUpdateMs,
563
+ this.#minIntervalFloorMs - timeSinceLastUpdateMs,
541
564
  () => this.#prepareDataUpdate(),
542
565
  ).start();
543
566
  return;
@@ -550,14 +573,14 @@ export class ServerSubscription extends Subscription {
550
573
  }
551
574
 
552
575
  #triggerSendUpdate() {
553
- if (this.currentUpdatePromise !== undefined) {
576
+ if (this.#currentUpdatePromise !== undefined) {
554
577
  logger.debug("Sending update already in progress, delaying update ...");
555
- this.sendNextUpdateImmediately = true;
578
+ this.#sendNextUpdateImmediately = true;
556
579
  return;
557
580
  }
558
- this.currentUpdatePromise = this.#sendUpdate()
581
+ this.#currentUpdatePromise = this.#sendUpdate()
559
582
  .catch(error => logger.warn("Sending subscription update failed:", error))
560
- .finally(() => (this.currentUpdatePromise = undefined));
583
+ .finally(() => (this.#currentUpdatePromise = undefined));
561
584
  }
562
585
 
563
586
  /**
@@ -593,20 +616,20 @@ export class ServerSubscription extends Subscription {
593
616
  this.#lastUpdateTimeMs = Time.nowMs();
594
617
 
595
618
  try {
596
- await this.sendUpdateMessage(attributeUpdatesToSend, eventUpdatesToSend);
597
- this.sendUpdateErrorCounter = 0;
619
+ await this.#sendUpdateMessage(attributeUpdatesToSend, eventUpdatesToSend);
620
+ this.#sendUpdateErrorCounter = 0;
598
621
  } catch (error) {
599
622
  if (this.isClosed) {
600
623
  // No need to care about resubmissions when the server is closing
601
624
  return;
602
625
  }
603
626
 
604
- this.sendUpdateErrorCounter++;
627
+ this.#sendUpdateErrorCounter++;
605
628
  logger.info(
606
- `Error sending subscription update message (error count=${this.sendUpdateErrorCounter}):`,
629
+ `Error sending subscription update message (error count=${this.#sendUpdateErrorCounter}):`,
607
630
  (error instanceof MatterError && error.message) || error,
608
631
  );
609
- if (this.sendUpdateErrorCounter <= 2) {
632
+ if (this.#sendUpdateErrorCounter <= 2) {
610
633
  // fill the data back in the queue to resend with next try
611
634
  const newAttributeUpdatesToSend = Array.from(this.#outstandingAttributeUpdates.values());
612
635
  this.#outstandingAttributeUpdates.clear();
@@ -622,13 +645,14 @@ export class ServerSubscription extends Subscription {
622
645
  logger.info(
623
646
  `Sending update failed 3 times in a row, canceling subscription ${this.id} and let controller subscribe again.`,
624
647
  );
625
- this.sendNextUpdateImmediately = false;
648
+ this.#sendNextUpdateImmediately = false;
626
649
  if (
627
650
  error instanceof NoResponseTimeoutError ||
628
651
  error instanceof NetworkError ||
629
652
  error instanceof NoChannelError
630
653
  ) {
631
654
  // Let's consider this subscription as dead and wait for a reconnect
655
+ this.isCanceledByPeer = true; // We handle this case like if the controller canceled the subscription
632
656
  await this.destroy();
633
657
  return;
634
658
  } else {
@@ -637,9 +661,9 @@ export class ServerSubscription extends Subscription {
637
661
  }
638
662
  }
639
663
 
640
- if (this.sendNextUpdateImmediately) {
664
+ if (this.#sendNextUpdateImmediately) {
641
665
  logger.debug("Sending delayed update immediately after last one was sent.");
642
- this.sendNextUpdateImmediately = false;
666
+ this.#sendNextUpdateImmediately = false;
643
667
  await this.#sendUpdate(true); // Send but only if non-empty
644
668
  }
645
669
  }
@@ -799,7 +823,7 @@ export class ServerSubscription extends Subscription {
799
823
  async sendInitialReport(messenger: InteractionServerMessenger) {
800
824
  this.#updateTimer.stop();
801
825
 
802
- const { newAttributes, attributeErrors } = this.registerNewAttributes();
826
+ const { newAttributes, attributeErrors } = this.#registerNewAttributes();
803
827
  const { newEvents, eventErrors } = this.#registerNewEvents();
804
828
  const { eventReportsPayload, eventsFiltered } = await this.#collectInitialEventReportPayloads(newEvents);
805
829
 
@@ -822,8 +846,8 @@ export class ServerSubscription extends Subscription {
822
846
  if (MaybePromise.is(changeResult)) {
823
847
  const resolver = Promise.resolve(changeResult)
824
848
  .catch(error => logger.error(`Error handling attribute change:`, error))
825
- .finally(() => this.attributeUpdatePromises.delete(resolver));
826
- this.attributeUpdatePromises.add(resolver);
849
+ .finally(() => this.#attributeUpdatePromises.delete(resolver));
850
+ this.#attributeUpdatePromises.add(resolver);
827
851
  }
828
852
  }
829
853
 
@@ -877,15 +901,15 @@ export class ServerSubscription extends Subscription {
877
901
  }
878
902
  }
879
903
 
880
- async flush() {
904
+ async #flush() {
881
905
  this.#sendDelayTimer.stop();
882
906
  if (this.#outstandingAttributeUpdates.size > 0 || this.#outstandingEventUpdates.size > 0) {
883
907
  logger.debug(
884
908
  `Flushing subscription ${this.id} with ${this.#outstandingAttributeUpdates.size} attributes and ${this.#outstandingEventUpdates.size} events${this.isClosed ? " (for closing)" : ""}`,
885
909
  );
886
910
  this.#triggerSendUpdate();
887
- if (this.currentUpdatePromise) {
888
- await this.currentUpdatePromise;
911
+ if (this.#currentUpdatePromise) {
912
+ await this.#currentUpdatePromise;
889
913
  }
890
914
  }
891
915
  }
@@ -894,9 +918,9 @@ export class ServerSubscription extends Subscription {
894
918
  this.#sendUpdatesActivated = false;
895
919
  this.unregisterAttributeListeners(Array.from(this.#attributeListeners.keys()));
896
920
  this.unregisterEventListeners(Array.from(this.#eventListeners.keys()));
897
- if (this.attributeUpdatePromises.size) {
898
- const resolvers = [...this.attributeUpdatePromises.values()];
899
- this.attributeUpdatePromises.clear();
921
+ if (this.#attributeUpdatePromises.size) {
922
+ const resolvers = [...this.#attributeUpdatePromises.values()];
923
+ this.#attributeUpdatePromises.clear();
900
924
  await MatterAggregateError.allSettled(resolvers, "Error receiving all outstanding attribute values").catch(
901
925
  error => logger.error(error),
902
926
  );
@@ -909,16 +933,19 @@ export class ServerSubscription extends Subscription {
909
933
  /**
910
934
  * Closes the subscription and flushes all outstanding data updates if requested.
911
935
  */
912
- override async close(graceful = false) {
936
+ override async close(graceful = false, cancelledByPeer = false) {
913
937
  if (this.isClosed) {
914
938
  return;
915
939
  }
940
+ if (cancelledByPeer) {
941
+ this.isCanceledByPeer = true;
942
+ }
916
943
  await this.destroy();
917
944
  if (graceful) {
918
- await this.flush();
945
+ await this.#flush();
919
946
  }
920
- if (this.currentUpdatePromise) {
921
- await this.currentUpdatePromise;
947
+ if (this.#currentUpdatePromise) {
948
+ await this.#currentUpdatePromise;
922
949
  }
923
950
  }
924
951
 
@@ -954,11 +981,8 @@ export class ServerSubscription extends Subscription {
954
981
  }
955
982
  }
956
983
 
957
- private async sendUpdateMessage(
958
- attributes: AttributePathWithValueVersion<any>[],
959
- events: EventPathWithEventData<any>[],
960
- ) {
961
- const exchange = this.#context.initiateExchange(this.peerAddress, INTERACTION_PROTOCOL_ID);
984
+ async #sendUpdateMessage(attributes: AttributePathWithValueVersion<any>[], events: EventPathWithEventData<any>[]) {
985
+ const exchange = this.#context.initiateExchange(this.#peerAddress, INTERACTION_PROTOCOL_ID);
962
986
  if (exchange === undefined) return;
963
987
  if (attributes.length) {
964
988
  logger.debug(
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
 
7
- import { Logger } from "#general";
7
+ import { InternalError, Logger, Observable } from "#general";
8
8
  import { type SecureSession } from "#session/SecureSession.js";
9
9
  import { TlvAttributePath, TlvDataVersionFilter, TlvEventFilter, TlvEventPath, TypeFromSchema } from "#types";
10
10
 
@@ -29,15 +29,13 @@ export abstract class Subscription {
29
29
  #isClosed?: boolean;
30
30
  #isCanceledByPeer?: boolean;
31
31
  #criteria: SubscriptionCriteria;
32
+ #cancelled = Observable<[subscription: Subscription]>();
33
+ #maxIntervalMs?: number;
32
34
 
33
35
  constructor(session: SecureSession, id: SubscriptionId, criteria: SubscriptionCriteria) {
34
36
  this.#session = session;
35
37
  this.#id = id;
36
38
  this.#criteria = criteria;
37
-
38
- // TODO Do not add to session but to node/peer
39
- this.#session.subscriptions.add(this);
40
- logger.debug(`Added subscription ${this.#id} to ${this.#session.name}`);
41
39
  }
42
40
 
43
41
  get id() {
@@ -60,6 +58,28 @@ export abstract class Subscription {
60
58
  return this.#session;
61
59
  }
62
60
 
61
+ get cancelled() {
62
+ return this.#cancelled;
63
+ }
64
+
65
+ get maxIntervalMs(): number {
66
+ if (this.#maxIntervalMs === undefined) {
67
+ throw new InternalError("Subscription MaxIntervalMs accessed before it was set");
68
+ }
69
+ return this.#maxIntervalMs;
70
+ }
71
+
72
+ set maxIntervalMs(value: number) {
73
+ if (this.#maxIntervalMs !== undefined) {
74
+ throw new InternalError("Subscription MaxIntervalMs set twice. This should never happen.");
75
+ }
76
+ this.#maxIntervalMs = value;
77
+ }
78
+
79
+ get maxInterval(): number {
80
+ return Math.ceil(this.maxIntervalMs / 1000);
81
+ }
82
+
63
83
  /**
64
84
  * Update session state. This probably is meaningless except in a server context.
65
85
  */
@@ -77,7 +97,7 @@ export abstract class Subscription {
77
97
  }
78
98
 
79
99
  /** Close the subscription with the option to gracefully flush outstanding data. */
80
- abstract close(graceful: boolean): Promise<void>;
100
+ abstract close(graceful: boolean, cancelledByPeer?: boolean): Promise<void>;
81
101
 
82
102
  /**
83
103
  * Destroy the subscription. Unsubscribe from all attributes and events and stop all timers.
@@ -86,5 +106,13 @@ export abstract class Subscription {
86
106
  this.#isClosed = true;
87
107
  this.#session.subscriptions.delete(this);
88
108
  logger.debug(`Removed subscription ${this.id} from ${this.#session.name}`);
109
+
110
+ this.#cancelled.emit(this);
111
+ }
112
+
113
+ protected activate() {
114
+ // TODO Do not add to session but to node/peer
115
+ this.#session.subscriptions.add(this);
116
+ logger.debug(`Added subscription ${this.#id} to ${this.#session.name}`);
89
117
  }
90
118
  }
@@ -407,15 +407,14 @@ export class ControllerCommissioner {
407
407
  }
408
408
 
409
409
  // Look for the device broadcast over MDNS and do CASE pairing
410
- return await this.#context.clients.connect(
411
- address,
412
- {
410
+ return await this.#context.clients.connect(address, {
411
+ discoveryOptions: {
413
412
  discoveryType: NodeDiscoveryType.TimedDiscovery,
414
413
  timeoutSeconds: 120,
415
414
  discoveryData,
416
415
  },
417
- true,
418
- ); // Wait maximum 120s to find the operational device for commissioning process
416
+ allowUnknownPeer: true,
417
+ }); // Wait maximum 120s to find the operational device for commissioning process
419
418
  },
420
419
  );
421
420
 
@@ -86,3 +86,17 @@ export class PeerAddressMap<T> extends Map<PeerAddress, T> {
86
86
  return super.get(PeerAddress(key));
87
87
  }
88
88
  }
89
+
90
+ export class PeerAddressSet extends Set<PeerAddress> {
91
+ override add(value: PeerAddress) {
92
+ return super.add(PeerAddress(value));
93
+ }
94
+
95
+ override has(value: PeerAddress) {
96
+ return super.has(PeerAddress(value));
97
+ }
98
+
99
+ override delete(value: PeerAddress) {
100
+ return super.delete(PeerAddress(value));
101
+ }
102
+ }
@@ -144,6 +144,7 @@ export class PeerSet implements ImmutableSet<OperationalPeer>, ObservableSet<Ope
144
144
 
145
145
  this.#sessions.resubmissionStarted.on(this.#handleResubmissionStarted.bind(this));
146
146
 
147
+ /** A channel was added by ourselves */
147
148
  this.#channels.added.on((address, msgChannel) => {
148
149
  if (isIpNetworkChannel(msgChannel.channel)) {
149
150
  // Update the channel address if it has one
@@ -230,7 +231,15 @@ export class PeerSet implements ImmutableSet<OperationalPeer>, ObservableSet<Ope
230
231
  /**
231
232
  * Ensure there is a channel to the designated peer.
232
233
  */
233
- async ensureConnection(address: PeerAddress, discoveryOptions: DiscoveryOptions, allowUnknownPeer = false) {
234
+ async ensureConnection(
235
+ address: PeerAddress,
236
+ options: {
237
+ discoveryOptions: DiscoveryOptions;
238
+ allowUnknownPeer?: boolean;
239
+ operationalAddress?: ServerAddressIp;
240
+ },
241
+ ) {
242
+ const { discoveryOptions, allowUnknownPeer, operationalAddress } = options;
234
243
  if (!this.#peersByAddress.has(address) && !allowUnknownPeer) {
235
244
  throw new UnknownNodeError(`Cannot connect to unknown device ${PeerAddress(address)}`);
236
245
  }
@@ -246,7 +255,7 @@ export class PeerSet implements ImmutableSet<OperationalPeer>, ObservableSet<Ope
246
255
  const { promise, resolver, rejecter } = createPromise<MessageChannel>();
247
256
  this.#runningPeerReconnections.set(address, { promise, rejecter });
248
257
 
249
- this.#resume(address, discoveryOptions)
258
+ this.#resume(address, discoveryOptions, operationalAddress)
250
259
  .then(channel => {
251
260
  this.#runningPeerReconnections.delete(address);
252
261
  resolver(channel);
@@ -268,7 +277,9 @@ export class PeerSet implements ImmutableSet<OperationalPeer>, ObservableSet<Ope
268
277
  return new ReconnectableExchangeProvider(this.#exchanges, this.#channels, address, async () => {
269
278
  if (!initiallyConnected && !this.#channels.hasChannel(address)) {
270
279
  // We got an uninitialized node, so do the first connection as usual
271
- await this.ensureConnection(address, { discoveryType: NodeDiscoveryType.None });
280
+ await this.ensureConnection(address, {
281
+ discoveryOptions: { discoveryType: NodeDiscoveryType.None },
282
+ });
272
283
  initiallyConnected = true; // We only do this connection once, rest is handled in following code
273
284
  if (this.#channels.hasChannel(address)) {
274
285
  return;
@@ -366,18 +377,22 @@ export class PeerSet implements ImmutableSet<OperationalPeer>, ObservableSet<Ope
366
377
  * device is discovered again using its operational instance details.
367
378
  * It returns the operational MessageChannel on success.
368
379
  */
369
- async #resume(address: PeerAddress, discoveryOptions?: DiscoveryOptions) {
380
+ async #resume(address: PeerAddress, discoveryOptions?: DiscoveryOptions, tryOperationalAddress?: ServerAddressIp) {
370
381
  const { discoveryType } = discoveryOptions ?? {};
382
+
371
383
  const operationalAddress =
372
- discoveryType === NodeDiscoveryType.None
384
+ tryOperationalAddress ??
385
+ (discoveryType === NodeDiscoveryType.None
373
386
  ? this.#getLastOperationalAddress(address)
374
- : this.#knownOperationalAddressFor(address);
387
+ : this.#knownOperationalAddressFor(address));
388
+
375
389
  try {
376
390
  return await this.#connectOrDiscoverNode(address, operationalAddress, discoveryOptions);
377
391
  } catch (error) {
378
392
  if (
379
393
  (error instanceof DiscoveryError || error instanceof NoResponseTimeoutError) &&
380
- this.#peersByAddress.has(address)
394
+ this.#peersByAddress.has(address) &&
395
+ tryOperationalAddress === undefined
381
396
  ) {
382
397
  logger.info(`Resume failed, remove all sessions for ${PeerAddress(address)}`);
383
398
  // We remove all sessions, this also informs the PairedNode class
@@ -432,7 +447,13 @@ export class PeerSet implements ImmutableSet<OperationalPeer>, ObservableSet<Ope
432
447
  operationalAddress !== undefined &&
433
448
  (runningDiscoveryType === NodeDiscoveryType.None || requestedDiscoveryType === NodeDiscoveryType.None)
434
449
  ) {
435
- const directReconnection = await this.#reconnectKnownAddress(address, operationalAddress, discoveryData);
450
+ const directReconnection = await this.#reconnectKnownAddress(
451
+ address,
452
+ operationalAddress,
453
+ discoveryData,
454
+ // When we use a timeout for discovery also use this for reconnecting to the node
455
+ timeoutSeconds ? timeoutSeconds * 1000 : undefined,
456
+ );
436
457
  if (directReconnection !== undefined) {
437
458
  return directReconnection;
438
459
  }
@@ -567,6 +588,7 @@ export class PeerSet implements ImmutableSet<OperationalPeer>, ObservableSet<Ope
567
588
  address = PeerAddress(address);
568
589
 
569
590
  const { ip, port } = operationalAddress;
591
+ const startTime = Time.nowMs();
570
592
  try {
571
593
  logger.debug(
572
594
  `Resuming connection to ${PeerAddress(address)} at ${ip}:${port}${
@@ -585,7 +607,7 @@ export class PeerSet implements ImmutableSet<OperationalPeer>, ObservableSet<Ope
585
607
  error,
586
608
  );
587
609
  // We remove all sessions, this also informs the PairedNode class
588
- await this.#sessions.removeAllSessionsForNode(address);
610
+ await this.#sessions.removeAllSessionsForNode(address, false, startTime);
589
611
  return undefined;
590
612
  } else {
591
613
  throw error;
@@ -43,6 +43,10 @@ export class SecureChannelMessenger {
43
43
  this.#defaultExpectedProcessingTimeMs = defaultExpectedProcessingTimeMs;
44
44
  }
45
45
 
46
+ get channel() {
47
+ return this.exchange.channel;
48
+ }
49
+
46
50
  async nextMessage(
47
51
  expectedMessageType: number,
48
52
  expectedProcessingTimeMs = this.#defaultExpectedProcessingTimeMs,
@@ -292,11 +292,12 @@ export class SecureSession extends Session {
292
292
  return this.#fabric;
293
293
  }
294
294
 
295
- async clearSubscriptions(flushSubscriptions = false) {
295
+ async clearSubscriptions(flushSubscriptions = false, cancelledByPeer = false) {
296
296
  const subscriptions = [...this.#subscriptions]; // get all values because subscriptions will remove themselves when cancelled
297
297
  for (const subscription of subscriptions) {
298
- await subscription.close(flushSubscriptions);
298
+ await subscription.close(flushSubscriptions, cancelledByPeer);
299
299
  }
300
+ return subscriptions.length;
300
301
  }
301
302
 
302
303
  /** Ends a session. Outstanding subscription data will be flushed before the session is destroyed. */
@@ -62,6 +62,7 @@ export abstract class Session {
62
62
  abstract get closingAfterExchangeFinished(): boolean;
63
63
  #manager?: SessionManager;
64
64
  timestamp = Time.nowMs();
65
+ readonly createdAt = Time.nowMs();
65
66
  activeTimestamp = 0;
66
67
  protected readonly idleIntervalMs: number;
67
68
  protected readonly activeIntervalMs: number;
@@ -378,11 +378,12 @@ export class SessionManager {
378
378
  });
379
379
  }
380
380
 
381
- async removeAllSessionsForNode(address: PeerAddress, sendClose = false) {
381
+ async removeAllSessionsForNode(address: PeerAddress, sendClose = false, closeBeforeCreatedTimestamp?: number) {
382
382
  await this.#construction;
383
383
 
384
384
  for (const session of this.#sessions) {
385
385
  if (!session.isSecure) continue;
386
+ if (closeBeforeCreatedTimestamp !== undefined && session.createdAt >= closeBeforeCreatedTimestamp) continue;
386
387
  const secureSession = session;
387
388
  if (secureSession.peerIs(address)) {
388
389
  await secureSession.destroy(sendClose, false);
@@ -564,17 +565,12 @@ export class SessionManager {
564
565
  }
565
566
 
566
567
  /** Clears all subscriptions for a given node and returns how many were cleared. */
567
- async clearSubscriptionsForNode(fabricIndex: FabricIndex, nodeId: NodeId, flushSubscriptions?: boolean) {
568
+ async clearSubscriptionsForNode(peerAddress: PeerAddress, flushSubscriptions?: boolean) {
568
569
  let clearedCount = 0;
569
570
  for (const session of this.#sessions) {
570
- if (session.fabric?.fabricIndex !== fabricIndex) {
571
- continue;
571
+ if (PeerAddress.is(session.peerAddress, peerAddress)) {
572
+ clearedCount += await session.clearSubscriptions(flushSubscriptions, true);
572
573
  }
573
- if (session.peerNodeId !== nodeId) {
574
- continue;
575
- }
576
- await session.clearSubscriptions(flushSubscriptions);
577
- clearedCount++;
578
574
  }
579
575
  return clearedCount;
580
576
  }