@dronedeploy/rocos-js-sdk 4.5.1 → 4.5.2

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.
@@ -1,6 +1,6 @@
1
+ import { ReportedRobotStatus } from './robot-status/reportedStatus';
1
2
  import { IBaseService, IRocosSDKConfig, RobotConnectivityStatus, RobotStatus, RobotStatusContributors, RocosError, ServiceConnection } from '../models';
2
3
  import { Observable } from 'rxjs';
3
- import { ReportedRobotStatus } from './robot-status/reportedStatus';
4
4
  import { BaseServiceAbstract } from './BaseServiceAbstract';
5
5
  /** Per-call tuning for the robot status observables. */
6
6
  export interface RobotStatusOptions {
@@ -49,7 +49,11 @@ export declare class RobotStatusService extends BaseServiceAbstract implements I
49
49
  * from a live one.
50
50
  */
51
51
  getTelemetryLatencyChanges(projectId: string, callsign: string): Observable<number>;
52
- /** Per-service connectivity plus the aggregate verdict, polled. */
52
+ /**
53
+ * Per-service connectivity plus the aggregate verdict, for `opts.expectedServices` plus any
54
+ * `opts.extraServices` (folded in on equal footing). HTTP services are read from their project's
55
+ * shared bulk poll; an unrecognised service id resolves to `UNKNOWN`.
56
+ */
53
57
  getConnectivityChanges(projectId: string, callsign: string, opts?: RobotStatusOptions): Observable<RobotConnectivityStatus>;
54
58
  /** One-shot connectivity snapshot: resolves once every expected service is known, or after a timeout. */
55
59
  getConnectivity(projectId: string, callsign: string, opts?: RobotStatusOptions): Promise<RobotConnectivityStatus>;
@@ -60,5 +64,20 @@ export declare class RobotStatusService extends BaseServiceAbstract implements I
60
64
  getRobotStatusChanges(projectId: string, callsign: string, opts?: RobotStatusOptions): Observable<RobotStatus>;
61
65
  protected getError(e: Error): RocosError;
62
66
  private get telemetryService();
63
- private connectivityDeps;
67
+ /**
68
+ * Shared streams are keyed by this, so equivalent SDK configurations (which `RocosStore` already
69
+ * treats as one SDK) share them, and different ones never do.
70
+ */
71
+ private get configKey();
72
+ /** Telemetry with one pooled subscription per robot and topic, however many status streams use it. */
73
+ private get sharedTelemetry();
74
+ private getTelemetryLiveness;
75
+ /** One service's connection for a callsign. Built-in services win over an injected one of the same id. */
76
+ private getServiceConnection;
77
+ /**
78
+ * A service's bulk (per-project) `connections` endpoint, polled every `pollMs`. One poll per project,
79
+ * service and interval is shared by every callsign and subscriber. A failed poll emits `undefined`
80
+ * rather than erroring, so one bad poll doesn't end the stream.
81
+ */
82
+ private getProjectConnections;
64
83
  }
@@ -2,14 +2,16 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RobotStatusService = void 0;
4
4
  const connectivity_1 = require("./robot-status/connectivity");
5
+ const reportedStatus_1 = require("./robot-status/reportedStatus");
5
6
  const models_1 = require("../models");
6
7
  const rxjs_1 = require("rxjs");
7
- const reportedStatus_1 = require("./robot-status/reportedStatus");
8
8
  const BaseServiceAbstract_1 = require("./BaseServiceAbstract");
9
9
  const PlatformTimeService_1 = require("./PlatformTimeService");
10
10
  const RocosLogger_1 = require("../logger/RocosLogger");
11
11
  const RocosStore_1 = require("../store/RocosStore");
12
12
  const getRobotStatusColour_1 = require("../helpers/getRobotStatusColour");
13
+ const getUniqueConfigKey_1 = require("../helpers/getUniqueConfigKey");
14
+ const sharedStreams_1 = require("./robot-status/sharedStreams");
13
15
  /** Upper bound on how long the one-shot {@link RobotStatusService.getConnectivity} waits to settle. */
14
16
  const ONE_SHOT_TIMEOUT_MS = 10000;
