@libo11y/rum 0.4.0 → 0.6.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.
Files changed (67) hide show
  1. package/README.md +37 -20
  2. package/dist/actions/collector.js +2 -2
  3. package/dist/actions/naming.d.ts +1 -1
  4. package/dist/actions/naming.js +1 -1
  5. package/dist/actions/record.d.ts +1 -1
  6. package/dist/actions/record.js +1 -1
  7. package/dist/actions/settle.d.ts +1 -1
  8. package/dist/actions/settle.js +1 -1
  9. package/dist/bind.d.ts +1 -1
  10. package/dist/bootstrap/buffer.d.ts +1 -1
  11. package/dist/bootstrap/buffer.js +1 -1
  12. package/dist/bootstrap/replay.d.ts +1 -1
  13. package/dist/config/clamp.d.ts +2 -2
  14. package/dist/config/clamp.js +2 -2
  15. package/dist/config/remote.d.ts +30 -7
  16. package/dist/config/remote.js +78 -46
  17. package/dist/context-manager.d.ts +1 -1
  18. package/dist/context-manager.js +1 -1
  19. package/dist/contracts/binding.d.ts +4 -2
  20. package/dist/contracts/retention.d.ts +7 -3
  21. package/dist/contracts/runtime.d.ts +24 -14
  22. package/dist/contracts/session.d.ts +6 -1
  23. package/dist/contracts/summary.d.ts +2 -2
  24. package/dist/contracts/views.d.ts +3 -3
  25. package/dist/core-setup.d.ts +43 -8
  26. package/dist/core-setup.js +286 -71
  27. package/dist/core.d.ts +13 -9
  28. package/dist/core.js +6 -5
  29. package/dist/errors/breadcrumbs.d.ts +1 -1
  30. package/dist/errors/breadcrumbs.js +1 -1
  31. package/dist/errors/record.d.ts +1 -1
  32. package/dist/errors/record.js +1 -1
  33. package/dist/frustration/detect.d.ts +1 -1
  34. package/dist/index.d.ts +1 -1
  35. package/dist/internal.d.ts +15 -9
  36. package/dist/internal.js +4 -5
  37. package/dist/pending-spans.d.ts +1 -1
  38. package/dist/query.d.ts +1 -1
  39. package/dist/query.js +1 -1
  40. package/dist/retention/buffer.d.ts +9 -5
  41. package/dist/retention/buffer.js +41 -15
  42. package/dist/retention/exporters.d.ts +56 -2
  43. package/dist/retention/exporters.js +214 -0
  44. package/dist/session/manager.js +1 -1
  45. package/dist/session/sampling.js +1 -1
  46. package/dist/setup.d.ts +3 -1
  47. package/dist/setup.js +14 -6
  48. package/dist/span-processor.d.ts +3 -3
  49. package/dist/span-processor.js +2 -2
  50. package/dist/summary/accumulator.d.ts +7 -2
  51. package/dist/summary/accumulator.js +4 -2
  52. package/dist/version.d.ts +1 -1
  53. package/dist/version.js +1 -1
  54. package/dist/views/collector.js +8 -7
  55. package/dist/views/naming.d.ts +1 -1
  56. package/dist/views/naming.js +1 -1
  57. package/dist/views/tracker.d.ts +15 -6
  58. package/dist/views/tracker.js +10 -13
  59. package/dist/vitals/collector.js +2 -2
  60. package/dist/webext/config-storage.d.ts +15 -4
  61. package/dist/webext/config-storage.js +78 -27
  62. package/dist/webext/scope.d.ts +1 -1
  63. package/dist/webext/session-store.js +12 -2
  64. package/dist/webext/setup.d.ts +5 -2
  65. package/dist/webext/setup.js +29 -16
  66. package/dist/webext.d.ts +1 -1
  67. package/package.json +11 -8
@@ -1,5 +1,5 @@
1
1
  /**
2
- * setupRumCore: RUM over a platform binding (decision P1, R3f, R5a). In order: settings, the
2
+ * setupRumCore: RUM over a platform binding. In order: settings, the
3
3
  * retention buffer (opened lazily), the session manager, the bus, the summary accumulator, the
4
4
  * view tracker, the span processor, then the binding, which runs the platform's setup with RUM's
5
5
  * wrappers. After setup: consent wiring (collectors run only while granted), session events, hide
@@ -18,9 +18,21 @@
18
18
  * injects its own spanExporter keeps it, routed by session; one that injects only a spanProcessor
19
19
  * keeps sole charge of span export.
20
20
  *
21
+ * Only spans and log records routed to OTLP wait in the retention buffer, which sends through the
22
+ * platform's delivery. Those of the console route, and those of an exporter the app injected, wait
23
+ * in memory instead (holdingSpanExporter, holdingLogExporter) and go to their own exporter once
24
+ * their session is kept.
25
+ *
21
26
  * Consent. Closing the gate stops RUM at once, in the gate listener, so a grant that follows a
22
- * revoke before the revoke hooks finish starts RUM again. The revoke hook then empties the
23
- * retention buffer. A page that never had consent touches no RUM storage on revoke.
27
+ * revoke before the revoke hooks finish starts RUM again. The revoke hook then removes the stored
28
+ * session, the configuration cache and the retention buffer, and waits for stores that write
29
+ * asynchronously. A start that is denied (consent.initial, or a respected privacy signal) removes
30
+ * them too, before setup resolves, so a later grant never resumes what an earlier page stored. A
31
+ * pending start touches no RUM storage.
32
+ *
33
+ * OTEL_SDK_DISABLED=true (outside hermetic mode) disables RUM as core disables its providers: no
34
+ * session, collector, remote configuration or bootstrap replay starts, on a grant or otherwise. A
35
+ * denied start and a revoke still remove what an earlier page stored.
24
36
  */
