@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,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The retention buffer (design, "What a client sends", item 4): detail of a session not yet kept,
|
|
3
|
+
* in its own IndexedDB queue so a reload keeps it and every tab of the session shares it. Flushing
|
|
4
|
+
* claims a few entries at a time with a lease and removes each one once it is handed over, so two
|
|
5
|
+
* tabs that both see the session become kept send each batch once. Where IndexedDB is unavailable,
|
|
6
|
+
* openQueue gives a memory queue and a reload loses it. The queue is opened on first use, so a
|
|
7
|
+
* caller that uses it only after consent creates no database before consent.
|
|
8
|
+
*/
|
|
9
|
+
import type { PersistentQueue } from "@libo11y/web/portable";
|
|
10
|
+
import type { RetentionBuffer } from "../contracts/retention.ts";
|
|
11
|
+
/** The retention queue's database and bounds. setupRum's rum.retention overrides the bounds. */
|
|
12
|
+
export declare const RETENTION_QUEUE_DEFAULTS: {
|
|
13
|
+
readonly databaseName: "libo11y-rum-retention";
|
|
14
|
+
readonly maxBytes: 2_097_152;
|
|
15
|
+
readonly maxAgeMillis: 900_000;
|
|
16
|
+
readonly maxEntries: 1000;
|
|
17
|
+
};
|
|
18
|
+
export interface RetentionBufferOptions {
|
|
19
|
+
readonly open: () => Promise<PersistentQueue>;
|
|
20
|
+
/** Epoch milliseconds. Default Date.now. */
|
|
21
|
+
readonly now?: () => number;
|
|
22
|
+
/** The longest one send can take, the transport timeout. Default 10000. Sets the claim lease. */
|
|
23
|
+
readonly sendTimeoutMillis?: number;
|
|
24
|
+
}
|
|
25
|
+
export declare function createRetentionBuffer(opts: RetentionBufferOptions): RetentionBuffer;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { diag } from "@opentelemetry/api";
|
|
2
|
+
/** The retention queue's database and bounds. setupRum's rum.retention overrides the bounds. */
|
|
3
|
+
export const RETENTION_QUEUE_DEFAULTS = {
|
|
4
|
+
databaseName: "libo11y-rum-retention",
|
|
5
|
+
maxBytes: 2_097_152,
|
|
6
|
+
maxAgeMillis: 900_000,
|
|
7
|
+
maxEntries: 1000,
|
|
8
|
+
};
|
|
9
|
+
/** Entries claimed per round. */
|
|
10
|
+
const CLAIM_BATCH = 5;
|
|
11
|
+
/** The lease covers a round of sends at the longest send time, plus a margin. */
|
|
12
|
+
const LEASE_MARGIN_MILLIS = 30_000;
|
|
13
|
+
const DEFAULT_SEND_TIMEOUT_MILLIS = 10_000;
|
|
14
|
+
export function createRetentionBuffer(opts) {
|
|
15
|
+
const now = opts.now ?? Date.now;
|
|
16
|
+
const lease = CLAIM_BATCH * (opts.sendTimeoutMillis ?? DEFAULT_SEND_TIMEOUT_MILLIS) + LEASE_MARGIN_MILLIS;
|
|
17
|
+
let opening;
|
|
18
|
+
let closed = false;
|
|
19
|
+
const queue = () => {
|
|
20
|
+
opening ??= opts.open().catch((err) => {
|
|
21
|
+
diag.warn("o11y: rum: the retention buffer could not open", err);
|
|
22
|
+
return undefined;
|
|
23
|
+
});
|
|
24
|
+
return opening;
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
async put(batch) {
|
|
28
|
+
if (closed)
|
|
29
|
+
return;
|
|
30
|
+
try {
|
|
31
|
+
await (await queue())?.put(batch);
|
|
32
|
+
}
|
|
33
|
+
catch (err) {
|
|
34
|
+
diag.warn("o11y: rum: a retention buffer write failed", err);
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
async flush(delivery, keep) {
|
|
38
|
+
if (closed)
|
|
39
|
+
return 0;
|
|
40
|
+
let sent = 0;
|
|
41
|
+
try {
|
|
42
|
+
const q = await queue();
|
|
43
|
+
if (q === undefined)
|
|
44
|
+
return 0;
|
|
45
|
+
for (;;) {
|
|
46
|
+
const entries = await q.claim(now(), CLAIM_BATCH, lease);
|
|
47
|
+
if (entries.length === 0)
|
|
48
|
+
return sent;
|
|
49
|
+
for (const e of entries) {
|
|
50
|
+
const batch = { signal: e.signal, body: e.body };
|
|
51
|
+
// The delivery keeps a retryable failure in its own retry queue, so the entry is done here.
|
|
52
|
+
if (keep === undefined || keep(batch)) {
|
|
53
|
+
await delivery.deliver(batch);
|
|
54
|
+
sent++;
|
|
55
|
+
}
|
|
56
|
+
await q.remove([e.id]);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
catch (err) {
|
|
61
|
+
diag.warn("o11y: rum: the retention flush failed", err);
|
|
62
|
+
return sent;
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
async discard(match) {
|
|
66
|
+
if (closed)
|
|
67
|
+
return 0;
|
|
68
|
+
try {
|
|
69
|
+
const q = await queue();
|
|
70
|
+
if (q === undefined)
|
|
71
|
+
return 0;
|
|
72
|
+
// A zero lease leaves every entry this claim reads claimable by other contexts at once.
|
|
73
|
+
const entries = await q.claim(now(), RETENTION_QUEUE_DEFAULTS.maxEntries, 0);
|
|
74
|
+
const ids = entries.filter((e) => match({ signal: e.signal, body: e.body })).map((e) => e.id);
|
|
75
|
+
if (ids.length > 0)
|
|
76
|
+
await q.remove(ids);
|
|
77
|
+
return ids.length;
|
|
78
|
+
}
|
|
79
|
+
catch (err) {
|
|
80
|
+
diag.warn("o11y: rum: discarding from the retention buffer failed", err);
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
async clear() {
|
|
85
|
+
if (closed)
|
|
86
|
+
return;
|
|
87
|
+
try {
|
|
88
|
+
// Opens the queue if needed: a previous page of the session may have left entries.
|
|
89
|
+
await (await queue())?.clear();
|
|
90
|
+
}
|
|
91
|
+
catch (err) {
|
|
92
|
+
diag.warn("o11y: rum: clearing the retention buffer failed", err);
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
async size() {
|
|
96
|
+
const q = opening === undefined ? undefined : await opening;
|
|
97
|
+
return q === undefined ? { entries: 0, bytes: 0 } : q.size();
|
|
98
|
+
},
|
|
99
|
+
close() {
|
|
100
|
+
closed = true;
|
|
101
|
+
void opening?.then((q) => q?.close());
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The retention router (decision P2). Wraps the exporters @libo11y/web builds, so each batch is
|
|
3
|
+
* split by the session.id of its records: kept sessions go to the inner exporter, the current
|
|
4
|
+
* unkept session is serialized into the retention buffer, and an old unkept session is dropped.
|
|
5
|
+
* Every o11y.rum.view.summary record goes to the inner exporter, because summaries are sent for
|
|
6
|
+
* every consented session. Metrics pass through untouched.
|
|
7
|
+
*/
|
|
8
|
+
import type { ExporterSet } from "@libo11y/core";
|
|
9
|
+
import type { LogRecordExporter } from "@opentelemetry/sdk-logs";
|
|
10
|
+
import type { SpanExporter } from "@opentelemetry/sdk-trace";
|
|
11
|
+
import type { RetentionRouting } from "../contracts/retention.ts";
|
|
12
|
+
/** A SpanExporter that routes each span by its session.id. */
|
|
13
|
+
export declare function retainingSpanExporter(inner: SpanExporter, routing: RetentionRouting): SpanExporter;
|
|
14
|
+
/** A LogRecordExporter that routes each record by its session.id, sending every view summary. */
|
|
15
|
+
export declare function retainingLogExporter(inner: LogRecordExporter, routing: RetentionRouting): LogRecordExporter;
|
|
16
|
+
/** The exporter set with traces and logs routed by session. The metric reader is unchanged. */
|
|
17
|
+
export declare function withRetention(set: ExporterSet, routing: RetentionRouting): ExporterSet;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { EVENT_RUM_VIEW_SUMMARY } from "@libo11y/spec";
|
|
2
|
+
import { serializeLogs, serializeSpans } from "@libo11y/web/portable";
|
|
3
|
+
import { ExportResultCode } from "@opentelemetry/core";
|
|
4
|
+
import { ATTR_SESSION_ID } from "../attrs.js";
|
|
5
|
+
const SUCCESS = { code: ExportResultCode.SUCCESS };
|
|
6
|
+
function sessionOf(attrs) {
|
|
7
|
+
const v = attrs[ATTR_SESSION_ID];
|
|
8
|
+
return typeof v === "string" ? v : undefined;
|
|
9
|
+
}
|
|
10
|
+
function partition(items, route) {
|
|
11
|
+
const send = [];
|
|
12
|
+
const buffer = [];
|
|
13
|
+
for (const item of items) {
|
|
14
|
+
const r = route(item);
|
|
15
|
+
if (r === "send")
|
|
16
|
+
send.push(item);
|
|
17
|
+
else if (r === "buffer")
|
|
18
|
+
buffer.push(item);
|
|
19
|
+
}
|
|
20
|
+
return { send, buffer };
|
|
21
|
+
}
|
|
22
|
+
/** A SpanExporter that routes each span by its session.id. */
|
|
23
|
+
export function retainingSpanExporter(inner, routing) {
|
|
24
|
+
return {
|
|
25
|
+
export(spans, done) {
|
|
26
|
+
const { send, buffer } = partition(spans, (s) => routing.decide(sessionOf(s.attributes)));
|
|
27
|
+
if (buffer.length > 0)
|
|
28
|
+
routing.buffer({ signal: "traces", body: serializeSpans(buffer) });
|
|
29
|
+
if (send.length === 0)
|
|
30
|
+
done(SUCCESS);
|
|
31
|
+
else
|
|
32
|
+
inner.export(send, done);
|
|
33
|
+
},
|
|
34
|
+
shutdown: () => inner.shutdown(),
|
|
35
|
+
...(inner.forceFlush === undefined
|
|
36
|
+
? {}
|
|
37
|
+
: { forceFlush: () => inner.forceFlush?.() ?? Promise.resolve() }),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** A LogRecordExporter that routes each record by its session.id, sending every view summary. */
|
|
41
|
+
export function retainingLogExporter(inner, routing) {
|
|
42
|
+
return {
|
|
43
|
+
export(records, done) {
|
|
44
|
+
const { send, buffer } = partition(records, (l) => l.attributes["event.name"] === EVENT_RUM_VIEW_SUMMARY
|
|
45
|
+
? "send"
|
|
46
|
+
: routing.decide(sessionOf(l.attributes)));
|
|
47
|
+
if (buffer.length > 0)
|
|
48
|
+
routing.buffer({ signal: "logs", body: serializeLogs(buffer) });
|
|
49
|
+
if (send.length === 0)
|
|
50
|
+
done(SUCCESS);
|
|
51
|
+
else
|
|
52
|
+
inner.export(send, done);
|
|
53
|
+
},
|
|
54
|
+
shutdown: () => inner.shutdown(),
|
|
55
|
+
forceFlush: () => inner.forceFlush(),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/** The exporter set with traces and logs routed by session. The metric reader is unchanged. */
|
|
59
|
+
export function withRetention(set, routing) {
|
|
60
|
+
return {
|
|
61
|
+
...set,
|
|
62
|
+
...(set.spanExporter === undefined
|
|
63
|
+
? {}
|
|
64
|
+
: { spanExporter: retainingSpanExporter(set.spanExporter, routing) }),
|
|
65
|
+
...(set.logExporter === undefined ? {} : { logExporter: retainingLogExporter(set.logExporter, routing) }),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** The sessions an OTLP JSON batch holds records of, so the retention flush can check each batch. */
|
|
2
|
+
import type { OtlpBatch } from "@libo11y/web/portable";
|
|
3
|
+
/** Every session.id in batch's records, or undefined when the body is not readable OTLP JSON. */
|
|
4
|
+
export declare function sessionsIn(batch: OtlpBatch): ReadonlySet<string> | undefined;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { ATTR_SESSION_ID } from "../attrs.js";
|
|
2
|
+
function collect(items, into) {
|
|
3
|
+
for (const item of items ?? []) {
|
|
4
|
+
for (const a of item.attributes ?? []) {
|
|
5
|
+
if (a.key === ATTR_SESSION_ID && typeof a.value?.stringValue === "string")
|
|
6
|
+
into.add(a.value.stringValue);
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/** Every session.id in batch's records, or undefined when the body is not readable OTLP JSON. */
|
|
11
|
+
export function sessionsIn(batch) {
|
|
12
|
+
let body;
|
|
13
|
+
try {
|
|
14
|
+
body = JSON.parse(batch.body);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
if (typeof body !== "object" || body === null)
|
|
20
|
+
return undefined;
|
|
21
|
+
const ids = new Set();
|
|
22
|
+
const b = body;
|
|
23
|
+
for (const rs of b.resourceSpans ?? [])
|
|
24
|
+
for (const ss of rs.scopeSpans ?? [])
|
|
25
|
+
collect(ss.spans, ids);
|
|
26
|
+
for (const rl of b.resourceLogs ?? [])
|
|
27
|
+
for (const sl of rl.scopeLogs ?? [])
|
|
28
|
+
collect(sl.logRecords, ids);
|
|
29
|
+
return ids;
|
|
30
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { SessionStore } from "../contracts/session.ts";
|
|
2
|
+
export { parseSessionState, SESSION_STORAGE_KEY } from "./state.ts";
|
|
3
|
+
export declare const SESSION_CHANNEL = "libo11y.rum";
|
|
4
|
+
/** The part of BroadcastChannel the store uses. */
|
|
5
|
+
export interface BroadcastChannelLike {
|
|
6
|
+
postMessage(message: unknown): void;
|
|
7
|
+
addEventListener(type: "message", listener: (event: {
|
|
8
|
+
readonly data: unknown;
|
|
9
|
+
}) => void): void;
|
|
10
|
+
removeEventListener(type: "message", listener: (event: {
|
|
11
|
+
readonly data: unknown;
|
|
12
|
+
}) => void): void;
|
|
13
|
+
close(): void;
|
|
14
|
+
}
|
|
15
|
+
export interface LocalSessionStoreOptions {
|
|
16
|
+
/** Default globalThis.localStorage; absent or throwing gives a store that only broadcasts. */
|
|
17
|
+
readonly storage?: Pick<Storage, "getItem" | "setItem" | "removeItem">;
|
|
18
|
+
/** Default new BroadcastChannel(SESSION_CHANNEL) where it exists. */
|
|
19
|
+
readonly channel?: BroadcastChannelLike;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The web SessionStore. Storage and the default channel are reached on first use, which the session
|
|
23
|
+
* manager makes only after consent is granted, so no BroadcastChannel exists before then.
|
|
24
|
+
*/
|
|
25
|
+
export declare function localStorageSessionStore(opts?: LocalSessionStoreOptions): SessionStore;
|
|
@@ -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 (decision P13):
|
|
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 (design D4). 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;
|