@libo11y/rum 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +478 -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 +103 -0
- package/dist/config/remote.js +241 -0
- package/dist/context-manager.d.ts +8 -0
- package/dist/context-manager.js +29 -0
- package/dist/contracts/binding.d.ts +82 -0
- package/dist/contracts/binding.js +1 -0
- package/dist/contracts/retention.d.ts +32 -0
- package/dist/contracts/retention.js +1 -0
- package/dist/contracts/runtime.d.ts +164 -0
- package/dist/contracts/runtime.js +1 -0
- package/dist/contracts/session.d.ts +68 -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 +121 -0
- package/dist/core-setup.js +1117 -0
- package/dist/core.d.ts +46 -0
- package/dist/core.js +36 -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 +34 -0
- package/dist/internal.js +25 -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 +29 -0
- package/dist/retention/buffer.js +130 -0
- package/dist/retention/exporters.d.ts +71 -0
- package/dist/retention/exporters.js +281 -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 +42 -0
- package/dist/setup.js +57 -0
- package/dist/span-processor.d.ts +38 -0
- package/dist/span-processor.js +125 -0
- package/dist/summary/accumulator.d.ts +30 -0
- package/dist/summary/accumulator.js +128 -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 +286 -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 +37 -0
- package/dist/views/tracker.js +114 -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 +18 -0
- package/dist/webext/config-storage.js +98 -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 +104 -0
- package/dist/webext/setup.d.ts +74 -0
- package/dist/webext/setup.js +206 -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 +60 -4
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The web session store: the record in localStorage, so a reload and every tab of the origin read
|
|
3
|
+
* it, and a BroadcastChannel, so other tabs hear a change at once. Saves are versioned JSON.
|
|
4
|
+
*/
|
|
5
|
+
import { diag } from "@opentelemetry/api";
|
|
6
|
+
import { parseSessionState, SESSION_STORAGE_KEY } from "./state.js";
|
|
7
|
+
export { parseSessionState, SESSION_STORAGE_KEY } from "./state.js";
|
|
8
|
+
export const SESSION_CHANNEL = "libo11y.rum";
|
|
9
|
+
function defaultStorage() {
|
|
10
|
+
try {
|
|
11
|
+
return globalThis.localStorage;
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return undefined; // a sandboxed frame throws on access
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function defaultChannel() {
|
|
18
|
+
const BC = globalThis
|
|
19
|
+
.BroadcastChannel;
|
|
20
|
+
return BC === undefined ? undefined : new BC(SESSION_CHANNEL);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The web SessionStore. Storage and the default channel are reached on first use, which the session
|
|
24
|
+
* manager makes only after consent is granted, so no BroadcastChannel exists before then.
|
|
25
|
+
*/
|
|
26
|
+
export function localStorageSessionStore(opts = {}) {
|
|
27
|
+
let storage;
|
|
28
|
+
let channel;
|
|
29
|
+
let opened = false;
|
|
30
|
+
const open = () => {
|
|
31
|
+
if (opened)
|
|
32
|
+
return;
|
|
33
|
+
opened = true;
|
|
34
|
+
storage = opts.storage ?? defaultStorage();
|
|
35
|
+
channel = opts.channel ?? defaultChannel();
|
|
36
|
+
channel?.addEventListener("message", onMessage);
|
|
37
|
+
};
|
|
38
|
+
const listeners = new Set();
|
|
39
|
+
const onMessage = (e) => {
|
|
40
|
+
const d = e.data;
|
|
41
|
+
if (typeof d !== "object" || d === null || !("session" in d))
|
|
42
|
+
return;
|
|
43
|
+
const s = d.session === null ? undefined : parseSessionState(d.session);
|
|
44
|
+
if (d.session !== null && s === undefined)
|
|
45
|
+
return;
|
|
46
|
+
for (const l of listeners)
|
|
47
|
+
l(s);
|
|
48
|
+
};
|
|
49
|
+
return {
|
|
50
|
+
async load() {
|
|
51
|
+
open();
|
|
52
|
+
try {
|
|
53
|
+
const raw = storage?.getItem(SESSION_STORAGE_KEY);
|
|
54
|
+
return raw == null ? undefined : parseSessionState(JSON.parse(raw));
|
|
55
|
+
}
|
|
56
|
+
catch (err) {
|
|
57
|
+
diag.debug("o11y: rum: session storage unreadable", err);
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
save(state) {
|
|
62
|
+
open();
|
|
63
|
+
const record = state === undefined ? null : { v: 1, ...state };
|
|
64
|
+
try {
|
|
65
|
+
if (record === null)
|
|
66
|
+
storage?.removeItem(SESSION_STORAGE_KEY);
|
|
67
|
+
else
|
|
68
|
+
storage?.setItem(SESSION_STORAGE_KEY, JSON.stringify(record));
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
diag.debug("o11y: rum: session storage write failed", err);
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
channel?.postMessage({ session: record });
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
diag.debug("o11y: rum: session broadcast failed", err);
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
onChange(listener) {
|
|
81
|
+
open();
|
|
82
|
+
listeners.add(listener);
|
|
83
|
+
return () => listeners.delete(listener);
|
|
84
|
+
},
|
|
85
|
+
close() {
|
|
86
|
+
channel?.removeEventListener("message", onMessage);
|
|
87
|
+
channel?.close();
|
|
88
|
+
listeners.clear();
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session manager. It keeps the session in memory, so current() is synchronous for the span
|
|
3
|
+
* processor, and saves to the store on every change and on activity at most every saveEveryMillis.
|
|
4
|
+
*
|
|
5
|
+
* Rules. A session is expired when now - lastActivityAt >= idleMillis or now - startedAt >=
|
|
6
|
+
* maxMillis. There is no session before start() has loaded the stored one. current() rotates an
|
|
7
|
+
* expired session: records made after expiry start a new session, and only touch() extends one.
|
|
8
|
+
* Rotation creates a session whose sampled flag is sessionSampled(id, rate), retained head_sampled
|
|
9
|
+
* when sampled, saves it, emits end (local) for the old one, then start (local, with previous).
|
|
10
|
+
*
|
|
11
|
+
* On another context's change: the same ID merges (the latest lastActivityAt, retained kept once
|
|
12
|
+
* set, emitting kept with local false when it newly became kept). A different ID is adopted when
|
|
13
|
+
* this context has none, or when its startedAt is later, or equal with a smaller ID, emitting start
|
|
14
|
+
* with local false. A removed session is forgotten, so the next current() creates one, with the
|
|
15
|
+
* removed session as its previous.
|
|
16
|
+
*
|
|
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.
|
|
20
|
+
*/
|
|
21
|
+
import type { SessionManager, SessionStore } from "../contracts/session.ts";
|
|
22
|
+
export interface SessionManagerOptions {
|
|
23
|
+
readonly store: SessionStore;
|
|
24
|
+
/** Read when a session is created. */
|
|
25
|
+
readonly sampleRate: () => number;
|
|
26
|
+
readonly idleMillis: number;
|
|
27
|
+
readonly maxMillis: number;
|
|
28
|
+
/** The least time between two activity saves. Default 5000. */
|
|
29
|
+
readonly saveEveryMillis?: number;
|
|
30
|
+
/** Read when a session is created. */
|
|
31
|
+
readonly configVersion?: () => string | undefined;
|
|
32
|
+
/** Epoch milliseconds. Default Date.now. */
|
|
33
|
+
readonly now?: () => number;
|
|
34
|
+
readonly randomId?: () => string;
|
|
35
|
+
}
|
|
36
|
+
export declare function createSessionManager(opts: SessionManagerOptions): SessionManager;
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { randomUuid } from "../ids.js";
|
|
2
|
+
import { sessionSampled } from "./sampling.js";
|
|
3
|
+
const RECENT = 4;
|
|
4
|
+
export function createSessionManager(opts) {
|
|
5
|
+
const now = opts.now ?? Date.now;
|
|
6
|
+
const randomId = opts.randomId ?? randomUuid;
|
|
7
|
+
const saveEvery = opts.saveEveryMillis ?? 5000;
|
|
8
|
+
const listeners = new Set();
|
|
9
|
+
/** Sessions this context knew, newest last, with whether each was kept. */
|
|
10
|
+
const recent = new Map();
|
|
11
|
+
let state;
|
|
12
|
+
/** start() was called and not cleared since. */
|
|
13
|
+
let started = false;
|
|
14
|
+
/** The stored session has loaded: until then there is no session, so none is created early. */
|
|
15
|
+
let ready = false;
|
|
16
|
+
let lastSave = 0;
|
|
17
|
+
let unsubscribe;
|
|
18
|
+
/** The session another context removed, so the next one starts with it as previous. */
|
|
19
|
+
let forgotten;
|
|
20
|
+
/** Bumped by clear(), so a start() whose load resolves after a clear does nothing. */
|
|
21
|
+
let generation = 0;
|
|
22
|
+
const emit = (e) => {
|
|
23
|
+
for (const l of listeners)
|
|
24
|
+
l(e);
|
|
25
|
+
};
|
|
26
|
+
const remember = (s) => {
|
|
27
|
+
recent.delete(s.id);
|
|
28
|
+
recent.set(s.id, s.retained !== undefined);
|
|
29
|
+
while (recent.size > RECENT)
|
|
30
|
+
recent.delete(recent.keys().next().value);
|
|
31
|
+
};
|
|
32
|
+
const expired = (s, t) => t - s.lastActivityAt >= opts.idleMillis || t - s.startedAt >= opts.maxMillis;
|
|
33
|
+
const save = (s) => {
|
|
34
|
+
lastSave = now();
|
|
35
|
+
opts.store.save(s);
|
|
36
|
+
};
|
|
37
|
+
const rotate = (t) => {
|
|
38
|
+
const ended = state;
|
|
39
|
+
const previous = state ?? forgotten;
|
|
40
|
+
forgotten = undefined;
|
|
41
|
+
const id = randomId();
|
|
42
|
+
const sampled = sessionSampled(id, opts.sampleRate());
|
|
43
|
+
const version = opts.configVersion?.();
|
|
44
|
+
const next = {
|
|
45
|
+
id,
|
|
46
|
+
startedAt: t,
|
|
47
|
+
lastActivityAt: t,
|
|
48
|
+
sampled,
|
|
49
|
+
...(sampled ? { retained: "head_sampled" } : {}),
|
|
50
|
+
...(version === undefined ? {} : { configVersion: version }),
|
|
51
|
+
};
|
|
52
|
+
state = next;
|
|
53
|
+
remember(next);
|
|
54
|
+
save(next);
|
|
55
|
+
if (ended !== undefined)
|
|
56
|
+
emit({ type: "end", session: ended, local: true });
|
|
57
|
+
emit({ type: "start", session: next, ...(previous === undefined ? {} : { previous }), local: true });
|
|
58
|
+
return next;
|
|
59
|
+
};
|
|
60
|
+
const live = () => {
|
|
61
|
+
if (!ready)
|
|
62
|
+
return undefined;
|
|
63
|
+
const t = now();
|
|
64
|
+
if (state === undefined || expired(state, t))
|
|
65
|
+
return rotate(t);
|
|
66
|
+
return state;
|
|
67
|
+
};
|
|
68
|
+
const adopt = (incoming) => {
|
|
69
|
+
if (incoming === undefined) {
|
|
70
|
+
forgotten = state ?? forgotten;
|
|
71
|
+
state = undefined;
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (state !== undefined && incoming.id === state.id) {
|
|
75
|
+
const becameKept = state.retained === undefined && incoming.retained !== undefined;
|
|
76
|
+
const retained = state.retained ?? incoming.retained;
|
|
77
|
+
state = {
|
|
78
|
+
...state,
|
|
79
|
+
lastActivityAt: Math.max(state.lastActivityAt, incoming.lastActivityAt),
|
|
80
|
+
...(retained === undefined ? {} : { retained }),
|
|
81
|
+
};
|
|
82
|
+
remember(state);
|
|
83
|
+
if (becameKept)
|
|
84
|
+
emit({ type: "kept", session: state, local: false });
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const newer = state === undefined ||
|
|
88
|
+
incoming.startedAt > state.startedAt ||
|
|
89
|
+
(incoming.startedAt === state.startedAt && incoming.id < state.id);
|
|
90
|
+
if (!newer)
|
|
91
|
+
return;
|
|
92
|
+
const previous = state;
|
|
93
|
+
state = incoming;
|
|
94
|
+
remember(incoming);
|
|
95
|
+
emit({ type: "start", session: incoming, ...(previous === undefined ? {} : { previous }), local: false });
|
|
96
|
+
};
|
|
97
|
+
return {
|
|
98
|
+
async start() {
|
|
99
|
+
if (started)
|
|
100
|
+
return;
|
|
101
|
+
started = true;
|
|
102
|
+
const gen = generation;
|
|
103
|
+
unsubscribe = opts.store.onChange(adopt);
|
|
104
|
+
const stored = await opts.store.load();
|
|
105
|
+
if (gen !== generation)
|
|
106
|
+
return; // cleared while loading
|
|
107
|
+
ready = true;
|
|
108
|
+
if (stored !== undefined && state === undefined) {
|
|
109
|
+
state = stored;
|
|
110
|
+
remember(stored);
|
|
111
|
+
// A live stored session was started elsewhere. An expired one is ended here:
|
|
112
|
+
// live() below rotates it and emits its local end.
|
|
113
|
+
if (!expired(stored, now()))
|
|
114
|
+
emit({ type: "start", session: stored, local: false });
|
|
115
|
+
}
|
|
116
|
+
live();
|
|
117
|
+
},
|
|
118
|
+
current: live,
|
|
119
|
+
touch() {
|
|
120
|
+
const s = live();
|
|
121
|
+
if (s === undefined)
|
|
122
|
+
return;
|
|
123
|
+
const t = now();
|
|
124
|
+
state = { ...s, lastActivityAt: t };
|
|
125
|
+
if (t - lastSave >= saveEvery)
|
|
126
|
+
save(state);
|
|
127
|
+
},
|
|
128
|
+
kept: () => live()?.retained !== undefined,
|
|
129
|
+
retain(reason) {
|
|
130
|
+
const s = live();
|
|
131
|
+
if (s === undefined || s.retained !== undefined)
|
|
132
|
+
return false;
|
|
133
|
+
state = { ...s, retained: reason };
|
|
134
|
+
remember(state);
|
|
135
|
+
save(state);
|
|
136
|
+
emit({ type: "kept", session: state, local: true });
|
|
137
|
+
return true;
|
|
138
|
+
},
|
|
139
|
+
decide(sessionId) {
|
|
140
|
+
const s = live();
|
|
141
|
+
const id = sessionId ?? s?.id;
|
|
142
|
+
if (id === undefined)
|
|
143
|
+
return "drop";
|
|
144
|
+
if (s !== undefined && id === s.id)
|
|
145
|
+
return s.retained === undefined ? "buffer" : "send";
|
|
146
|
+
return recent.get(id) === true ? "send" : "drop";
|
|
147
|
+
},
|
|
148
|
+
clear() {
|
|
149
|
+
generation++;
|
|
150
|
+
forgotten = undefined;
|
|
151
|
+
state = undefined;
|
|
152
|
+
recent.clear();
|
|
153
|
+
started = false;
|
|
154
|
+
ready = false;
|
|
155
|
+
unsubscribe?.();
|
|
156
|
+
unsubscribe = undefined;
|
|
157
|
+
save(undefined);
|
|
158
|
+
},
|
|
159
|
+
subscribe(listener) {
|
|
160
|
+
listeners.add(listener);
|
|
161
|
+
return () => listeners.delete(listener);
|
|
162
|
+
},
|
|
163
|
+
close() {
|
|
164
|
+
unsubscribe?.();
|
|
165
|
+
opts.store.close();
|
|
166
|
+
listeners.clear();
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** FNV-1a 32-bit over the UTF-8 bytes of s, as an unsigned integer. */
|
|
2
|
+
export declare function fnv1a32(s: string): number;
|
|
3
|
+
/** Whether the session with this ID is head-sampled at rate (0..1). NaN and rates at or below 0 keep nothing. */
|
|
4
|
+
export declare function sessionSampled(sessionId: string, rate: number): boolean;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session sampling. The decision is a hash of session.id, so every tab of a session,
|
|
3
|
+
* and every client language, agrees: kept when fnv1a32(utf8(id)) / 2^32 < rate.
|
|
4
|
+
*/
|
|
5
|
+
const encoder = new TextEncoder();
|
|
6
|
+
/** FNV-1a 32-bit over the UTF-8 bytes of s, as an unsigned integer. */
|
|
7
|
+
export function fnv1a32(s) {
|
|
8
|
+
let h = 0x811c9dc5;
|
|
9
|
+
for (const b of encoder.encode(s))
|
|
10
|
+
h = Math.imul(h ^ b, 0x01000193) >>> 0;
|
|
11
|
+
return h;
|
|
12
|
+
}
|
|
13
|
+
/** Whether the session with this ID is head-sampled at rate (0..1). NaN and rates at or below 0 keep nothing. */
|
|
14
|
+
export function sessionSampled(sessionId, rate) {
|
|
15
|
+
if (!(rate > 0))
|
|
16
|
+
return false;
|
|
17
|
+
if (rate >= 1)
|
|
18
|
+
return true;
|
|
19
|
+
return fnv1a32(sessionId) / 2 ** 32 < rate;
|
|
20
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { SessionState } from "../contracts/session.ts";
|
|
2
|
+
export declare const SESSION_STORAGE_KEY = "libo11y.rum.session";
|
|
3
|
+
/** The SessionState in a stored or broadcast record, or undefined when it is not a valid version 1 record. */
|
|
4
|
+
export declare function parseSessionState(value: unknown): SessionState | undefined;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** The stored session record every session store shares: version 1 JSON under one key. */
|
|
2
|
+
import { RUM_SESSION_RETAINED_VALUES } from "@libo11y/spec";
|
|
3
|
+
export const SESSION_STORAGE_KEY = "libo11y.rum.session";
|
|
4
|
+
const RETAINED = new Set(RUM_SESSION_RETAINED_VALUES);
|
|
5
|
+
/** The SessionState in a stored or broadcast record, or undefined when it is not a valid version 1 record. */
|
|
6
|
+
export function parseSessionState(value) {
|
|
7
|
+
if (typeof value !== "object" || value === null)
|
|
8
|
+
return undefined;
|
|
9
|
+
const r = value;
|
|
10
|
+
if (r.v !== 1 || typeof r.id !== "string" || r.id === "")
|
|
11
|
+
return undefined;
|
|
12
|
+
if (typeof r.startedAt !== "number" || typeof r.lastActivityAt !== "number")
|
|
13
|
+
return undefined;
|
|
14
|
+
if (typeof r.sampled !== "boolean")
|
|
15
|
+
return undefined;
|
|
16
|
+
if (r.retained !== undefined && (typeof r.retained !== "string" || !RETAINED.has(r.retained)))
|
|
17
|
+
return undefined;
|
|
18
|
+
if (r.configVersion !== undefined && typeof r.configVersion !== "string")
|
|
19
|
+
return undefined;
|
|
20
|
+
return {
|
|
21
|
+
id: r.id,
|
|
22
|
+
startedAt: r.startedAt,
|
|
23
|
+
lastActivityAt: r.lastActivityAt,
|
|
24
|
+
sampled: r.sampled,
|
|
25
|
+
...(r.retained === undefined ? {} : { retained: r.retained }),
|
|
26
|
+
...(r.configVersion === undefined ? {} : { configVersion: r.configVersion }),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { RumCollector, RumSettings } from "./contracts/runtime.ts";
|
|
2
|
+
import type { RumOptions } from "./options.ts";
|
|
3
|
+
/** The settings and the collectors to start. */
|
|
4
|
+
export interface ResolvedRum extends RumSettings {
|
|
5
|
+
readonly collectors: readonly RumCollector[];
|
|
6
|
+
}
|
|
7
|
+
/** The settings for o. Throws O11yError INVALID_OPTION for an invalid value. */
|
|
8
|
+
export declare function resolveSettings(o: RumOptions | undefined): ResolvedRum;
|
package/dist/settings.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Resolves RumOptions into RumSettings, refusing invalid values. */
|
|
2
|
+
import { O11yError } from "@libo11y/core";
|
|
3
|
+
import { defaultViewName } from "./views/naming.js";
|
|
4
|
+
function positive(name, v, dflt) {
|
|
5
|
+
if (v === undefined)
|
|
6
|
+
return dflt;
|
|
7
|
+
if (!(Number.isFinite(v) && v > 0))
|
|
8
|
+
throw new O11yError("INVALID_OPTION", `rum.${name} must be a positive number`);
|
|
9
|
+
return v;
|
|
10
|
+
}
|
|
11
|
+
/** The settings for o. Throws O11yError INVALID_OPTION for an invalid value. */
|
|
12
|
+
export function resolveSettings(o) {
|
|
13
|
+
const rate = o?.sessionSampleRate ?? 1;
|
|
14
|
+
if (!(rate >= 0 && rate <= 1))
|
|
15
|
+
throw new O11yError("INVALID_OPTION", "rum.sessionSampleRate must be between 0 and 1");
|
|
16
|
+
if (o?.clientToken !== undefined && (typeof o.clientToken !== "string" || o.clientToken === "")) {
|
|
17
|
+
throw new O11yError("INVALID_OPTION", "rum.clientToken must be a non-empty string");
|
|
18
|
+
}
|
|
19
|
+
const collectors = o?.collectors ?? [];
|
|
20
|
+
const names = new Set();
|
|
21
|
+
for (const c of collectors) {
|
|
22
|
+
if (names.has(c.name))
|
|
23
|
+
throw new O11yError("INVALID_OPTION", `rum.collectors lists ${c.name} twice`);
|
|
24
|
+
names.add(c.name);
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
sessionSampleRate: rate,
|
|
28
|
+
sessionIdleMillis: positive("sessionIdleMillis", o?.sessionIdleMillis, 900_000),
|
|
29
|
+
sessionMaxMillis: positive("sessionMaxMillis", o?.sessionMaxMillis, 14_400_000),
|
|
30
|
+
queryAllowList: new Set(o?.queryAllowList ?? []),
|
|
31
|
+
enabled: names,
|
|
32
|
+
viewName: o?.viewName ?? defaultViewName,
|
|
33
|
+
collectors,
|
|
34
|
+
...(o?.clientToken === undefined ? {} : { clientToken: o.clientToken }),
|
|
35
|
+
};
|
|
36
|
+
}
|
package/dist/setup.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* setupRum: @libo11y/web's setup with RUM wired in. setupRumWith binds the RUM core
|
|
3
|
+
* (core-setup.ts) to the web: web's setupWithDeps through webBinding, the page's lifecycle from
|
|
4
|
+
* visibilitychange, pagehide and pageshow, remote configuration cached in localStorage, and the
|
|
5
|
+
* bootstrap buffer replayed. The extension contexts pass their own binding and stores in deps.
|
|
6
|
+
*/
|
|
7
|
+
import type { RUMPlatform } from "@libo11y/spec";
|
|
8
|
+
import type { WebSetupOptions, WebTelemetry } from "@libo11y/web";
|
|
9
|
+
import { type SetupDeps } from "@libo11y/web/internal";
|
|
10
|
+
import type { RumBind, RumLifecycle } from "./contracts/binding.ts";
|
|
11
|
+
import { type RumCoreDeps } from "./core-setup.ts";
|
|
12
|
+
import type { RumSetupOptions, RumTelemetry } from "./options.ts";
|
|
13
|
+
export { runtimeOf, SESSION_END_ELECTION_MILLIS } from "./core-setup.ts";
|
|
14
|
+
/** What setupRumWith builds on. Internal: tests and the extension wiring replace parts of it. */
|
|
15
|
+
export interface RumDeps extends Omit<RumCoreDeps<WebSetupOptions, WebTelemetry>, "platform" | "bind" | "lifecycle" | "window" | "bootstrap" | "storage"> {
|
|
16
|
+
readonly web: SetupDeps;
|
|
17
|
+
readonly document: (EventTarget & {
|
|
18
|
+
readonly visibilityState?: string;
|
|
19
|
+
}) | undefined;
|
|
20
|
+
readonly window: EventTarget | undefined;
|
|
21
|
+
/** Install the telemetry globally, as setup does. Default true; tests that run two tabs in one process pass false. */
|
|
22
|
+
readonly install?: boolean;
|
|
23
|
+
/** The platform summaries, session starts and app_load record. Default "web". */
|
|
24
|
+
readonly platform?: RUMPlatform;
|
|
25
|
+
/** Runs the platform's setup with RUM's wrappers. Default webBinding(web, install). */
|
|
26
|
+
readonly bind?: RumBind<WebSetupOptions, WebTelemetry>;
|
|
27
|
+
/** Default webLifecycle(document, window). */
|
|
28
|
+
readonly lifecycle?: RumLifecycle;
|
|
29
|
+
/**
|
|
30
|
+
* Where remote configuration is cached. Default localStorage. Called only once consent is granted.
|
|
31
|
+
* It may resolve later, as a cache in chrome.storage.local does once it has read the stored value.
|
|
32
|
+
*/
|
|
33
|
+
readonly storage?: RumCoreDeps<WebSetupOptions, WebTelemetry>["storage"];
|
|
34
|
+
}
|
|
35
|
+
/** Browser dependencies shared by pages and extension contexts, without web setup or localStorage. */
|
|
36
|
+
export declare function defaultBrowserRumDeps(): Omit<RumDeps, "web" | "sessionStore">;
|
|
37
|
+
/** The real dependencies of a page. */
|
|
38
|
+
export declare function defaultRumDeps(): RumDeps;
|
|
39
|
+
/** Builds browser telemetry with RUM and installs it globally, as the setup of `@libo11y/web` does. */
|
|
40
|
+
export declare function setupRum(options?: RumSetupOptions): Promise<RumTelemetry>;
|
|
41
|
+
/** setupRum over deps. Internal: the seam the unit tests and the extension wiring use. */
|
|
42
|
+
export declare function setupRumWith(options: RumSetupOptions, deps: RumDeps): Promise<RumTelemetry>;
|
package/dist/setup.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { defaultSetupDeps, openQueue } from "@libo11y/web/internal";
|
|
2
|
+
import { webBinding, webLifecycle } from "./bind.js";
|
|
3
|
+
import { takeBootstrap } from "./bootstrap/buffer.js";
|
|
4
|
+
import { replayBootstrap } from "./bootstrap/replay.js";
|
|
5
|
+
import { setupRumCore } from "./core-setup.js";
|
|
6
|
+
import { localStorageSessionStore } from "./session/local-store.js";
|
|
7
|
+
export { runtimeOf, SESSION_END_ELECTION_MILLIS } from "./core-setup.js";
|
|
8
|
+
/** Browser dependencies shared by pages and extension contexts, without web setup or localStorage. */
|
|
9
|
+
export function defaultBrowserRumDeps() {
|
|
10
|
+
const g = globalThis;
|
|
11
|
+
const doc = g.document;
|
|
12
|
+
return {
|
|
13
|
+
openRetentionQueue: openQueue,
|
|
14
|
+
now: Date.now,
|
|
15
|
+
perfNow: () => performance.now(),
|
|
16
|
+
timeOrigin: performance.timeOrigin,
|
|
17
|
+
location: () => g.location?.href ?? "about:blank",
|
|
18
|
+
prerendered: () => {
|
|
19
|
+
if (g.document?.prerendering === true)
|
|
20
|
+
return true;
|
|
21
|
+
const nav = performance.getEntriesByType?.("navigation")[0];
|
|
22
|
+
return (nav?.activationStart ?? 0) > 0;
|
|
23
|
+
},
|
|
24
|
+
connection: () => g.navigator?.connection?.effectiveType,
|
|
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(),
|
|
36
|
+
window: web.window,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** Builds browser telemetry with RUM and installs it globally, as the setup of `@libo11y/web` does. */
|
|
40
|
+
export function setupRum(options = {}) {
|
|
41
|
+
return setupRumWith(options, defaultRumDeps());
|
|
42
|
+
}
|
|
43
|
+
/** setupRum over deps. Internal: the seam the unit tests and the extension wiring use. */
|
|
44
|
+
export function setupRumWith(options, deps) {
|
|
45
|
+
const { rum, ...webOptions } = options;
|
|
46
|
+
return setupRumCore(webOptions, rum, {
|
|
47
|
+
...deps,
|
|
48
|
+
platform: deps.platform ?? "web",
|
|
49
|
+
bind: deps.bind ?? webBinding(deps.web, deps.install !== false),
|
|
50
|
+
lifecycle: deps.lifecycle ?? webLifecycle(deps.document, deps.window),
|
|
51
|
+
storage: deps.storage ?? (() => globalThis.localStorage),
|
|
52
|
+
bootstrap: () => {
|
|
53
|
+
const early = takeBootstrap();
|
|
54
|
+
return (runtime) => replayBootstrap(runtime, early);
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The RUM span processor. On every span start it adds session.id, o11y.rum.view.id (unless the
|
|
3
|
+
* span already names them) and user.id,
|
|
4
|
+
* removes disallowed query parameters from url.full, and turns web's documentLoad span into the
|
|
5
|
+
* app_load shape of the load view: it is renamed app_load and carries o11y.rum.span.shape app_load,
|
|
6
|
+
* the attribute the gateway keys on. Its documentFetch child also belongs to the load view, and it
|
|
7
|
+
* is not a request of the view. It publishes client request starts and ends on the bus for
|
|
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. It runs before the exporting processors, so they see the
|
|
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.
|
|
12
|
+
*/
|
|
13
|
+
import { type RUMPlatform } from "@libo11y/spec";
|
|
14
|
+
import type { SpanProcessor } from "@opentelemetry/sdk-trace";
|
|
15
|
+
import type { RumBus } from "./contracts/runtime.ts";
|
|
16
|
+
import type { SessionManager } from "./contracts/session.ts";
|
|
17
|
+
import type { ViewTracker } from "./contracts/views.ts";
|
|
18
|
+
import type { PendingSpans } from "./pending-spans.ts";
|
|
19
|
+
/** The name of the app_load span shape. */
|
|
20
|
+
export declare const APP_LOAD_SPAN = "app_load";
|
|
21
|
+
export interface RumSpanProcessorOptions {
|
|
22
|
+
readonly platform: RUMPlatform;
|
|
23
|
+
readonly session: Pick<SessionManager, "current">;
|
|
24
|
+
readonly views: Pick<ViewTracker, "current" | "loadView" | "appLoadStarted">;
|
|
25
|
+
readonly queryAllowList: () => ReadonlySet<string>;
|
|
26
|
+
readonly userId: () => string | undefined;
|
|
27
|
+
readonly bus: RumBus;
|
|
28
|
+
/** performance.now(). */
|
|
29
|
+
readonly now: () => number;
|
|
30
|
+
/**
|
|
31
|
+
* performance.timeOrigin, to read a span's end time on the now() clock. Without it the bus
|
|
32
|
+
* reports now() alone.
|
|
33
|
+
*/
|
|
34
|
+
readonly timeOrigin?: number | undefined;
|
|
35
|
+
/** Where spans that start while the session loads wait for it. */
|
|
36
|
+
readonly pending?: Pick<PendingSpans, "isOpen" | "hold">;
|
|
37
|
+
}
|
|
38
|
+
export declare function rumSpanProcessor(opts: RumSpanProcessorOptions): SpanProcessor;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The RUM span processor. On every span start it adds session.id, o11y.rum.view.id (unless the
|
|
3
|
+
* span already names them) and user.id,
|
|
4
|
+
* removes disallowed query parameters from url.full, and turns web's documentLoad span into the
|
|
5
|
+
* app_load shape of the load view: it is renamed app_load and carries o11y.rum.span.shape app_load,
|
|
6
|
+
* the attribute the gateway keys on. Its documentFetch child also belongs to the load view, and it
|
|
7
|
+
* is not a request of the view. It publishes client request starts and ends on the bus for
|
|
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. It runs before the exporting processors, so they see the
|
|
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.
|
|
12
|
+
*/
|
|
13
|
+
import { ATTR_RUM_PLATFORM, ATTR_RUM_SPAN_SHAPE, ATTR_RUM_VIEW_ID, RUM_SPAN_SHAPE_VALUE_APP_LOAD, } from "@libo11y/spec";
|
|
14
|
+
import { SpanKind } from "@opentelemetry/api";
|
|
15
|
+
import { hrTimeToMilliseconds } from "@opentelemetry/core";
|
|
16
|
+
import { ATTR_SESSION_ID, ATTR_USER_ID } from "./attrs.js";
|
|
17
|
+
import { stripQuery } from "./query.js";
|
|
18
|
+
/** The name of the app_load span shape. */
|
|
19
|
+
export const APP_LOAD_SPAN = "app_load";
|
|
20
|
+
const DOCUMENT_LOAD = "documentLoad";
|
|
21
|
+
/** web's child of documentLoad: the document request, part of the load and not a request the view made. */
|
|
22
|
+
const DOCUMENT_FETCH = "documentFetch";
|
|
23
|
+
const WEB_SCOPE = "@libo11y/web";
|
|
24
|
+
function fromWeb(span, name) {
|
|
25
|
+
return span.name === name && span.instrumentationScope.name === WEB_SCOPE;
|
|
26
|
+
}
|
|
27
|
+
function hostOf(span) {
|
|
28
|
+
const address = span.attributes["server.address"];
|
|
29
|
+
if (typeof address === "string" && address !== "")
|
|
30
|
+
return address;
|
|
31
|
+
const full = span.attributes["url.full"];
|
|
32
|
+
try {
|
|
33
|
+
return typeof full === "string" ? new URL(full).hostname : "";
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return "";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function isRequest(span) {
|
|
40
|
+
return (span.kind === SpanKind.CLIENT &&
|
|
41
|
+
typeof span.attributes["http.request.method"] === "string" &&
|
|
42
|
+
!fromWeb(span, DOCUMENT_FETCH));
|
|
43
|
+
}
|
|
44
|
+
export function rumSpanProcessor(opts) {
|
|
45
|
+
// Request spans this processor announced, so request-end is published only for them.
|
|
46
|
+
const announced = new Set();
|
|
47
|
+
return {
|
|
48
|
+
onStart(span, _parent) {
|
|
49
|
+
const session = opts.session.current();
|
|
50
|
+
if (session === undefined && opts.pending?.isOpen() !== true)
|
|
51
|
+
return;
|
|
52
|
+
const appLoad = fromWeb(span, DOCUMENT_LOAD);
|
|
53
|
+
const ofLoad = appLoad || fromWeb(span, DOCUMENT_FETCH);
|
|
54
|
+
if (session === undefined) {
|
|
55
|
+
// Consent is granted and the session still loading: the span waits for it.
|
|
56
|
+
opts.pending?.hold(span, ofLoad);
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
// RUM's own view and action spans name their view and session, which may be older ones.
|
|
60
|
+
if (span.attributes[ATTR_SESSION_ID] === undefined)
|
|
61
|
+
span.setAttribute(ATTR_SESSION_ID, session.id);
|
|
62
|
+
const view = ofLoad ? opts.views.loadView() : opts.views.current();
|
|
63
|
+
if (view !== undefined && span.attributes[ATTR_RUM_VIEW_ID] === undefined) {
|
|
64
|
+
span.setAttribute(ATTR_RUM_VIEW_ID, view.id);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const user = opts.userId();
|
|
68
|
+
if (user !== undefined)
|
|
69
|
+
span.setAttribute(ATTR_USER_ID, user);
|
|
70
|
+
const full = span.attributes["url.full"];
|
|
71
|
+
const url = typeof full === "string" ? stripQuery(full, opts.queryAllowList()) : undefined;
|
|
72
|
+
if (url !== undefined && url !== full)
|
|
73
|
+
span.setAttribute("url.full", url);
|
|
74
|
+
if (appLoad) {
|
|
75
|
+
span.updateName(APP_LOAD_SPAN);
|
|
76
|
+
span.setAttribute(ATTR_RUM_SPAN_SHAPE, RUM_SPAN_SHAPE_VALUE_APP_LOAD);
|
|
77
|
+
span.setAttribute(ATTR_RUM_PLATFORM, opts.platform);
|
|
78
|
+
opts.views.appLoadStarted(span.spanContext());
|
|
79
|
+
}
|
|
80
|
+
if (isRequest(span)) {
|
|
81
|
+
const spanId = span.spanContext().spanId;
|
|
82
|
+
const parent = span.parentSpanContext?.spanId;
|
|
83
|
+
announced.add(spanId);
|
|
84
|
+
opts.bus.publish({
|
|
85
|
+
type: "request-start",
|
|
86
|
+
spanId,
|
|
87
|
+
...(parent === undefined ? {} : { parentSpanId: parent }),
|
|
88
|
+
method: String(span.attributes["http.request.method"]),
|
|
89
|
+
url: url ?? "",
|
|
90
|
+
at: opts.now(),
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
onEnd(span) {
|
|
95
|
+
const spanId = span.spanContext().spanId;
|
|
96
|
+
if (!announced.delete(spanId))
|
|
97
|
+
return;
|
|
98
|
+
const status = span.attributes["http.response.status_code"];
|
|
99
|
+
const errorType = span.attributes["error.type"];
|
|
100
|
+
// The later of now and the span's own end, so an action that settles at this time never
|
|
101
|
+
// ends before the request it caused (WebKit's span end can trail now() by a millisecond).
|
|
102
|
+
const origin = opts.timeOrigin;
|
|
103
|
+
const spanEnd = origin === undefined ? Number.NaN : hrTimeToMilliseconds(span.endTime) - origin;
|
|
104
|
+
const at = Number.isFinite(spanEnd) ? Math.max(opts.now(), spanEnd) : opts.now();
|
|
105
|
+
opts.bus.publish({
|
|
106
|
+
type: "request-end",
|
|
107
|
+
spanId,
|
|
108
|
+
...(typeof status === "number" ? { status } : {}),
|
|
109
|
+
...(typeof status !== "number" && typeof errorType === "string" ? { errorType } : {}),
|
|
110
|
+
at,
|
|
111
|
+
});
|
|
112
|
+
const rpc = span.attributes["rpc.method"];
|
|
113
|
+
opts.bus.publish(rpc === undefined
|
|
114
|
+
? {
|
|
115
|
+
type: "breadcrumb",
|
|
116
|
+
kind: "fetch",
|
|
117
|
+
label: `${String(span.attributes["http.request.method"])} ${hostOf(span)} ${typeof status === "number" ? status : "failed"}`,
|
|
118
|
+
at,
|
|
119
|
+
}
|
|
120
|
+
: { type: "breadcrumb", kind: "rpc", label: String(rpc), at });
|
|
121
|
+
},
|
|
122
|
+
forceFlush: () => Promise.resolve(),
|
|
123
|
+
shutdown: () => Promise.resolve(),
|
|
124
|
+
};
|
|
125
|
+
}
|