@libo11y/rum 0.0.0-stage → 0.4.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.
- package/LICENSE +202 -0
- package/README.md +461 -2
- package/dist/actions/collector.d.ts +29 -0
- package/dist/actions/collector.js +260 -0
- package/dist/actions/naming.d.ts +15 -0
- package/dist/actions/naming.js +65 -0
- package/dist/actions/record.d.ts +13 -0
- package/dist/actions/record.js +28 -0
- package/dist/actions/settle.d.ts +28 -0
- package/dist/actions/settle.js +53 -0
- package/dist/attrs.d.ts +10 -0
- package/dist/attrs.js +12 -0
- package/dist/bind.d.ts +23 -0
- package/dist/bind.js +55 -0
- package/dist/bootstrap/buffer.d.ts +72 -0
- package/dist/bootstrap/buffer.js +95 -0
- package/dist/bootstrap/replay.d.ts +10 -0
- package/dist/bootstrap/replay.js +11 -0
- package/dist/bootstrap.d.ts +17 -0
- package/dist/bootstrap.js +33 -0
- package/dist/bus.d.ts +3 -0
- package/dist/bus.js +21 -0
- package/dist/config/clamp.d.ts +34 -0
- package/dist/config/clamp.js +79 -0
- package/dist/config/remote.d.ts +80 -0
- package/dist/config/remote.js +209 -0
- package/dist/context-manager.d.ts +8 -0
- package/dist/context-manager.js +29 -0
- package/dist/contracts/binding.d.ts +80 -0
- package/dist/contracts/binding.js +1 -0
- package/dist/contracts/retention.d.ts +28 -0
- package/dist/contracts/retention.js +1 -0
- package/dist/contracts/runtime.d.ts +154 -0
- package/dist/contracts/runtime.js +1 -0
- package/dist/contracts/session.d.ts +63 -0
- package/dist/contracts/session.js +1 -0
- package/dist/contracts/summary.d.ts +28 -0
- package/dist/contracts/summary.js +1 -0
- package/dist/contracts/views.d.ts +71 -0
- package/dist/contracts/views.js +1 -0
- package/dist/core-setup.d.ts +86 -0
- package/dist/core-setup.js +902 -0
- package/dist/core.d.ts +42 -0
- package/dist/core.js +35 -0
- package/dist/errors/breadcrumbs.d.ts +16 -0
- package/dist/errors/breadcrumbs.js +27 -0
- package/dist/errors/collector.d.ts +17 -0
- package/dist/errors/collector.js +186 -0
- package/dist/errors/normalize.d.ts +7 -0
- package/dist/errors/normalize.js +31 -0
- package/dist/errors/record.d.ts +20 -0
- package/dist/errors/record.js +46 -0
- package/dist/frustration/detect.d.ts +38 -0
- package/dist/frustration/detect.js +62 -0
- package/dist/ids.d.ts +2 -0
- package/dist/ids.js +2 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +12 -0
- package/dist/internal.d.ts +28 -0
- package/dist/internal.js +26 -0
- package/dist/loaf.d.ts +15 -0
- package/dist/loaf.js +27 -0
- package/dist/options.d.ts +84 -0
- package/dist/options.js +1 -0
- package/dist/pending-spans.d.ts +29 -0
- package/dist/pending-spans.js +92 -0
- package/dist/query.d.ts +2 -0
- package/dist/query.js +19 -0
- package/dist/resources/collector.d.ts +76 -0
- package/dist/resources/collector.js +270 -0
- package/dist/resources/server-timing.d.ts +18 -0
- package/dist/resources/server-timing.js +21 -0
- package/dist/retention/buffer.d.ts +25 -0
- package/dist/retention/buffer.js +104 -0
- package/dist/retention/exporters.d.ts +17 -0
- package/dist/retention/exporters.js +67 -0
- package/dist/retention/sessions.d.ts +4 -0
- package/dist/retention/sessions.js +30 -0
- package/dist/session/local-store.d.ts +25 -0
- package/dist/session/local-store.js +91 -0
- package/dist/session/manager.d.ts +36 -0
- package/dist/session/manager.js +169 -0
- package/dist/session/sampling.d.ts +4 -0
- package/dist/session/sampling.js +20 -0
- package/dist/session/state.d.ts +4 -0
- package/dist/session/state.js +28 -0
- package/dist/settings.d.ts +8 -0
- package/dist/settings.js +36 -0
- package/dist/setup.d.ts +40 -0
- package/dist/setup.js +49 -0
- package/dist/span-processor.d.ts +38 -0
- package/dist/span-processor.js +125 -0
- package/dist/summary/accumulator.d.ts +25 -0
- package/dist/summary/accumulator.js +126 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/dist/views/collector.d.ts +40 -0
- package/dist/views/collector.js +285 -0
- package/dist/views/history.d.ts +18 -0
- package/dist/views/history.js +42 -0
- package/dist/views/naming.d.ts +6 -0
- package/dist/views/naming.js +12 -0
- package/dist/views/paint.d.ts +12 -0
- package/dist/views/paint.js +15 -0
- package/dist/views/tracker.d.ts +28 -0
- package/dist/views/tracker.js +117 -0
- package/dist/vitals/attribution.d.ts +14 -0
- package/dist/vitals/attribution.js +60 -0
- package/dist/vitals/collector.d.ts +24 -0
- package/dist/vitals/collector.js +232 -0
- package/dist/vitals/lcp.d.ts +32 -0
- package/dist/vitals/lcp.js +49 -0
- package/dist/webext/chrome.d.ts +45 -0
- package/dist/webext/chrome.js +13 -0
- package/dist/webext/config-storage.d.ts +7 -0
- package/dist/webext/config-storage.js +47 -0
- package/dist/webext/scope.d.ts +22 -0
- package/dist/webext/scope.js +50 -0
- package/dist/webext/session-access.d.ts +13 -0
- package/dist/webext/session-access.js +9 -0
- package/dist/webext/session-store.d.ts +5 -0
- package/dist/webext/session-store.js +94 -0
- package/dist/webext/setup.d.ts +71 -0
- package/dist/webext/setup.js +193 -0
- package/dist/webext.d.ts +10 -0
- package/dist/webext.js +8 -0
- package/dist/wire.d.ts +13 -0
- package/dist/wire.js +30 -0
- package/package.json +57 -4
|
@@ -0,0 +1,902 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* setupRumCore: RUM over a platform binding (decision P1, R3f, R5a). In order: settings, the
|
|
3
|
+
* retention buffer (opened lazily), the session manager, the bus, the summary accumulator, the
|
|
4
|
+
* view tracker, the span processor, then the binding, which runs the platform's setup with RUM's
|
|
5
|
+
* wrappers. After setup: consent wiring (collectors run only while granted), session events, hide
|
|
6
|
+
* handling and activity from the platform's lifecycle. The returned handle is the platform's
|
|
7
|
+
* telemetry extended in place with rum. setupRumWith (setup.ts) binds it to the web.
|
|
8
|
+
*
|
|
9
|
+
* Nothing here imports a browser-only module or reads a browser global; every platform part is a
|
|
10
|
+
* dependency (core.test.ts enforces the imports), so a platform without a DOM, such as React
|
|
11
|
+
* Native, can bind it.
|
|
12
|
+
*
|
|
13
|
+
* The span processor reaches core as options.spanProcessor. Core treats an injected processor as
|
|
14
|
+
* the traces route ("injected") and then uses no span exporter the platform builds, so RUM also
|
|
15
|
+
* injects a forwarding span exporter. When the binding hands RUM its platform's delivery (before
|
|
16
|
+
* core builds anything), RUM builds the span exporter for the route traces would have had without
|
|
17
|
+
* RUM: none in hermetic mode, else OTEL_TRACES_EXPORTER from the platform's env. An app that
|
|
18
|
+
* injects its own spanExporter keeps it, routed by session; one that injects only a spanProcessor
|
|
19
|
+
* keeps sole charge of span export.
|
|
20
|
+
*
|
|
21
|
+
* 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.
|
|
24
|
+
*/
|
|
25
|
+
import { O11yError } from "@libo11y/core";
|
|
26
|
+
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";
|
|
27
|
+
import { createContextManager, createSpanExporter, isIgnored, OTLP_SIGNALS, pristineFetch, reportFlush, } from "@libo11y/web/portable";
|
|
28
|
+
import { diag, ROOT_CONTEXT, SeverityNumber } from "@opentelemetry/api";
|
|
29
|
+
import { ExportResultCode } from "@opentelemetry/core";
|
|
30
|
+
import { ConsoleSpanExporter } from "@opentelemetry/sdk-trace";
|
|
31
|
+
import { recordInstantAction } from "./actions/record.js";
|
|
32
|
+
import { ATTR_SESSION_ID, ATTR_USER_ID } from "./attrs.js";
|
|
33
|
+
import { createBus } from "./bus.js";
|
|
34
|
+
import { rumContextManager } from "./context-manager.js";
|
|
35
|
+
import { createBreadcrumbs } from "./errors/breadcrumbs.js";
|
|
36
|
+
import { recordError } from "./errors/record.js";
|
|
37
|
+
import { createPendingSpans } from "./pending-spans.js";
|
|
38
|
+
import { createRetentionBuffer, RETENTION_QUEUE_DEFAULTS } from "./retention/buffer.js";
|
|
39
|
+
import { retainingSpanExporter, withRetention } from "./retention/exporters.js";
|
|
40
|
+
import { sessionsIn } from "./retention/sessions.js";
|
|
41
|
+
import { createSessionManager } from "./session/manager.js";
|
|
42
|
+
import { resolveSettings } from "./settings.js";
|
|
43
|
+
import { rumSpanProcessor } from "./span-processor.js";
|
|
44
|
+
import { createSummaryAccumulator } from "./summary/accumulator.js";
|
|
45
|
+
import { VERSION } from "./version.js";
|
|
46
|
+
import { createViewTracker } from "./views/tracker.js";
|
|
47
|
+
import { gatewayTransportOptions } from "./wire.js";
|
|
48
|
+
const runtimes = new WeakMap();
|
|
49
|
+
/** The RUM runtime behind a RUM telemetry, for the adapter packages and the browser fixtures. */
|
|
50
|
+
export function runtimeOf(telemetry) {
|
|
51
|
+
return runtimes.get(telemetry);
|
|
52
|
+
}
|
|
53
|
+
function composeProcessors(first, second) {
|
|
54
|
+
if (second === undefined)
|
|
55
|
+
return first;
|
|
56
|
+
return {
|
|
57
|
+
onStart: (s, c) => {
|
|
58
|
+
first.onStart(s, c);
|
|
59
|
+
second.onStart(s, c);
|
|
60
|
+
},
|
|
61
|
+
onEnd: (s) => {
|
|
62
|
+
first.onEnd(s);
|
|
63
|
+
second.onEnd(s);
|
|
64
|
+
},
|
|
65
|
+
forceFlush: async () => {
|
|
66
|
+
await Promise.all([first.forceFlush(), second.forceFlush()]);
|
|
67
|
+
},
|
|
68
|
+
shutdown: async () => {
|
|
69
|
+
await Promise.all([first.shutdown(), second.shutdown()]);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const SUCCESS = { code: ExportResultCode.SUCCESS };
|
|
74
|
+
/** How long a tab that ended a session waits to hear whether another tab's rotation won. */
|
|
75
|
+
export const SESSION_END_ELECTION_MILLIS = 500;
|
|
76
|
+
/**
|
|
77
|
+
* A span exporter that hands every batch to the target set later, and succeeds while there is none.
|
|
78
|
+
* A batch with a span that waits for the session goes on once the session is known.
|
|
79
|
+
*/
|
|
80
|
+
function forwardingSpanExporter(target, pending) {
|
|
81
|
+
return {
|
|
82
|
+
export(spans, done) {
|
|
83
|
+
const go = (batch) => {
|
|
84
|
+
const t = target();
|
|
85
|
+
if (t === undefined)
|
|
86
|
+
done(SUCCESS);
|
|
87
|
+
else
|
|
88
|
+
t.export(batch, done);
|
|
89
|
+
};
|
|
90
|
+
const send = (batch) => {
|
|
91
|
+
try {
|
|
92
|
+
go(batch);
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
done({ code: ExportResultCode.FAILED, error: err instanceof Error ? err : new Error(String(err)) });
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
const ready = pending.prepare(spans);
|
|
99
|
+
if (Array.isArray(ready))
|
|
100
|
+
send(ready);
|
|
101
|
+
else
|
|
102
|
+
ready.then(send, () => done(SUCCESS));
|
|
103
|
+
},
|
|
104
|
+
forceFlush: async () => {
|
|
105
|
+
await target()?.forceFlush?.();
|
|
106
|
+
},
|
|
107
|
+
shutdown: async () => {
|
|
108
|
+
await target()?.shutdown();
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** The traces route core would have resolved without RUM's injected processor and exporter. */
|
|
113
|
+
function naturalTracesRoute(hermetic, env) {
|
|
114
|
+
if (hermetic || (env.OTEL_SDK_DISABLED ?? "").trim().toLowerCase() === "true")
|
|
115
|
+
return "none";
|
|
116
|
+
const first = (env.OTEL_TRACES_EXPORTER ?? "")
|
|
117
|
+
.split(",")
|
|
118
|
+
.map((v) => v.trim().toLowerCase())
|
|
119
|
+
.find((v) => v !== "");
|
|
120
|
+
const value = first ?? "otlp";
|
|
121
|
+
if (value === "otlp" || value === "console" || value === "none")
|
|
122
|
+
return value;
|
|
123
|
+
throw new O11yError("EXPORTER", `o11y: building span exporter: unknown exporter ${value}`);
|
|
124
|
+
}
|
|
125
|
+
/** The remote configuration URL: base, else the export endpoint next to /v1/<signal>, with the service and client token. */
|
|
126
|
+
function configUrl(base, endpoints, page, service, clientToken) {
|
|
127
|
+
let raw = base;
|
|
128
|
+
if (raw === undefined && endpoints !== undefined) {
|
|
129
|
+
for (const [signal, u] of Object.entries(endpoints)) {
|
|
130
|
+
const suffix = `/v1/${signal}`;
|
|
131
|
+
if (u?.endsWith(suffix) === true) {
|
|
132
|
+
raw = `${u.slice(0, -suffix.length)}/v1/config`;
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (raw === undefined || typeof service !== "string" || service === "")
|
|
138
|
+
return undefined;
|
|
139
|
+
let url;
|
|
140
|
+
try {
|
|
141
|
+
url = new URL(raw, page);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
url.searchParams.set("service", service);
|
|
147
|
+
if (clientToken !== undefined)
|
|
148
|
+
url.searchParams.set("client_token", clientToken);
|
|
149
|
+
return url.href;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* RUM over deps.bind: options are the platform's setup options, rumOptions RUM's own. Resolves with
|
|
153
|
+
* the platform's telemetry, with rum added.
|
|
154
|
+
*/
|
|
155
|
+
export async function setupRumCore(options, rumOptions, deps) {
|
|
156
|
+
const resolved = resolveSettings(rumOptions);
|
|
157
|
+
const platform = deps.platform;
|
|
158
|
+
// Remote configuration (decisions P15, P16). The connection opens on the first grant. settings
|
|
159
|
+
// are those of the current session: the document it started under, within the code's limits. A
|
|
160
|
+
// new session takes the newest document. killed is the kill switch of the newest document.
|
|
161
|
+
const rc = rumOptions?.remoteConfig;
|
|
162
|
+
let remote;
|
|
163
|
+
let killed = false;
|
|
164
|
+
let settings = resolved;
|
|
165
|
+
const forSession = (version) => remote === undefined ? resolved : remote.apply(resolved, remote.find(version));
|
|
166
|
+
const newest = () => remote === undefined ? resolved : remote.apply(resolved, remote.current());
|
|
167
|
+
const retention = createRetentionBuffer({
|
|
168
|
+
open: () => deps.openRetentionQueue({
|
|
169
|
+
...RETENTION_QUEUE_DEFAULTS,
|
|
170
|
+
...(rumOptions?.retention?.maxBytes === undefined ? {} : { maxBytes: rumOptions.retention.maxBytes }),
|
|
171
|
+
...(rumOptions?.retention?.maxAgeMillis === undefined
|
|
172
|
+
? {}
|
|
173
|
+
: { maxAgeMillis: rumOptions.retention.maxAgeMillis }),
|
|
174
|
+
}),
|
|
175
|
+
now: deps.now,
|
|
176
|
+
...(options.transport?.timeoutMillis === undefined
|
|
177
|
+
? {}
|
|
178
|
+
: { sendTimeoutMillis: options.transport.timeoutMillis }),
|
|
179
|
+
});
|
|
180
|
+
const session = createSessionManager({
|
|
181
|
+
store: deps.sessionStore(),
|
|
182
|
+
sampleRate: () => newest().sessionSampleRate,
|
|
183
|
+
idleMillis: resolved.sessionIdleMillis,
|
|
184
|
+
maxMillis: resolved.sessionMaxMillis,
|
|
185
|
+
configVersion: () => newest().configVersion,
|
|
186
|
+
now: deps.now,
|
|
187
|
+
});
|
|
188
|
+
const bus = createBus();
|
|
189
|
+
// The breadcrumb ring every error carries (decision P18): actions, view starts and requests.
|
|
190
|
+
const crumbs = createBreadcrumbs();
|
|
191
|
+
// A request that ends after a revoke must not leave a breadcrumb for the next grant.
|
|
192
|
+
bus.subscribe((s) => {
|
|
193
|
+
if (s.type === "breadcrumb" && controller?.recording() === true)
|
|
194
|
+
crumbs.add(s.kind, s.label, s.at, s.key);
|
|
195
|
+
});
|
|
196
|
+
/** The open action, so requests started meanwhile become its children (decision P10). */
|
|
197
|
+
let active;
|
|
198
|
+
const hooks = new Set();
|
|
199
|
+
let userId;
|
|
200
|
+
let telemetry;
|
|
201
|
+
let controller;
|
|
202
|
+
let delivery;
|
|
203
|
+
let endpoints;
|
|
204
|
+
const lifecycle = deps.lifecycle;
|
|
205
|
+
const shown = lifecycle.visible;
|
|
206
|
+
const summary = createSummaryAccumulator({
|
|
207
|
+
platform,
|
|
208
|
+
emit: (attrs) => telemetry?.event(EVENT_RUM_VIEW_SUMMARY, attrs),
|
|
209
|
+
now: deps.perfNow,
|
|
210
|
+
visible: shown,
|
|
211
|
+
context: () => {
|
|
212
|
+
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
|
+
};
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
// Every client request counts toward the current view's summary (o11y.rum.summary.requests).
|
|
224
|
+
bus.subscribe((s) => {
|
|
225
|
+
if (s.type === "request-start")
|
|
226
|
+
summary.count("requests");
|
|
227
|
+
});
|
|
228
|
+
const views = createViewTracker({
|
|
229
|
+
session,
|
|
230
|
+
summary,
|
|
231
|
+
viewName: (u) => settings.viewName(u),
|
|
232
|
+
location: deps.location,
|
|
233
|
+
now: deps.perfNow,
|
|
234
|
+
prerendered: deps.prerendered,
|
|
235
|
+
...(deps.window === undefined ? {} : { window: deps.window }),
|
|
236
|
+
...(deps.scope?.fixedView === true ? { initialStart: deps.perfNow } : {}),
|
|
237
|
+
});
|
|
238
|
+
views.subscribe((e) => {
|
|
239
|
+
if (e.type === "start") {
|
|
240
|
+
bus.publish({
|
|
241
|
+
type: "breadcrumb",
|
|
242
|
+
kind: "view",
|
|
243
|
+
label: e.view.name,
|
|
244
|
+
at: e.view.startTime,
|
|
245
|
+
key: e.view.id,
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
else if (e.type === "rename")
|
|
249
|
+
crumbs.relabel(e.view.id, e.view.name);
|
|
250
|
+
});
|
|
251
|
+
/**
|
|
252
|
+
* What the router adapter last reported, kept while consent is not granted too: the path it was
|
|
253
|
+
* on, the name it gave the view and when the view rendered. A grant applies it to the view RUM
|
|
254
|
+
* starts then, so a route that rendered before consent is named and rendered, not left to the
|
|
255
|
+
* view span cap. It applies only while the URL path is still the one reported.
|
|
256
|
+
*/
|
|
257
|
+
let routed;
|
|
258
|
+
const pathNow = () => {
|
|
259
|
+
try {
|
|
260
|
+
return new URL(deps.location()).pathname;
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
return "";
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
/** What the adapter reported on this path, or a fresh record when it moved to another path. */
|
|
267
|
+
const samePath = () => {
|
|
268
|
+
const path = pathNow();
|
|
269
|
+
return routed?.path === path ? routed : { path };
|
|
270
|
+
};
|
|
271
|
+
const routedNow = () => routed !== undefined && routed.path === pathNow() ? routed : undefined;
|
|
272
|
+
const pending = createPendingSpans();
|
|
273
|
+
const processor = rumSpanProcessor({
|
|
274
|
+
platform,
|
|
275
|
+
pending,
|
|
276
|
+
session,
|
|
277
|
+
views,
|
|
278
|
+
queryAllowList: () => settings.queryAllowList,
|
|
279
|
+
userId: () => userId,
|
|
280
|
+
bus,
|
|
281
|
+
now: deps.perfNow,
|
|
282
|
+
...(deps.timeOrigin === undefined ? {} : { timeOrigin: deps.timeOrigin }),
|
|
283
|
+
});
|
|
284
|
+
const onStart = (span, request) => {
|
|
285
|
+
for (const h of hooks) {
|
|
286
|
+
try {
|
|
287
|
+
h(span, request);
|
|
288
|
+
}
|
|
289
|
+
catch (err) {
|
|
290
|
+
diag.warn("o11y: rum: onRequestStart hook threw", err);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
// Buffer writes still in flight, so a flush after retention sees every batch exported before it.
|
|
295
|
+
// put never rejects.
|
|
296
|
+
const puts = new Set();
|
|
297
|
+
const settled = async () => {
|
|
298
|
+
await Promise.allSettled([...puts]);
|
|
299
|
+
};
|
|
300
|
+
const routing = {
|
|
301
|
+
decide: (id) => session.decide(id),
|
|
302
|
+
buffer: (b) => {
|
|
303
|
+
const p = retention.put(b).finally(() => puts.delete(p));
|
|
304
|
+
puts.add(p);
|
|
305
|
+
},
|
|
306
|
+
};
|
|
307
|
+
// A buffered batch goes out only when every session it holds records of is to be sent, because
|
|
308
|
+
// the buffer is shared by every tab and may hold another session's batches.
|
|
309
|
+
const keep = (b) => {
|
|
310
|
+
const ids = sessionsIn(b);
|
|
311
|
+
return ids !== undefined && [...ids].every((id) => session.decide(id) === "send");
|
|
312
|
+
};
|
|
313
|
+
const appExporter = options.spanExporter;
|
|
314
|
+
// An app that injects only a processor exports spans itself, so RUM adds no exporter.
|
|
315
|
+
const forward = options.spanProcessor === undefined || appExporter !== undefined;
|
|
316
|
+
/** The OTLP endpoints, once web resolved them. */
|
|
317
|
+
let ownUrls = [];
|
|
318
|
+
/** Endpoints collectors count as RUM's own traffic (ignoreUrl), as origin plus path, such as the replay endpoint. */
|
|
319
|
+
const collectorUrls = new Map();
|
|
320
|
+
/** Attributes collectors add to named events (addEventAttributes). */
|
|
321
|
+
const decorators = new Set();
|
|
322
|
+
const ignoreUrls = options.instrumentations?.ignoreUrls ?? [];
|
|
323
|
+
let spanTarget = appExporter === undefined ? undefined : retainingSpanExporter(appExporter, routing);
|
|
324
|
+
const wrappers = {
|
|
325
|
+
consentController: (c) => {
|
|
326
|
+
controller = c;
|
|
327
|
+
return c;
|
|
328
|
+
},
|
|
329
|
+
transportOptions: (o) => gatewayTransportOptions(o, resolved.clientToken, deps.now),
|
|
330
|
+
platform: (po, env) => {
|
|
331
|
+
delivery = po.delivery;
|
|
332
|
+
endpoints = po.endpoints;
|
|
333
|
+
ownUrls = OTLP_SIGNALS.flatMap((s) => (po.endpoints[s] === undefined ? [] : [po.endpoints[s]]));
|
|
334
|
+
if (forward && appExporter === undefined) {
|
|
335
|
+
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);
|
|
342
|
+
}
|
|
343
|
+
},
|
|
344
|
+
exporterSet: (set) => withRetention(set, routing),
|
|
345
|
+
onRequestStart: onStart,
|
|
346
|
+
};
|
|
347
|
+
// Hide handling. On a navigation, every engine fires pagehide before visibilitychange, and web's
|
|
348
|
+
// flush on hide runs once per hide and exports whatever is pending at that moment; a flush
|
|
349
|
+
// started after it waits for its export, which never completes once the page is gone. So RUM
|
|
350
|
+
// subscribes to the lifecycle before the binding runs the platform's setup: on the first hide
|
|
351
|
+
// signal it runs the hide hooks (vitals commit their values) and emits the summaries, and the
|
|
352
|
+
// platform's flush then exports them with the detail already pending. web-vitals listens in the
|
|
353
|
+
// capture phase on window, so its own hide reports land before either listener runs, and a
|
|
354
|
+
// later hide signal of the same hide sends what they added.
|
|
355
|
+
//
|
|
356
|
+
// RUM never exports on hide itself. Firefox and WebKit fire pagehide while the document still
|
|
357
|
+
// reports visible, so the send mode is "unload" only once web's own pagehide listener has run,
|
|
358
|
+
// and the microtasks after each listener would carry an export RUM started to the transport
|
|
359
|
+
// before that: a normal send, which the browser drops with the page.
|
|
360
|
+
const hideHooks = new Set();
|
|
361
|
+
let hideHandled = false;
|
|
362
|
+
/** What a hide sends, once setup finished. */
|
|
363
|
+
let afterHide;
|
|
364
|
+
const runHide = () => {
|
|
365
|
+
if (hideHandled)
|
|
366
|
+
return;
|
|
367
|
+
hideHandled = true;
|
|
368
|
+
summary.visibility(false);
|
|
369
|
+
for (const hook of [...hideHooks]) {
|
|
370
|
+
try {
|
|
371
|
+
hook();
|
|
372
|
+
}
|
|
373
|
+
catch (err) {
|
|
374
|
+
diag.warn("o11y: rum: a hide hook threw", err);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
const offLifecycle = lifecycle.subscribe({
|
|
379
|
+
hide: () => {
|
|
380
|
+
runHide();
|
|
381
|
+
afterHide?.();
|
|
382
|
+
},
|
|
383
|
+
show: () => {
|
|
384
|
+
hideHandled = false;
|
|
385
|
+
summary.visibility(true);
|
|
386
|
+
if (!killed)
|
|
387
|
+
session.touch();
|
|
388
|
+
},
|
|
389
|
+
restore: () => {
|
|
390
|
+
hideHandled = false;
|
|
391
|
+
},
|
|
392
|
+
});
|
|
393
|
+
let t;
|
|
394
|
+
try {
|
|
395
|
+
t = await deps.bind({
|
|
396
|
+
...options,
|
|
397
|
+
spanProcessor: composeProcessors(processor, options.spanProcessor),
|
|
398
|
+
contextManager: () => rumContextManager((options.contextManager ?? createContextManager)(), () => active),
|
|
399
|
+
...(forward ? { spanExporter: forwardingSpanExporter(() => spanTarget, pending) } : {}),
|
|
400
|
+
}, wrappers);
|
|
401
|
+
}
|
|
402
|
+
catch (err) {
|
|
403
|
+
offLifecycle();
|
|
404
|
+
views.close();
|
|
405
|
+
session.close();
|
|
406
|
+
retention.close();
|
|
407
|
+
throw err;
|
|
408
|
+
}
|
|
409
|
+
telemetry = t;
|
|
410
|
+
const gate = controller;
|
|
411
|
+
if (gate === undefined) {
|
|
412
|
+
await t.shutdown();
|
|
413
|
+
throw new O11yError("INVALID_OPTION", "rum: web setup built no consent controller");
|
|
414
|
+
}
|
|
415
|
+
/** RUM records: consent is granted and remote configuration has not switched it off. */
|
|
416
|
+
const on = () => gate.recording() && !killed;
|
|
417
|
+
// Events with a body (semconv's browser.web_vital) are bridge records: core's redacting log
|
|
418
|
+
// processor classifies their attributes, and the retention exporters route them by session.id.
|
|
419
|
+
const bodyLogger = t.loggerProvider.getLogger("@libo11y/rum", VERSION);
|
|
420
|
+
const runtime = {
|
|
421
|
+
platform,
|
|
422
|
+
...(deps.scope === undefined ? {} : { scope: deps.scope }),
|
|
423
|
+
telemetry: t,
|
|
424
|
+
tracer: t.tracerProvider.getTracer("@libo11y/rum", VERSION),
|
|
425
|
+
gate,
|
|
426
|
+
session,
|
|
427
|
+
views,
|
|
428
|
+
summary,
|
|
429
|
+
bus,
|
|
430
|
+
settings: () => settings,
|
|
431
|
+
now: deps.perfNow,
|
|
432
|
+
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();
|
|
438
|
+
let decorated = {};
|
|
439
|
+
for (const d of decorators) {
|
|
440
|
+
if (!d.names.has(name))
|
|
441
|
+
continue;
|
|
442
|
+
try {
|
|
443
|
+
decorated = { ...decorated, ...d.attrs() };
|
|
444
|
+
}
|
|
445
|
+
catch (err) {
|
|
446
|
+
diag.warn("o11y: rum: an event attributes hook threw", err);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
const merged = {
|
|
450
|
+
...(s === undefined ? {} : { [ATTR_SESSION_ID]: s.id }),
|
|
451
|
+
...(v === undefined ? {} : { [ATTR_RUM_VIEW_ID]: v.id }),
|
|
452
|
+
...(userId === undefined ? {} : { [ATTR_USER_ID]: userId }),
|
|
453
|
+
...decorated,
|
|
454
|
+
...attrs,
|
|
455
|
+
};
|
|
456
|
+
if (body === undefined) {
|
|
457
|
+
t.event(name, merged, ctx);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
bodyLogger.emit({
|
|
461
|
+
eventName: name,
|
|
462
|
+
severityNumber: SeverityNumber.INFO,
|
|
463
|
+
severityText: "INFO",
|
|
464
|
+
body: { ...body },
|
|
465
|
+
attributes: { ...merged, [EVENT_NAME_KEY]: name },
|
|
466
|
+
// Body events report page-level values at a hide, so the span active then is unrelated.
|
|
467
|
+
context: ctx ?? ROOT_CONTEXT,
|
|
468
|
+
});
|
|
469
|
+
},
|
|
470
|
+
onRequestStart(hook) {
|
|
471
|
+
hooks.add(hook);
|
|
472
|
+
return () => hooks.delete(hook);
|
|
473
|
+
},
|
|
474
|
+
activeAction: () => active,
|
|
475
|
+
setActiveAction(span) {
|
|
476
|
+
active = span;
|
|
477
|
+
},
|
|
478
|
+
breadcrumbs: () => crumbs.snapshot(deps.perfNow()),
|
|
479
|
+
onHide(hook) {
|
|
480
|
+
hideHooks.add(hook);
|
|
481
|
+
return () => hideHooks.delete(hook);
|
|
482
|
+
},
|
|
483
|
+
ignored(url) {
|
|
484
|
+
let u;
|
|
485
|
+
try {
|
|
486
|
+
u = new URL(url);
|
|
487
|
+
}
|
|
488
|
+
catch {
|
|
489
|
+
return false;
|
|
490
|
+
}
|
|
491
|
+
return (ownUrls.some((own) => u.href.startsWith(own)) ||
|
|
492
|
+
[...collectorUrls.values()].some((own) => `${u.origin}${u.pathname}` === own) ||
|
|
493
|
+
isIgnored(u, ignoreUrls));
|
|
494
|
+
},
|
|
495
|
+
remoteDocument: () => (remote === undefined ? undefined : remote.find(session.current()?.configVersion)),
|
|
496
|
+
addEventAttributes(names, attrs) {
|
|
497
|
+
const d = { names: new Set(names), attrs };
|
|
498
|
+
decorators.add(d);
|
|
499
|
+
return () => decorators.delete(d);
|
|
500
|
+
},
|
|
501
|
+
ignoreUrl(url) {
|
|
502
|
+
const key = Symbol(url);
|
|
503
|
+
let path = url;
|
|
504
|
+
try {
|
|
505
|
+
const u = new URL(url, deps.location());
|
|
506
|
+
path = `${u.origin}${u.pathname}`;
|
|
507
|
+
}
|
|
508
|
+
catch {
|
|
509
|
+
// kept as given
|
|
510
|
+
}
|
|
511
|
+
collectorUrls.set(key, path);
|
|
512
|
+
return () => collectorUrls.delete(key);
|
|
513
|
+
},
|
|
514
|
+
};
|
|
515
|
+
// Collectors run only while consent is granted, remote configuration has not switched RUM off,
|
|
516
|
+
// and the current session's settings enable them.
|
|
517
|
+
const running = new Map();
|
|
518
|
+
/** The session is up and the view begun, so the enabled collectors are to run. */
|
|
519
|
+
let collecting = false;
|
|
520
|
+
let starting;
|
|
521
|
+
let stopRemote;
|
|
522
|
+
/** Consent was granted at some point in this page, so RUM may have stored something. */
|
|
523
|
+
let everStarted = false;
|
|
524
|
+
/** Bumped by stopAll, so a start whose session load outlived a revoke does nothing. */
|
|
525
|
+
let generation = 0;
|
|
526
|
+
const reconcile = () => {
|
|
527
|
+
const want = collecting && on() ? settings.enabled : new Set();
|
|
528
|
+
for (const [name, stop] of [...running].reverse()) {
|
|
529
|
+
if (want.has(name))
|
|
530
|
+
continue;
|
|
531
|
+
running.delete(name);
|
|
532
|
+
try {
|
|
533
|
+
stop();
|
|
534
|
+
}
|
|
535
|
+
catch (err) {
|
|
536
|
+
diag.warn(`o11y: rum: collector ${name} failed to stop`, err);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
for (const c of resolved.collectors) {
|
|
540
|
+
if (!want.has(c.name) || running.has(c.name))
|
|
541
|
+
continue;
|
|
542
|
+
try {
|
|
543
|
+
running.set(c.name, c.start(runtime));
|
|
544
|
+
}
|
|
545
|
+
catch (err) {
|
|
546
|
+
diag.warn(`o11y: rum: collector ${c.name} failed to start`, err);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
/** Starts the session, the view and the collectors. */
|
|
551
|
+
const activate = async (gen) => {
|
|
552
|
+
if (killed) {
|
|
553
|
+
pending.discard();
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
await session.start();
|
|
557
|
+
// Revoked while the session loaded, and maybe granted again: that later start runs instead.
|
|
558
|
+
if (gen !== generation || !gate.recording() || killed) {
|
|
559
|
+
if (gen === generation)
|
|
560
|
+
pending.discard();
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
settings = forSession(session.current()?.configVersion);
|
|
564
|
+
views.begin();
|
|
565
|
+
// Spans that started while the session loaded, such as app_load right after a late grant.
|
|
566
|
+
const s = session.current();
|
|
567
|
+
pending.resolve((load) => {
|
|
568
|
+
const v = load ? views.loadView() : views.current();
|
|
569
|
+
return {
|
|
570
|
+
...(s === undefined ? {} : { [ATTR_SESSION_ID]: s.id }),
|
|
571
|
+
...(v === undefined ? {} : { [ATTR_RUM_VIEW_ID]: v.id }),
|
|
572
|
+
};
|
|
573
|
+
});
|
|
574
|
+
const r = routedNow();
|
|
575
|
+
if (r?.name !== undefined)
|
|
576
|
+
views.rename(r.name);
|
|
577
|
+
// A kept session may find batches an earlier page of it left in the buffer.
|
|
578
|
+
if (session.kept()) {
|
|
579
|
+
flushRetention().catch((err) => diag.warn("o11y: rum: retention flush failed", err));
|
|
580
|
+
}
|
|
581
|
+
collecting = true;
|
|
582
|
+
reconcile();
|
|
583
|
+
if (r?.renderedAt !== undefined)
|
|
584
|
+
views.rendered(r.renderedAt);
|
|
585
|
+
// A fixed view (a content script) is on screen as soon as it starts.
|
|
586
|
+
else if (deps.scope?.fixedView === true)
|
|
587
|
+
views.rendered();
|
|
588
|
+
};
|
|
589
|
+
/** The kill switch acts at once; every other change waits for the next session. */
|
|
590
|
+
const onRemote = (doc) => {
|
|
591
|
+
if (!gate.recording())
|
|
592
|
+
return;
|
|
593
|
+
const off = doc?.enabled === false;
|
|
594
|
+
if (off && !killed) {
|
|
595
|
+
killed = true;
|
|
596
|
+
collecting = false;
|
|
597
|
+
reconcile();
|
|
598
|
+
active = undefined;
|
|
599
|
+
views.end();
|
|
600
|
+
}
|
|
601
|
+
else if (!off && killed) {
|
|
602
|
+
killed = false;
|
|
603
|
+
activate(generation).catch((err) => diag.warn("o11y: rum: start failed", err));
|
|
604
|
+
}
|
|
605
|
+
else if (!off && collecting) {
|
|
606
|
+
// The document the current session started under may only now be known, as when another
|
|
607
|
+
// tab started the session under a document this tab had not fetched yet.
|
|
608
|
+
settings = forSession(session.current()?.configVersion);
|
|
609
|
+
reconcile();
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
const openRemote = () => {
|
|
613
|
+
if (rc === undefined)
|
|
614
|
+
return undefined;
|
|
615
|
+
const url = configUrl(rc.url, endpoints, deps.location(), t.resource.attributes["service.name"], resolved.clientToken);
|
|
616
|
+
const f = deps.fetch ?? pristineFetch;
|
|
617
|
+
if (url === undefined || f === undefined) {
|
|
618
|
+
diag.warn("o11y: rum: remote configuration has no URL or no fetch; it is off");
|
|
619
|
+
return undefined;
|
|
620
|
+
}
|
|
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
|
+
});
|
|
631
|
+
let storage;
|
|
632
|
+
try {
|
|
633
|
+
storage = deps.storage?.();
|
|
634
|
+
}
|
|
635
|
+
catch {
|
|
636
|
+
storage = undefined;
|
|
637
|
+
}
|
|
638
|
+
return storage instanceof Promise ? storage.then(connect, () => connect(undefined)) : connect(storage);
|
|
639
|
+
};
|
|
640
|
+
/** The connection being opened, while its cache storage loads. */
|
|
641
|
+
let opening;
|
|
642
|
+
const startAll = () => {
|
|
643
|
+
everStarted = true;
|
|
644
|
+
const gen = generation;
|
|
645
|
+
pending.open();
|
|
646
|
+
starting ??= (async () => {
|
|
647
|
+
try {
|
|
648
|
+
if (remote === undefined) {
|
|
649
|
+
const opened = opening ?? openRemote();
|
|
650
|
+
if (opened instanceof Promise) {
|
|
651
|
+
opening = opened;
|
|
652
|
+
const connection = await opened;
|
|
653
|
+
remote ??= connection;
|
|
654
|
+
if (opening === opened)
|
|
655
|
+
opening = undefined;
|
|
656
|
+
// Revoked while the cache loaded: the revoke found no connection to clear.
|
|
657
|
+
if (gen !== generation) {
|
|
658
|
+
if (!gate.recording())
|
|
659
|
+
remote?.clear();
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
else
|
|
664
|
+
remote = opened;
|
|
665
|
+
}
|
|
666
|
+
killed = remote?.current()?.enabled === false;
|
|
667
|
+
await activate(gen);
|
|
668
|
+
if (gen !== generation || !gate.recording())
|
|
669
|
+
return;
|
|
670
|
+
stopRemote = remote?.start(onRemote);
|
|
671
|
+
}
|
|
672
|
+
catch (err) {
|
|
673
|
+
// A start that failed releases the spans waiting for its session, so no export stalls.
|
|
674
|
+
if (gen === generation)
|
|
675
|
+
pending.discard();
|
|
676
|
+
throw err;
|
|
677
|
+
}
|
|
678
|
+
})();
|
|
679
|
+
return starting;
|
|
680
|
+
};
|
|
681
|
+
const stopAll = () => {
|
|
682
|
+
generation++;
|
|
683
|
+
pending.discard();
|
|
684
|
+
collecting = false;
|
|
685
|
+
reconcile();
|
|
686
|
+
stopRemote?.();
|
|
687
|
+
stopRemote = undefined;
|
|
688
|
+
starting = undefined;
|
|
689
|
+
};
|
|
690
|
+
const flushRetention = async () => {
|
|
691
|
+
reportFlush(t, "rum: retention flush", await t.forceFlush());
|
|
692
|
+
await settled();
|
|
693
|
+
if (delivery !== undefined && gate.recording())
|
|
694
|
+
await retention.flush(delivery, keep);
|
|
695
|
+
};
|
|
696
|
+
// Session end (decision P13): when tabs rotate an expired session at the same moment, each ends
|
|
697
|
+
// it and starts a session of its own, then all adopt the same newest one. The tab whose session
|
|
698
|
+
// won emits o11y.rum.session.end, so it is emitted once: each tab waits SESSION_END_ELECTION_MILLIS
|
|
699
|
+
// for the others' broadcasts and emits only if its successor is still the current session. An
|
|
700
|
+
// unkept session that ends removes only its own records from the shared retention buffer.
|
|
701
|
+
//
|
|
702
|
+
// Session start (R3f): the o11y.rum.session.start of a kept session waits for the same election,
|
|
703
|
+
// so only the session every context ends up sharing sends its start. That covers two tabs rotating at once and two
|
|
704
|
+
// contexts that both find nothing stored and create the first session, as an extension's side
|
|
705
|
+
// panel and content script do, each before it hears of the other's. A context whose session lost
|
|
706
|
+
// abandons its start. A page that hides first sends its pending start if that session is still
|
|
707
|
+
// current, because a hidden page may never run again.
|
|
708
|
+
const endTimers = new Set();
|
|
709
|
+
let endingSession;
|
|
710
|
+
const pendingStarts = new Map();
|
|
711
|
+
const sendStart = (s) => {
|
|
712
|
+
t.event(EVENT_RUM_SESSION_START, {
|
|
713
|
+
[ATTR_SESSION_ID]: s.id,
|
|
714
|
+
[ATTR_RUM_PLATFORM]: platform,
|
|
715
|
+
...(s.configVersion === undefined ? {} : { [ATTR_RUM_CONFIG_VERSION]: s.configVersion }),
|
|
716
|
+
});
|
|
717
|
+
};
|
|
718
|
+
/** Decides every start still waiting for its election now. */
|
|
719
|
+
const settleStarts = () => {
|
|
720
|
+
for (const [timer, decide] of [...pendingStarts]) {
|
|
721
|
+
clearTimeout(timer);
|
|
722
|
+
decide();
|
|
723
|
+
}
|
|
724
|
+
};
|
|
725
|
+
const offSession = session.subscribe((e) => {
|
|
726
|
+
if (e.type === "start") {
|
|
727
|
+
// A new session takes the newest document; an adopted one, the document it started under.
|
|
728
|
+
settings = forSession(e.session.configVersion);
|
|
729
|
+
queueMicrotask(reconcile);
|
|
730
|
+
}
|
|
731
|
+
// While remote configuration has switched RUM off, a rotation sends no session events.
|
|
732
|
+
if (e.type === "kept") {
|
|
733
|
+
if (on())
|
|
734
|
+
flushRetention().catch((err) => diag.warn("o11y: rum: retention flush failed", err));
|
|
735
|
+
}
|
|
736
|
+
else if (e.type === "start" && e.local && on()) {
|
|
737
|
+
if (endingSession !== undefined && e.previous?.id === endingSession.id)
|
|
738
|
+
endingSession.successor = e.session.id;
|
|
739
|
+
const started = e.session;
|
|
740
|
+
// An unkept session's start waits in the retention buffer and is sent only if the session is
|
|
741
|
+
// kept. A session that lost its election is abandoned and never kept, so its start is never
|
|
742
|
+
// sent, and buffering it at once means a reload before the election cannot lose it.
|
|
743
|
+
if (started.retained === undefined) {
|
|
744
|
+
sendStart(started);
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
const decide = () => {
|
|
748
|
+
pendingStarts.delete(timer);
|
|
749
|
+
if (on() && session.current()?.id === started.id)
|
|
750
|
+
sendStart(started);
|
|
751
|
+
};
|
|
752
|
+
const timer = setTimeout(decide, SESSION_END_ELECTION_MILLIS);
|
|
753
|
+
pendingStarts.set(timer, decide);
|
|
754
|
+
}
|
|
755
|
+
else if (e.type === "end" && e.local) {
|
|
756
|
+
const ended = e.session;
|
|
757
|
+
if (ended.retained === undefined) {
|
|
758
|
+
void (async () => {
|
|
759
|
+
await settled();
|
|
760
|
+
await retention.discard((b) => sessionsIn(b)?.has(ended.id) === true);
|
|
761
|
+
})();
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
const candidate = { id: ended.id, retained: ended.retained, successor: undefined };
|
|
765
|
+
endingSession = candidate;
|
|
766
|
+
const timer = setTimeout(() => {
|
|
767
|
+
endTimers.delete(timer);
|
|
768
|
+
if (endingSession === candidate)
|
|
769
|
+
endingSession = undefined;
|
|
770
|
+
if (!on() || candidate.successor === undefined)
|
|
771
|
+
return;
|
|
772
|
+
if (session.current()?.id !== candidate.successor)
|
|
773
|
+
return; // another tab's rotation won
|
|
774
|
+
t.event(EVENT_RUM_SESSION_END, {
|
|
775
|
+
[ATTR_SESSION_ID]: candidate.id,
|
|
776
|
+
[ATTR_RUM_SESSION_RETAINED]: candidate.retained,
|
|
777
|
+
});
|
|
778
|
+
}, SESSION_END_ELECTION_MILLIS);
|
|
779
|
+
endTimers.add(timer);
|
|
780
|
+
}
|
|
781
|
+
});
|
|
782
|
+
const stopRecording = () => {
|
|
783
|
+
stopAll();
|
|
784
|
+
// A revoked session sends no start.
|
|
785
|
+
for (const timer of pendingStarts.keys())
|
|
786
|
+
clearTimeout(timer);
|
|
787
|
+
pendingStarts.clear();
|
|
788
|
+
active = undefined;
|
|
789
|
+
crumbs.clear();
|
|
790
|
+
summary.reset();
|
|
791
|
+
views.end();
|
|
792
|
+
session.clear();
|
|
793
|
+
};
|
|
794
|
+
const offRevoke = gate.onRevoke(async () => {
|
|
795
|
+
if (!everStarted)
|
|
796
|
+
return;
|
|
797
|
+
await settled();
|
|
798
|
+
// 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
|
+
}
|
|
803
|
+
});
|
|
804
|
+
const offGate = gate.subscribe((recording) => {
|
|
805
|
+
if (recording)
|
|
806
|
+
startAll().catch((err) => diag.warn("o11y: rum: start failed", err));
|
|
807
|
+
else if (everStarted)
|
|
808
|
+
stopRecording();
|
|
809
|
+
});
|
|
810
|
+
// A hidden page may never run again (frozen or discarded on mobile), so a start still waiting for
|
|
811
|
+
// its election goes out now if its session is still current.
|
|
812
|
+
afterHide = () => {
|
|
813
|
+
settleStarts();
|
|
814
|
+
summary.flush();
|
|
815
|
+
};
|
|
816
|
+
const onActivity = () => {
|
|
817
|
+
if (!killed)
|
|
818
|
+
session.touch();
|
|
819
|
+
};
|
|
820
|
+
const offActivity = lifecycle.activity?.(onActivity);
|
|
821
|
+
const rum = {
|
|
822
|
+
sessionId: () => (gate.recording() ? session.current()?.id : undefined),
|
|
823
|
+
identify(id) {
|
|
824
|
+
if (id?.includes("@")) {
|
|
825
|
+
throw new O11yError("INVALID_OPTION", "rum.identify: an email address is not a pseudonymous ID");
|
|
826
|
+
}
|
|
827
|
+
userId = id;
|
|
828
|
+
},
|
|
829
|
+
onRequestStart: (hook) => runtime.onRequestStart(hook),
|
|
830
|
+
startView(o) {
|
|
831
|
+
routed = { path: pathNow(), ...(o?.name === undefined ? {} : { name: o.name }) };
|
|
832
|
+
if (!on())
|
|
833
|
+
return;
|
|
834
|
+
const cause = active?.isRecording() === true ? active.spanContext() : undefined;
|
|
835
|
+
views.start({
|
|
836
|
+
kind: "soft",
|
|
837
|
+
...(o?.name === undefined ? {} : { name: o.name }),
|
|
838
|
+
...(cause === undefined ? {} : { cause }),
|
|
839
|
+
});
|
|
840
|
+
},
|
|
841
|
+
setViewName(name) {
|
|
842
|
+
routed = { ...samePath(), name };
|
|
843
|
+
if (on())
|
|
844
|
+
views.rename(name);
|
|
845
|
+
},
|
|
846
|
+
viewRendered() {
|
|
847
|
+
routed = { ...samePath(), renderedAt: deps.perfNow() };
|
|
848
|
+
if (on())
|
|
849
|
+
views.rendered();
|
|
850
|
+
},
|
|
851
|
+
addAction(name) {
|
|
852
|
+
if (on())
|
|
853
|
+
recordInstantAction(runtime, "custom", name);
|
|
854
|
+
},
|
|
855
|
+
addError(error, o) {
|
|
856
|
+
if (!on())
|
|
857
|
+
return;
|
|
858
|
+
recordError(runtime, o?.source ?? "custom", error, o?.componentStack === undefined ? {} : { componentStack: o.componentStack });
|
|
859
|
+
},
|
|
860
|
+
};
|
|
861
|
+
const handle = t;
|
|
862
|
+
Object.defineProperty(handle, "rum", { value: rum, enumerable: true });
|
|
863
|
+
runtimes.set(handle, runtime);
|
|
864
|
+
const webShutdown = t.shutdown.bind(t);
|
|
865
|
+
let shutdownPromise;
|
|
866
|
+
handle.shutdown = (opts) => {
|
|
867
|
+
shutdownPromise ??= (async () => {
|
|
868
|
+
stopAll();
|
|
869
|
+
views.end();
|
|
870
|
+
summary.flush();
|
|
871
|
+
offLifecycle();
|
|
872
|
+
offActivity?.();
|
|
873
|
+
offGate();
|
|
874
|
+
offRevoke();
|
|
875
|
+
offSession();
|
|
876
|
+
settleStarts();
|
|
877
|
+
for (const timer of endTimers)
|
|
878
|
+
clearTimeout(timer);
|
|
879
|
+
endTimers.clear();
|
|
880
|
+
const report = await webShutdown(opts);
|
|
881
|
+
views.close();
|
|
882
|
+
session.close();
|
|
883
|
+
await settled();
|
|
884
|
+
retention.close();
|
|
885
|
+
return report;
|
|
886
|
+
})();
|
|
887
|
+
return shutdownPromise;
|
|
888
|
+
};
|
|
889
|
+
// The bootstrap buffer (decision P9) is replayed only into the start setup makes with consent
|
|
890
|
+
// granted. A page that starts pending discards it, even if consent is granted later. It is taken
|
|
891
|
+
// before the collectors start, so an event is never both buffered and seen by a collector; one
|
|
892
|
+
// that happens while the session loads, between the two, is not recorded.
|
|
893
|
+
const replay = deps.bootstrap?.();
|
|
894
|
+
if (gate.recording()) {
|
|
895
|
+
await startAll();
|
|
896
|
+
// A scoped context (a content script) shares its world with no page bootstrap of its own: what
|
|
897
|
+
// a bootstrap there buffered may be the host page's, so it is dropped.
|
|
898
|
+
if (!killed && deps.scope === undefined)
|
|
899
|
+
replay?.(runtime);
|
|
900
|
+
}
|
|
901
|
+
return handle;
|
|
902
|
+
}
|