@libo11y/rum 0.4.0 → 0.7.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 (68) 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 +30 -15
  22. package/dist/contracts/session.d.ts +12 -1
  23. package/dist/contracts/summary.d.ts +15 -4
  24. package/dist/contracts/views.d.ts +3 -3
  25. package/dist/core-setup.d.ts +43 -8
  26. package/dist/core-setup.js +300 -82
  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.d.ts +2 -2
  45. package/dist/session/manager.js +18 -2
  46. package/dist/session/sampling.js +1 -1
  47. package/dist/setup.d.ts +3 -1
  48. package/dist/setup.js +14 -6
  49. package/dist/span-processor.d.ts +3 -3
  50. package/dist/span-processor.js +2 -2
  51. package/dist/summary/accumulator.d.ts +11 -5
  52. package/dist/summary/accumulator.js +27 -6
  53. package/dist/version.d.ts +1 -1
  54. package/dist/version.js +1 -1
  55. package/dist/views/collector.js +8 -7
  56. package/dist/views/naming.d.ts +1 -1
  57. package/dist/views/naming.js +1 -1
  58. package/dist/views/tracker.d.ts +15 -6
  59. package/dist/views/tracker.js +10 -13
  60. package/dist/vitals/collector.js +2 -2
  61. package/dist/webext/config-storage.d.ts +15 -4
  62. package/dist/webext/config-storage.js +78 -27
  63. package/dist/webext/scope.d.ts +1 -1
  64. package/dist/webext/session-store.js +12 -2
  65. package/dist/webext/setup.d.ts +5 -2
  66. package/dist/webext/setup.js +29 -16
  67. package/dist/webext.d.ts +1 -1
  68. 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,23 +299,26 @@ 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({
207
307
  platform,
208
- emit: (attrs) => telemetry?.event(EVENT_RUM_VIEW_SUMMARY, attrs),
308
+ emit: (attrs) => telemetry?.event(EVENT_RUM_VIEW_SUMMARY, attrs) ?? false,
209
309
  now: deps.perfNow,
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);
@@ -430,13 +563,16 @@ export async function setupRumCore(options, rumOptions, deps) {
430
563
  settings: () => settings,
431
564
  now: deps.perfNow,
432
565
  timeOrigin: deps.timeOrigin ?? performance.timeOrigin,
433
- emit(name, attrs = {}, ctx, body) {
434
- if (!gate.recording())
435
- return;
436
- const s = session.current();
437
- const v = views.current();
566
+ emit(name, attrs = {}, ctx, body, time) {
567
+ if (sdkDisabled || !gate.recording())
568
+ return false;
569
+ // An event of something earlier carries only what its caller knows of that time: the
570
+ // session, view, user and event attributes current now may not be its own.
571
+ const earlier = time !== undefined;
572
+ const s = earlier ? undefined : session.current();
573
+ const v = earlier ? undefined : views.current();
438
574
  let decorated = {};
439
- for (const d of decorators) {
575
+ for (const d of earlier ? [] : decorators) {
440
576
  if (!d.names.has(name))
441
577
  continue;
442
578
  try {
@@ -449,15 +585,14 @@ export async function setupRumCore(options, rumOptions, deps) {
449
585
  const merged = {
450
586
  ...(s === undefined ? {} : { [ATTR_SESSION_ID]: s.id }),
451
587
  ...(v === undefined ? {} : { [ATTR_RUM_VIEW_ID]: v.id }),
452
- ...(userId === undefined ? {} : { [ATTR_USER_ID]: userId }),
588
+ ...(userId === undefined || earlier ? {} : { [ATTR_USER_ID]: userId }),
453
589
  ...decorated,
454
590
  ...attrs,
455
591
  };
456
- if (body === undefined) {
457
- t.event(name, merged, ctx);
458
- return;
459
- }
592
+ if (body === undefined)
593
+ return t.event(name, merged, ctx, time === undefined ? undefined : new Date(time));
460
594
  bodyLogger.emit({
595
+ ...(time === undefined ? {} : { timestamp: time }),
461
596
  eventName: name,
462
597
  severityNumber: SeverityNumber.INFO,
463
598
  severityText: "INFO",
@@ -466,6 +601,7 @@ export async function setupRumCore(options, rumOptions, deps) {
466
601
  // Body events report page-level values at a hide, so the span active then is unrelated.
467
602
  context: ctx ?? ROOT_CONTEXT,
468
603
  });
604
+ return true;
469
605
  },
470
606
  onRequestStart(hook) {
471
607
  hooks.add(hook);
@@ -492,7 +628,7 @@ export async function setupRumCore(options, rumOptions, deps) {
492
628
  [...collectorUrls.values()].some((own) => `${u.origin}${u.pathname}` === own) ||
493
629
  isIgnored(u, ignoreUrls));
494
630
  },
495
- remoteDocument: () => (remote === undefined ? undefined : remote.find(session.current()?.configVersion)),
631
+ remoteDocument: () => sessionDocument(session.current()),
496
632
  addEventAttributes(names, attrs) {
497
633
  const d = { names: new Set(names), attrs };
498
634
  decorators.add(d);
@@ -512,6 +648,7 @@ export async function setupRumCore(options, rumOptions, deps) {
512
648
  return () => collectorUrls.delete(key);
513
649
  },
514
650
  };
651
+ deps.onRuntime?.(runtime);
515
652
  // Collectors run only while consent is granted, remote configuration has not switched RUM off,
516
653
  // and the current session's settings enable them.
517
654
  const running = new Map();
@@ -560,7 +697,7 @@ export async function setupRumCore(options, rumOptions, deps) {
560
697
  pending.discard();
561
698
  return;
562
699
  }
563
- settings = forSession(session.current()?.configVersion);
700
+ settings = forSession(session.current());
564
701
  views.begin();
565
702
  // Spans that started while the session loaded, such as app_load right after a late grant.
566
703
  const s = session.current();
@@ -605,8 +742,9 @@ export async function setupRumCore(options, rumOptions, deps) {
605
742
  else if (!off && collecting) {
606
743
  // The document the current session started under may only now be known, as when another
607
744
  // tab started the session under a document this tab had not fetched yet.
608
- settings = forSession(session.current()?.configVersion);
745
+ settings = forSession(session.current());
609
746
  reconcile();
747
+ bus.publish({ type: "config" });
610
748
  }
611
749
  };
612
750
  const openRemote = () => {
@@ -618,28 +756,35 @@ export async function setupRumCore(options, rumOptions, deps) {
618
756
  diag.warn("o11y: rum: remote configuration has no URL or no fetch; it is off");
619
757
  return undefined;
620
758
  }
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
- });
759
+ const connect = (storage) => {
760
+ configCache = storage;
761
+ return rc.open({
762
+ url,
763
+ fetch: f,
764
+ storage,
765
+ timers: {
766
+ setTimeout: (cb, ms) => setTimeout(cb, ms),
767
+ clearTimeout: (h) => clearTimeout(h),
768
+ },
769
+ visible: shown,
770
+ });
771
+ };
631
772
  let storage;
632
773
  try {
633
774
  storage = deps.storage?.();
634
775
  }
635
776
  catch {
636
- storage = undefined;
777
+ // No storage: remote configuration caches nothing.
637
778
  }
638
779
  return storage instanceof Promise ? storage.then(connect, () => connect(undefined)) : connect(storage);
639
780
  };
640
781
  /** The connection being opened, while its cache storage loads. */
641
782
  let opening;
783
+ /** The storage the connection caches in, for its flush. */
784
+ let configCache;
642
785
  const startAll = () => {
786
+ if (sdkDisabled)
787
+ return Promise.resolve();
643
788
  everStarted = true;
644
789
  const gen = generation;
645
790
  pending.open();
@@ -667,7 +812,13 @@ export async function setupRumCore(options, rumOptions, deps) {
667
812
  await activate(gen);
668
813
  if (gen !== generation || !gate.recording())
669
814
  return;
670
- stopRemote = remote?.start(onRemote);
815
+ // A refresh that changed nothing (a 304) may still find the session's own document, which
816
+ // another tab pinned since. A session without a version finds none.
817
+ stopRemote = remote?.start(onRemote, () => {
818
+ const s = session.current();
819
+ if (pinned?.id !== s?.id && sessionDocument(s))
820
+ onRemote(remote?.current());
821
+ });
671
822
  }
672
823
  catch (err) {
673
824
  // A start that failed releases the spans waiting for its session, so no export stalls.
@@ -688,18 +839,24 @@ export async function setupRumCore(options, rumOptions, deps) {
688
839
  starting = undefined;
689
840
  };
690
841
  const flushRetention = async () => {
842
+ // A revoke or shutdown meanwhile (stopAll) ends this flush, even once a new grant records again.
843
+ const gen = generation;
844
+ const still = () => gen === generation && gate.recording();
691
845
  reportFlush(t, "rum: retention flush", await t.forceFlush());
692
846
  await settled();
693
- if (delivery !== undefined && gate.recording())
694
- await retention.flush(delivery, keep);
847
+ if (still())
848
+ for (const h of holders())
849
+ h.release();
850
+ if (delivery !== undefined && still())
851
+ await retention.flush(delivery, keep, still);
695
852
  };
696
- // Session end (decision P13): when tabs rotate an expired session at the same moment, each ends
853
+ // Session end: when tabs rotate an expired session at the same moment, each ends
697
854
  // it and starts a session of its own, then all adopt the same newest one. The tab whose session
698
855
  // won emits o11y.rum.session.end, so it is emitted once: each tab waits SESSION_END_ELECTION_MILLIS
699
856
  // for the others' broadcasts and emits only if its successor is still the current session. An
700
857
  // unkept session that ends removes only its own records from the shared retention buffer.
701
858
  //
702
- // Session start (R3f): the o11y.rum.session.start of a kept session waits for the same election,
859
+ // Session start: the o11y.rum.session.start of a kept session waits for the same election,
703
860
  // so only the session every context ends up sharing sends its start. That covers two tabs rotating at once and two
704
861
  // contexts that both find nothing stored and create the first session, as an extension's side
705
862
  // panel and content script do, each before it hears of the other's. A context whose session lost
@@ -725,7 +882,7 @@ export async function setupRumCore(options, rumOptions, deps) {
725
882
  const offSession = session.subscribe((e) => {
726
883
  if (e.type === "start") {
727
884
  // A new session takes the newest document; an adopted one, the document it started under.
728
- settings = forSession(e.session.configVersion);
885
+ settings = forSession(e.session);
729
886
  queueMicrotask(reconcile);
730
887
  }
731
888
  // While remote configuration has switched RUM off, a rotation sends no session events.
@@ -755,6 +912,8 @@ export async function setupRumCore(options, rumOptions, deps) {
755
912
  else if (e.type === "end" && e.local) {
756
913
  const ended = e.session;
757
914
  if (ended.retained === undefined) {
915
+ for (const h of holders())
916
+ h.discard(ended.id);
758
917
  void (async () => {
759
918
  await settled();
760
919
  await retention.discard((b) => sessionsIn(b)?.has(ended.id) === true);
@@ -790,16 +949,57 @@ export async function setupRumCore(options, rumOptions, deps) {
790
949
  summary.reset();
791
950
  views.end();
792
951
  session.clear();
952
+ pinned = undefined;
953
+ for (const h of holders())
954
+ h.discard();
793
955
  };
794
- const offRevoke = gate.onRevoke(async () => {
795
- if (!everStarted)
956
+ /** Removes the configuration cache, opening its storage when this page has not. */
957
+ const clearConfigCache = async () => {
958
+ const connection = remote ?? (await opening);
959
+ if (connection !== undefined) {
960
+ connection.clear();
961
+ await configCache?.flush?.();
796
962
  return;
963
+ }
964
+ let storage;
965
+ try {
966
+ storage = await deps.storage?.();
967
+ storage?.removeItem(CONFIG_STORAGE_KEY);
968
+ storage?.removeItem(CONFIG_PINNED_STORAGE_KEY);
969
+ }
970
+ catch (err) {
971
+ diag.debug("o11y: rum: removing the remote configuration cache failed", err);
972
+ }
973
+ await storage?.flush?.();
974
+ };
975
+ /**
976
+ * Asks every collector to remove what it stored. One that fails keeps no other from it. Replay in a
977
+ * scoped context (a content script) stored nothing, and its storage there is the host page's.
978
+ */
979
+ const clearCollectors = async () => {
980
+ const cs = resolved.collectors.filter((c) => deps.scope === undefined || c.name !== "replay");
981
+ for (const r of await Promise.allSettled(cs.map(async (c) => c.clear?.()))) {
982
+ if (r.status === "rejected")
983
+ diag.debug("o11y: rum: a collector failed to remove what it stored", r.reason);
984
+ }
985
+ };
986
+ /**
987
+ * Removes what RUM stored, in this page or an earlier one: the session, the configuration cache,
988
+ * the retention buffer and what each collector stored. Resolves once stores that write
989
+ * asynchronously have removed them.
990
+ */
991
+ const forgetStored = async () => {
992
+ // A session started in this page was removed by session.clear when the gate closed.
993
+ if (!everStarted)
994
+ sessionStore.save(undefined);
995
+ await Promise.all([clearConfigCache(), retention.clear(), clearCollectors()]);
996
+ await sessionStore.flush?.();
997
+ };
998
+ const offRevoke = gate.onRevoke(async () => {
797
999
  await settled();
798
1000
  // 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
- }
1001
+ if (!gate.recording())
1002
+ await forgetStored();
803
1003
  });
804
1004
  const offGate = gate.subscribe((recording) => {
805
1005
  if (recording)
@@ -819,7 +1019,7 @@ export async function setupRumCore(options, rumOptions, deps) {
819
1019
  };
820
1020
  const offActivity = lifecycle.activity?.(onActivity);
821
1021
  const rum = {
822
- sessionId: () => (gate.recording() ? session.current()?.id : undefined),
1022
+ sessionId: () => (!sdkDisabled && gate.recording() ? session.current()?.id : undefined),
823
1023
  identify(id) {
824
1024
  if (id?.includes("@")) {
825
1025
  throw new O11yError("INVALID_OPTION", "rum.identify: an email address is not a pseudonymous ID");
@@ -833,7 +1033,7 @@ export async function setupRumCore(options, rumOptions, deps) {
833
1033
  return;
834
1034
  const cause = active?.isRecording() === true ? active.spanContext() : undefined;
835
1035
  views.start({
836
- kind: "soft",
1036
+ kind: deps.viewKind ?? "soft",
837
1037
  ...(o?.name === undefined ? {} : { name: o.name }),
838
1038
  ...(cause === undefined ? {} : { cause }),
839
1039
  });
@@ -865,6 +1065,8 @@ export async function setupRumCore(options, rumOptions, deps) {
865
1065
  let shutdownPromise;
866
1066
  handle.shutdown = (opts) => {
867
1067
  shutdownPromise ??= (async () => {
1068
+ const deadline = shutdownMillis(opts?.timeoutMillis);
1069
+ const started = Date.now();
868
1070
  stopAll();
869
1071
  views.end();
870
1072
  summary.flush();
@@ -880,18 +1082,34 @@ export async function setupRumCore(options, rumOptions, deps) {
880
1082
  const report = await webShutdown(opts);
881
1083
  views.close();
882
1084
  session.close();
883
- await settled();
1085
+ // A holding exporter whose shutdown outlived core's deadline still stops its exporter. Buffer
1086
+ // writes, and then the holding exporters' stops, get what is left of the same deadline.
1087
+ const closing = Promise.all(holders().map((h) => h.close()));
1088
+ const left = () => Math.max(0, deadline - (Date.now() - started));
1089
+ const done = await within(left(), settled());
1090
+ await within(left(), closing);
884
1091
  retention.close();
885
- return report;
1092
+ if (done)
1093
+ return report;
1094
+ return {
1095
+ ok: false,
1096
+ errors: [
1097
+ ...report.errors,
1098
+ { signal: "lifecycle", error: new Error("o11y: shutdown rum retention: deadline exceeded") },
1099
+ ],
1100
+ };
886
1101
  })();
887
1102
  return shutdownPromise;
888
1103
  };
889
- // The bootstrap buffer (decision P9) is replayed only into the start setup makes with consent
1104
+ // The bootstrap buffer is replayed only into the start setup makes with consent
890
1105
  // granted. A page that starts pending discards it, even if consent is granted later. It is taken
891
1106
  // before the collectors start, so an event is never both buffered and seen by a collector; one
892
1107
  // that happens while the session loads, between the two, is not recorded.
893
1108
  const replay = deps.bootstrap?.();
894
- if (gate.recording()) {
1109
+ // A denied start removes what an earlier page stored, as revoking would.
1110
+ if (gate.consent.state() === "denied")
1111
+ await forgetStored();
1112
+ if (!sdkDisabled && gate.recording()) {
895
1113
  await startAll();
896
1114
  // A scoped context (a content script) shares its world with no page bootstrap of its own: what
897
1115
  // a bootstrap there buffered may be the host page's, so it is dropped.