@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,6 @@
1
1
  import { EVENT_RUM_VIEW_SUMMARY } from "@libo11y/spec";
2
2
  import { serializeLogs, serializeSpans } from "@libo11y/web/portable";
3
+ import { diag } from "@opentelemetry/api";
3
4
  import { ExportResultCode } from "@opentelemetry/core";
4
5
  import { ATTR_SESSION_ID } from "../attrs.js";
5
6
  const SUCCESS = { code: ExportResultCode.SUCCESS };
@@ -37,6 +38,219 @@ export function retainingSpanExporter(inner, routing) {
37
38
  : { forceFlush: () => inner.forceFlush?.() ?? Promise.resolve() }),
38
39
  };
39
40
  }
41
+ /** The most spans holdingSpanExporter holds. Past it the oldest are dropped first. */
42
+ export const HELD_SPANS_MAX = 1000;
43
+ /** The most log records holdingLogExporter holds. Past it the oldest are dropped first. */
44
+ export const HELD_LOGS_MAX = 1000;
45
+ /** How long one export the holding exporters start may take before it counts as failed, as upstream's batch processors wait. */
46
+ const HELD_EXPORT_TIMEOUT_MILLIS = 30_000;
47
+ function asError(err) {
48
+ return err instanceof Error ? err : new Error(String(err));
49
+ }
50
+ function holding(inner, what, route, idOf, max, o) {
51
+ const allowed = o.allowed ?? (() => true);
52
+ const timeoutMillis = o.timeoutMillis ?? HELD_EXPORT_TIMEOUT_MILLIS;
53
+ let held = [];
54
+ let jobs = [];
55
+ /** An export whose caller is still waiting for it. */
56
+ let busy = false;
57
+ /** The inner exporter has not yet called back, even if the export timed out. */
58
+ let innerBusy = false;
59
+ let closed = false;
60
+ let epoch = 0;
61
+ /** The first release export that failed and was not yet reported by forceFlush or shutdown. */
62
+ let failure;
63
+ /** Waiting for every queued and in-flight export to finish. */
64
+ let idleWaiters = [];
65
+ let innerStopped;
66
+ /** Ends a shutdown that waits for a release, once close is called. */
67
+ let abort = () => { };
68
+ const aborted = new Promise((resolve) => {
69
+ abort = resolve;
70
+ });
71
+ const idle = () => !busy && jobs.length === 0 ? Promise.resolve() : new Promise((resolve) => idleWaiters.push(resolve));
72
+ const settleIdle = () => {
73
+ const waiters = idleWaiters;
74
+ idleWaiters = [];
75
+ for (const w of waiters)
76
+ w();
77
+ };
78
+ const stopInner = () => {
79
+ innerStopped ??= Promise.resolve().then(() => inner.shutdown());
80
+ return innerStopped;
81
+ };
82
+ const shutDown = () => ({
83
+ code: ExportResultCode.FAILED,
84
+ error: new Error(`o11y: rum: ${what} exporter is shut down`),
85
+ });
86
+ const timedOut = () => ({
87
+ code: ExportResultCode.FAILED,
88
+ error: new Error(`o11y: rum: exporting ${what} timed out`),
89
+ });
90
+ const pump = () => {
91
+ while (!busy) {
92
+ const job = jobs.shift();
93
+ if (job === undefined) {
94
+ settleIdle();
95
+ return;
96
+ }
97
+ // What waits for its turn after a revoke, or past a grant revoked since, exports nothing.
98
+ if (closed || !allowed() || job.epoch !== epoch) {
99
+ job.done(closed && !job.release ? shutDown() : SUCCESS);
100
+ continue;
101
+ }
102
+ // The inner exporter has yet to answer an export that timed out, and never exports two
103
+ // batches at once: what is queued meanwhile fails.
104
+ if (innerBusy) {
105
+ job.done(timedOut());
106
+ continue;
107
+ }
108
+ busy = true;
109
+ innerBusy = true;
110
+ let answered = false;
111
+ let finished = false;
112
+ const finish = (r) => {
113
+ if (finished)
114
+ return;
115
+ finished = true;
116
+ clearTimeout(timer);
117
+ busy = false;
118
+ job.done(r);
119
+ pump();
120
+ };
121
+ const timer = setTimeout(() => finish(timedOut()), timeoutMillis);
122
+ timer.unref?.();
123
+ const answer = (r) => {
124
+ if (answered)
125
+ return;
126
+ answered = true;
127
+ innerBusy = false;
128
+ finish(r);
129
+ };
130
+ try {
131
+ inner.export(job.items, answer);
132
+ }
133
+ catch (err) {
134
+ answer({ code: ExportResultCode.FAILED, error: asError(err) });
135
+ }
136
+ }
137
+ };
138
+ const enqueue = (items, done, release) => {
139
+ jobs.push({ items, done, release, epoch });
140
+ pump();
141
+ };
142
+ /** Settles every queued export with r without exporting it; a release settles as a success. */
143
+ const drain = (r) => {
144
+ const queued = jobs;
145
+ jobs = [];
146
+ for (const job of queued)
147
+ job.done(job.release ? SUCCESS : r);
148
+ if (!busy)
149
+ settleIdle();
150
+ };
151
+ const report = () => {
152
+ const err = failure;
153
+ failure = undefined;
154
+ if (err !== undefined)
155
+ throw err;
156
+ };
157
+ return {
158
+ export(items, done) {
159
+ if (closed) {
160
+ done({ code: ExportResultCode.FAILED, error: new Error(`o11y: rum: ${what} exporter is shut down`) });
161
+ return;
162
+ }
163
+ const send = [];
164
+ for (const item of items) {
165
+ const r = route(item);
166
+ if (r === "send")
167
+ send.push(item);
168
+ else if (r === "buffer")
169
+ held.push({ id: idOf(item), item });
170
+ }
171
+ if (held.length > max)
172
+ held = held.slice(held.length - max);
173
+ if (send.length === 0)
174
+ done(SUCCESS);
175
+ else
176
+ enqueue(send, done, false);
177
+ },
178
+ release() {
179
+ if (closed)
180
+ return;
181
+ const send = [];
182
+ const keep = [];
183
+ for (const h of held) {
184
+ const r = h.id === undefined ? "drop" : route(h.item);
185
+ if (r === "send")
186
+ send.push(h.item);
187
+ else if (r === "buffer")
188
+ keep.push(h);
189
+ }
190
+ held = keep;
191
+ if (send.length === 0)
192
+ return;
193
+ enqueue(send, (r) => {
194
+ if (r.code === ExportResultCode.SUCCESS)
195
+ return;
196
+ const err = r.error ?? new Error(`o11y: rum: exporting held ${what} failed`);
197
+ diag.warn(`o11y: rum: exporting held ${what} failed`, err);
198
+ failure ??= err;
199
+ }, true);
200
+ },
201
+ discard(sessionId) {
202
+ if (sessionId !== undefined) {
203
+ held = held.filter((h) => h.id !== sessionId);
204
+ return;
205
+ }
206
+ // A revoke: nothing held or queued under the grant it ends is exported, even after a new grant.
207
+ held = [];
208
+ epoch++;
209
+ drain(SUCCESS);
210
+ },
211
+ async forceFlush() {
212
+ await Promise.race([idle(), aborted]);
213
+ await inner.forceFlush?.();
214
+ report();
215
+ },
216
+ async shutdown() {
217
+ await Promise.race([idle(), aborted]);
218
+ await stopInner();
219
+ report();
220
+ },
221
+ async close() {
222
+ closed = true;
223
+ held = [];
224
+ abort();
225
+ // What still waits for its turn is not exported. A queued release is dropped as a revoke drops it.
226
+ drain(shutDown());
227
+ try {
228
+ await stopInner();
229
+ }
230
+ catch (err) {
231
+ diag.debug(`o11y: rum: stopping the ${what} exporter failed`, err);
232
+ }
233
+ },
234
+ };
235
+ }
236
+ /**
237
+ * A SpanExporter that routes each span by its session.id as retainingSpanExporter does, but holds
238
+ * the spans to be buffered in memory, at most max of them, instead of in the retention buffer. The
239
+ * retention buffer sends through the platform's delivery, so an exporter the app injected, or the
240
+ * console exporter, would never see a span that waited there. A held span without a session.id is
241
+ * never released.
242
+ */
243
+ export function holdingSpanExporter(inner, decide, o = {}) {
244
+ return holding(inner, "spans", (s) => decide(sessionOf(s.attributes)), (s) => sessionOf(s.attributes), o.max ?? HELD_SPANS_MAX, o);
245
+ }
246
+ /**
247
+ * A LogRecordExporter that routes each record as holdingSpanExporter routes spans, sending every
248
+ * o11y.rum.view.summary record at once, as retainingLogExporter does.
249
+ */
250
+ export function holdingLogExporter(inner, decide, o = {}) {
251
+ const h = holding(inner, "log records", (l) => (l.attributes["event.name"] === EVENT_RUM_VIEW_SUMMARY ? "send" : decide(sessionOf(l.attributes))), (l) => sessionOf(l.attributes), o.max ?? HELD_LOGS_MAX, o);
252
+ return { ...h, forceFlush: () => h.forceFlush?.() ?? Promise.resolve() };
253
+ }
40
254
  /** A LogRecordExporter that routes each record by its session.id, sending every view summary. */
