@webex/internal-plugin-metrics 3.12.0-next.45 → 3.12.0-next.47

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.
package/README.md CHANGED
@@ -9,6 +9,7 @@ This is an internal Cisco Webex plugin. As such, it does not strictly adhere to
9
9
  - [Install](#install)
10
10
  - [Usage](#usage)
11
11
  - [Unhandled exception telemetry](#unhandled-exception-telemetry)
12
+ - [Network request telemetry](#network-request-telemetry)
12
13
  - [Contribute](#contribute)
13
14
  - [Maintainers](#maintainers)
14
15
  - [License](#license)
@@ -47,7 +48,7 @@ Telemetry is disabled by default. Enable it with
47
48
  include application context such as `orgId` and `dataCenter`. Metadata must not contain personally
48
49
  identifiable information or credentials.
49
50
 
50
- ```js
51
+ ````js
51
52
  import Webex from 'webex';
52
53
 
53
54
  const webex = Webex.init({
@@ -63,6 +64,243 @@ const webex = Webex.init({
63
64
  },
64
65
  },
65
66
  });
67
+ ## Network request telemetry
68
+
69
+ Network request telemetry is disabled by default. Enable it with
70
+ `metrics.networkTelemetry.enabled: true`. When enabled, the metrics plugin summarizes requests
71
+ made through the Webex SDK request pipeline. The reporting interval is configurable with
72
+ `metrics.networkTelemetry.intervalMs` and defaults to ten minutes. It listens to the SDK-wide `request:start`,
73
+ `request:success`, and `request:failure` events, so individual plugins do not need to wrap or
74
+ replace `webex.request()`.
75
+
76
+ For example, to collect one-minute windows:
77
+
78
+ ```js
79
+ const webex = Webex.init({
80
+ config: {
81
+ metrics: {
82
+ networkTelemetry: {
83
+ enabled: true,
84
+ intervalMs: 60 * 1_000,
85
+ },
86
+ },
87
+ },
88
+ });
89
+ ```
90
+
91
+ The listeners are installed once for each Webex instance when `webex.internal.metrics` is
92
+ constructed and the feature is enabled. The metrics package must be imported before constructing
93
+ the Webex instance. Standard Webex SDK bundles already import and register the metrics plugin.
94
+
95
+ ### Scope
96
+
97
+ The collector counts request and response outcomes that pass through `webex.request()` and its interceptors. For failures, it also records aggregated error details covering:
98
+
99
+ - HTTP responses rejected by the SDK, such as `4xx` and `5xx` responses.
100
+ - Network or CORS failures where no HTTP response is available.
101
+ - Aborted and timed-out SDK requests when the error exposes that information.
102
+ - Request preparation failures that emit `request:failure`.
103
+
104
+ It does not monitor arbitrary application `fetch()`, `XMLHttpRequest`, WebSocket, or other traffic outside the SDK request pipeline. It also does not use `PerformanceObserver` or browser-wide request interception.
105
+
106
+ ### Event flow
107
+
108
+ ```text
109
+ webex.request()
110
+ -> SDK request interceptors
111
+ -> request:start(options)
112
+ -> request:success(options, response) or request:failure(options, reason)
113
+ -> metrics request outcome listeners
114
+ -> aggregate host, endpoint, response, and error counts
115
+ -> every configured interval, submit JS_SDK_NETWORK_REQUEST_SUMMARY
116
+ ````
117
+
118
+ The listeners and ten-minute accumulator are registered during metrics plugin initialization:
119
+
120
+ ```js
121
+ initialize(...args) {
122
+ WebexPlugin.prototype.initialize.call(this, ...args);
123
+ if (this.webex.config.metrics.networkTelemetry.enabled !== true) {
124
+ return;
125
+ }
126
+ this.networkTelemetry = createNetworkTelemetryCollector(/* submission callbacks */);
127
+ this.listenTo(this.webex, 'request:start', this.recordNetworkRequestStart);
128
+ this.listenTo(this.webex, 'request:success', this.recordNetworkRequestSuccess);
129
+ this.listenTo(this.webex, 'request:failure', this.recordNetworkRequestFailure);
130
+ }
131
+ ```
132
+
133
+ The metrics plugin exposes `flushNetworkTelemetry()` for callers that need to submit the current
134
+ non-empty window immediately, such as after an early call failure. When the metrics plugin is
135
+ stopped, any non-empty partial window is submitted once before the collector is disposed. Empty
136
+ windows are not submitted during shutdown, and the shutdown hook waits for the submission attempt
137
+ to settle.
138
+
139
+ ```js
140
+ await webex.internal.metrics.flushNetworkTelemetry();
141
+ ```
142
+
143
+ ### Metric schema
144
+
145
+ One operational client metric named `JS_SDK_NETWORK_REQUEST_SUMMARY` is submitted at the configured
146
+ interval. Its `eventPayload` has this shape:
147
+
148
+ ```ts
149
+ type NetworkTelemetry = {
150
+ metricsSummary: {
151
+ totalSendRequest: number;
152
+ totalFailedRequest: number;
153
+ totalRecvdResponse: number;
154
+ totalFailedResponse: number;
155
+ };
156
+ metrics: Array<{
157
+ host: string;
158
+ endPoint: string;
159
+ countSendRequest: number;
160
+ countFailedRequest: number;
161
+ countRecvdResponse: number;
162
+ countFailedResponse: number;
163
+ averageNetworkDurationMs: number;
164
+ maxNetworkDurationP90Ms: number;
165
+ maxNetworkDurationP99Ms: number;
166
+ }>;
167
+ errorMetrics: Array<{
168
+ host: string;
169
+ endPoint: string;
170
+ statusCode: number;
171
+ errorCode: string;
172
+ method: string;
173
+ errorType: string;
174
+ errorMessage: string;
175
+ trackingIds: string[];
176
+ countError: number;
177
+ }>;
178
+ errorMetricsSummary: Record<string, {count: number}>;
179
+ };
180
+ ```
181
+
182
+ The SDK adds application metadata to the outer client metric when it wraps this `eventPayload`:
183
+
184
+ | Property | Source |
185
+ | -------------------- | --------------------------------------------------------------------------- |
186
+ | `tags.app_name` | `webex.config.appName`, or `unknown` |
187
+ | `tags.app_version` | `webex.config.appVersion`, or `unknown` |
188
+ | `tags.app_url` | Browser origin without path/query data, hostname fallback, or `non-browser` |
189
+ | `fields.sdk_version` | `webex.version` |
190
+
191
+ Counter mapping:
192
+
193
+ | Event or outcome | Summary and endpoint counters |
194
+ | --------------------------------------------------- | --------------------------------------------------------------------------- |
195
+ | `request:start` | `totalSendRequest`, `countSendRequest` |
196
+ | `request:success` | `totalRecvdResponse`, `countRecvdResponse` |
197
+ | `request:failure` without an HTTP response | `totalFailedRequest`, `countFailedRequest` |
198
+ | `request:failure` with an HTTP status (`4xx`/`5xx`) | Received-response counters plus `totalFailedResponse`/`countFailedResponse` |
199
+
200
+ The `metrics` array is grouped by `host` and `endPoint`. For service-based SDK requests, `host` is the normalized logical service name. Direct-URI requests use the URI host. `endPoint` is a sanitized resource or URI path. `averageNetworkDurationMs` is the average measured network duration for completed requests in the group, while `maxNetworkDurationP90Ms` and `maxNetworkDurationP99Ms` are the maximum durations at the nearest-rank 90th and 99th percentiles. All values are in milliseconds.
201
+
202
+ The `errorMetrics` array groups identical failures by host, endpoint, status code, error code, method, error type, and error message. `countError` records the number of occurrences, while `trackingIds` retains at most ten unique identifiers. `errorMetricsSummary` counts errors by status code; status `0` means no HTTP response was available.
203
+
204
+ Example:
205
+
206
+ ```js
207
+ {
208
+ metricName: 'JS_SDK_NETWORK_REQUEST_SUMMARY',
209
+ type: 'operational',
210
+ fields: {
211
+ totalSendRequest: 14,
212
+ totalFailedRequest: 1,
213
+ totalRecvdResponse: 13,
214
+ totalFailedResponse: 1
215
+ },
216
+ eventPayload: {
217
+ metricsSummary: {
218
+ totalSendRequest: 14,
219
+ totalFailedRequest: 1,
220
+ totalRecvdResponse: 13,
221
+ totalFailedResponse: 1
222
+ },
223
+ metrics: [{
224
+ host: 'hydra',
225
+ endPoint: 'rooms/:id/messages',
226
+ countSendRequest: 2,
227
+ countFailedRequest: 0,
228
+ countRecvdResponse: 2,
229
+ countFailedResponse: 1,
230
+ averageNetworkDurationMs: 410,
231
+ maxNetworkDurationP90Ms: 510,
232
+ maxNetworkDurationP99Ms: 640
233
+ }],
234
+ errorMetrics: [{
235
+ host: 'hydra',
236
+ endPoint: 'rooms/:id/messages',
237
+ statusCode: 503,
238
+ errorCode: 'SERVICE_UNAVAILABLE',
239
+ method: 'POST',
240
+ errorType: 'server_error',
241
+ errorMessage: 'Service unavailable',
242
+ trackingIds: ['example-tracking-id'],
243
+ countError: 1
244
+ }],
245
+ errorMetricsSummary: {
246
+ 503: {count: 1}
247
+ }
248
+ }
249
+ }
250
+ ```
251
+
252
+ ### Failure classification
253
+
254
+ Classification is evaluated in the following order:
255
+
256
+ | Condition | `errorType` |
257
+ | --------------------------------------------------------------------------------------------------------- | --------------- |
258
+ | Error name is `AbortError` | `aborted` |
259
+ | Status is `408` or `504`, timeout appears in the error details, or the configured request timeout elapsed | `timeout` |
260
+ | Status is `429` | `rate_limited` |
261
+ | Status is `5xx` | `server_error` |
262
+ | Status is `4xx` | `client_error` |
263
+ | No response status is available, or the error name contains `network` | `network_error` |
264
+ | Any other SDK request failure | `request_error` |
265
+
266
+ ### Telemetry request exclusion
267
+
268
+ Requests to the `metrics` and `unifiedTelemetry` services are excluded from both success and failure collection. The exclusion also covers the legacy `api: 'metrics'` request option. This prevents a telemetry upload from affecting its own summary.
269
+
270
+ The exclusion is centralized in the collector; telemetry request call sites do not require special flags.
271
+
272
+ ### Endpoint normalization and cardinality
273
+
274
+ The `endPoint` value is derived from `options.resource`, or from the URI path for a direct-URI request:
275
+
276
+ - Query parameters and fragments are removed.
277
+ - Numeric, percent-encoded, uppercase, and otherwise non-route-looking segments are replaced with `:id`.
278
+
279
+ For example:
280
+
281
+ ```text
282
+ rooms/Y2lzY29zcGFyazovL3VzL1JPT00/messages?personId=secret
283
+ ```
284
+
285
+ becomes:
286
+
287
+ ```text
288
+ rooms/:id/messages
289
+ ```
290
+
291
+ Endpoint normalization is heuristic. A short lowercase alphabetic identifier can resemble a static route segment. Do not place sensitive values directly in a resource path; use normal SDK resource identifiers and avoid embedding credentials or personal data in route names. Error messages are included because they are part of the requested error aggregate schema; callers should not put credentials or personal data in thrown error messages.
292
+
293
+ ### Submission behavior
294
+
295
+ Each ten-minute summary uses the existing `submitClientMetrics()` batching and transport path. The accumulator resets at the reporting boundary before asynchronous submission, so requests received while a summary is being sent belong to the next window. A telemetry submission failure is caught and logged.
296
+
297
+ ### Tests
298
+
299
+ Run the focused unit tests with Node.js 22.14:
300
+
301
+ ```bash
302
+ nvm use 22.14
303
+ yarn workspace @webex/internal-plugin-metrics test:unit --targets network-telemetry.ts
66
304
  ```
67
305
 
68
306
  ## Maintainers
@@ -354,6 +354,22 @@ var CallDiagnosticMetrics = exports.default = /*#__PURE__*/function (_StatelessW
354
354
  throw new Error("ClientType and SubClientType can't be undefined");
355
355
  }
356
356
 
357
+ /**
358
+ * Returns the signed-in user's CI ID derived from credentials tokens.
359
+ * Used as a fallback when no device is registered.
360
+ * @returns the userId, or undefined if it can't be determined
361
+ */
362
+ }, {
363
+ key: "getUserIdFromCredentials",
364
+ value: function getUserIdFromCredentials() {
365
+ try {
366
+ // @ts-ignore
367
+ return this.webex.credentials.getUserId();
368
+ } catch (_unused) {
369
+ return undefined;
370
+ }
371
+ }
372
+
357
373
  /**
358
374
  * Gather identifier details for call diagnostic payload.
359
375
  * @throws Error if initialization fails.
@@ -362,7 +378,7 @@ var CallDiagnosticMetrics = exports.default = /*#__PURE__*/function (_StatelessW
362
378
  }, {
363
379
  key: "getIdentifiers",
364
380
  value: function getIdentifiers(options) {
365
- var _meeting$locusInfo, _meeting$meetingInfo2, _meeting$meetingInfo3, _meeting$meetingInfo6, _meeting$meetingInfo8;
381
+ var _this$device, _meeting$locusInfo, _meeting$meetingInfo2, _meeting$meetingInfo3, _meeting$meetingInfo6, _meeting$meetingInfo8;
366
382
  var meeting = options.meeting,
367
383
  mediaConnections = options.mediaConnections,
368
384
  correlationId = options.correlationId,
@@ -395,7 +411,6 @@ var CallDiagnosticMetrics = exports.default = /*#__PURE__*/function (_StatelessW
395
411
  var device = this.device;
396
412
  var _ref3 = (device === null || device === void 0 ? void 0 : device.config) || {},
397
413
  installationId = _ref3.installationId;
398
- identifiers.userId = (device === null || device === void 0 ? void 0 : device.userId) || preLoginId;
399
414
  identifiers.deviceId = device === null || device === void 0 ? void 0 : device.url;
400
415
  identifiers.orgId = device === null || device === void 0 ? void 0 : device.orgId;
401
416
  // @ts-ignore
@@ -404,6 +419,10 @@ var CallDiagnosticMetrics = exports.default = /*#__PURE__*/function (_StatelessW
404
419
  identifiers.machineId = installationId;
405
420
  }
406
421
  }
422
+
423
+ // Prefer the device's userId, but fall back to the signed-in user's ID from
424
+ // credentials when no device is registered, then to the pre-login ID.
425
+ identifiers.userId = ((_this$device = this.device) === null || _this$device === void 0 ? void 0 : _this$device.userId) || this.getUserIdFromCredentials() || preLoginId;
407
426
  if (meeting !== null && meeting !== void 0 && (_meeting$locusInfo = meeting.locusInfo) !== null && _meeting$locusInfo !== void 0 && _meeting$locusInfo.fullState) {
408
427
  identifiers.locusUrl = meeting.locusUrl;
409
428
  identifiers.locusId = meeting.locusUrl && meeting.locusUrl.split('/').pop();