15
17
  const isKnown = (status) => {
@@ -42,11 +44,11 @@ class RobotStatusService extends BaseServiceAbstract_1.BaseServiceAbstract {
42
44
  }
43
45
  /** Health + readiness as reported by the robot (new topic, legacy heartbeat fallback). */
44
46
  getReportedStatusChanges(projectId, callsign) {
45
- return (0, reportedStatus_1.getReportedStatusChanges)(this.telemetryService, projectId, callsign);
47
+ return sharedStreams_1.sharedStreamPool.get(['reported-status', this.configKey, projectId, callsign], () => (0, reportedStatus_1.getReportedStatusChanges)(this.sharedTelemetry, projectId, callsign), { replay: true });
46
48
  }
47
49
  /** Per-contributor breakdown behind the reported health and readiness, with the reason for each. */
48
50
  getStatusContributorsChanges(projectId, callsign) {
49
- return (0, reportedStatus_1.getStatusContributorsChanges)(this.telemetryService, projectId, callsign);
51
+ return sharedStreams_1.sharedStreamPool.get(['status-contributors', this.configKey, projectId, callsign], () => (0, reportedStatus_1.getStatusContributorsChanges)(this.sharedTelemetry, projectId, callsign), { replay: true });
50
52
  }
51
53
  /**
52
54
  * Telemetry latency in milliseconds — platform time minus when the agent created each liveness
@@ -55,11 +57,34 @@ class RobotStatusService extends BaseServiceAbstract_1.BaseServiceAbstract {
55
57
  * from a live one.
56
58
  */
57
59
  getTelemetryLatencyChanges(projectId, callsign) {
58
- return (0, reportedStatus_1.getTelemetryLatencyChanges)(this.telemetryService, projectId, callsign, () => this.platformTime.platformTime);
60
+ return (0, reportedStatus_1.getTelemetryLatencyChanges)(this.sharedTelemetry, projectId, callsign, () => this.platformTime.platformTime);
59
61
  }
60
- /** Per-service connectivity plus the aggregate verdict, polled. */
62
+ /**
63
+ * Per-service connectivity plus the aggregate verdict, for `opts.expectedServices` plus any
64
+ * `opts.extraServices` (folded in on equal footing). HTTP services are read from their project's
65
+ * shared bulk poll; an unrecognised service id resolves to `UNKNOWN`.
66
+ */
61
67
  getConnectivityChanges(projectId, callsign, opts) {
62
- return (0, connectivity_1.getConnectivityChanges)(this.connectivityDeps(projectId, callsign, opts), projectId, callsign, opts?.expectedServices, opts?.connectivityPollMs);
68
+ const expectedServices = opts?.expectedServices ?? connectivity_1.DEFAULT_EXPECTED_SERVICES;
69
+ const extraServices = opts?.extraServices ?? {};
70
+ const serviceIds = [
71
+ ...expectedServices,
72
+ ...Object.keys(extraServices).filter((id) => !expectedServices.includes(id)),
73
+ ];
74
+ // combineLatest([]) completes without emitting; emit an explicit empty/offline status instead.
75
+ if (serviceIds.length === 0) {
76
+ return (0, rxjs_1.of)({ overall: models_1.RobotConnectivity.OFFLINE, services: {} });
77
+ }
78
+ const pollMs = (0, connectivity_1.clampPollInterval)(opts?.connectivityPollMs ?? connectivity_1.DEFAULT_CONNECTIVITY_POLL_MS);
79
+ const perService = serviceIds.map((serviceId) => {
80
+ return this.getServiceConnection(projectId, callsign, serviceId, pollMs, opts).pipe((0, rxjs_1.startWith)(models_1.ServiceConnection.UNKNOWN), (0, rxjs_1.map)((connection) => ({ serviceId, connection })));
81
+ });
82
+ return (0, rxjs_1.combineLatest)(perService).pipe((0, rxjs_1.map)((entries) => {
83
+ const services = {};
84
+ for (const { serviceId, connection } of entries)
85
+ services[serviceId] = connection;
86
+ return { overall: (0, connectivity_1.aggregateConnectivity)(services), services };
87
+ }), (0, rxjs_1.distinctUntilChanged)(connectivity_1.connectivityEquals));
63
88
  }
64
89
  /** One-shot connectivity snapshot: resolves once every expected service is known, or after a timeout. */
65
90
  getConnectivity(projectId, callsign, opts) {
@@ -95,16 +120,57 @@ class RobotStatusService extends BaseServiceAbstract_1.BaseServiceAbstract {
95
120
  get telemetryService() {
96
121
  return RocosStore_1.RocosStore.getSDKInstance(this.config).getTelemetryService();
97
122
  }
98
- connectivityDeps(projectId, callsign, opts) {
123
+ /**
124
+ * Shared streams are keyed by this, so equivalent SDK configurations (which `RocosStore` already
125
+ * treats as one SDK) share them, and different ones never do.
126
+ */
127
+ get configKey() {
128
+ return (0, getUniqueConfigKey_1.getUniqueConfigKey)(this.config);
129
+ }
130
+ /** Telemetry with one pooled subscription per robot and topic, however many status streams use it. */
131
+ get sharedTelemetry() {
99
132
  return {
100
- httpGet: (url) => {
101
- return this.callGet(url, `Failed to get connection status for ${callsign} in project ${projectId}.`);
133
+ subscribe: (params) => {
134
+ return sharedStreams_1.sharedStreamPool.get(['telemetry', this.configKey, params.projectId, params.callsigns, params.sources], () => this.telemetryService.subscribe(params),
135
+ // Raw messages are events: replaying one to a late subscriber would read as a fresh message.
136
+ { replay: false });
102
137
  },
103
- baseUrl: this.config.url,
104
- insecure: this.config.insecure,
105
- telemetryLiveness$: (0, reportedStatus_1.getTelemetryLiveness)(this.telemetryService, projectId, callsign, opts?.heartbeatTimeoutMs),
106
- extraServices: opts?.extraServices,
107
138
  };
108
139
  }
140
+ getTelemetryLiveness(projectId, callsign, heartbeatTimeoutMs = reportedStatus_1.DEFAULT_HEARTBEAT_TIMEOUT_MS) {
141
+ // Key on the resolved timeout, so omitting it shares a stream with passing the default explicitly.
142
+ return sharedStreams_1.sharedStreamPool.get(['telemetry-liveness', this.configKey, projectId, callsign, heartbeatTimeoutMs], () => (0, reportedStatus_1.getTelemetryLiveness)(this.sharedTelemetry, projectId, callsign, heartbeatTimeoutMs), { replay: true });
143
+ }
144
+ /** One service's connection for a callsign. Built-in services win over an injected one of the same id. */
145
+ getServiceConnection(projectId, callsign, serviceId, pollMs, opts) {
146
+ if (serviceId === connectivity_1.TELEMETRY_LIVENESS_SERVICE) {
147
+ return this.getTelemetryLiveness(projectId, callsign, opts?.heartbeatTimeoutMs);
148
+ }
149
+ if (Object.prototype.hasOwnProperty.call(connectivity_1.CONNECTION_SERVICE_PREFIXES, serviceId)) {
150
+ return this.getProjectConnections(projectId, serviceId, pollMs).pipe((0, rxjs_1.map)((poll) => (0, connectivity_1.getCallsignConnection)(poll, callsign)), (0, rxjs_1.distinctUntilChanged)());
151
+ }
152
+ const extraServices = opts?.extraServices;
153
+ if (extraServices && Object.prototype.hasOwnProperty.call(extraServices, serviceId)) {
154
+ // Contain an injected observable's errors as UNKNOWN, mirroring the built-in sources, so a
155
+ // faulty caller signal can't error out combineLatest and tear down the whole aggregate.
156
+ return extraServices[serviceId].pipe((0, rxjs_1.catchError)(() => (0, rxjs_1.of)(models_1.ServiceConnection.UNKNOWN)));
157
+ }
158
+ return (0, rxjs_1.of)(models_1.ServiceConnection.UNKNOWN);
159
+ }
160
+ /**
161
+ * A service's bulk (per-project) `connections` endpoint, polled every `pollMs`. One poll per project,
162
+ * service and interval is shared by every callsign and subscriber. A failed poll emits `undefined`
163
+ * rather than erroring, so one bad poll doesn't end the stream.
164
+ */
165
+ getProjectConnections(projectId, serviceId, pollMs) {
166
+ const url = (0, connectivity_1.buildConnectionsUrl)(serviceId, this.config.url, projectId, undefined, this.config.insecure);
167
+ return sharedStreams_1.sharedStreamPool.get(['connections', this.configKey, url, pollMs], () => {
168
+ return (0, rxjs_1.timer)(0, pollMs).pipe((0, rxjs_1.switchMap)(() => {
169
+ return (0, rxjs_1.from)(this.callGet(url, `Failed to get connection statuses for project ${projectId}.`)).pipe(
170
+ // Go encodes an empty map as null: a successful poll in which nobody is connected.
171
+ (0, rxjs_1.map)((connections) => connections ?? {}), (0, rxjs_1.catchError)(() => (0, rxjs_1.of)(undefined)));
172
+ }));
173
+ }, { replay: true });
174
+ }
109
175
  }
110
176
  exports.RobotStatusService = RobotStatusService;
@@ -1,5 +1,4 @@
1
1
  import { IConnectedCallsign, RobotConnectivity, RobotConnectivityStatus, ServiceConnection } from '../../models';
2
- import { Observable } from 'rxjs';
3
2
  /**
4
3
  * Service id → public path prefix, for services that expose the standard
5
4
  * `connections` endpoint. New services adopting the convention are added here.
@@ -9,12 +8,13 @@ import { Observable } from 'rxjs';
9
8
  export declare const CONNECTION_SERVICE_PREFIXES: Record<string, string>;
10
9
  /**
11
10
  * The telemetry-liveness signal is derived from heartbeat freshness rather than
12
- * an HTTP endpoint, so it is handled specially (its observable is supplied by
13
- * the caller). See `getTelemetryLiveness`.
11
+ * an HTTP endpoint, so it is handled specially. See `getTelemetryLiveness`.
14
12
  */
15
13
  export declare const TELEMETRY_LIVENESS_SERVICE = "telemetry-liveness";
16
14
  /** The services evaluated by default. */
17
15
  export declare const DEFAULT_EXPECTED_SERVICES: string[];
16
+ /** How often the bulk `connections` endpoints are polled by default (ms). */
17
+ export declare const DEFAULT_CONNECTIVITY_POLL_MS = 5000;
18
18
  /**
19
19
  * Floor for the connections-endpoint poll interval. Guards against a caller
20
20
  * passing `0` (or any tiny value), which would otherwise poll the API on every
@@ -23,8 +23,16 @@ export declare const DEFAULT_EXPECTED_SERVICES: string[];
23
23
  export declare const MIN_CONNECTIVITY_POLL_MS = 250;
24
24
  /** Clamps a requested poll interval up to {@link MIN_CONNECTIVITY_POLL_MS}. */
25
25
  export declare const clampPollInterval: (pollMs: number) => number;
26
- /** Authenticated GET used to poll a service's `connections` endpoint. */
27
- export type ConnectionsHttpGet = (url: string) => Promise<IConnectedCallsign>;
26
+ /**
27
+ * A bulk `connections` endpoint response: callsign → connection. A callsign that isn't listed is not
28
+ * connected (Teletubby lists only connected callsigns).
29
+ */
30
+ export type ProjectConnections = Record<string, IConnectedCallsign>;
31
+ /**
32
+ * One poll of a bulk `connections` endpoint: the project's connections, or `undefined` when the poll
33
+ * failed — distinct from a successful but empty response, in which every callsign is disconnected.
34
+ */
35
+ export type ProjectConnectionsPoll = ProjectConnections | undefined;
28
36
  /**
29
37
  * Builds the `connections` endpoint URL for a service — per-callsign when a
30
38
  * callsign is given, otherwise the bulk per-project variant.
@@ -50,29 +58,10 @@ export declare const mapConnectionStatus: (connection?: IConnectedCallsign | nul
50
58
  */
51
59
  export declare const aggregateConnectivity: (services: Record<string, ServiceConnection>) => RobotConnectivity;
52
60
  /**
53
- * Polls a single service's `connections` endpoint on an interval, emitting its
54
- * {@link ServiceConnection} (change-only). A failed/timed-out poll yields
55
- * `UNKNOWN` (held transitional) rather than `DISCONNECTED`, to avoid a spurious
56
- * degraded flash on a transient error.
57
- *
58
- * `pollMs` is floored at {@link MIN_CONNECTIVITY_POLL_MS} so the endpoint can't
59
- * be polled unreasonably fast.
60
- */
61
- export declare const getServiceConnectionChanges: (httpGet: ConnectionsHttpGet, url: string, pollMs?: number) => Observable<ServiceConnection>;
62
- export interface ConnectivityDeps {
63
- httpGet: ConnectionsHttpGet;
64
- baseUrl: string;
65
- insecure?: boolean;
66
- /** The telemetry-liveness signal (from `getTelemetryLiveness`), folded in as one service. */
67
- telemetryLiveness$: Observable<ServiceConnection>;
68
- /** Caller-injected connectivity signals, keyed by service id, folded in on equal footing. */
69
- extraServices?: Record<string, Observable<ServiceConnection>>;
70
- }
71
- /**
72
- * Emits the robot's {@link RobotConnectivityStatus} — the per-service breakdown
73
- * plus the aggregate verdict — for the configured `expectedServices`, plus any
74
- * caller-injected `extraServices` (folded in on equal footing). HTTP services
75
- * are polled; `telemetry-liveness` and injected services use their supplied
76
- * observable; any unrecognised service id resolves to `UNKNOWN`.
61
+ * One callsign's {@link ServiceConnection} from a bulk poll. A failed poll is `UNKNOWN` (held
62
+ * transitional) rather than `DISCONNECTED`, to avoid a spurious degraded flash on a transient error;
63
+ * a callsign missing from a successful poll is `DISCONNECTED`.
77
64
  */
78
- export declare const getConnectivityChanges: (deps: ConnectivityDeps, projectId: string, callsign: string, expectedServices?: string[], pollMs?: number) => Observable<RobotConnectivityStatus>;
65
+ export declare const getCallsignConnection: (poll: ProjectConnectionsPoll, callsign: string) => ServiceConnection;
66
+ /** Whether two connectivity statuses carry the same verdict and per-service breakdown. */
67
+ export declare const connectivityEquals: (a: RobotConnectivityStatus, b: RobotConnectivityStatus) => boolean;
@@ -1,9 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getConnectivityChanges = exports.getServiceConnectionChanges = exports.aggregateConnectivity = exports.mapConnectionStatus = exports.buildConnectionsUrl = exports.clampPollInterval = exports.MIN_CONNECTIVITY_POLL_MS = exports.DEFAULT_EXPECTED_SERVICES = exports.TELEMETRY_LIVENESS_SERVICE = exports.CONNECTION_SERVICE_PREFIXES = void 0;
3
+ exports.connectivityEquals = exports.getCallsignConnection = exports.aggregateConnectivity = exports.mapConnectionStatus = exports.buildConnectionsUrl = exports.clampPollInterval = exports.MIN_CONNECTIVITY_POLL_MS = exports.DEFAULT_CONNECTIVITY_POLL_MS = exports.DEFAULT_EXPECTED_SERVICES = exports.TELEMETRY_LIVENESS_SERVICE = exports.CONNECTION_SERVICE_PREFIXES = void 0;
4
4
  const api_1 = require("../../constants/api");
5
5
  const models_1 = require("../../models");
6
- const rxjs_1 = require("rxjs");
7
6
  const formatServiceUrl_1 = require("../../helpers/formatServiceUrl");
8
7
  /**
9
8
  * Service id → public path prefix, for services that expose the standard
@@ -18,8 +17,7 @@ exports.CONNECTION_SERVICE_PREFIXES = {
18
17
  };
19
18
  /**
20
19
  * The telemetry-liveness signal is derived from heartbeat freshness rather than
21
- * an HTTP endpoint, so it is handled specially (its observable is supplied by
22
- * the caller). See `getTelemetryLiveness`.
20
+ * an HTTP endpoint, so it is handled specially. See `getTelemetryLiveness`.
23
21
  */
24
22
  exports.TELEMETRY_LIVENESS_SERVICE = 'telemetry-liveness';
25
23
  /** The services evaluated by default. */
@@ -29,7 +27,8 @@ exports.DEFAULT_EXPECTED_SERVICES = [
29
27
  'robot-services',
30
28
  'robot-telemetry',
31
29
  ];
32
- const DEFAULT_CONNECTIVITY_POLL_MS = 5000;
30
+ /** How often the bulk `connections` endpoints are polled by default (ms). */
31
+ exports.DEFAULT_CONNECTIVITY_POLL_MS = 5000;
33
32
  /**
34
33
  * Floor for the connections-endpoint poll interval. Guards against a caller
35
34
  * passing `0` (or any tiny value), which would otherwise poll the API on every
@@ -90,20 +89,19 @@ const aggregateConnectivity = (services) => {
90
89
  };
91
90
  exports.aggregateConnectivity = aggregateConnectivity;
92
91
  /**
93
- * Polls a single service's `connections` endpoint on an interval, emitting its
94
- * {@link ServiceConnection} (change-only). A failed/timed-out poll yields
95
- * `UNKNOWN` (held transitional) rather than `DISCONNECTED`, to avoid a spurious
96
- * degraded flash on a transient error.
97
- *
98
- * `pollMs` is floored at {@link MIN_CONNECTIVITY_POLL_MS} so the endpoint can't
99
- * be polled unreasonably fast.
92
+ * One callsign's {@link ServiceConnection} from a bulk poll. A failed poll is `UNKNOWN` (held
93
+ * transitional) rather than `DISCONNECTED`, to avoid a spurious degraded flash on a transient error;
94
+ * a callsign missing from a successful poll is `DISCONNECTED`.
100
95
  */
101
- const getServiceConnectionChanges = (httpGet, url, pollMs = DEFAULT_CONNECTIVITY_POLL_MS) => {
102
- return (0, rxjs_1.timer)(0, (0, exports.clampPollInterval)(pollMs)).pipe((0, rxjs_1.switchMap)(() => {
103
- return (0, rxjs_1.from)(httpGet(url)).pipe((0, rxjs_1.map)(exports.mapConnectionStatus), (0, rxjs_1.catchError)(() => (0, rxjs_1.of)(models_1.ServiceConnection.UNKNOWN)));
104
- }), (0, rxjs_1.startWith)(models_1.ServiceConnection.UNKNOWN), (0, rxjs_1.distinctUntilChanged)());
96
+ const getCallsignConnection = (poll, callsign) => {
97
+ if (poll === undefined)
98
+ return models_1.ServiceConnection.UNKNOWN;
99
+ if (!Object.prototype.hasOwnProperty.call(poll, callsign))
100
+ return models_1.ServiceConnection.DISCONNECTED;
101
+ return (0, exports.mapConnectionStatus)(poll[callsign]);
105
102
  };
106
- exports.getServiceConnectionChanges = getServiceConnectionChanges;
103
+ exports.getCallsignConnection = getCallsignConnection;
104
+ /** Whether two connectivity statuses carry the same verdict and per-service breakdown. */
107
105
  const connectivityEquals = (a, b) => {
108
106
  if (a.overall !== b.overall)
109
107
  return false;
@@ -112,44 +110,4 @@ const connectivityEquals = (a, b) => {
112
110
  return false;
113
111
  return keys.every((key) => a.services[key] === b.services[key]);
114
112
  };
115
- /**
116
- * Emits the robot's {@link RobotConnectivityStatus} — the per-service breakdown
117
- * plus the aggregate verdict — for the configured `expectedServices`, plus any
118
- * caller-injected `extraServices` (folded in on equal footing). HTTP services
119
- * are polled; `telemetry-liveness` and injected services use their supplied
120
- * observable; any unrecognised service id resolves to `UNKNOWN`.
121
- */
122
- const getConnectivityChanges = (deps, projectId, callsign, expectedServices = exports.DEFAULT_EXPECTED_SERVICES, pollMs = DEFAULT_CONNECTIVITY_POLL_MS) => {
123
- const extraServices = deps.extraServices ?? {};
124
- const serviceIds = [...expectedServices, ...Object.keys(extraServices).filter((id) => !expectedServices.includes(id))];
125
- // combineLatest([]) completes without emitting; emit an explicit empty/offline status instead.
126
- if (serviceIds.length === 0) {
127
- return (0, rxjs_1.of)({ overall: models_1.RobotConnectivity.OFFLINE, services: {} });
128
- }
129
- const perService = serviceIds.map((serviceId) => {
130
- let source$;
131
- if (serviceId === exports.TELEMETRY_LIVENESS_SERVICE) {
132
- source$ = deps.telemetryLiveness$;
133
- }
134
- else if (Object.prototype.hasOwnProperty.call(exports.CONNECTION_SERVICE_PREFIXES, serviceId)) {
135
- const url = (0, exports.buildConnectionsUrl)(serviceId, deps.baseUrl, projectId, callsign, deps.insecure);
136
- source$ = (0, exports.getServiceConnectionChanges)(deps.httpGet, url, pollMs);
137
- }
138
- else if (Object.prototype.hasOwnProperty.call(extraServices, serviceId)) {
139
- // Contain an injected observable's errors as UNKNOWN, mirroring the built-in sources, so a
140
- // faulty caller signal can't error out combineLatest and tear down the whole aggregate.
141
- source$ = extraServices[serviceId].pipe((0, rxjs_1.catchError)(() => (0, rxjs_1.of)(models_1.ServiceConnection.UNKNOWN)));
142
- }
143
- else {
144
- source$ = (0, rxjs_1.of)(models_1.ServiceConnection.UNKNOWN);
145
- }
146
- return source$.pipe((0, rxjs_1.startWith)(models_1.ServiceConnection.UNKNOWN), (0, rxjs_1.map)((connection) => ({ serviceId, connection })));
147
- });
148
- return (0, rxjs_1.combineLatest)(perService).pipe((0, rxjs_1.map)((entries) => {
149
- const services = {};
150
- for (const { serviceId, connection } of entries)
151
- services[serviceId] = connection;
152
- return { overall: (0, exports.aggregateConnectivity)(services), services };
153
- }), (0, rxjs_1.distinctUntilChanged)(connectivityEquals));
154
- };
155
- exports.getConnectivityChanges = getConnectivityChanges;
113
+ exports.connectivityEquals = connectivityEquals;
@@ -7,6 +7,13 @@ export declare const ROBOT_STATUS_SOURCE = "/diagnostics/robot/status";
7
7
  export declare const LEGACY_HEARTBEAT_SOURCE = "/rocos/agent/telemetry/heartbeat";
8
8
  /** The per-contributor breakdown behind the reported status (health + readiness). */
9
9
  export declare const ROBOT_STATUS_CONTRIBUTORS_SOURCE = "/diagnostics/robot/status/contributors";
10
+ /** How long without a liveness message before `telemetry-liveness` reports `DISCONNECTED` (ms). */
11
+ export declare const DEFAULT_HEARTBEAT_TIMEOUT_MS = 5000;
12
+ /**
13
+ * The telemetry these streams subscribe through. `RobotStatusService` passes a pooled implementation,
14
+ * so every status stream for a robot shares one subscription per topic.
15
+ */
16
+ export type StatusTelemetry = Pick<TelemetryService, 'subscribe'>;
10
17
  export interface ReportedRobotStatus {
11
18
  health: RobotHealth;
12
19
  readiness: RobotReadiness;
@@ -29,7 +36,7 @@ export declare const parseRobotReadiness: (value: unknown) => RobotReadiness;
29
36
  * preserves today's "online ⇒ green" behaviour for agents not yet emitting the
30
37
  * new topic.
31
38
  */
32
- export declare const getReportedStatusChanges: (telemetry: TelemetryService, projectId: string, callsign: string) => Observable<ReportedRobotStatus>;
39
+ export declare const getReportedStatusChanges: (telemetry: StatusTelemetry, projectId: string, callsign: string) => Observable<ReportedRobotStatus>;
33
40
  /**
34
41
  * Emits the per-contributor breakdown behind the robot's reported health and
35
42
  * readiness, from the agent's `robot/status/contributors` topic. Each
@@ -40,7 +47,7 @@ export declare const getReportedStatusChanges: (telemetry: TelemetryService, pro
40
47
  * emit immediately, and — like {@link getReportedStatusChanges} — a telemetry
41
48
  * error falls back to an empty breakdown rather than terminating the stream.
42
49
  */
43
- export declare const getStatusContributorsChanges: (telemetry: TelemetryService, projectId: string, callsign: string) => Observable<RobotStatusContributors>;
50
+ export declare const getStatusContributorsChanges: (telemetry: StatusTelemetry, projectId: string, callsign: string) => Observable<RobotStatusContributors>;
44
51
  /**
45
52
  * Emits the robot's telemetry latency in milliseconds, once per liveness message (from either the
46
53
  * new `robot/status` topic or the legacy heartbeat — the same messages {@link getTelemetryLiveness}
@@ -52,7 +59,7 @@ export declare const getStatusContributorsChanges: (telemetry: TelemetryService,
52
59
  * {@link getTelemetryLiveness} to tell a stale value from a live one. A telemetry error completes
53
60
  * the stream rather than erroring it.
54
61
  */
55
- export declare const getTelemetryLatencyChanges: (telemetry: TelemetryService, projectId: string, callsign: string, now: () => number) => Observable<number>;
62
+ export declare const getTelemetryLatencyChanges: (telemetry: StatusTelemetry, projectId: string, callsign: string, now: () => number) => Observable<number>;
56
63
  /**
57
64
  * Emits the `telemetry-liveness` connectivity signal: whether a heartbeat (from
58
65
  * either the new `robot/status` topic or the legacy heartbeat) has been received
@@ -60,4 +67,4 @@ export declare const getTelemetryLatencyChanges: (telemetry: TelemetryService, p
60
67
  * but spans both topics and maps onto {@link ServiceConnection} so it can be
61
68
  * folded into connectivity aggregation as just another service entry.
62
69
  */
63
- export declare const getTelemetryLiveness: (telemetry: TelemetryService, projectId: string, callsign: string, heartbeatTimeoutMs?: number, intervalMs?: number) => Observable<ServiceConnection>;
70
+ export declare const getTelemetryLiveness: (telemetry: StatusTelemetry, projectId: string, callsign: string, heartbeatTimeoutMs?: number, intervalMs?: number) => Observable<ServiceConnection>;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
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;
3
+ exports.getTelemetryLiveness = exports.getTelemetryLatencyChanges = exports.getStatusContributorsChanges = exports.getReportedStatusChanges = exports.parseRobotReadiness = exports.parseRobotHealth = exports.DEFAULT_HEARTBEAT_TIMEOUT_MS = 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). */
@@ -9,8 +9,17 @@ exports.ROBOT_STATUS_SOURCE = '/diagnostics/robot/status';
9
9
  exports.LEGACY_HEARTBEAT_SOURCE = '/rocos/agent/telemetry/heartbeat';
10
10
  /** The per-contributor breakdown behind the reported status (health + readiness). */
11
11
  exports.ROBOT_STATUS_CONTRIBUTORS_SOURCE = `${exports.ROBOT_STATUS_SOURCE}/contributors`;
12
- const DEFAULT_HEARTBEAT_TIMEOUT_MS = 5000;
12
+ /** How long without a liveness message before `telemetry-liveness` reports `DISCONNECTED` (ms). */
13
+ exports.DEFAULT_HEARTBEAT_TIMEOUT_MS = 5000;
13
14
  const DEFAULT_INTERVAL_MS = 2000;
15
+ /**
16
+ * Every liveness message — the new `robot/status` topic or the legacy heartbeat — as one stream. The
17
+ * topics are subscribed separately, so the subscriptions are the same ones
18
+ * {@link getReportedStatusChanges} makes and can be shared with it.
19
+ */
20
+ const getLivenessMessages = (telemetry, projectId, callsign) => {
21
+ return (0, rxjs_1.merge)(telemetry.subscribe({ projectId, callsigns: [callsign], sources: [exports.ROBOT_STATUS_SOURCE] }), telemetry.subscribe({ projectId, callsigns: [callsign], sources: [exports.LEGACY_HEARTBEAT_SOURCE] }));
22
+ };
14
23
  /**
15
24
  * Maps a `robot/status` wire value (integer, or its string equivalent) to a
16
25
  * {@link RobotHealth}. Anything unrecognised — including `0` / `'unknown'` —
@@ -131,9 +140,7 @@ exports.getStatusContributorsChanges = getStatusContributorsChanges;
131
140
  * the stream rather than erroring it.
132
141
  */
133
142
  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));
143
+ return getLivenessMessages(telemetry, projectId, callsign).pipe((0, rxjs_1.map)((message) => now() - message.createdAt.getTime()), (0, rxjs_1.catchError)(() => rxjs_1.EMPTY));
137
144
  };
138
145
  exports.getTelemetryLatencyChanges = getTelemetryLatencyChanges;
139
146
  /**
@@ -143,11 +150,9 @@ exports.getTelemetryLatencyChanges = getTelemetryLatencyChanges;
143
150
  * but spans both topics and maps onto {@link ServiceConnection} so it can be
144
151
  * folded into connectivity aggregation as just another service entry.
145
152
  */
146
- const getTelemetryLiveness = (telemetry, projectId, callsign, heartbeatTimeoutMs = DEFAULT_HEARTBEAT_TIMEOUT_MS, intervalMs = DEFAULT_INTERVAL_MS) => {
153
+ const getTelemetryLiveness = (telemetry, projectId, callsign, heartbeatTimeoutMs = exports.DEFAULT_HEARTBEAT_TIMEOUT_MS, intervalMs = DEFAULT_INTERVAL_MS) => {
147
154
  const startedAt = Date.now();
148
- const lastMessageAt$ = telemetry
149
- .subscribe({ projectId, callsigns: [callsign], sources: [exports.ROBOT_STATUS_SOURCE, exports.LEGACY_HEARTBEAT_SOURCE] })
150
- .pipe((0, rxjs_1.map)(() => Date.now()));
155
+ const lastMessageAt$ = getLivenessMessages(telemetry, projectId, callsign).pipe((0, rxjs_1.map)(() => Date.now()));
151
156
  return (0, rxjs_1.combineLatest)([lastMessageAt$.pipe((0, rxjs_1.startWith)(startedAt)), (0, rxjs_1.interval)(intervalMs)]).pipe((0, rxjs_1.map)(([lastMessageAt]) => {
152
157
  const now = Date.now();
153
158
  // No message yet, but still within the initial grace period.
@@ -0,0 +1,28 @@
1
+ import { Observable } from 'rxjs';
2
+ export interface SharedStreamOptions {
3
+ /**
4
+ * Replay the latest value to a subscriber that joins late. Use it for state (a status, a poll
5
+ * result); leave it off for events (raw telemetry messages), where a replayed message would be
6
+ * mistaken for a fresh one.
7
+ */
8
+ replay: boolean;
9
+ }
10
+ /**
11
+ * Hands out one shared, reference-counted observable per key, so equivalent subscribers (e.g. every
12
+ * status dot for robots in one project) share a single upstream subscription or poll.
13
+ *
14
+ * The upstream is subscribed on the first subscriber and torn down after the last one leaves, at
15
+ * which point the entry is dropped; a later subscriber starts it afresh. An upstream that errors or
16
+ * completes is reset the same way, so one failure never leaves a dead stream in the pool.
17
+ */
18
+ export declare class SharedStreamPool {
19
+ private readonly streams;
20
+ get<T>(key: unknown[], create: () => Observable<T>, options: SharedStreamOptions): Observable<T>;
21
+ /** How many streams are currently pooled (subscribed and live). */
22
+ get size(): number;
23
+ }
24
+ /**
25
+ * The process-wide pool, shared across `RobotStatusService` instances. Keys include the SDK's unique
26
+ * config key, so only equivalent SDK configurations share streams.
27
+ */
28
+ export declare const sharedStreamPool: SharedStreamPool;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sharedStreamPool = exports.SharedStreamPool = void 0;
4
+ const rxjs_1 = require("rxjs");
5
+ /**
6
+ * Hands out one shared, reference-counted observable per key, so equivalent subscribers (e.g. every
7
+ * status dot for robots in one project) share a single upstream subscription or poll.
8
+ *
9
+ * The upstream is subscribed on the first subscriber and torn down after the last one leaves, at
10
+ * which point the entry is dropped; a later subscriber starts it afresh. An upstream that errors or
11
+ * completes is reset the same way, so one failure never leaves a dead stream in the pool.
12
+ */
13
+ class SharedStreamPool {
14
+ constructor() {
15
+ this.streams = new Map();
16
+ }
17
+ get(key, create, options) {
18
+ const id = JSON.stringify(key);
19
+ const existing = this.streams.get(id);
20
+ if (existing)
21
+ return existing;
22
+ // Registered only once subscribed, so a stream handed out but never subscribed leaves no entry
23
+ // behind. Until then (or after the pool dropped it, for a caller that held on to it and
24
+ // resubscribes) another stream may have taken the key: join that rather than run a second upstream.
25
+ const shared$ = (0, rxjs_1.defer)(() => {
26
+ const current = this.streams.get(id);
27
+ if (current && current !== shared$)
28
+ return current;
29
+ this.streams.set(id, shared$);
30
+ return create();
31
+ }).pipe((0, rxjs_1.finalize)(() => {
32
+ if (this.streams.get(id) === shared$)
33
+ this.streams.delete(id);
34
+ }), (0, rxjs_1.share)({
35
+ connector: () => (options.replay ? new rxjs_1.ReplaySubject(1) : new rxjs_1.Subject()),
36
+ resetOnError: true,
37
+ resetOnComplete: true,
38
+ resetOnRefCountZero: true,
39
+ }));
40
+ return shared$;
41
+ }
42
+ /** How many streams are currently pooled (subscribed and live). */
43
+ get size() {
44
+ return this.streams.size;
45
+ }
46
+ }
47
+ exports.SharedStreamPool = SharedStreamPool;
48
+ /**
49
+ * The process-wide pool, shared across `RobotStatusService` instances. Keys include the SDK's unique
50
+ * config key, so only equivalent SDK configurations share streams.
51
+ */
52
+ exports.sharedStreamPool = new SharedStreamPool();
@@ -1,6 +1,6 @@
1
+ import { ReportedRobotStatus } from './robot-status/reportedStatus';
1
2
  import { IBaseService, IRocosSDKConfig, RobotConnectivityStatus, RobotStatus, RobotStatusContributors, RocosError, ServiceConnection } from '../models';
2
3
  import { Observable } from 'rxjs';
3
- import { ReportedRobotStatus } from './robot-status/reportedStatus';
4
4
  import { BaseServiceAbstract } from './BaseServiceAbstract';
5
5
  /** Per-call tuning for the robot status observables. */
6
6
  export interface RobotStatusOptions {
@@ -49,7 +49,11 @@ export declare class RobotStatusService extends BaseServiceAbstract implements I
49
49
  * from a live one.
50
50
  */
51
51
  getTelemetryLatencyChanges(projectId: string, callsign: string): Observable<number>;
52
- /** Per-service connectivity plus the aggregate verdict, polled. */
52
+ /**
53
+ * Per-service connectivity plus the aggregate verdict, for `opts.expectedServices` plus any
54
+ * `opts.extraServices` (folded in on equal footing). HTTP services are read from their project's
55
+ * shared bulk poll; an unrecognised service id resolves to `UNKNOWN`.
56
+ */
53
57
  getConnectivityChanges(projectId: string, callsign: string, opts?: RobotStatusOptions): Observable<RobotConnectivityStatus>;
54
58
  /** One-shot connectivity snapshot: resolves once every expected service is known, or after a timeout. */
55
59
  getConnectivity(projectId: string, callsign: string, opts?: RobotStatusOptions): Promise<RobotConnectivityStatus>;
@@ -60,5 +64,20 @@ export declare class RobotStatusService extends BaseServiceAbstract implements I
60
64
  getRobotStatusChanges(projectId: string, callsign: string, opts?: RobotStatusOptions): Observable<RobotStatus>;
61
65
  protected getError(e: Error): RocosError;
62
66
  private get telemetryService();
63
- private connectivityDeps;
67
+ /**
68
+ * Shared streams are keyed by this, so equivalent SDK configurations (which `RocosStore` already
69
+ * treats as one SDK) share them, and different ones never do.
70
+ */
71
+ private get configKey();
72
+ /** Telemetry with one pooled subscription per robot and topic, however many status streams use it. */
73
+ private get sharedTelemetry();
74
+ private getTelemetryLiveness;
75
+ /** One service's connection for a callsign. Built-in services win over an injected one of the same id. */
76
+ private getServiceConnection;
77
+ /**
78
+ * A service's bulk (per-project) `connections` endpoint, polled every `pollMs`. One poll per project,
79
+ * service and interval is shared by every callsign and subscriber. A failed poll emits `undefined`
80
+ * rather than erroring, so one bad poll doesn't end the stream.
81
+ */
82
+ private getProjectConnections;
64
83
  }
@@ -1,12 +1,14 @@
1
- import { getConnectivityChanges } from './robot-status/connectivity';
2
- import { RobotHealth, RobotReadiness, RocosError, ServiceConnection, errorCodes, } from '../models';
3
- import { combineLatest, distinctUntilChanged, first, firstValueFrom, map, of, shareReplay, startWith, take, tap, timeout, } from 'rxjs';
4
- import { getReportedStatusChanges, getStatusContributorsChanges, getTelemetryLatencyChanges, getTelemetryLiveness, } from './robot-status/reportedStatus';
1
+ import { CONNECTION_SERVICE_PREFIXES, DEFAULT_CONNECTIVITY_POLL_MS, DEFAULT_EXPECTED_SERVICES, TELEMETRY_LIVENESS_SERVICE, aggregateConnectivity, buildConnectionsUrl, clampPollInterval, connectivityEquals, getCallsignConnection, } from './robot-status/connectivity';
2
+ import { DEFAULT_HEARTBEAT_TIMEOUT_MS, getReportedStatusChanges, getStatusContributorsChanges, getTelemetryLatencyChanges, getTelemetryLiveness, } from './robot-status/reportedStatus';
3
+ import { RobotConnectivity, RobotHealth, RobotReadiness, RocosError, ServiceConnection, errorCodes, } from '../models';
4
+ import { catchError, combineLatest, distinctUntilChanged, first, firstValueFrom, from, map, of, shareReplay, startWith, switchMap, take, tap, timeout, timer, } from 'rxjs';
5
5
  import { BaseServiceAbstract } from './BaseServiceAbstract';
6
6
  import { PlatFormTimeService } from './PlatformTimeService';
7
7
  import { RocosLogger } from '../logger/RocosLogger';
8
8
  import { RocosStore } from '../store/RocosStore';
9
9
  import { getRobotStatusColour } from '../helpers/getRobotStatusColour';
10
+ import { getUniqueConfigKey } from '../helpers/getUniqueConfigKey';
11
+ import { sharedStreamPool } from './robot-status/sharedStreams';
10
12
  /** Upper bound on how long the one-shot {@link RobotStatusService.getConnectivity} waits to settle. */
11
13
  const ONE_SHOT_TIMEOUT_MS = 10000;
12
14
  const isKnown = (status) => {
@@ -39,11 +41,11 @@ export class RobotStatusService extends BaseServiceAbstract {
39
41
  }
40
42
  /** Health + readiness as reported by the robot (new topic, legacy heartbeat fallback). */
41
43
  getReportedStatusChanges(projectId, callsign) {
42
- return getReportedStatusChanges(this.telemetryService, projectId, callsign);
44
+ return sharedStreamPool.get(['reported-status', this.configKey, projectId, callsign], () => getReportedStatusChanges(this.sharedTelemetry, projectId, callsign), { replay: true });
43
45
  }
44
46
  /** Per-contributor breakdown behind the reported health and readiness, with the reason for each. */
45
47
  getStatusContributorsChanges(projectId, callsign) {
46
- return getStatusContributorsChanges(this.telemetryService, projectId, callsign);
48
+ return sharedStreamPool.get(['status-contributors', this.configKey, projectId, callsign], () => getStatusContributorsChanges(this.sharedTelemetry, projectId, callsign), { replay: true });
47
49
  }
48
50
  /**
49
51
  * Telemetry latency in milliseconds — platform time minus when the agent created each liveness
@@ -52,11 +54,34 @@ export class RobotStatusService extends BaseServiceAbstract {
52
54
  * from a live one.
53
55
  */
54
56
  getTelemetryLatencyChanges(projectId, callsign) {
55
- return getTelemetryLatencyChanges(this.telemetryService, projectId, callsign, () => this.platformTime.platformTime);
57
+ return getTelemetryLatencyChanges(this.sharedTelemetry, projectId, callsign, () => this.platformTime.platformTime);
56
58
  }
57
- /** Per-service connectivity plus the aggregate verdict, polled. */
59
+ /**
60
+ * Per-service connectivity plus the aggregate verdict, for `opts.expectedServices` plus any
61
+ * `opts.extraServices` (folded in on equal footing). HTTP services are read from their project's
62
+ * shared bulk poll; an unrecognised service id resolves to `UNKNOWN`.
63
+ */
58
64
  getConnectivityChanges(projectId, callsign, opts) {
59
- return getConnectivityChanges(this.connectivityDeps(projectId, callsign, opts), projectId, callsign, opts?.expectedServices, opts?.connectivityPollMs);
65
+ const expectedServices = opts?.expectedServices ?? DEFAULT_EXPECTED_SERVICES;
66
+ const extraServices = opts?.extraServices ?? {};
67
+ const serviceIds = [
68
+ ...expectedServices,
69
+ ...Object.keys(extraServices).filter((id) => !expectedServices.includes(id)),
70
+ ];
71
+ // combineLatest([]) completes without emitting; emit an explicit empty/offline status instead.
72
+ if (serviceIds.length === 0) {
73
+ return of({ overall: RobotConnectivity.OFFLINE, services: {} });
74
+ }
75
+ const pollMs = clampPollInterval(opts?.connectivityPollMs ?? DEFAULT_CONNECTIVITY_POLL_MS);
76
+ const perService = serviceIds.map((serviceId) => {
77
+ return this.getServiceConnection(projectId, callsign, serviceId, pollMs, opts).pipe(startWith(ServiceConnection.UNKNOWN), map((connection) => ({ serviceId, connection })));
78
+ });
79
+ return combineLatest(perService).pipe(map((entries) => {
80
+ const services = {};
81
+ for (const { serviceId, connection } of entries)
82
+ services[serviceId] = connection;
83
+ return { overall: aggregateConnectivity(services), services };
84
+ }), distinctUntilChanged(connectivityEquals));
60
85
  }
61
86
  /** One-shot connectivity snapshot: resolves once every expected service is known, or after a timeout. */
62
87
  getConnectivity(projectId, callsign, opts) {
@@ -92,15 +117,56 @@ export class RobotStatusService extends BaseServiceAbstract {
92
117
  get telemetryService() {
93
118
  return RocosStore.getSDKInstance(this.config).getTelemetryService();
94
119
  }
95
- connectivityDeps(projectId, callsign, opts) {
120
+ /**
121
+ * Shared streams are keyed by this, so equivalent SDK configurations (which `RocosStore` already
122
+ * treats as one SDK) share them, and different ones never do.
123
+ */
124
+ get configKey() {
125
+ return getUniqueConfigKey(this.config);
126
+ }
127
+ /** Telemetry with one pooled subscription per robot and topic, however many status streams use it. */
128
+ get sharedTelemetry() {
96
129
  return {
97
- httpGet: (url) => {
98
- return this.callGet(url, `Failed to get connection status for ${callsign} in project ${projectId}.`);
130
+ subscribe: (params) => {
131
+ return sharedStreamPool.get(['telemetry', this.configKey, params.projectId, params.callsigns, params.sources], () => this.telemetryService.subscribe(params),
132
+ // Raw messages are events: replaying one to a late subscriber would read as a fresh message.
133
+ { replay: false });
99
134
  },
100
- baseUrl: this.config.url,
101
- insecure: this.config.insecure,
102
- telemetryLiveness$: getTelemetryLiveness(this.telemetryService, projectId, callsign, opts?.heartbeatTimeoutMs),
103
- extraServices: opts?.extraServices,
104
135
  };
105
136
  }
137
+ getTelemetryLiveness(projectId, callsign, heartbeatTimeoutMs = DEFAULT_HEARTBEAT_TIMEOUT_MS) {
138
+ // Key on the resolved timeout, so omitting it shares a stream with passing the default explicitly.
139
+ return sharedStreamPool.get(['telemetry-liveness', this.configKey, projectId, callsign, heartbeatTimeoutMs], () => getTelemetryLiveness(this.sharedTelemetry, projectId, callsign, heartbeatTimeoutMs), { replay: true });
140
+ }
141
+ /** One service's connection for a callsign. Built-in services win over an injected one of the same id. */
142
+ getServiceConnection(projectId, callsign, serviceId, pollMs, opts) {
143
+ if (serviceId === TELEMETRY_LIVENESS_SERVICE) {
144
+ return this.getTelemetryLiveness(projectId, callsign, opts?.heartbeatTimeoutMs);
145
+ }
146
+ if (Object.prototype.hasOwnProperty.call(CONNECTION_SERVICE_PREFIXES, serviceId)) {
147
+ return this.getProjectConnections(projectId, serviceId, pollMs).pipe(map((poll) => getCallsignConnection(poll, callsign)), distinctUntilChanged());
148
+ }
149
+ const extraServices = opts?.extraServices;
150
+ if (extraServices && Object.prototype.hasOwnProperty.call(extraServices, serviceId)) {
151
+ // Contain an injected observable's errors as UNKNOWN, mirroring the built-in sources, so a
152
+ // faulty caller signal can't error out combineLatest and tear down the whole aggregate.
153
+ return extraServices[serviceId].pipe(catchError(() => of(ServiceConnection.UNKNOWN)));
154
+ }
155
+ return of(ServiceConnection.UNKNOWN);
156
+ }
157
+ /**
158
+ * A service's bulk (per-project) `connections` endpoint, polled every `pollMs`. One poll per project,
159
+ * service and interval is shared by every callsign and subscriber. A failed poll emits `undefined`
160
+ * rather than erroring, so one bad poll doesn't end the stream.
161
+ */
162
+ getProjectConnections(projectId, serviceId, pollMs) {
163
+ const url = buildConnectionsUrl(serviceId, this.config.url, projectId, undefined, this.config.insecure);
164
+ return sharedStreamPool.get(['connections', this.configKey, url, pollMs], () => {
165
+ return timer(0, pollMs).pipe(switchMap(() => {
166
+ return from(this.callGet(url, `Failed to get connection statuses for project ${projectId}.`)).pipe(
167
+ // Go encodes an empty map as null: a successful poll in which nobody is connected.
168
+ map((connections) => connections ?? {}), catchError(() => of(undefined)));
169
+ }));
170
+ }, { replay: true });
171
+ }
106
172
  }
@@ -1,5 +1,4 @@
1
1
  import { IConnectedCallsign, RobotConnectivity, RobotConnectivityStatus, ServiceConnection } from '../../models';
2
- import { Observable } from 'rxjs';
3
2
  /**
4
3
  * Service id → public path prefix, for services that expose the standard
5
4
  * `connections` endpoint. New services adopting the convention are added here.
@@ -9,12 +8,13 @@ import { Observable } from 'rxjs';
9
8
  export declare const CONNECTION_SERVICE_PREFIXES: Record<string, string>;
10
9
  /**
11
10
  * The telemetry-liveness signal is derived from heartbeat freshness rather than
12
- * an HTTP endpoint, so it is handled specially (its observable is supplied by
13
- * the caller). See `getTelemetryLiveness`.
11
+ * an HTTP endpoint, so it is handled specially. See `getTelemetryLiveness`.
14
12
  */
15
13
  export declare const TELEMETRY_LIVENESS_SERVICE = "telemetry-liveness";
16
14
  /** The services evaluated by default. */
17
15
  export declare const DEFAULT_EXPECTED_SERVICES: string[];
16
+ /** How often the bulk `connections` endpoints are polled by default (ms). */
17
+ export declare const DEFAULT_CONNECTIVITY_POLL_MS = 5000;
18
18
  /**
19
19
  * Floor for the connections-endpoint poll interval. Guards against a caller
20
20
  * passing `0` (or any tiny value), which would otherwise poll the API on every
@@ -23,8 +23,16 @@ export declare const DEFAULT_EXPECTED_SERVICES: string[];
23
23
  export declare const MIN_CONNECTIVITY_POLL_MS = 250;
24
24
  /** Clamps a requested poll interval up to {@link MIN_CONNECTIVITY_POLL_MS}. */
25
25
  export declare const clampPollInterval: (pollMs: number) => number;
26
- /** Authenticated GET used to poll a service's `connections` endpoint. */
27
- export type ConnectionsHttpGet = (url: string) => Promise<IConnectedCallsign>;
26
+ /**
27
+ * A bulk `connections` endpoint response: callsign → connection. A callsign that isn't listed is not
28
+ * connected (Teletubby lists only connected callsigns).
29
+ */
30
+ export type ProjectConnections = Record<string, IConnectedCallsign>;
31
+ /**
32
+ * One poll of a bulk `connections` endpoint: the project's connections, or `undefined` when the poll
33
+ * failed — distinct from a successful but empty response, in which every callsign is disconnected.
34
+ */
35
+ export type ProjectConnectionsPoll = ProjectConnections | undefined;
28
36
  /**
29
37
  * Builds the `connections` endpoint URL for a service — per-callsign when a
30
38
  * callsign is given, otherwise the bulk per-project variant.
@@ -50,29 +58,10 @@ export declare const mapConnectionStatus: (connection?: IConnectedCallsign | nul
50
58
  */
51
59
  export declare const aggregateConnectivity: (services: Record<string, ServiceConnection>) => RobotConnectivity;
52
60
  /**
53
- * Polls a single service's `connections` endpoint on an interval, emitting its
54
- * {@link ServiceConnection} (change-only). A failed/timed-out poll yields
55
- * `UNKNOWN` (held transitional) rather than `DISCONNECTED`, to avoid a spurious
56
- * degraded flash on a transient error.
57
- *
58
- * `pollMs` is floored at {@link MIN_CONNECTIVITY_POLL_MS} so the endpoint can't
59
- * be polled unreasonably fast.
60
- */
61
- export declare const getServiceConnectionChanges: (httpGet: ConnectionsHttpGet, url: string, pollMs?: number) => Observable<ServiceConnection>;
62
- export interface ConnectivityDeps {
63
- httpGet: ConnectionsHttpGet;
64
- baseUrl: string;
65
- insecure?: boolean;
66
- /** The telemetry-liveness signal (from `getTelemetryLiveness`), folded in as one service. */
67
- telemetryLiveness$: Observable<ServiceConnection>;
68
- /** Caller-injected connectivity signals, keyed by service id, folded in on equal footing. */
69
- extraServices?: Record<string, Observable<ServiceConnection>>;
70
- }
71
- /**
72
- * Emits the robot's {@link RobotConnectivityStatus} — the per-service breakdown
73
- * plus the aggregate verdict — for the configured `expectedServices`, plus any
74
- * caller-injected `extraServices` (folded in on equal footing). HTTP services
75
- * are polled; `telemetry-liveness` and injected services use their supplied
76
- * observable; any unrecognised service id resolves to `UNKNOWN`.
61
+ * One callsign's {@link ServiceConnection} from a bulk poll. A failed poll is `UNKNOWN` (held
62
+ * transitional) rather than `DISCONNECTED`, to avoid a spurious degraded flash on a transient error;
63
+ * a callsign missing from a successful poll is `DISCONNECTED`.
77
64
  */
78
- export declare const getConnectivityChanges: (deps: ConnectivityDeps, projectId: string, callsign: string, expectedServices?: string[], pollMs?: number) => Observable<RobotConnectivityStatus>;
65
+ export declare const getCallsignConnection: (poll: ProjectConnectionsPoll, callsign: string) => ServiceConnection;
66
+ /** Whether two connectivity statuses carry the same verdict and per-service breakdown. */
67
+ export declare const connectivityEquals: (a: RobotConnectivityStatus, b: RobotConnectivityStatus) => boolean;
@@ -1,6 +1,5 @@
1
1
  import { API_SERVICE_CONNECTIONS_URL, API_SERVICE_CONNECTION_URL } from '../../constants/api';
2
2
  import { ConnectionStatus, RobotConnectivity, ServiceConnection, } from '../../models';
3
- import { catchError, combineLatest, distinctUntilChanged, from, map, of, startWith, switchMap, timer, } from 'rxjs';
4
3
  import { formatServiceUrl } from '../../helpers/formatServiceUrl';
5
4
  /**
6
5
  * Service id → public path prefix, for services that expose the standard
@@ -15,8 +14,7 @@ export const CONNECTION_SERVICE_PREFIXES = {
15
14
  };
16
15
  /**
17
16
  * The telemetry-liveness signal is derived from heartbeat freshness rather than
18
- * an HTTP endpoint, so it is handled specially (its observable is supplied by
19
- * the caller). See `getTelemetryLiveness`.
17
+ * an HTTP endpoint, so it is handled specially. See `getTelemetryLiveness`.
20
18
  */
21
19
  export const TELEMETRY_LIVENESS_SERVICE = 'telemetry-liveness';
22
20
  /** The services evaluated by default. */
@@ -26,7 +24,8 @@ export const DEFAULT_EXPECTED_SERVICES = [
26
24
  'robot-services',
27
25
  'robot-telemetry',
28
26
  ];
29
- const DEFAULT_CONNECTIVITY_POLL_MS = 5000;
27
+ /** How often the bulk `connections` endpoints are polled by default (ms). */
28
+ export const DEFAULT_CONNECTIVITY_POLL_MS = 5000;
30
29
  /**
31
30
  * Floor for the connections-endpoint poll interval. Guards against a caller
32
31
  * passing `0` (or any tiny value), which would otherwise poll the API on every
@@ -83,20 +82,19 @@ export const aggregateConnectivity = (services) => {
83
82
  return RobotConnectivity.OFFLINE;
84
83
  };
85
84
  /**
86
- * Polls a single service's `connections` endpoint on an interval, emitting its
87
- * {@link ServiceConnection} (change-only). A failed/timed-out poll yields
88
- * `UNKNOWN` (held transitional) rather than `DISCONNECTED`, to avoid a spurious
89
- * degraded flash on a transient error.
90
- *
91
- * `pollMs` is floored at {@link MIN_CONNECTIVITY_POLL_MS} so the endpoint can't
92
- * be polled unreasonably fast.
85
+ * One callsign's {@link ServiceConnection} from a bulk poll. A failed poll is `UNKNOWN` (held
86
+ * transitional) rather than `DISCONNECTED`, to avoid a spurious degraded flash on a transient error;
87
+ * a callsign missing from a successful poll is `DISCONNECTED`.
93
88
  */
94
- export const getServiceConnectionChanges = (httpGet, url, pollMs = DEFAULT_CONNECTIVITY_POLL_MS) => {
95
- return timer(0, clampPollInterval(pollMs)).pipe(switchMap(() => {
96
- return from(httpGet(url)).pipe(map(mapConnectionStatus), catchError(() => of(ServiceConnection.UNKNOWN)));
97
- }), startWith(ServiceConnection.UNKNOWN), distinctUntilChanged());
89
+ export const getCallsignConnection = (poll, callsign) => {
90
+ if (poll === undefined)
91
+ return ServiceConnection.UNKNOWN;
92
+ if (!Object.prototype.hasOwnProperty.call(poll, callsign))
93
+ return ServiceConnection.DISCONNECTED;
94
+ return mapConnectionStatus(poll[callsign]);
98
95
  };
99
- const connectivityEquals = (a, b) => {
96
+ /** Whether two connectivity statuses carry the same verdict and per-service breakdown. */
97
+ export const connectivityEquals = (a, b) => {
100
98
  if (a.overall !== b.overall)
101
99
  return false;
102
100
  const keys = Object.keys(a.services);
@@ -104,43 +102,3 @@ const connectivityEquals = (a, b) => {
104
102
  return false;
105
103
  return keys.every((key) => a.services[key] === b.services[key]);
106
104
  };
107
- /**
108
- * Emits the robot's {@link RobotConnectivityStatus} — the per-service breakdown
109
- * plus the aggregate verdict — for the configured `expectedServices`, plus any
110
- * caller-injected `extraServices` (folded in on equal footing). HTTP services
111
- * are polled; `telemetry-liveness` and injected services use their supplied
112
- * observable; any unrecognised service id resolves to `UNKNOWN`.
113
- */
114
- export const getConnectivityChanges = (deps, projectId, callsign, expectedServices = DEFAULT_EXPECTED_SERVICES, pollMs = DEFAULT_CONNECTIVITY_POLL_MS) => {
115
- const extraServices = deps.extraServices ?? {};
116
- const serviceIds = [...expectedServices, ...Object.keys(extraServices).filter((id) => !expectedServices.includes(id))];
117
- // combineLatest([]) completes without emitting; emit an explicit empty/offline status instead.
118
- if (serviceIds.length === 0) {
119
- return of({ overall: RobotConnectivity.OFFLINE, services: {} });
120
- }
121
- const perService = serviceIds.map((serviceId) => {
122
- let source$;
123
- if (serviceId === TELEMETRY_LIVENESS_SERVICE) {
124
- source$ = deps.telemetryLiveness$;
125
- }
126
- else if (Object.prototype.hasOwnProperty.call(CONNECTION_SERVICE_PREFIXES, serviceId)) {
127
- const url = buildConnectionsUrl(serviceId, deps.baseUrl, projectId, callsign, deps.insecure);
128
- source$ = getServiceConnectionChanges(deps.httpGet, url, pollMs);
129
- }
130
- else if (Object.prototype.hasOwnProperty.call(extraServices, serviceId)) {
131
- // Contain an injected observable's errors as UNKNOWN, mirroring the built-in sources, so a
132
- // faulty caller signal can't error out combineLatest and tear down the whole aggregate.
133
- source$ = extraServices[serviceId].pipe(catchError(() => of(ServiceConnection.UNKNOWN)));
134
- }
135
- else {
136
- source$ = of(ServiceConnection.UNKNOWN);
137
- }
138
- return source$.pipe(startWith(ServiceConnection.UNKNOWN), map((connection) => ({ serviceId, connection })));
139
- });
140
- return combineLatest(perService).pipe(map((entries) => {
141
- const services = {};
142
- for (const { serviceId, connection } of entries)
143
- services[serviceId] = connection;
144
- return { overall: aggregateConnectivity(services), services };
145
- }), distinctUntilChanged(connectivityEquals));
146
- };
@@ -7,6 +7,13 @@ export declare const ROBOT_STATUS_SOURCE = "/diagnostics/robot/status";
7
7
  export declare const LEGACY_HEARTBEAT_SOURCE = "/rocos/agent/telemetry/heartbeat";
8
8
  /** The per-contributor breakdown behind the reported status (health + readiness). */
9
9
  export declare const ROBOT_STATUS_CONTRIBUTORS_SOURCE = "/diagnostics/robot/status/contributors";
10
+ /** How long without a liveness message before `telemetry-liveness` reports `DISCONNECTED` (ms). */
11
+ export declare const DEFAULT_HEARTBEAT_TIMEOUT_MS = 5000;
12
+ /**
13
+ * The telemetry these streams subscribe through. `RobotStatusService` passes a pooled implementation,
14
+ * so every status stream for a robot shares one subscription per topic.
15
+ */
16
+ export type StatusTelemetry = Pick<TelemetryService, 'subscribe'>;
10
17
  export interface ReportedRobotStatus {
11
18
  health: RobotHealth;
12
19
  readiness: RobotReadiness;
@@ -29,7 +36,7 @@ export declare const parseRobotReadiness: (value: unknown) => RobotReadiness;
29
36
  * preserves today's "online ⇒ green" behaviour for agents not yet emitting the
30
37
  * new topic.
31
38
  */
32
- export declare const getReportedStatusChanges: (telemetry: TelemetryService, projectId: string, callsign: string) => Observable<ReportedRobotStatus>;
39
+ export declare const getReportedStatusChanges: (telemetry: StatusTelemetry, projectId: string, callsign: string) => Observable<ReportedRobotStatus>;
33
40
  /**
34
41
  * Emits the per-contributor breakdown behind the robot's reported health and
35
42
  * readiness, from the agent's `robot/status/contributors` topic. Each
@@ -40,7 +47,7 @@ export declare const getReportedStatusChanges: (telemetry: TelemetryService, pro
40
47
  * emit immediately, and — like {@link getReportedStatusChanges} — a telemetry
41
48
  * error falls back to an empty breakdown rather than terminating the stream.
42
49
  */
43
- export declare const getStatusContributorsChanges: (telemetry: TelemetryService, projectId: string, callsign: string) => Observable<RobotStatusContributors>;
50
+ export declare const getStatusContributorsChanges: (telemetry: StatusTelemetry, projectId: string, callsign: string) => Observable<RobotStatusContributors>;
44
51
  /**
45
52
  * Emits the robot's telemetry latency in milliseconds, once per liveness message (from either the
46
53
  * new `robot/status` topic or the legacy heartbeat — the same messages {@link getTelemetryLiveness}
@@ -52,7 +59,7 @@ export declare const getStatusContributorsChanges: (telemetry: TelemetryService,
52
59
  * {@link getTelemetryLiveness} to tell a stale value from a live one. A telemetry error completes
53
60
  * the stream rather than erroring it.
54
61
  */
55
- export declare const getTelemetryLatencyChanges: (telemetry: TelemetryService, projectId: string, callsign: string, now: () => number) => Observable<number>;
62
+ export declare const getTelemetryLatencyChanges: (telemetry: StatusTelemetry, projectId: string, callsign: string, now: () => number) => Observable<number>;
56
63
  /**
57
64
  * Emits the `telemetry-liveness` connectivity signal: whether a heartbeat (from
58
65
  * either the new `robot/status` topic or the legacy heartbeat) has been received
@@ -60,4 +67,4 @@ export declare const getTelemetryLatencyChanges: (telemetry: TelemetryService, p
60
67
  * but spans both topics and maps onto {@link ServiceConnection} so it can be
61
68
  * folded into connectivity aggregation as just another service entry.
62
69
  */
63
- export declare const getTelemetryLiveness: (telemetry: TelemetryService, projectId: string, callsign: string, heartbeatTimeoutMs?: number, intervalMs?: number) => Observable<ServiceConnection>;
70
+ export declare const getTelemetryLiveness: (telemetry: StatusTelemetry, projectId: string, callsign: string, heartbeatTimeoutMs?: number, intervalMs?: number) => Observable<ServiceConnection>;
@@ -6,8 +6,17 @@ export const ROBOT_STATUS_SOURCE = '/diagnostics/robot/status';
6
6
  export const LEGACY_HEARTBEAT_SOURCE = '/rocos/agent/telemetry/heartbeat';
7
7
  /** The per-contributor breakdown behind the reported status (health + readiness). */
8
8
  export const ROBOT_STATUS_CONTRIBUTORS_SOURCE = `${ROBOT_STATUS_SOURCE}/contributors`;
9
- const DEFAULT_HEARTBEAT_TIMEOUT_MS = 5000;
9
+ /** How long without a liveness message before `telemetry-liveness` reports `DISCONNECTED` (ms). */
10
+ export const DEFAULT_HEARTBEAT_TIMEOUT_MS = 5000;
10
11
  const DEFAULT_INTERVAL_MS = 2000;
12
+ /**
13
+ * Every liveness message — the new `robot/status` topic or the legacy heartbeat — as one stream. The
14
+ * topics are subscribed separately, so the subscriptions are the same ones
15
+ * {@link getReportedStatusChanges} makes and can be shared with it.
16
+ */
17
+ const getLivenessMessages = (telemetry, projectId, callsign) => {
18
+ return merge(telemetry.subscribe({ projectId, callsigns: [callsign], sources: [ROBOT_STATUS_SOURCE] }), telemetry.subscribe({ projectId, callsigns: [callsign], sources: [LEGACY_HEARTBEAT_SOURCE] }));
19
+ };
11
20
  /**
12
21
  * Maps a `robot/status` wire value (integer, or its string equivalent) to a
13
22
  * {@link RobotHealth}. Anything unrecognised — including `0` / `'unknown'` —
@@ -124,9 +133,7 @@ export const getStatusContributorsChanges = (telemetry, projectId, callsign) =>
124
133
  * the stream rather than erroring it.
125
134
  */
126
135
  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));
136
+ return getLivenessMessages(telemetry, projectId, callsign).pipe(map((message) => now() - message.createdAt.getTime()), catchError(() => EMPTY));
130
137
  };
131
138
  /**
132
139
  * Emits the `telemetry-liveness` connectivity signal: whether a heartbeat (from
@@ -137,9 +144,7 @@ export const getTelemetryLatencyChanges = (telemetry, projectId, callsign, now)
137
144
  */
138
145
  export const getTelemetryLiveness = (telemetry, projectId, callsign, heartbeatTimeoutMs = DEFAULT_HEARTBEAT_TIMEOUT_MS, intervalMs = DEFAULT_INTERVAL_MS) => {
139
146
  const startedAt = Date.now();
140
- const lastMessageAt$ = telemetry
141
- .subscribe({ projectId, callsigns: [callsign], sources: [ROBOT_STATUS_SOURCE, LEGACY_HEARTBEAT_SOURCE] })
142
- .pipe(map(() => Date.now()));
147
+ const lastMessageAt$ = getLivenessMessages(telemetry, projectId, callsign).pipe(map(() => Date.now()));
143
148
  return combineLatest([lastMessageAt$.pipe(startWith(startedAt)), interval(intervalMs)]).pipe(map(([lastMessageAt]) => {
144
149
  const now = Date.now();
145
150
  // No message yet, but still within the initial grace period.
@@ -0,0 +1,28 @@
1
+ import { Observable } from 'rxjs';
2
+ export interface SharedStreamOptions {
3
+ /**
4
+ * Replay the latest value to a subscriber that joins late. Use it for state (a status, a poll
5
+ * result); leave it off for events (raw telemetry messages), where a replayed message would be
6
+ * mistaken for a fresh one.
7
+ */
8
+ replay: boolean;
9
+ }
10
+ /**
11
+ * Hands out one shared, reference-counted observable per key, so equivalent subscribers (e.g. every
12
+ * status dot for robots in one project) share a single upstream subscription or poll.
13
+ *
14
+ * The upstream is subscribed on the first subscriber and torn down after the last one leaves, at
15
+ * which point the entry is dropped; a later subscriber starts it afresh. An upstream that errors or
16
+ * completes is reset the same way, so one failure never leaves a dead stream in the pool.
17
+ */
18
+ export declare class SharedStreamPool {
19
+ private readonly streams;
20
+ get<T>(key: unknown[], create: () => Observable<T>, options: SharedStreamOptions): Observable<T>;
21
+ /** How many streams are currently pooled (subscribed and live). */
22
+ get size(): number;
23
+ }
24
+ /**
25
+ * The process-wide pool, shared across `RobotStatusService` instances. Keys include the SDK's unique
26
+ * config key, so only equivalent SDK configurations share streams.
27
+ */
28
+ export declare const sharedStreamPool: SharedStreamPool;
@@ -0,0 +1,48 @@
1
+ import { ReplaySubject, Subject, defer, finalize, share } from 'rxjs';
2
+ /**
3
+ * Hands out one shared, reference-counted observable per key, so equivalent subscribers (e.g. every
4
+ * status dot for robots in one project) share a single upstream subscription or poll.
5
+ *
6
+ * The upstream is subscribed on the first subscriber and torn down after the last one leaves, at
7
+ * which point the entry is dropped; a later subscriber starts it afresh. An upstream that errors or
8
+ * completes is reset the same way, so one failure never leaves a dead stream in the pool.
9
+ */
10
+ export class SharedStreamPool {
11
+ constructor() {
12
+ this.streams = new Map();
13
+ }
14
+ get(key, create, options) {
15
+ const id = JSON.stringify(key);
16
+ const existing = this.streams.get(id);
17
+ if (existing)
18
+ return existing;
19
+ // Registered only once subscribed, so a stream handed out but never subscribed leaves no entry
20
+ // behind. Until then (or after the pool dropped it, for a caller that held on to it and
21
+ // resubscribes) another stream may have taken the key: join that rather than run a second upstream.
22
+ const shared$ = defer(() => {
23
+ const current = this.streams.get(id);
24
+ if (current && current !== shared$)
25
+ return current;
26
+ this.streams.set(id, shared$);
27
+ return create();
28
+ }).pipe(finalize(() => {
29
+ if (this.streams.get(id) === shared$)
30
+ this.streams.delete(id);
31
+ }), share({
32
+ connector: () => (options.replay ? new ReplaySubject(1) : new Subject()),
33
+ resetOnError: true,
34
+ resetOnComplete: true,
35
+ resetOnRefCountZero: true,
36
+ }));
37
+ return shared$;
38
+ }
39
+ /** How many streams are currently pooled (subscribed and live). */
40
+ get size() {
41
+ return this.streams.size;
42
+ }
43
+ }
44
+ /**
45
+ * The process-wide pool, shared across `RobotStatusService` instances. Keys include the SDK's unique
46
+ * config key, so only equivalent SDK configurations share streams.
47
+ */
48
+ export const sharedStreamPool = new SharedStreamPool();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dronedeploy/rocos-js-sdk",
3
- "version": "4.5.1",
3
+ "version": "4.5.2",
4
4
  "description": "Javascript SDK for rocos",
5
5
  "main": "cjs/index.js",
6
6
  "module": "esm/index.js",