41
255
  export function retainingLogExporter(inner, routing) {
42
256
  return {
@@ -15,8 +15,8 @@
15
15
  * removed session as its previous.
16
16
  *
17
17
  * decide(id): a missing ID means the current session. The current session sends when kept and
18
- * buffers otherwise. Any of the last four sessions this context knew sends when it was kept and
19
- * drops otherwise. An unknown ID drops.
18
+ * buffers otherwise. Any of the last four sessions this context knew, or recalled from an earlier
19
+ * process, sends when it was kept and drops otherwise. An unknown ID drops.
20
20
  */
21
21
  import type { SessionManager, SessionStore } from "../contracts/session.ts";
22
22
  export interface SessionManagerOptions {
@@ -1,6 +1,11 @@
1
1
  import { randomUuid } from "../ids.js";
2
2
  import { sessionSampled } from "./sampling.js";
3
3
  const RECENT = 4;
4
+ /**
5
+ * The earlier processes' sessions recall keeps decisions for: as many as the native context
6
+ * history holds entries, so one poll's reports cannot push out each other's before export.
7
+ */
8
+ const RECALLED = 64;
4
9
  export function createSessionManager(opts) {
5
10
  const now = opts.now ?? Date.now;
6
11
  const randomId = opts.randomId ?? randomUuid;
@@ -8,6 +13,8 @@ export function createSessionManager(opts) {
8
13
  const listeners = new Set();
9
14
  /** Sessions this context knew, newest last, with whether each was kept. */
10
15
  const recent = new Map();
16
+ /** Decisions recall gave for sessions an earlier process had, apart from recent. */
17
+ const recalled = new Map();
11
18
  let state;
12
19
  /** start() was called and not cleared since. */
13
20
  let started = false;
@@ -108,7 +115,7 @@ export function createSessionManager(opts) {
108
115
  if (stored !== undefined && state === undefined) {
109
116
  state = stored;
110
117
  remember(stored);
111
- // A live stored session was started elsewhere. An expired one is ended here (decision P13):
118
+ // A live stored session was started elsewhere. An expired one is ended here:
112
119
  // live() below rotates it and emits its local end.
113
120
  if (!expired(stored, now()))
114
121
  emit({ type: "start", session: stored, local: false });
@@ -143,13 +150,22 @@ export function createSessionManager(opts) {
143
150
  return "drop";
144
151
  if (s !== undefined && id === s.id)
145
152
  return s.retained === undefined ? "buffer" : "send";
146
- return recent.get(id) === true ? "send" : "drop";
153
+ return (recent.get(id) ?? recalled.get(id)) === true ? "send" : "drop";
154
+ },
155
+ recall(sessionId, kept) {
156
+ if (recent.has(sessionId) || live()?.id === sessionId)
157
+ return;
158
+ recalled.delete(sessionId);
159
+ recalled.set(sessionId, kept);
160
+ while (recalled.size > RECALLED)
161
+ recalled.delete(recalled.keys().next().value);
147
162
  },
148
163
  clear() {
149
164
  generation++;
150
165
  forgotten = undefined;
151
166
  state = undefined;
152
167
  recent.clear();
168
+ recalled.clear();
153
169
  started = false;
154
170
  ready = false;
155
171
  unsubscribe?.();
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Session sampling (design D4). The decision is a hash of session.id, so every tab of a session,
2
+ * Session sampling. The decision is a hash of session.id, so every tab of a session,
3
3
  * and every client language, agrees: kept when fnv1a32(utf8(id)) / 2^32 < rate.
4
4
  */
5
5
  const encoder = new TextEncoder();
package/dist/setup.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * setupRum: @libo11y/web's setup with RUM wired in (decision P1). setupRumWith binds the RUM core
2
+ * setupRum: @libo11y/web's setup with RUM wired in. setupRumWith binds the RUM core
3
3
  * (core-setup.ts) to the web: web's setupWithDeps through webBinding, the page's lifecycle from
4
4
  * visibilitychange, pagehide and pageshow, remote configuration cached in localStorage, and the
5
5
  * bootstrap buffer replayed. The extension contexts pass their own binding and stores in deps.
@@ -32,6 +32,8 @@ export interface RumDeps extends Omit<RumCoreDeps<WebSetupOptions, WebTelemetry>
32
32
  */
33
33
  readonly storage?: RumCoreDeps<WebSetupOptions, WebTelemetry>["storage"];
34
34
  }
35
+ /** Browser dependencies shared by pages and extension contexts, without web setup or localStorage. */
36
+ export declare function defaultBrowserRumDeps(): Omit<RumDeps, "web" | "sessionStore">;
35
37
  /** The real dependencies of a page. */
36
38
  export declare function defaultRumDeps(): RumDeps;
37
39
  /** Builds browser telemetry with RUM and installs it globally, as the setup of `@libo11y/web` does. */
package/dist/setup.js CHANGED
@@ -5,14 +5,12 @@ import { replayBootstrap } from "./bootstrap/replay.js";
5
5
  import { setupRumCore } from "./core-setup.js";
6
6
  import { localStorageSessionStore } from "./session/local-store.js";
7
7
  export { runtimeOf, SESSION_END_ELECTION_MILLIS } from "./core-setup.js";
8
- /** The real dependencies of a page. */
9
- export function defaultRumDeps() {
8
+ /** Browser dependencies shared by pages and extension contexts, without web setup or localStorage. */
9
+ export function defaultBrowserRumDeps() {
10
10
  const g = globalThis;
11
- const web = defaultSetupDeps();
11
+ const doc = g.document;
12
12
  return {
13
- web,
14
13
  openRetentionQueue: openQueue,
15
- sessionStore: () => localStorageSessionStore(),
16
14
  now: Date.now,
17
15
  perfNow: () => performance.now(),
18
16
  timeOrigin: performance.timeOrigin,
@@ -24,7 +22,17 @@ export function defaultRumDeps() {
24
22
  return (nav?.activationStart ?? 0) > 0;
25
23
  },
26
24
  connection: () => g.navigator?.connection?.effectiveType,
27
- document: g.document,
25
+ document: doc,
26
+ window: doc !== undefined && typeof g.addEventListener === "function" ? globalThis : undefined,
27
+ };
28
+ }
29
+ /** The real dependencies of a page. */
30
+ export function defaultRumDeps() {
31
+ const web = defaultSetupDeps();
32
+ return {
33
+ ...defaultBrowserRumDeps(),
34
+ web,
35
+ sessionStore: () => localStorageSessionStore(),
28
36
  window: web.window,
29
37
  };
30
38
  }
@@ -6,9 +6,9 @@
6
6
  * the attribute the gateway keys on. Its documentFetch child also belongs to the load view, and it
7
7
  * is not a request of the view. It publishes client request starts and ends on the bus for
8
8
  * actions, summaries and errors, and a breadcrumb for each finished request: "fetch <METHOD> <host>
9
- * <status or failed>", or "rpc <method>" for a span with rpc.method, never a path (decision P18). It runs before the exporting processors, so they see the
9
+ * <status or failed>", or "rpc <method>" for a span with rpc.method, never a path. It runs before the exporting processors, so they see the
10
10
  * attributes. A span that starts while the session loads after a grant gets the same treatment,
11
- * and waits in pending for its session.id and view (R3f).
11
+ * and waits in pending for its session.id and view.
12
12
  */
13
13
  import { type RUMPlatform } from "@libo11y/spec";
14
14
  import type { SpanProcessor } from "@opentelemetry/sdk-trace";
@@ -31,7 +31,7 @@ export interface RumSpanProcessorOptions {
31
31
  * performance.timeOrigin, to read a span's end time on the now() clock. Without it the bus
32
32
  * reports now() alone.
33
33
  */
34
- readonly timeOrigin?: number;
34
+ readonly timeOrigin?: number | undefined;
35
35
  /** Where spans that start while the session loads wait for it. */
36
36
  readonly pending?: Pick<PendingSpans, "isOpen" | "hold">;
37
37
  }
@@ -6,9 +6,9 @@
6
6
  * the attribute the gateway keys on. Its documentFetch child also belongs to the load view, and it
7
7
  * is not a request of the view. It publishes client request starts and ends on the bus for
8
8
  * actions, summaries and errors, and a breadcrumb for each finished request: "fetch <METHOD> <host>
9
- * <status or failed>", or "rpc <method>" for a span with rpc.method, never a path (decision P18). It runs before the exporting processors, so they see the
9
+ * <status or failed>", or "rpc <method>" for a span with rpc.method, never a path. It runs before the exporting processors, so they see the
10
10
  * attributes. A span that starts while the session loads after a grant gets the same treatment,
11
- * and waits in pending for its session.id and view (R3f).
11
+ * and waits in pending for its session.id and view.
12
12
  */
13
13
  import { ATTR_RUM_PLATFORM, ATTR_RUM_SPAN_SHAPE, ATTR_RUM_VIEW_ID, RUM_SPAN_SHAPE_VALUE_APP_LOAD, } from "@libo11y/spec";
14
14
  import { SpanKind } from "@opentelemetry/api";
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The view summary accumulator (design D2, spec 1.3.0 o11y.rum.view.summary). conformance/rum-summary
2
+ * The view summary accumulator (spec 1.3.0 o11y.rum.view.summary). conformance/rum-summary
3
3
  * holds the shared vectors.
4
4
  *
5
5
  * Rules. A tracked view emits on close, and on flush when it has never emitted (seq 0) or has a
@@ -7,19 +7,25 @@
7
7
  * the view's previous summary; a zero count is omitted. A vital is accepted once per view and name
8
8
  * and is sent in the next summary of that view. A closed view stays tracked, for late vitals, until
9
9
  * ten newer views closed after it, and while it is pinned (vitals() pins the load view until it has
10
- * committed its held vitals).
10
+ * committed its held vitals). late() sends a one-off summary of a view an earlier process showed,
11
+ * for a native crash or hang a later launch delivers (spec 1.4.0).
11
12
  */
12
13
  import { type RUMPlatform } from "@libo11y/spec";
13
14
  import type { SummaryAccumulator } from "../contracts/summary.ts";
14
15
  export interface SummaryOptions {
15
16
  readonly platform: RUMPlatform;
16
- /** Emits one o11y.rum.view.summary record with these attributes. */
17
- readonly emit: (attrs: Record<string, string | number>) => void;
17
+ /** Emits one o11y.rum.view.summary record with these attributes; false when it was not taken. */
18
+ readonly emit: (attrs: Record<string, string | number>) => unknown;
18
19
  /** performance.now(). */
19
20
  readonly now: () => number;
20
21
  /** Whether the page is visible now. */
21
22
  readonly visible: () => boolean;
22
- /** Optional attributes added to every summary: o11y.rum.connection.effective, o11y.rum.config.version. */
23
+ /** Optional attributes added to every summary, read as it is emitted: o11y.rum.connection.effective. */
23
24
  readonly context?: () => Readonly<Record<string, string | number>>;
25
+ /**
26
+ * Optional attributes read once, when a view opens, and added to every summary of that view, late
27
+ * vitals included: o11y.rum.config.version of the session the view opened in.
28
+ */
29
+ readonly origin?: () => Readonly<Record<string, string | number>>;
24
30
  }
25
31
  export declare function createSummaryAccumulator(opts: SummaryOptions): SummaryAccumulator;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The view summary accumulator (design D2, spec 1.3.0 o11y.rum.view.summary). conformance/rum-summary
2
+ * The view summary accumulator (spec 1.3.0 o11y.rum.view.summary). conformance/rum-summary
3
3
  * holds the shared vectors.
4
4
  *
5
5
  * Rules. A tracked view emits on close, and on flush when it has never emitted (seq 0) or has a
@@ -7,7 +7,8 @@
7
7
  * the view's previous summary; a zero count is omitted. A vital is accepted once per view and name
8
8
  * and is sent in the next summary of that view. A closed view stays tracked, for late vitals, until
9
9
  * ten newer views closed after it, and while it is pinned (vitals() pins the load view until it has
10
- * committed its held vitals).
10
+ * committed its held vitals). late() sends a one-off summary of a view an earlier process showed,
11
+ * for a native crash or hang a later launch delivers (spec 1.4.0).
11
12
  */
12
13
  import { ATTR_RUM_PLATFORM, ATTR_RUM_SUMMARY_SEQ, ATTR_RUM_SUMMARY_TIME_ON_VIEW, ATTR_RUM_VIEW_ID, ATTR_RUM_VIEW_KIND, ATTR_RUM_VIEW_NAME, } from "@libo11y/spec";
13
14
  import { ATTR_SESSION_ID, summaryCountKey, summaryVitalKey } from "../attrs.js";
@@ -23,12 +24,14 @@ export function createSummaryAccumulator(opts) {
23
24
  t.resumedAt = n;
24
25
  };
25
26
  const pending = (t) => t.seq === 0 || t.counts.size > 0 || t.vitals.size > 0 || t.visibleMillis > 0;
27
+ /** Sends t's summary when it has unsent data; false when the pipeline did not take it. */
26
28
  const send = (t) => {
27
29
  accrue(t);
28
30
  if (!pending(t))
29
- return;
31
+ return true;
30
32
  const attrs = {
31
- ...(opts.context?.() ?? {}),
33
+ ...opts.context?.(),
34
+ ...t.origin,
32
35
  [ATTR_RUM_PLATFORM]: opts.platform,
33
36
  [ATTR_RUM_VIEW_ID]: t.view.id,
34
37
  [ATTR_RUM_VIEW_NAME]: t.view.name,
@@ -48,7 +51,7 @@ export function createSummaryAccumulator(opts) {
48
51
  t.counts = new Map();
49
52
  t.vitals = new Map();
50
53
  t.visibleMillis = 0;
51
- opts.emit(attrs);
54
+ return opts.emit(attrs) !== false;
52
55
  };
53
56
  const prune = () => {
54
57
  const closed = [...tracked.values()].filter((t) => !t.open && !t.pinned);
@@ -67,6 +70,7 @@ export function createSummaryAccumulator(opts) {
67
70
  resumedAt: opts.visible() ? opts.now() : undefined,
68
71
  open: true,
69
72
  pinned: false,
73
+ origin: opts.origin?.(),
70
74
  };
71
75
  tracked.set(view.id, t);
72
76
  current = t;
@@ -114,13 +118,30 @@ export function createSummaryAccumulator(opts) {
114
118
  }
115
119
  },
116
120
  flush() {
121
+ let taken = true;
117
122
  for (const t of tracked.values())
118
- send(t);
123
+ taken = send(t) && taken;
119
124
  prune();
125
+ return taken;
120
126
  },
121
127
  reset() {
122
128
  tracked.clear();
123
129
  current = undefined;
124
130
  },
131
+ nextSeq(viewId) {
132
+ return tracked.get(viewId)?.seq;
133
+ },
134
+ late(view, seq, key) {
135
+ return (opts.emit({
136
+ [ATTR_RUM_PLATFORM]: opts.platform,
137
+ [ATTR_RUM_VIEW_ID]: view.id,
138
+ [ATTR_RUM_VIEW_NAME]: view.name,
139
+ [ATTR_RUM_VIEW_KIND]: view.kind,
140
+ [ATTR_SESSION_ID]: view.sessionId,
141
+ [ATTR_RUM_SUMMARY_SEQ]: seq,
142
+ [ATTR_RUM_SUMMARY_TIME_ON_VIEW]: 0,
143
+ [summaryCountKey(key)]: 1,
144
+ }) !== false);
145
+ },
125
146
  };
126
147
  }
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The `@libo11y/rum` package version. scripts/release.ts keeps it equal to package.json. */
2
- export declare const VERSION = "0.4.0";
2
+ export declare const VERSION = "0.7.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The `@libo11y/rum` package version. scripts/release.ts keeps it equal to package.json. */
2
- export const VERSION = "0.4.0";
2
+ export const VERSION = "0.7.0";
@@ -4,8 +4,8 @@
4
4
  * Every view the tracker starts gets a view span named "view <o11y.rum.view.name>" with
5
5
  * o11y.rum.span.shape view, the platform, the view's name, ID and kind, and its session.id. It
6
6
  * starts at the view's startTime. A soft or bfcache_restore view span is a root, linked to the
7
- * action that caused it when there is one. An initial or prerender view span is a child of
8
- * app_load (web's documentLoad span). Its creation waits for the span processor to report
7
+ * action that caused it when there is one. The load view's span (initial or prerender on the web,
8
+ * the first screen on React Native) is a child of app_load (web's documentLoad span). Its creation waits for the span processor to report
9
9
  * app_load, and once the view span is due to end it waits at most APP_LOAD_WAIT_MILLIS more, then
10
10
  * starts as a root. The tracker learns the span's context (attachSpan), so actions link to it.
11
11
  *
@@ -40,7 +40,6 @@ export const MUTATIONS = {
40
40
  attributes: true,
41
41
  characterData: true,
42
42
  };
43
- const LOAD_SPAN_KINDS = new Set(["initial", "prerender"]);
44
43
  export function viewsWith(opts, env) {
45
44
  const followHistory = opts.history !== false;
46
45
  return {
@@ -68,12 +67,12 @@ export function viewsWith(opts, env) {
68
67
  o.offLoad = undefined;
69
68
  };
70
69
  // A fixed view (a content script) has no app_load: the host page's load is not its own.
71
- const waitsForAppLoad = (o) => LOAD_SPAN_KINDS.has(o.view.kind) && rt.views.appLoad() === undefined && rt.scope?.fixedView !== true;
70
+ const waitsForAppLoad = (o) => o.load && rt.views.appLoad() === undefined && rt.scope?.fixedView !== true;
72
71
  const create = (o) => {
73
72
  if (o.span !== undefined)
74
73
  return o.span;
75
74
  const v = o.view;
76
- const appLoad = LOAD_SPAN_KINDS.has(v.kind) ? rt.views.appLoad() : undefined;
75
+ const appLoad = o.load ? rt.views.appLoad() : undefined;
77
76
  const span = rt.tracer.startSpan(`view ${v.name}`, {
78
77
  startTime: env.timeOrigin + v.startTime,
79
78
  attributes: {
@@ -94,12 +93,13 @@ export function viewsWith(opts, env) {
94
93
  const close = (o) => {
95
94
  quiet(o);
96
95
  open.delete(o.view.id);
97
- create(o).end(env.timeOrigin + (o.endAt ?? rt.now()));
96
+ const capAt = o.view.startTime + VIEW_SPAN_CAP_MILLIS;
97
+ create(o).end(env.timeOrigin + Math.min(o.endAt ?? rt.now(), capAt));
98
98
  };
99
99
  const finish = (o, at) => {
100
100
  if (o.endAt !== undefined)
101
101
  return;
102
- o.endAt = at;
102
+ o.endAt = Math.min(at, o.view.startTime + VIEW_SPAN_CAP_MILLIS);
103
103
  if (o.span !== undefined || !waitsForAppLoad(o)) {
104
104
  close(o);
105
105
  return;
@@ -151,6 +151,7 @@ export function viewsWith(opts, env) {
151
151
  const start = (view, cause, atSetup, onScreen = false) => {
152
152
  const o = {
153
153
  view,
154
+ load: view.kind !== "bfcache_restore" && rt.views.loadView()?.id === view.id,
154
155
  ...(cause === undefined ? {} : { cause }),
155
156
  rendered: false,
156
157
  timers: new Set(),
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The view name when no router adapter names the view (decision P17): the path, with every
2
+ * The view name when no router adapter names the view: the path, with every
3
3
  * segment that holds a digit or is longer than 24 characters replaced by $id. Query and fragment
4
4
  * are dropped, so a raw URL never becomes a view name.
5
5
  */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The view name when no router adapter names the view (decision P17): the path, with every
2
+ * The view name when no router adapter names the view: the path, with every
3
3
  * segment that holds a digit or is longer than 24 characters replaced by $id. Query and fragment
4
4
  * are dropped, so a raw URL never becomes a view name.
5
5
  */
@@ -1,9 +1,12 @@
1
1
  /**
2
2
  * The view tracker: the initial (or prerender) view at begin, a bfcache_restore view on a
3
- * persisted pageshow, a soft view of the same name when the session changes (decision P14), and
4
- * the soft views views() and the router adapters start. Every view opens in the summary
5
- * accumulator and closes when it ends. views() records the view spans and attaches their contexts.
3
+ * persisted pageshow, a soft view of the same name when the session changes, and
4
+ * the soft views views() and the router adapters start. A platform whose views are all of one
5
+ * kind, as React Native's screens, passes viewKind: the first begin's view is then the load view and
6
+ * every view has that kind. Every view opens in the summary accumulator and closes when it ends.
7
+ * views() records the view spans and attaches their contexts.
6
8
  */
9
+ import type { RUMViewKind } from "@libo11y/spec";
7
10
  import type { SessionManager } from "../contracts/session.ts";
8
11
  import type { SummaryAccumulator } from "../contracts/summary.ts";
9
12
  import type { ViewTracker } from "../contracts/views.ts";
@@ -15,12 +18,18 @@ export interface ViewTrackerOptions {
15
18
  readonly location: () => string;
16
19
  /** performance.now(). */
17
20
  readonly now: () => number;
18
- /** document.prerendering, or a navigation entry with activationStart > 0. */
21
+ /** document.prerendering, or a navigation entry with `activationStart > 0`. */
19
22
  readonly prerendered: () => boolean;
20
23
  /** Where pageshow fires, for back/forward-cache restores. */
21
- readonly window?: EventTarget;
24
+ readonly window?: EventTarget | undefined;
22
25
  /** When the initial view starts, performance.now(). Default 0, navigation start; a content script's view starts when RUM begins. */
23
- readonly initialStart?: () => number;
26
+ readonly initialStart?: (() => number) | undefined;
27
+ /**
28
+ * The kind of every view the tracker starts itself (the load view, the view of a session change
29
+ * and of a later begin), for a platform with one kind of view, such as React Native's screen.
30
+ * Default the web's: initial or prerender, then soft.
31
+ */
32
+ readonly viewKind?: RUMViewKind | undefined;
24
33
  readonly randomId?: () => string;
25
34
  }
26
35
  export declare function createViewTracker(opts: ViewTrackerOptions): ViewTracker & {