25
37
  import { O11yError } from "@libo11y/core";
26
38
  import { ATTR_RUM_CONFIG_VERSION, ATTR_RUM_CONNECTION_EFFECTIVE, ATTR_RUM_PLATFORM, ATTR_RUM_SESSION_RETAINED, ATTR_RUM_VIEW_ID, EVENT_NAME_KEY, EVENT_RUM_SESSION_END, EVENT_RUM_SESSION_START, EVENT_RUM_VIEW_SUMMARY, RUM_CONNECTION_EFFECTIVE_VALUES, } from "@libo11y/spec";
@@ -31,12 +43,13 @@ import { ConsoleSpanExporter } from "@opentelemetry/sdk-trace";
31
43
  import { recordInstantAction } from "./actions/record.js";
32
44
  import { ATTR_SESSION_ID, ATTR_USER_ID } from "./attrs.js";
33
45
  import { createBus } from "./bus.js";
46
+ import { CONFIG_PINNED_STORAGE_KEY, CONFIG_STORAGE_KEY, } from "./config/remote.js";
34
47
  import { rumContextManager } from "./context-manager.js";
35
48
  import { createBreadcrumbs } from "./errors/breadcrumbs.js";
36
49
  import { recordError } from "./errors/record.js";
37
50
  import { createPendingSpans } from "./pending-spans.js";
38
51
  import { createRetentionBuffer, RETENTION_QUEUE_DEFAULTS } from "./retention/buffer.js";
39
- import { retainingSpanExporter, withRetention } from "./retention/exporters.js";
52
+ import { holdingLogExporter, holdingSpanExporter, retainingLogExporter, retainingSpanExporter, } from "./retention/exporters.js";
40
53
  import { sessionsIn } from "./retention/sessions.js";
41
54
  import { createSessionManager } from "./session/manager.js";
42
55
  import { resolveSettings } from "./settings.js";
