@dronedeploy/rocos-js-sdk 4.4.15 → 4.5.0

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.
@@ -55,9 +55,9 @@ export declare abstract class TelemetryStreamAbstract implements ITelemetryStrea
55
55
  * unsubscribe landing last strands a subscribe and nothing re-adds it.
56
56
  */
57
57
  private enqueueTelemetryAction;
58
- private takeTelemetryAction;
58
+ private sendTelemetryBatch;
59
+ private sendTelemetryQuery;
59
60
  protected listenMessagesAndRenew(): void;
60
- private addTerminateToAction;
61
61
  private renewReceiver;
62
62
  private messageTimeoutTryAgain;
63
63
  /**
@@ -39,7 +39,6 @@ const takeNextTelemetryBatch = (queueState) => {
39
39
  const [nextAction] = queueState.pendingActions;
40
40
  if (nextAction.callsignsLookup.isQuery() ||
41
41
  nextAction.terminate ||
42
- nextAction.actionType !== firstAction.actionType ||
43
42
  nextAction.subscriberId !== firstAction.subscriberId ||
44
43
  nextAction.registration !== firstAction.registration) {
45
44
  break;
@@ -48,6 +47,103 @@ const takeNextTelemetryBatch = (queueState) => {
48
47
  }
49
48
  return activeBatch;
50
49
  };
50
+ const withTerminateOption = (telemetryAction) => {
51
+ telemetryAction.content = {
52
+ oneofKind: 'unsubscribeOperation',
53
+ unsubscribeOperation: teletubby_pb_1.UnsubscribeOperation.create({
54
+ options: [
55
+ {
56
+ content: {
57
+ receivergroupUnsubscribeOption: {
58
+ terminate: true,
59
+ },
60
+ oneofKind: 'receivergroupUnsubscribeOption',
61
+ },
62
+ },
63
+ ],
64
+ }),
65
+ };
66
+ return telemetryAction;
67
+ };
68
+ const pairKey = (callsign, source) => `${callsign}\u0000${source}`;
69
+ const groupCallsignsBySources = (sourcesByCallsign) => {
70
+ const groups = new Map();
71
+ sourcesByCallsign.forEach((sources, callsign) => {
72
+ const key = sources.join('\u0000');
73
+ const group = groups.get(key);
74
+ if (group) {
75
+ group.callsigns.push(callsign);
76
+ }
77
+ else {
78
+ groups.set(key, { callsigns: [callsign], sources });
79
+ }
80
+ });
81
+ return [...groups.values()];
82
+ };
83
+ /**
84
+ * Turns a batch of queued subscribe/unsubscribe actions into the actions of one TelemetryRequest.
85
+ *
86
+ * teletubby holds a set of (callsign, source) pairs per receiver and applies a request's actions
87
+ * one at a time, in order. Sending the batch as queued is wrong in two ways:
88
+ *
89
+ * 1. If an unsubscribe ever leaves the receiver with no pairs, teletubby removes the receiver on
90
+ * the spot and every later request is rejected. A client swapping its only source (unsubscribe A,
91
+ * then subscribe B) hits exactly that. So the subscribes come first in the request: the receiver
92
+ * can only shrink after it has grown.
93
+ *
94
+ * 2. One batch can name the same pair more than once, e.g. a caller that unsubscribes from P and
95
+ * subscribes to it again before the queue has drained. Only the last action for a pair
96
+ * reflects what the caller wants now, so that action owns the pair and earlier ones drop it.
97
+ * And when the first and last actions for a pair disagree, nothing is sent for it at all:
98
+ * actions are only queued when local state actually changed, so a pair that was unsubscribed and
99
+ * then resubscribed within the batch is still held by teletubby, and one that was subscribed
100
+ * and then unsubscribed was never sent. Sending the last action anyway would be harmless but
101
+ * could, in the unsubscribe case, be the action that empties the receiver.
102
+ *
103
+ * Each queued action is emitted trimmed to the pairs it still owns, split per distinct source list
104
+ * so the callsigns-by-sources shape teletubby expects is kept. The terminate option on an
105
+ * unsubscribe is carried through unchanged.
106
+ */
107
+ const planTelemetryActions = (batch) => {
108
+ const firstIntent = new Map();
109
+ const owner = new Map();
110
+ batch.forEach((action, index) => {
111
+ action.callsignsLookup.getCallsigns().forEach((callsign) => {
112
+ action.sources.forEach((source) => {
113
+ const key = pairKey(callsign, source);
114
+ if (!firstIntent.has(key))
115
+ firstIntent.set(key, action.actionType);
116
+ owner.set(key, index);
117
+ });
118
+ });
119
+ });
120
+ const subscribes = [];
121
+ const unsubscribes = [];
122
+ batch.forEach((action, index) => {
123
+ const sourcesByCallsign = new Map();
124
+ action.callsignsLookup.getCallsigns().forEach((callsign) => {
125
+ const ownedSources = action.sources.filter((source) => {
126
+ const key = pairKey(callsign, source);
127
+ return owner.get(key) === index && firstIntent.get(key) === action.actionType;
128
+ });
129
+ if (ownedSources.length)
130
+ sourcesByCallsign.set(callsign, ownedSources);
131
+ });
132
+ groupCallsignsBySources(sourcesByCallsign).forEach(({ callsigns, sources }) => {
133
+ const telemetryAction = teletubby_pb_1.TelemetryAction.create({ operation: action.actionType, callsigns, sources });
134
+ if (action.actionType === 'subscribe') {
135
+ subscribes.push(telemetryAction);
136
+ }
137
+ else if (action.terminate) {
138
+ unsubscribes.push(withTerminateOption(telemetryAction));
139
+ }
140
+ else {
141
+ unsubscribes.push(telemetryAction);
142
+ }
143
+ });
144
+ });
145
+ return [...subscribes, ...unsubscribes];
146
+ };
51
147
  class TelemetryStreamAbstract {
52
148
  constructor(config) {
53
149
  this.telemetryActionQueue = Promise.resolve();
@@ -76,7 +172,6 @@ class TelemetryStreamAbstract {
76
172
  this.heartbeat = new StreamHeartbeat_1.StreamHeartbeat(this.identifier);
77
173
  telemetryActionQueueStates.set(this, {
78
174
  pendingActions: [],
79
- activeBatch: [],
80
175
  registration: 0,
81
176
  drainScheduled: false,
82
177
  requestInFlight: false,
@@ -357,20 +452,17 @@ class TelemetryStreamAbstract {
357
452
  if (queueState.stopped || queueState.requestInFlight)
358
453
  return;
359
454
  const activeBatch = takeNextTelemetryBatch(queueState);
360
- const [firstAction] = activeBatch;
361
- if (!firstAction)
455
+ if (activeBatch.length === 0)
362
456
  return;
363
- queueState.activeBatch = activeBatch;
364
457
  queueState.requestInFlight = true;
365
458
  try {
366
- await this.takeTelemetryAction(firstAction.actionType, firstAction.callsignsLookup, firstAction.sources);
459
+ await this.sendTelemetryBatch(activeBatch);
367
460
  resolveTelemetryActions(activeBatch);
368
461
  }
369
462
  catch (error) {
370
463
  activeBatch.forEach((action) => action.reject(error));
371
464
  }
372
465
  finally {
373
- queueState.activeBatch = [];
374
466
  queueState.requestInFlight = false;
375
467
  scheduleDrain();
376
468
  }
@@ -379,77 +471,64 @@ class TelemetryStreamAbstract {
379
471
  scheduleDrain();
380
472
  return completion;
381
473
  }
382
- async takeTelemetryAction(actionType, callsignsLookup, sources) {
383
- this.logger.debug('takeTelemetryAction', actionType);
474
+ sendTelemetryBatch(batch) {
475
+ const [firstAction] = batch;
384
476
  const queueState = telemetryActionQueueStates.get(this);
385
- const activeBatch = queueState?.activeBatch ?? [];
386
- const [firstAction] = activeBatch;
477
+ this.logger.debug('sendTelemetryBatch', batch.map((action) => action.actionType));
387
478
  // A config fault, not a race: this stream can never address a request.
388
479
  if (!this.projectId) {
389
- this.logger.warn('takeTelemetryAction', actionType, `${actionType} without a projectId - dropped`);
480
+ this.logger.warn('sendTelemetryBatch', 'request without a projectId - dropped');
390
481
  return Promise.resolve();
391
482
  }
392
- if (!firstAction?.subscriberId ||
483
+ if (!firstAction.subscriberId ||
393
484
  firstAction.subscriberId !== this.subscriberId ||
394
485
  firstAction.registration !== queueState?.registration) {
395
486
  // Deferred, not lost: `onData` re-asserts `this.sources` when the subscriberId arrives.
396
- this.logger.debug('takeTelemetryAction', actionType, `${actionType} before the receiver was registered - deferred to the post-registration re-assert`);
487
+ this.logger.debug('sendTelemetryBatch', 'request before the receiver was registered - deferred to the post-registration re-assert');
397
488
  return Promise.resolve();
398
489
  }
399
- const actionSources = sources ?? this.sources;
400
- const actionCallsigns = callsignsLookup ?? this.callsignsLookup;
401
- if (!actionCallsigns.isQuery()) {
402
- const req = teletubby_pb_1.TelemetryRequest.create({
403
- subscriberId: firstAction.subscriberId,
404
- requestedActions: activeBatch.map((action) => {
405
- const telemetryAction = teletubby_pb_1.TelemetryAction.create({
406
- operation: action.actionType,
407
- callsigns: action.callsignsLookup.getCallsigns(),
408
- sources: action.sources,
409
- });
410
- if (action.actionType === 'unsubscribe' && action.terminate) {
411
- this.addTerminateToAction(telemetryAction);
412
- }
413
- return telemetryAction;
414
- }),
415
- });
416
- this.logger.debug('takeTelemetryAction', actionType, 'client.requestTelemetry', this.subscriberId);
417
- // Send the message to back-end.
418
- return this.requestTelemetry(req);
490
+ if (firstAction.callsignsLookup.isQuery())
491
+ return this.sendTelemetryQuery(firstAction);
492
+ const requestedActions = planTelemetryActions(batch);
493
+ if (requestedActions.length === 0) {
494
+ this.logger.debug('sendTelemetryBatch', 'every pending delta cancelled out - nothing to send');
495
+ return Promise.resolve();
419
496
  }
420
- const query = actionCallsigns.getQuery();
421
- if (query) {
422
- // We don't support nested query at the moment
423
- const queryOrPredicatesList = [];
424
- // Loop through user provided predicates to construct a telemetry query request
425
- query.predicates.forEach((callsignsPredicate) => {
426
- const queryOrPredicate = teletubby_pb_1.QueryOrPredicate.create({
427
- content: {
428
- oneofKind: 'predicate',
429
- predicate: {
430
- attribute: callsignsPredicate.attribute.valueOf(),
431
- operation: callsignsPredicate.operation.valueOf(),
432
- value: callsignsPredicate.value,
433
- },
497
+ const req = teletubby_pb_1.TelemetryRequest.create({ subscriberId: firstAction.subscriberId, requestedActions });
498
+ this.logger.debug('sendTelemetryBatch', 'client.requestTelemetry', this.subscriberId);
499
+ return this.requestTelemetry(req);
500
+ }
501
+ sendTelemetryQuery(action) {
502
+ const query = action.callsignsLookup.getQuery();
503
+ if (!query)
504
+ return Promise.reject('Unsupported lookupType');
505
+ // We don't support nested query at the moment
506
+ const queryOrPredicatesList = [];
507
+ // Loop through user provided predicates to construct a telemetry query request
508
+ query.predicates.forEach((callsignsPredicate) => {
509
+ const queryOrPredicate = teletubby_pb_1.QueryOrPredicate.create({
510
+ content: {
511
+ oneofKind: 'predicate',
512
+ predicate: {
513
+ attribute: callsignsPredicate.attribute.valueOf(),
514
+ operation: callsignsPredicate.operation.valueOf(),
515
+ value: callsignsPredicate.value,
434
516
  },
435
- });
436
- queryOrPredicatesList.push(queryOrPredicate);
437
- });
438
- // Compose the request message
439
- const req = teletubby_pb_1.TelemetryQueryRequest.create({
440
- subscriberId: firstAction.subscriberId,
441
- sources: actionSources,
442
- operation: actionType,
443
- callsignQuery: {
444
- operation: query.operation.valueOf(),
445
- queryOrPredicates: queryOrPredicatesList,
446
517
  },
447
518
  });
448
- this.logger.debug('takeTelemetryAction', actionType, 'client.requestTelemetry', this.subscriberId);
449
- // Send the telemetry query request to back-end.
450
- return this.requestTelemetryQuery(req);
451
- }
452
- return Promise.reject('Unsupported lookupType');
519
+ queryOrPredicatesList.push(queryOrPredicate);
520
+ });
521
+ const req = teletubby_pb_1.TelemetryQueryRequest.create({
522
+ subscriberId: action.subscriberId,
523
+ sources: action.sources,
524
+ operation: action.actionType,
525
+ callsignQuery: {
526
+ operation: query.operation.valueOf(),
527
+ queryOrPredicates: queryOrPredicatesList,
528
+ },
529
+ });
530
+ this.logger.debug('sendTelemetryQuery', action.actionType, 'client.requestTelemetryQuery', this.subscriberId);
531
+ return this.requestTelemetryQuery(req);
453
532
  }
454
533
  listenMessagesAndRenew() {
455
534
  const timer = this.messagesTimer;
@@ -519,24 +598,6 @@ class TelemetryStreamAbstract {
519
598
  this.logger.debug('listenMessagesAndRenew', 'Message stats', this.receivedDataStats);
520
599
  }, this.timerIntervalInSec * 1000);
521
600
  }
522
- addTerminateToAction(telemetryAction) {
523
- const unsubscribeOperation = teletubby_pb_1.UnsubscribeOperation.create({
524
- options: [
525
- {
526
- content: {
527
- receivergroupUnsubscribeOption: {
528
- terminate: true,
529
- },
530
- oneofKind: 'receivergroupUnsubscribeOption',
531
- },
532
- },
533
- ],
534
- });
535
- telemetryAction.content = {
536
- oneofKind: 'unsubscribeOperation',
537
- unsubscribeOperation,
538
- };
539
- }
540
601
  renewReceiver() {
541
602
  try {
542
603
  // Remove the received call anyway.
@@ -35,12 +35,20 @@ export interface RobotStatusOptions {
35
35
  * rather than deriving "is the robot online" themselves.
36
36
  */
37
37
  export declare class RobotStatusService extends BaseServiceAbstract implements IBaseService {
38
+ private platformTime;
38
39
  constructor(config: IRocosSDKConfig);
39
40
  getStatus(): boolean;
40
41
  /** Health + readiness as reported by the robot (new topic, legacy heartbeat fallback). */
41
42
  getReportedStatusChanges(projectId: string, callsign: string): Observable<ReportedRobotStatus>;
42
43
  /** Per-contributor breakdown behind the reported health and readiness, with the reason for each. */
43
44
  getStatusContributorsChanges(projectId: string, callsign: string): Observable<RobotStatusContributors>;
45
+ /**
46
+ * Telemetry latency in milliseconds — platform time minus when the agent created each liveness
47
+ * message (`robot/status`, or the legacy heartbeat). Emits once per message, and nothing while
48
+ * none arrive: pair it with the `telemetry-liveness` connectivity service to tell a stale value
49
+ * from a live one.
50
+ */
51
+ getTelemetryLatencyChanges(projectId: string, callsign: string): Observable<number>;
44
52
  /** Per-service connectivity plus the aggregate verdict, polled. */
45
53
  getConnectivityChanges(projectId: string, callsign: string, opts?: RobotStatusOptions): Observable<RobotConnectivityStatus>;
46
54
  /** One-shot connectivity snapshot: resolves once every expected service is known, or after a timeout. */
@@ -6,6 +6,7 @@ const models_1 = require("../models");
6
6
  const rxjs_1 = require("rxjs");
7
7
  const reportedStatus_1 = require("./robot-status/reportedStatus");
8
8
  const BaseServiceAbstract_1 = require("./BaseServiceAbstract");
9
+ const PlatformTimeService_1 = require("./PlatformTimeService");
9
10
  const RocosLogger_1 = require("../logger/RocosLogger");
10
11
  const RocosStore_1 = require("../store/RocosStore");
11
12
  const getRobotStatusColour_1 = require("../helpers/getRobotStatusColour");
@@ -34,6 +35,7 @@ class RobotStatusService extends BaseServiceAbstract_1.BaseServiceAbstract {
34
35
  constructor(config) {
35
36
  super(config);
36
37
  this.logger = RocosLogger_1.RocosLogger.getInstance(`RobotStatusService(${this.config.url})`);
38
+ this.platformTime = PlatformTimeService_1.PlatFormTimeService.getInstance(RocosStore_1.RocosStore.getSDKInstance(this.config).getTimeSyncerService());
37
39
  }
38
40
  getStatus() {
39
41
  return true;
@@ -46,6 +48,15 @@ class RobotStatusService extends BaseServiceAbstract_1.BaseServiceAbstract {
46
48
  getStatusContributorsChanges(projectId, callsign) {
47
49
  return (0, reportedStatus_1.getStatusContributorsChanges)(this.telemetryService, projectId, callsign);
48
50
  }
51
+ /**
52
+ * Telemetry latency in milliseconds — platform time minus when the agent created each liveness
53
+ * message (`robot/status`, or the legacy heartbeat). Emits once per message, and nothing while
54
+ * none arrive: pair it with the `telemetry-liveness` connectivity service to tell a stale value
55
+ * from a live one.
56
+ */
57
+ getTelemetryLatencyChanges(projectId, callsign) {
58
+ return (0, reportedStatus_1.getTelemetryLatencyChanges)(this.telemetryService, projectId, callsign, () => this.platformTime.platformTime);
59
+ }
49
60
  /** Per-service connectivity plus the aggregate verdict, polled. */
50
61
  getConnectivityChanges(projectId, callsign, opts) {
51
62
  return (0, connectivity_1.getConnectivityChanges)(this.connectivityDeps(projectId, callsign, opts), projectId, callsign, opts?.expectedServices, opts?.connectivityPollMs);
@@ -41,6 +41,18 @@ export declare const getReportedStatusChanges: (telemetry: TelemetryService, pro
41
41
  * error falls back to an empty breakdown rather than terminating the stream.
42
42
  */
43
43
  export declare const getStatusContributorsChanges: (telemetry: TelemetryService, projectId: string, callsign: string) => Observable<RobotStatusContributors>;
44
+ /**
45
+ * Emits the robot's telemetry latency in milliseconds, once per liveness message (from either the
46
+ * new `robot/status` topic or the legacy heartbeat — the same messages {@link getTelemetryLiveness}
47
+ * watches): `now()` minus the time the agent created the message.
48
+ *
49
+ * `now` should return platform time, so the measurement isn't skewed by the client's clock. Any
50
+ * remaining offset between the agent's clock and platform time feeds straight through, so a value
51
+ * can be slightly negative. Nothing is emitted while no messages arrive; pair this with
52
+ * {@link getTelemetryLiveness} to tell a stale value from a live one. A telemetry error completes
53
+ * the stream rather than erroring it.
54
+ */
55
+ export declare const getTelemetryLatencyChanges: (telemetry: TelemetryService, projectId: string, callsign: string, now: () => number) => Observable<number>;
44
56
  /**
45
57
  * Emits the `telemetry-liveness` connectivity signal: whether a heartbeat (from
46
58
  * either the new `robot/status` topic or the legacy heartbeat) has been received
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getTelemetryLiveness = exports.getStatusContributorsChanges = exports.getReportedStatusChanges = exports.parseRobotReadiness = exports.parseRobotHealth = exports.ROBOT_STATUS_CONTRIBUTORS_SOURCE = exports.LEGACY_HEARTBEAT_SOURCE = exports.ROBOT_STATUS_SOURCE = void 0;
3
+ exports.getTelemetryLiveness = exports.getTelemetryLatencyChanges = exports.getStatusContributorsChanges = exports.getReportedStatusChanges = exports.parseRobotReadiness = exports.parseRobotHealth = exports.ROBOT_STATUS_CONTRIBUTORS_SOURCE = exports.LEGACY_HEARTBEAT_SOURCE = exports.ROBOT_STATUS_SOURCE = void 0;
4
4
  const rxjs_1 = require("rxjs");
5
5
  const models_1 = require("../../models");
6
6
  /** The new agent topic carrying health + readiness (replaces the heartbeat). */
@@ -119,6 +119,23 @@ const getStatusContributorsChanges = (telemetry, projectId, callsign) => {
119
119
  }), (0, rxjs_1.startWith)(EMPTY_CONTRIBUTORS), (0, rxjs_1.distinctUntilChanged)((a, b) => JSON.stringify(a) === JSON.stringify(b)), (0, rxjs_1.catchError)(() => (0, rxjs_1.of)(EMPTY_CONTRIBUTORS)));
120
120
  };
121
121
  exports.getStatusContributorsChanges = getStatusContributorsChanges;
122
+ /**
123
+ * Emits the robot's telemetry latency in milliseconds, once per liveness message (from either the
124
+ * new `robot/status` topic or the legacy heartbeat — the same messages {@link getTelemetryLiveness}
125
+ * watches): `now()` minus the time the agent created the message.
126
+ *
127
+ * `now` should return platform time, so the measurement isn't skewed by the client's clock. Any
128
+ * remaining offset between the agent's clock and platform time feeds straight through, so a value
129
+ * can be slightly negative. Nothing is emitted while no messages arrive; pair this with
130
+ * {@link getTelemetryLiveness} to tell a stale value from a live one. A telemetry error completes
131
+ * the stream rather than erroring it.
132
+ */
133
+ const getTelemetryLatencyChanges = (telemetry, projectId, callsign, now) => {
134
+ return telemetry
135
+ .subscribe({ projectId, callsigns: [callsign], sources: [exports.ROBOT_STATUS_SOURCE, exports.LEGACY_HEARTBEAT_SOURCE] })
136
+ .pipe((0, rxjs_1.map)((message) => now() - message.createdAt.getTime()), (0, rxjs_1.catchError)(() => rxjs_1.EMPTY));
137
+ };
138
+ exports.getTelemetryLatencyChanges = getTelemetryLatencyChanges;
122
139
  /**
123
140
  * Emits the `telemetry-liveness` connectivity signal: whether a heartbeat (from
124
141
  * either the new `robot/status` topic or the legacy heartbeat) has been received
@@ -55,9 +55,9 @@ export declare abstract class TelemetryStreamAbstract implements ITelemetryStrea
55
55
  * unsubscribe landing last strands a subscribe and nothing re-adds it.
56
56
  */
57
57
  private enqueueTelemetryAction;
58
- private takeTelemetryAction;
58
+ private sendTelemetryBatch;
59
+ private sendTelemetryQuery;
59
60
  protected listenMessagesAndRenew(): void;
60
- private addTerminateToAction;
61
61
  private renewReceiver;
62
62
  private messageTimeoutTryAgain;
63
63
  /**
@@ -36,7 +36,6 @@ const takeNextTelemetryBatch = (queueState) => {
36
36
  const [nextAction] = queueState.pendingActions;
37
37
  if (nextAction.callsignsLookup.isQuery() ||
38
38
  nextAction.terminate ||
39
- nextAction.actionType !== firstAction.actionType ||
40
39
  nextAction.subscriberId !== firstAction.subscriberId ||
41
40
  nextAction.registration !== firstAction.registration) {
42
41
  break;
@@ -45,6 +44,103 @@ const takeNextTelemetryBatch = (queueState) => {
45
44
  }
46
45
  return activeBatch;
47
46
  };
47
+ const withTerminateOption = (telemetryAction) => {
48
+ telemetryAction.content = {
49
+ oneofKind: 'unsubscribeOperation',
50
+ unsubscribeOperation: UnsubscribeOperation.create({
51
+ options: [
52
+ {
53
+ content: {
54
+ receivergroupUnsubscribeOption: {
55
+ terminate: true,
56
+ },
57
+ oneofKind: 'receivergroupUnsubscribeOption',
58
+ },
59
+ },
60
+ ],
61
+ }),
62
+ };
63
+ return telemetryAction;
64
+ };
65
+ const pairKey = (callsign, source) => `${callsign}\u0000${source}`;
66
+ const groupCallsignsBySources = (sourcesByCallsign) => {
67
+ const groups = new Map();
68
+ sourcesByCallsign.forEach((sources, callsign) => {
69
+ const key = sources.join('\u0000');
70
+ const group = groups.get(key);
71
+ if (group) {
72
+ group.callsigns.push(callsign);
73
+ }
74
+ else {
75
+ groups.set(key, { callsigns: [callsign], sources });
76
+ }
77
+ });
78
+ return [...groups.values()];
79
+ };
80
+ /**
81
+ * Turns a batch of queued subscribe/unsubscribe actions into the actions of one TelemetryRequest.
82
+ *
83
+ * teletubby holds a set of (callsign, source) pairs per receiver and applies a request's actions
84
+ * one at a time, in order. Sending the batch as queued is wrong in two ways:
85
+ *
86
+ * 1. If an unsubscribe ever leaves the receiver with no pairs, teletubby removes the receiver on
87
+ * the spot and every later request is rejected. A client swapping its only source (unsubscribe A,
88
+ * then subscribe B) hits exactly that. So the subscribes come first in the request: the receiver
89
+ * can only shrink after it has grown.
90
+ *
91
+ * 2. One batch can name the same pair more than once, e.g. a caller that unsubscribes from P and
92
+ * subscribes to it again before the queue has drained. Only the last action for a pair
93
+ * reflects what the caller wants now, so that action owns the pair and earlier ones drop it.
94
+ * And when the first and last actions for a pair disagree, nothing is sent for it at all:
95
+ * actions are only queued when local state actually changed, so a pair that was unsubscribed and
96
+ * then resubscribed within the batch is still held by teletubby, and one that was subscribed
97
+ * and then unsubscribed was never sent. Sending the last action anyway would be harmless but
98
+ * could, in the unsubscribe case, be the action that empties the receiver.
99
+ *
100
+ * Each queued action is emitted trimmed to the pairs it still owns, split per distinct source list
101
+ * so the callsigns-by-sources shape teletubby expects is kept. The terminate option on an
102
+ * unsubscribe is carried through unchanged.
103
+ */
104
+ const planTelemetryActions = (batch) => {
105
+ const firstIntent = new Map();
106
+ const owner = new Map();
107
+ batch.forEach((action, index) => {
108
+ action.callsignsLookup.getCallsigns().forEach((callsign) => {
109
+ action.sources.forEach((source) => {
110
+ const key = pairKey(callsign, source);
111
+ if (!firstIntent.has(key))
112
+ firstIntent.set(key, action.actionType);
113
+ owner.set(key, index);
114
+ });
115
+ });
116
+ });
117
+ const subscribes = [];
118
+ const unsubscribes = [];
119
+ batch.forEach((action, index) => {
120
+ const sourcesByCallsign = new Map();
121
+ action.callsignsLookup.getCallsigns().forEach((callsign) => {
122
+ const ownedSources = action.sources.filter((source) => {
123
+ const key = pairKey(callsign, source);
124
+ return owner.get(key) === index && firstIntent.get(key) === action.actionType;
125
+ });
126
+ if (ownedSources.length)
127
+ sourcesByCallsign.set(callsign, ownedSources);
128
+ });
129
+ groupCallsignsBySources(sourcesByCallsign).forEach(({ callsigns, sources }) => {
130
+ const telemetryAction = TelemetryAction.create({ operation: action.actionType, callsigns, sources });
131
+ if (action.actionType === 'subscribe') {
132
+ subscribes.push(telemetryAction);
133
+ }
134
+ else if (action.terminate) {
135
+ unsubscribes.push(withTerminateOption(telemetryAction));
136
+ }
137
+ else {
138
+ unsubscribes.push(telemetryAction);
139
+ }
140
+ });
141
+ });
142
+ return [...subscribes, ...unsubscribes];
143
+ };
48
144
  export class TelemetryStreamAbstract {
49
145
  constructor(config) {
50
146
  this.telemetryActionQueue = Promise.resolve();
@@ -73,7 +169,6 @@ export class TelemetryStreamAbstract {
73
169
  this.heartbeat = new StreamHeartbeat(this.identifier);
74
170
  telemetryActionQueueStates.set(this, {
75
171
  pendingActions: [],
76
- activeBatch: [],
77
172
  registration: 0,
78
173
  drainScheduled: false,
79
174
  requestInFlight: false,
@@ -354,20 +449,17 @@ export class TelemetryStreamAbstract {
354
449
  if (queueState.stopped || queueState.requestInFlight)
355
450
  return;
356
451
  const activeBatch = takeNextTelemetryBatch(queueState);
357
- const [firstAction] = activeBatch;
358
- if (!firstAction)
452
+ if (activeBatch.length === 0)
359
453
  return;
360
- queueState.activeBatch = activeBatch;
361
454
  queueState.requestInFlight = true;
362
455
  try {
363
- await this.takeTelemetryAction(firstAction.actionType, firstAction.callsignsLookup, firstAction.sources);
456
+ await this.sendTelemetryBatch(activeBatch);
364
457
  resolveTelemetryActions(activeBatch);
365
458
  }
366
459
  catch (error) {
367
460
  activeBatch.forEach((action) => action.reject(error));
368
461
  }
369
462
  finally {
370
- queueState.activeBatch = [];
371
463
  queueState.requestInFlight = false;
372
464
  scheduleDrain();
373
465
  }
@@ -376,77 +468,64 @@ export class TelemetryStreamAbstract {
376
468
  scheduleDrain();
377
469
  return completion;
378
470
  }
379
- async takeTelemetryAction(actionType, callsignsLookup, sources) {
380
- this.logger.debug('takeTelemetryAction', actionType);
471
+ sendTelemetryBatch(batch) {
472
+ const [firstAction] = batch;
381
473
  const queueState = telemetryActionQueueStates.get(this);
382
- const activeBatch = queueState?.activeBatch ?? [];
383
- const [firstAction] = activeBatch;
474
+ this.logger.debug('sendTelemetryBatch', batch.map((action) => action.actionType));
384
475
  // A config fault, not a race: this stream can never address a request.
385
476
  if (!this.projectId) {
386
- this.logger.warn('takeTelemetryAction', actionType, `${actionType} without a projectId - dropped`);
477
+ this.logger.warn('sendTelemetryBatch', 'request without a projectId - dropped');
387
478
  return Promise.resolve();
388
479
  }
389
- if (!firstAction?.subscriberId ||
480
+ if (!firstAction.subscriberId ||
390
481
  firstAction.subscriberId !== this.subscriberId ||
391
482
  firstAction.registration !== queueState?.registration) {
392
483
  // Deferred, not lost: `onData` re-asserts `this.sources` when the subscriberId arrives.
393
- this.logger.debug('takeTelemetryAction', actionType, `${actionType} before the receiver was registered - deferred to the post-registration re-assert`);
484
+ this.logger.debug('sendTelemetryBatch', 'request before the receiver was registered - deferred to the post-registration re-assert');
394
485
  return Promise.resolve();
395
486
  }
396
- const actionSources = sources ?? this.sources;
397
- const actionCallsigns = callsignsLookup ?? this.callsignsLookup;
398
- if (!actionCallsigns.isQuery()) {
399
- const req = TelemetryRequest.create({
400
- subscriberId: firstAction.subscriberId,
401
- requestedActions: activeBatch.map((action) => {
402
- const telemetryAction = TelemetryAction.create({
403
- operation: action.actionType,
404
- callsigns: action.callsignsLookup.getCallsigns(),
405
- sources: action.sources,
406
- });
407
- if (action.actionType === 'unsubscribe' && action.terminate) {
408
- this.addTerminateToAction(telemetryAction);
409
- }
410
- return telemetryAction;
411
- }),
412
- });
413
- this.logger.debug('takeTelemetryAction', actionType, 'client.requestTelemetry', this.subscriberId);
414
- // Send the message to back-end.
415
- return this.requestTelemetry(req);
487
+ if (firstAction.callsignsLookup.isQuery())
488
+ return this.sendTelemetryQuery(firstAction);
489
+ const requestedActions = planTelemetryActions(batch);
490
+ if (requestedActions.length === 0) {
491
+ this.logger.debug('sendTelemetryBatch', 'every pending delta cancelled out - nothing to send');
492
+ return Promise.resolve();
416
493
  }
417
- const query = actionCallsigns.getQuery();
418
- if (query) {
419
- // We don't support nested query at the moment
420
- const queryOrPredicatesList = [];
421
- // Loop through user provided predicates to construct a telemetry query request
422
- query.predicates.forEach((callsignsPredicate) => {
423
- const queryOrPredicate = QueryOrPredicate.create({
424
- content: {
425
- oneofKind: 'predicate',
426
- predicate: {
427
- attribute: callsignsPredicate.attribute.valueOf(),
428
- operation: callsignsPredicate.operation.valueOf(),
429
- value: callsignsPredicate.value,
430
- },
494
+ const req = TelemetryRequest.create({ subscriberId: firstAction.subscriberId, requestedActions });
495
+ this.logger.debug('sendTelemetryBatch', 'client.requestTelemetry', this.subscriberId);
496
+ return this.requestTelemetry(req);
497
+ }
498
+ sendTelemetryQuery(action) {
499
+ const query = action.callsignsLookup.getQuery();
500
+ if (!query)
501
+ return Promise.reject('Unsupported lookupType');
502
+ // We don't support nested query at the moment
503
+ const queryOrPredicatesList = [];
504
+ // Loop through user provided predicates to construct a telemetry query request
505
+ query.predicates.forEach((callsignsPredicate) => {
506
+ const queryOrPredicate = QueryOrPredicate.create({
507
+ content: {
508
+ oneofKind: 'predicate',
509
+ predicate: {
510
+ attribute: callsignsPredicate.attribute.valueOf(),
511
+ operation: callsignsPredicate.operation.valueOf(),
512
+ value: callsignsPredicate.value,
431
513
  },
432
- });
433
- queryOrPredicatesList.push(queryOrPredicate);
434
- });
435
- // Compose the request message
436
- const req = TelemetryQueryRequest.create({
437
- subscriberId: firstAction.subscriberId,
438
- sources: actionSources,
439
- operation: actionType,
440
- callsignQuery: {
441
- operation: query.operation.valueOf(),
442
- queryOrPredicates: queryOrPredicatesList,
443
514
  },
444
515
  });
445
- this.logger.debug('takeTelemetryAction', actionType, 'client.requestTelemetry', this.subscriberId);
446
- // Send the telemetry query request to back-end.
447
- return this.requestTelemetryQuery(req);
448
- }
449
- return Promise.reject('Unsupported lookupType');
516
+ queryOrPredicatesList.push(queryOrPredicate);
517
+ });
518
+ const req = TelemetryQueryRequest.create({
519
+ subscriberId: action.subscriberId,
520
+ sources: action.sources,
521
+ operation: action.actionType,
522
+ callsignQuery: {
523
+ operation: query.operation.valueOf(),
524
+ queryOrPredicates: queryOrPredicatesList,
525
+ },
526
+ });
527
+ this.logger.debug('sendTelemetryQuery', action.actionType, 'client.requestTelemetryQuery', this.subscriberId);
528
+ return this.requestTelemetryQuery(req);
450
529
  }
451
530
  listenMessagesAndRenew() {
452
531
  const timer = this.messagesTimer;
@@ -516,24 +595,6 @@ export class TelemetryStreamAbstract {
516
595
  this.logger.debug('listenMessagesAndRenew', 'Message stats', this.receivedDataStats);
517
596
  }, this.timerIntervalInSec * 1000);
518
597
  }
519
- addTerminateToAction(telemetryAction) {
520
- const unsubscribeOperation = UnsubscribeOperation.create({
521
- options: [
522
- {
523
- content: {
524
- receivergroupUnsubscribeOption: {
525
- terminate: true,
526
- },
527
- oneofKind: 'receivergroupUnsubscribeOption',
528
- },
529
- },
530
- ],
531
- });
532
- telemetryAction.content = {
533
- oneofKind: 'unsubscribeOperation',
534
- unsubscribeOperation,
535
- };
536
- }
537
598
  renewReceiver() {
538
599
  try {
539
600
  // Remove the received call anyway.
@@ -35,12 +35,20 @@ export interface RobotStatusOptions {
35
35
  * rather than deriving "is the robot online" themselves.
36
36
  */
37
37
  export declare class RobotStatusService extends BaseServiceAbstract implements IBaseService {
38
+ private platformTime;
38
39
  constructor(config: IRocosSDKConfig);
39
40
  getStatus(): boolean;
40
41
  /** Health + readiness as reported by the robot (new topic, legacy heartbeat fallback). */
41
42
  getReportedStatusChanges(projectId: string, callsign: string): Observable<ReportedRobotStatus>;
42
43
  /** Per-contributor breakdown behind the reported health and readiness, with the reason for each. */
43
44
  getStatusContributorsChanges(projectId: string, callsign: string): Observable<RobotStatusContributors>;
45
+ /**
46
+ * Telemetry latency in milliseconds — platform time minus when the agent created each liveness
47
+ * message (`robot/status`, or the legacy heartbeat). Emits once per message, and nothing while
48
+ * none arrive: pair it with the `telemetry-liveness` connectivity service to tell a stale value
49
+ * from a live one.
50
+ */
51
+ getTelemetryLatencyChanges(projectId: string, callsign: string): Observable<number>;
44
52
  /** Per-service connectivity plus the aggregate verdict, polled. */
45
53
  getConnectivityChanges(projectId: string, callsign: string, opts?: RobotStatusOptions): Observable<RobotConnectivityStatus>;
46
54
  /** One-shot connectivity snapshot: resolves once every expected service is known, or after a timeout. */
@@ -1,8 +1,9 @@
1
1
  import { getConnectivityChanges } from './robot-status/connectivity';
2
2
  import { RobotHealth, RobotReadiness, RocosError, ServiceConnection, errorCodes, } from '../models';
3
3
  import { combineLatest, distinctUntilChanged, first, firstValueFrom, map, of, shareReplay, startWith, take, tap, timeout, } from 'rxjs';
4
- import { getReportedStatusChanges, getStatusContributorsChanges, getTelemetryLiveness, } from './robot-status/reportedStatus';
4
+ import { getReportedStatusChanges, getStatusContributorsChanges, getTelemetryLatencyChanges, getTelemetryLiveness, } from './robot-status/reportedStatus';
5
5
  import { BaseServiceAbstract } from './BaseServiceAbstract';
6
+ import { PlatFormTimeService } from './PlatformTimeService';
6
7
  import { RocosLogger } from '../logger/RocosLogger';
7
8
  import { RocosStore } from '../store/RocosStore';
8
9
  import { getRobotStatusColour } from '../helpers/getRobotStatusColour';
@@ -31,6 +32,7 @@ export class RobotStatusService extends BaseServiceAbstract {
31
32
  constructor(config) {
32
33
  super(config);
33
34
  this.logger = RocosLogger.getInstance(`RobotStatusService(${this.config.url})`);
35
+ this.platformTime = PlatFormTimeService.getInstance(RocosStore.getSDKInstance(this.config).getTimeSyncerService());
34
36
  }
35
37
  getStatus() {
36
38
  return true;
@@ -43,6 +45,15 @@ export class RobotStatusService extends BaseServiceAbstract {
43
45
  getStatusContributorsChanges(projectId, callsign) {
44
46
  return getStatusContributorsChanges(this.telemetryService, projectId, callsign);
45
47
  }
48
+ /**
49
+ * Telemetry latency in milliseconds — platform time minus when the agent created each liveness
50
+ * message (`robot/status`, or the legacy heartbeat). Emits once per message, and nothing while
51
+ * none arrive: pair it with the `telemetry-liveness` connectivity service to tell a stale value
52
+ * from a live one.
53
+ */
54
+ getTelemetryLatencyChanges(projectId, callsign) {
55
+ return getTelemetryLatencyChanges(this.telemetryService, projectId, callsign, () => this.platformTime.platformTime);
56
+ }
46
57
  /** Per-service connectivity plus the aggregate verdict, polled. */
47
58
  getConnectivityChanges(projectId, callsign, opts) {
48
59
  return getConnectivityChanges(this.connectivityDeps(projectId, callsign, opts), projectId, callsign, opts?.expectedServices, opts?.connectivityPollMs);
@@ -41,6 +41,18 @@ export declare const getReportedStatusChanges: (telemetry: TelemetryService, pro
41
41
  * error falls back to an empty breakdown rather than terminating the stream.
42
42
  */
43
43
  export declare const getStatusContributorsChanges: (telemetry: TelemetryService, projectId: string, callsign: string) => Observable<RobotStatusContributors>;
44
+ /**
45
+ * Emits the robot's telemetry latency in milliseconds, once per liveness message (from either the
46
+ * new `robot/status` topic or the legacy heartbeat — the same messages {@link getTelemetryLiveness}
47
+ * watches): `now()` minus the time the agent created the message.
48
+ *
49
+ * `now` should return platform time, so the measurement isn't skewed by the client's clock. Any
50
+ * remaining offset between the agent's clock and platform time feeds straight through, so a value
51
+ * can be slightly negative. Nothing is emitted while no messages arrive; pair this with
52
+ * {@link getTelemetryLiveness} to tell a stale value from a live one. A telemetry error completes
53
+ * the stream rather than erroring it.
54
+ */
55
+ export declare const getTelemetryLatencyChanges: (telemetry: TelemetryService, projectId: string, callsign: string, now: () => number) => Observable<number>;
44
56
  /**
45
57
  * Emits the `telemetry-liveness` connectivity signal: whether a heartbeat (from
46
58
  * either the new `robot/status` topic or the legacy heartbeat) has been received
@@ -1,4 +1,4 @@
1
- import { catchError, combineLatest, distinctUntilChanged, filter, interval, map, merge, of, scan, startWith, } from 'rxjs';
1
+ import { EMPTY, catchError, combineLatest, distinctUntilChanged, filter, interval, map, merge, of, scan, startWith, } from 'rxjs';
2
2
  import { RobotHealth, RobotReadiness, ServiceConnection, } from '../../models';
3
3
  /** The new agent topic carrying health + readiness (replaces the heartbeat). */
4
4
  export const ROBOT_STATUS_SOURCE = '/diagnostics/robot/status';
@@ -112,6 +112,22 @@ export const getStatusContributorsChanges = (telemetry, projectId, callsign) =>
112
112
  };
113
113
  }), startWith(EMPTY_CONTRIBUTORS), distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)), catchError(() => of(EMPTY_CONTRIBUTORS)));
114
114
  };
115
+ /**
116
+ * Emits the robot's telemetry latency in milliseconds, once per liveness message (from either the
117
+ * new `robot/status` topic or the legacy heartbeat — the same messages {@link getTelemetryLiveness}
118
+ * watches): `now()` minus the time the agent created the message.
119
+ *
120
+ * `now` should return platform time, so the measurement isn't skewed by the client's clock. Any
121
+ * remaining offset between the agent's clock and platform time feeds straight through, so a value
122
+ * can be slightly negative. Nothing is emitted while no messages arrive; pair this with
123
+ * {@link getTelemetryLiveness} to tell a stale value from a live one. A telemetry error completes
124
+ * the stream rather than erroring it.
125
+ */
126
+ export const getTelemetryLatencyChanges = (telemetry, projectId, callsign, now) => {
127
+ return telemetry
128
+ .subscribe({ projectId, callsigns: [callsign], sources: [ROBOT_STATUS_SOURCE, LEGACY_HEARTBEAT_SOURCE] })
129
+ .pipe(map((message) => now() - message.createdAt.getTime()), catchError(() => EMPTY));
130
+ };
115
131
  /**
116
132
  * Emits the `telemetry-liveness` connectivity signal: whether a heartbeat (from
117
133
  * either the new `robot/status` topic or the legacy heartbeat) has been received
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dronedeploy/rocos-js-sdk",
3
- "version": "4.4.15",
3
+ "version": "4.5.0",
4
4
  "description": "Javascript SDK for rocos",
5
5
  "main": "cjs/index.js",
6
6
  "module": "esm/index.js",