@@ -53,7 +66,7 @@ export function runtimeOf(telemetry) {
53
66
  function composeProcessors(first, second) {
54
67
  if (second === undefined)
55
68
  return first;
56
- return {
69
+ const composed = {
57
70
  onStart: (s, c) => {
58
71
  first.onStart(s, c);
59
72
  second.onStart(s, c);
@@ -69,6 +82,15 @@ function composeProcessors(first, second) {
69
82
  await Promise.all([first.shutdown(), second.shutdown()]);
70
83
  },
71
84
  };
85
+ if (first.onEnding !== undefined || second.onEnding !== undefined) {
86
+ const a = first.onEnding?.bind(first);
87
+ const b = second.onEnding?.bind(second);
88
+ composed.onEnding = (span) => {
89
+ a?.(span);
90
+ b?.(span);
91
+ };
92
+ }
93
+ return composed;
72
94
  }
73
95
  const SUCCESS = { code: ExportResultCode.SUCCESS };
74
96
  /** How long a tab that ended a session waits to hear whether another tab's rotation won. */
@@ -109,6 +131,48 @@ function forwardingSpanExporter(target, pending) {
109
131
  },
110
132
  };
111
133
  }
134
+ /** LifecycleOptions.timeoutMillis when none is given, as in core. */
135
+ const DEFAULT_SHUTDOWN_MILLIS = 5000;
136
+ /** The longest a timer can wait. */
137
+ const MAX_TIMER_MILLIS = 2_147_483_647;
138
+ /** The caller's shutdown deadline, read as core and web read it. */
139
+ function shutdownMillis(given) {
140
+ const ms = typeof given === "string" && given.trim() !== "" ? Number(given) : given;
141
+ if (typeof ms !== "number" || Number.isNaN(ms))
142
+ return DEFAULT_SHUTDOWN_MILLIS;
143
+ return Math.min(Math.max(ms, 0), MAX_TIMER_MILLIS);
144
+ }
145
+ /** True when work settles within ms, false when the deadline passes first. The timer never holds a process open. */
146
+ async function within(ms, work) {
147
+ let timer;
148
+ const expired = new Promise((resolve) => {
149
+ timer = setTimeout(() => resolve(false), ms);
150
+ timer.unref?.();
151
+ });
152
+ try {
153
+ return await Promise.race([work.then(() => true), expired]);
154
+ }
155
+ finally {
156
+ clearTimeout(timer);
157
+ }
158
+ }
159
+ /** OTEL_SDK_DISABLED as core reads it: ignored in hermetic mode, else true when it is "true" in any case. */
160
+ function sdkDisabledIn(hermetic, env) {
161
+ return !hermetic && (env.OTEL_SDK_DISABLED ?? "").trim().toLowerCase() === "true";
162
+ }
163
+ /**
164
+ * The OTLP protocol of traces: OTEL_EXPORTER_OTLP_TRACES_PROTOCOL, else OTEL_EXPORTER_OTLP_PROTOCOL,
165
+ * else http/json. Throws O11yError UNSUPPORTED_PROTOCOL for anything but http/json, the only
166
+ * protocol of the span exporter RUM builds.
167
+ */
168
+ function checkTracesProtocol(env) {
169
+ const protocol = (env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL ?? "").trim() ||
170
+ (env.OTEL_EXPORTER_OTLP_PROTOCOL ?? "").trim() ||
171
+ "http/json";
172
+ if (protocol !== "http/json") {
173
+ throw new O11yError("UNSUPPORTED_PROTOCOL", `o11y: unsupported OTLP protocol ${JSON.stringify(protocol)} for traces: RUM exports http/json only`);
174
+ }
175
+ }
112
176
  /** The traces route core would have resolved without RUM's injected processor and exporter. */
113
177
  function naturalTracesRoute(hermetic, env) {
114
178
  if (hermetic || (env.OTEL_SDK_DISABLED ?? "").trim().toLowerCase() === "true")
@@ -122,6 +186,19 @@ function naturalTracesRoute(hermetic, env) {
122
186
  return value;
123
187
  throw new O11yError("EXPORTER", `o11y: building span exporter: unknown exporter ${value}`);
124
188
  }
189
+ /**
190
+ * The logs route core resolves: none in hermetic mode or with the SDK disabled, else the first
191
+ * value of OTEL_LOGS_EXPORTER, default otlp. Core refuses an unknown value itself.
192
+ */
193
+ function naturalLogsRoute(hermetic, env) {
194
+ if (hermetic || (env.OTEL_SDK_DISABLED ?? "").trim().toLowerCase() === "true")
195
+ return "none";
196
+ const first = (env.OTEL_LOGS_EXPORTER ?? "")
197
+ .split(",")
198
+ .map((v) => v.trim().toLowerCase())
199
+ .find((v) => v !== "");
200
+ return first ?? "otlp";
201
+ }
125
202
  /** The remote configuration URL: base, else the export endpoint next to /v1/<signal>, with the service and client token. */
126
203
  function configUrl(base, endpoints, page, service, clientToken) {
127
204
  let raw = base;
@@ -155,30 +232,51 @@ function configUrl(base, endpoints, page, service, clientToken) {
155
232
  export async function setupRumCore(options, rumOptions, deps) {
156
233
  const resolved = resolveSettings(rumOptions);
157
234
  const platform = deps.platform;
158
- // Remote configuration (decisions P15, P16). The connection opens on the first grant. settings
235
+ // Remote configuration. The connection opens on the first grant. settings
159
236
  // are those of the current session: the document it started under, within the code's limits. A
160
237
  // new session takes the newest document. killed is the kill switch of the newest document.
161
238
  const rc = rumOptions?.remoteConfig;
162
239
  let remote;
163
240
  let killed = false;
164
241
  let settings = resolved;
165
- const forSession = (version) => remote === undefined ? resolved : remote.apply(resolved, remote.find(version));
242
+ /**
243
+ * The document the current session started under, once known. Newer documents push it out of the
244
+ * cache's newest two while the session runs, so it is kept here and pinned in the cache, where a
245
+ * reload or another tab resuming the session finds it.
246
+ */
247
+ let pinned;
248
+ const sessionDocument = (s) => {
249
+ if (remote === undefined || s === undefined)
250
+ return undefined;
251
+ if (pinned?.id === s.id && pinned.doc.version === s.configVersion)
252
+ return pinned.doc;
253
+ const doc = remote.find(s.configVersion);
254
+ if (doc !== undefined) {
255
+ pinned = { id: s.id, doc };
256
+ remote.pin?.(doc);
257
+ }
258
+ return doc;
259
+ };
260
+ /**
261
+ * A session started under a document this context has not got yet runs under the newest one until
262
+ * its own arrives, when onRemote reapplies. One started without a version keeps the code settings.
263
+ */
264
+ const forSession = (s) => remote === undefined
265
+ ? resolved
266
+ : remote.apply(resolved, sessionDocument(s) ?? (s?.configVersion === undefined ? undefined : remote.current()));
166
267
  const newest = () => remote === undefined ? resolved : remote.apply(resolved, remote.current());
167
268
  const retention = createRetentionBuffer({
168
269
  open: () => deps.openRetentionQueue({
169
270
  ...RETENTION_QUEUE_DEFAULTS,
170
- ...(rumOptions?.retention?.maxBytes === undefined ? {} : { maxBytes: rumOptions.retention.maxBytes }),
171
- ...(rumOptions?.retention?.maxAgeMillis === undefined
172
- ? {}
173
- : { maxAgeMillis: rumOptions.retention.maxAgeMillis }),
271
+ maxBytes: rumOptions?.retention?.maxBytes ?? RETENTION_QUEUE_DEFAULTS.maxBytes,
272
+ maxAgeMillis: rumOptions?.retention?.maxAgeMillis ?? RETENTION_QUEUE_DEFAULTS.maxAgeMillis,
174
273
  }),
175
274
  now: deps.now,
176
- ...(options.transport?.timeoutMillis === undefined
177
- ? {}
178
- : { sendTimeoutMillis: options.transport.timeoutMillis }),
275
+ sendTimeoutMillis: options.transport?.timeoutMillis,
179
276
  });
277
+ const sessionStore = deps.sessionStore();
180
278
  const session = createSessionManager({
181
- store: deps.sessionStore(),
279
+ store: sessionStore,
182
280
  sampleRate: () => newest().sessionSampleRate,
183
281
  idleMillis: resolved.sessionIdleMillis,
184
282
  maxMillis: resolved.sessionMaxMillis,
@@ -186,14 +284,14 @@ export async function setupRumCore(options, rumOptions, deps) {
186
284
  now: deps.now,
187
285
  });
188
286
  const bus = createBus();
189
- // The breadcrumb ring every error carries (decision P18): actions, view starts and requests.
287
+ // The breadcrumb ring every error carries: actions, view starts and requests.
190
288
  const crumbs = createBreadcrumbs();
191
289
  // A request that ends after a revoke must not leave a breadcrumb for the next grant.
192
290
  bus.subscribe((s) => {
193
291
  if (s.type === "breadcrumb" && controller?.recording() === true)
194
292
  crumbs.add(s.kind, s.label, s.at, s.key);
195
293
  });
196
- /** The open action, so requests started meanwhile become its children (decision P10). */
294
+ /** The open action, so requests started meanwhile become its children. */
197
295
  let active;
198
296
  const hooks = new Set();
199
297
  let userId;
@@ -201,6 +299,8 @@ export async function setupRumCore(options, rumOptions, deps) {
201
299
  let controller;
202
300
  let delivery;
203
301
  let endpoints;
302
+ /** OTEL_SDK_DISABLED is true in the platform's env: RUM starts nothing. */
303
+ let sdkDisabled = false;
204
304
  const lifecycle = deps.lifecycle;
205
305
  const shown = lifecycle.visible;
206
306
  const summary = createSummaryAccumulator({
@@ -210,14 +310,15 @@ export async function setupRumCore(options, rumOptions, deps) {
210
310
  visible: shown,
211
311
  context: () => {
212
312
  const c = deps.connection();
213
- return {
214
- ...(c !== undefined && RUM_CONNECTION_EFFECTIVE_VALUES.includes(c)
215
- ? { [ATTR_RUM_CONNECTION_EFFECTIVE]: c }
216
- : {}),
217
- ...(settings.configVersion === undefined
218
- ? {}
219
- : { [ATTR_RUM_CONFIG_VERSION]: settings.configVersion }),
220
- };
313
+ return c !== undefined && RUM_CONNECTION_EFFECTIVE_VALUES.includes(c)
314
+ ? { [ATTR_RUM_CONNECTION_EFFECTIVE]: c }
315
+ : {};
316
+ },
317
+ // The version of the session a view opens in, so a late vital of a view whose session has
318
+ // rotated since never carries the newer session's version.
319
+ origin: () => {
320
+ const v = session.current()?.configVersion;
321
+ return v === undefined ? {} : { [ATTR_RUM_CONFIG_VERSION]: v };
221
322
  },
222
323
  });
223
324
  // Every client request counts toward the current view's summary (o11y.rum.summary.requests).
@@ -232,8 +333,9 @@ export async function setupRumCore(options, rumOptions, deps) {
232
333
  location: deps.location,
233
334
  now: deps.perfNow,
234
335
  prerendered: deps.prerendered,
235
- ...(deps.window === undefined ? {} : { window: deps.window }),
236
- ...(deps.scope?.fixedView === true ? { initialStart: deps.perfNow } : {}),
336
+ window: deps.window,
337
+ initialStart: deps.scope?.fixedView === true ? deps.perfNow : deps.initialViewStart,
338
+ viewKind: deps.viewKind,
237
339
  });
238
340
  views.subscribe((e) => {
239
341
  if (e.type === "start") {
@@ -279,7 +381,7 @@ export async function setupRumCore(options, rumOptions, deps) {
279
381
  userId: () => userId,
280
382
  bus,
281
383
  now: deps.perfNow,
282
- ...(deps.timeOrigin === undefined ? {} : { timeOrigin: deps.timeOrigin }),
384
+ timeOrigin: deps.timeOrigin,
283
385
  });
284
386
  const onStart = (span, request) => {
285
387
  for (const h of hooks) {
@@ -320,7 +422,17 @@ export async function setupRumCore(options, rumOptions, deps) {
320
422
  /** Attributes collectors add to named events (addEventAttributes). */
321
423
  const decorators = new Set();
322
424
  const ignoreUrls = options.instrumentations?.ignoreUrls ?? [];
323
- let spanTarget = appExporter === undefined ? undefined : retainingSpanExporter(appExporter, routing);
425
+ // The retention buffer sends through the platform's delivery, so the spans and log records an
426
+ // app's own exporter or a console exporter would get wait in memory instead, and go to that
427
+ // exporter once their session is kept. A release that comes after a revoke exports nothing.
428
+ const holdOpts = { allowed: () => controller?.recording() === true };
429
+ let held = appExporter === undefined ? undefined : holdingSpanExporter(appExporter, routing.decide, holdOpts);
430
+ let spanTarget = held;
431
+ const appLogExporter = options.logExporter;
432
+ let heldLogs = appLogExporter === undefined ? undefined : holdingLogExporter(appLogExporter, routing.decide, holdOpts);
433
+ /** The logs route core resolves, once the platform's env is known. */
434
+ let logsRoute = "otlp";
435
+ const holders = () => [held, heldLogs].filter((h) => h !== undefined);
324
436
  const wrappers = {
325
437
  consentController: (c) => {
326
438
  controller = c;
@@ -331,17 +443,37 @@ export async function setupRumCore(options, rumOptions, deps) {
331
443
  delivery = po.delivery;
332
444
  endpoints = po.endpoints;
333
445
  ownUrls = OTLP_SIGNALS.flatMap((s) => (po.endpoints[s] === undefined ? [] : [po.endpoints[s]]));
446
+ sdkDisabled = sdkDisabledIn(options.hermetic === true, env);
447
+ logsRoute = naturalLogsRoute(options.hermetic === true, env);
334
448
  if (forward && appExporter === undefined) {
335
449
  const route = naturalTracesRoute(options.hermetic === true, env);
336
- const inner = route === "console"
337
- ? new ConsoleSpanExporter()
338
- : route === "otlp" && po.endpoints.traces !== undefined
339
- ? createSpanExporter(po.delivery, po.mode === undefined ? {} : { mode: po.mode })
340
- : undefined;
341
- spanTarget = inner === undefined ? undefined : retainingSpanExporter(inner, routing);
450
+ // Core checks the protocol only of a route it builds, and traces reach it injected.
451
+ if (route === "otlp")
452
+ checkTracesProtocol(env);
453
+ if (route === "console") {
454
+ held = holdingSpanExporter(new ConsoleSpanExporter(), routing.decide, holdOpts);
455
+ spanTarget = held;
456
+ }
457
+ else if (route === "otlp" && po.endpoints.traces !== undefined) {
458
+ const inner = createSpanExporter(po.delivery, po.mode === undefined ? {} : { mode: po.mode });
459
+ spanTarget = retainingSpanExporter(inner, routing);
460
+ }
461
+ else
462
+ spanTarget = undefined;
342
463
  }
343
464
  },
344
- exporterSet: (set) => withRetention(set, routing),
465
+ // Traces reach core injected, so the set's span exporter goes unused. Only OTLP log records wait
466
+ // in the retention buffer; console ones wait in memory.
467
+ exporterSet: (set) => {
468
+ const logs = set.logExporter;
469
+ if (logs === undefined)
470
+ return set;
471
+ if (logsRoute === "console") {
472
+ heldLogs = holdingLogExporter(logs, routing.decide, holdOpts);
473
+ return { ...set, logExporter: heldLogs };
474
+ }
475
+ return { ...set, logExporter: retainingLogExporter(logs, routing) };
476
+ },
345
477
  onRequestStart: onStart,
346
478
  };
347
479
  // Hide handling. On a navigation, every engine fires pagehide before visibilitychange, and web's
@@ -397,6 +529,7 @@ export async function setupRumCore(options, rumOptions, deps) {
397
529
  spanProcessor: composeProcessors(processor, options.spanProcessor),
398
530
  contextManager: () => rumContextManager((options.contextManager ?? createContextManager)(), () => active),
399
531
  ...(forward ? { spanExporter: forwardingSpanExporter(() => spanTarget, pending) } : {}),
532
+ ...(heldLogs === undefined ? {} : { logExporter: heldLogs }),
400
533
  }, wrappers);
401
534
  }
402
535
  catch (err) {
@@ -412,8 +545,8 @@ export async function setupRumCore(options, rumOptions, deps) {
412
545
  await t.shutdown();
413
546
  throw new O11yError("INVALID_OPTION", "rum: web setup built no consent controller");
414
547
  }
415
- /** RUM records: consent is granted and remote configuration has not switched it off. */
416
- const on = () => gate.recording() && !killed;
548
+ /** RUM records: the SDK is enabled, consent is granted and remote configuration has not switched it off. */
549
+ const on = () => !sdkDisabled && gate.recording() && !killed;
417
550
  // Events with a body (semconv's browser.web_vital) are bridge records: core's redacting log
418
551
  // processor classifies their attributes, and the retention exporters route them by session.id.
419
552
  const bodyLogger = t.loggerProvider.getLogger("@libo11y/rum", VERSION);
@@ -431,7 +564,7 @@ export async function setupRumCore(options, rumOptions, deps) {
431
564
  now: deps.perfNow,
432
565
  timeOrigin: deps.timeOrigin ?? performance.timeOrigin,
433
566
  emit(name, attrs = {}, ctx, body) {
434
- if (!gate.recording())
567
+ if (sdkDisabled || !gate.recording())
435
568
  return;
436
569
  const s = session.current();
437
570
  const v = views.current();
@@ -492,7 +625,7 @@ export async function setupRumCore(options, rumOptions, deps) {
492
625
  [...collectorUrls.values()].some((own) => `${u.origin}${u.pathname}` === own) ||
493
626
  isIgnored(u, ignoreUrls));
494
627
  },
495
- remoteDocument: () => (remote === undefined ? undefined : remote.find(session.current()?.configVersion)),
628
+ remoteDocument: () => sessionDocument(session.current()),
496
629
  addEventAttributes(names, attrs) {
497
630
  const d = { names: new Set(names), attrs };
498
631
  decorators.add(d);
@@ -512,6 +645,7 @@ export async function setupRumCore(options, rumOptions, deps) {
512
645
  return () => collectorUrls.delete(key);
513
646
  },
514
647
  };
648
+ deps.onRuntime?.(runtime);
515
649
  // Collectors run only while consent is granted, remote configuration has not switched RUM off,
516
650
  // and the current session's settings enable them.
517
651
  const running = new Map();
@@ -560,7 +694,7 @@ export async function setupRumCore(options, rumOptions, deps) {
560
694
  pending.discard();
561
695
  return;
562
696
  }
563
- settings = forSession(session.current()?.configVersion);
697
+ settings = forSession(session.current());
564
698
  views.begin();
565
699
  // Spans that started while the session loaded, such as app_load right after a late grant.
566
700
  const s = session.current();
@@ -605,8 +739,9 @@ export async function setupRumCore(options, rumOptions, deps) {
605
739
  else if (!off && collecting) {
606
740
  // The document the current session started under may only now be known, as when another
607
741
  // tab started the session under a document this tab had not fetched yet.
608
- settings = forSession(session.current()?.configVersion);
742
+ settings = forSession(session.current());
609
743
  reconcile();
744
+ bus.publish({ type: "config" });
610
745
  }
611
746
  };
612
747
  const openRemote = () => {
@@ -618,28 +753,35 @@ export async function setupRumCore(options, rumOptions, deps) {
618
753
  diag.warn("o11y: rum: remote configuration has no URL or no fetch; it is off");
619
754
  return undefined;
620
755
  }
621
- const connect = (storage) => rc.open({
622
- url,
623
- fetch: f,
624
- ...(storage === undefined ? {} : { storage }),
625
- timers: {
626
- setTimeout: (cb, ms) => setTimeout(cb, ms),
627
- clearTimeout: (h) => clearTimeout(h),
628
- },
629
- visible: shown,
630
- });
756
+ const connect = (storage) => {
757
+ configCache = storage;
758
+ return rc.open({
759
+ url,
760
+ fetch: f,
761
+ storage,
762
+ timers: {
763
+ setTimeout: (cb, ms) => setTimeout(cb, ms),
764
+ clearTimeout: (h) => clearTimeout(h),
765
+ },
766
+ visible: shown,
767
+ });
768
+ };
631
769
  let storage;
632
770
  try {
633
771
  storage = deps.storage?.();
634
772
  }
635
773
  catch {
636
- storage = undefined;
774
+ // No storage: remote configuration caches nothing.
637
775
  }
638
776
  return storage instanceof Promise ? storage.then(connect, () => connect(undefined)) : connect(storage);
639
777
  };
640
778
  /** The connection being opened, while its cache storage loads. */
641
779
  let opening;
780
+ /** The storage the connection caches in, for its flush. */
781
+ let configCache;
642
782
  const startAll = () => {
783
+ if (sdkDisabled)
784
+ return Promise.resolve();
643
785
  everStarted = true;
644
786
  const gen = generation;
645
787
  pending.open();
@@ -667,7 +809,13 @@ export async function setupRumCore(options, rumOptions, deps) {
667
809
  await activate(gen);
668
810
  if (gen !== generation || !gate.recording())
669
811
  return;
670
- stopRemote = remote?.start(onRemote);
812
+ // A refresh that changed nothing (a 304) may still find the session's own document, which
813
+ // another tab pinned since. A session without a version finds none.
814
+ stopRemote = remote?.start(onRemote, () => {
815
+ const s = session.current();
816
+ if (pinned?.id !== s?.id && sessionDocument(s))
817
+ onRemote(remote?.current());
818
+ });
671
819
  }
672
820
  catch (err) {
673
821
  // A start that failed releases the spans waiting for its session, so no export stalls.
@@ -688,18 +836,24 @@ export async function setupRumCore(options, rumOptions, deps) {
688
836
  starting = undefined;
689
837
  };
690
838
  const flushRetention = async () => {
839
+ // A revoke or shutdown meanwhile (stopAll) ends this flush, even once a new grant records again.
840
+ const gen = generation;
841
+ const still = () => gen === generation && gate.recording();
691
842
  reportFlush(t, "rum: retention flush", await t.forceFlush());
692
843
  await settled();
693
- if (delivery !== undefined && gate.recording())
694
- await retention.flush(delivery, keep);
844
+ if (still())
845
+ for (const h of holders())
846
+ h.release();
847
+ if (delivery !== undefined && still())
848
+ await retention.flush(delivery, keep, still);
695
849
  };
696
- // Session end (decision P13): when tabs rotate an expired session at the same moment, each ends
850
+ // Session end: when tabs rotate an expired session at the same moment, each ends
697
851
  // it and starts a session of its own, then all adopt the same newest one. The tab whose session
698
852
  // won emits o11y.rum.session.end, so it is emitted once: each tab waits SESSION_END_ELECTION_MILLIS
699
853
  // for the others' broadcasts and emits only if its successor is still the current session. An
700
854
  // unkept session that ends removes only its own records from the shared retention buffer.
701
855
  //
702
- // Session start (R3f): the o11y.rum.session.start of a kept session waits for the same election,
856
+ // Session start: the o11y.rum.session.start of a kept session waits for the same election,
703
857
  // so only the session every context ends up sharing sends its start. That covers two tabs rotating at once and two
704
858
  // contexts that both find nothing stored and create the first session, as an extension's side
705
859
  // panel and content script do, each before it hears of the other's. A context whose session lost
@@ -725,7 +879,7 @@ export async function setupRumCore(options, rumOptions, deps) {
725
879
  const offSession = session.subscribe((e) => {
726
880
  if (e.type === "start") {
727
881
  // A new session takes the newest document; an adopted one, the document it started under.
728
- settings = forSession(e.session.configVersion);
882
+ settings = forSession(e.session);
729
883
  queueMicrotask(reconcile);
730
884
  }
731
885
  // While remote configuration has switched RUM off, a rotation sends no session events.
@@ -755,6 +909,8 @@ export async function setupRumCore(options, rumOptions, deps) {
755
909
  else if (e.type === "end" && e.local) {
756
910
  const ended = e.session;
757
911
  if (ended.retained === undefined) {
912
+ for (const h of holders())
913
+ h.discard(ended.id);
758
914
  void (async () => {
759
915
  await settled();
760
916
  await retention.discard((b) => sessionsIn(b)?.has(ended.id) === true);
@@ -790,16 +946,57 @@ export async function setupRumCore(options, rumOptions, deps) {
790
946
  summary.reset();
791
947
  views.end();
792
948
  session.clear();
949
+ pinned = undefined;
950
+ for (const h of holders())
951
+ h.discard();
793
952
  };
794
- const offRevoke = gate.onRevoke(async () => {
795
- if (!everStarted)
953
+ /** Removes the configuration cache, opening its storage when this page has not. */
954
+ const clearConfigCache = async () => {
955
+ const connection = remote ?? (await opening);
956
+ if (connection !== undefined) {
957
+ connection.clear();
958
+ await configCache?.flush?.();
796
959
  return;
960
+ }
961
+ let storage;
962
+ try {
963
+ storage = await deps.storage?.();
964
+ storage?.removeItem(CONFIG_STORAGE_KEY);
965
+ storage?.removeItem(CONFIG_PINNED_STORAGE_KEY);
966
+ }
967
+ catch (err) {
968
+ diag.debug("o11y: rum: removing the remote configuration cache failed", err);
969
+ }
970
+ await storage?.flush?.();
971
+ };
972
+ /**
973
+ * Asks every collector to remove what it stored. One that fails keeps no other from it. Replay in a
974
+ * scoped context (a content script) stored nothing, and its storage there is the host page's.
975
+ */
976
+ const clearCollectors = async () => {
977
+ const cs = resolved.collectors.filter((c) => deps.scope === undefined || c.name !== "replay");
978
+ for (const r of await Promise.allSettled(cs.map(async (c) => c.clear?.()))) {
979
+ if (r.status === "rejected")
980
+ diag.debug("o11y: rum: a collector failed to remove what it stored", r.reason);
981
+ }
982
+ };
983
+ /**
984
+ * Removes what RUM stored, in this page or an earlier one: the session, the configuration cache,
985
+ * the retention buffer and what each collector stored. Resolves once stores that write
986
+ * asynchronously have removed them.
987
+ */
988
+ const forgetStored = async () => {
989
+ // A session started in this page was removed by session.clear when the gate closed.
990
+ if (!everStarted)
991
+ sessionStore.save(undefined);
992
+ await Promise.all([clearConfigCache(), retention.clear(), clearCollectors()]);
993
+ await sessionStore.flush?.();
994
+ };
995
+ const offRevoke = gate.onRevoke(async () => {
797
996
  await settled();
798
997
  // A grant may already have followed the revoke; its session's records are not to be removed.
799
- if (!gate.recording()) {
800
- remote?.clear();
801
- await retention.clear();
802
- }
998
+ if (!gate.recording())
999
+ await forgetStored();
803
1000
  });
804
1001
  const offGate = gate.subscribe((recording) => {
805
1002
  if (recording)
@@ -819,7 +1016,7 @@ export async function setupRumCore(options, rumOptions, deps) {
819
1016
  };
820
1017
  const offActivity = lifecycle.activity?.(onActivity);
821
1018
  const rum = {
822
- sessionId: () => (gate.recording() ? session.current()?.id : undefined),
1019
+ sessionId: () => (!sdkDisabled && gate.recording() ? session.current()?.id : undefined),
823
1020
  identify(id) {
824
1021
  if (id?.includes("@")) {
825
1022
  throw new O11yError("INVALID_OPTION", "rum.identify: an email address is not a pseudonymous ID");
@@ -833,7 +1030,7 @@ export async function setupRumCore(options, rumOptions, deps) {
833
1030
  return;
834
1031
  const cause = active?.isRecording() === true ? active.spanContext() : undefined;
835
1032
  views.start({
836
- kind: "soft",
1033
+ kind: deps.viewKind ?? "soft",
837
1034
  ...(o?.name === undefined ? {} : { name: o.name }),
838
1035
  ...(cause === undefined ? {} : { cause }),
839
1036
  });
@@ -865,6 +1062,8 @@ export async function setupRumCore(options, rumOptions, deps) {
865
1062
  let shutdownPromise;
866
1063
  handle.shutdown = (opts) => {
867
1064
  shutdownPromise ??= (async () => {
1065
+ const deadline = shutdownMillis(opts?.timeoutMillis);
1066
+ const started = Date.now();
868
1067
  stopAll();
869
1068
  views.end();
870
1069
  summary.flush();
@@ -880,18 +1079,34 @@ export async function setupRumCore(options, rumOptions, deps) {
880
1079
  const report = await webShutdown(opts);
881
1080
  views.close();
882
1081
  session.close();
883
- await settled();
1082
+ // A holding exporter whose shutdown outlived core's deadline still stops its exporter. Buffer
1083
+ // writes, and then the holding exporters' stops, get what is left of the same deadline.
1084
+ const closing = Promise.all(holders().map((h) => h.close()));
1085
+ const left = () => Math.max(0, deadline - (Date.now() - started));
1086
+ const done = await within(left(), settled());
1087
+ await within(left(), closing);
884
1088
  retention.close();
885
- return report;
1089
+ if (done)
1090
+ return report;
1091
+ return {
1092
+ ok: false,
1093
+ errors: [
1094
+ ...report.errors,
1095
+ { signal: "lifecycle", error: new Error("o11y: shutdown rum retention: deadline exceeded") },
1096
+ ],
1097
+ };
886
1098
  })();
887
1099
  return shutdownPromise;
888
1100
  };
889
- // The bootstrap buffer (decision P9) is replayed only into the start setup makes with consent
1101
+ // The bootstrap buffer is replayed only into the start setup makes with consent
890
1102
  // granted. A page that starts pending discards it, even if consent is granted later. It is taken
891
1103
  // before the collectors start, so an event is never both buffered and seen by a collector; one
892
1104
  // that happens while the session loads, between the two, is not recorded.
893
1105
  const replay = deps.bootstrap?.();
894
- if (gate.recording()) {
1106
+ // A denied start removes what an earlier page stored, as revoking would.
1107
+ if (gate.consent.state() === "denied")
1108
+ await forgetStored();
1109
+ if (!sdkDisabled && gate.recording()) {
895
1110
  await startAll();
896
1111
  // A scoped context (a content script) shares its world with no page bootstrap of its own: what
897
1112
  // a bootstrap there buffered may be the host page's, so it is dropped.