@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,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-Timing on a resource's response. A valid traceparent entry names the server span that
|
|
3
|
+
* served the resource, which the resource span links to. Every other entry with a name and a
|
|
4
|
+
* finite duration is reported in seconds, at most MAX_ENTRIES of them.
|
|
5
|
+
*/
|
|
6
|
+
import { remoteParentFromTraceparent } from "@libo11y/web/internal";
|
|
7
|
+
/** The most Server-Timing entries one resource span reports. */
|
|
8
|
+
export const MAX_SERVER_TIMING_ENTRIES = 10;
|
|
9
|
+
export function readServerTiming(entries) {
|
|
10
|
+
let remote;
|
|
11
|
+
const out = [];
|
|
12
|
+
for (const e of entries) {
|
|
13
|
+
if (e.name === "traceparent") {
|
|
14
|
+
remote ??= remoteParentFromTraceparent(e.description);
|
|
15
|
+
}
|
|
16
|
+
else if (e.name !== "" && Number.isFinite(e.duration) && out.length < MAX_SERVER_TIMING_ENTRIES) {
|
|
17
|
+
out.push({ name: e.name, seconds: e.duration / 1000 });
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return { ...(remote === undefined ? {} : { remote }), entries: out };
|
|
21
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The retention buffer: 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. A flush leases only the batches
|
|
6
|
+
* keep accepts, so another session's batches stay claimable while it sends. A clear or close ends
|
|
7
|
+
* every flush begun before it, and close closes the queue once the batches already handed over are
|
|
8
|
+
* removed.
|
|
9
|
+
* Where IndexedDB is unavailable, openQueue gives a memory queue and a reload loses it. The queue
|
|
10
|
+
* is opened on first use, so a caller that uses it only after consent creates no database before
|
|
11
|
+
* consent.
|
|
12
|
+
*/
|
|
13
|
+
import type { PersistentQueue } from "@libo11y/web/portable";
|
|
14
|
+
import type { RetentionBuffer } from "../contracts/retention.ts";
|
|
15
|
+
/** The retention queue's database and bounds. setupRum's rum.retention overrides the bounds. */
|
|
16
|
+
export declare const RETENTION_QUEUE_DEFAULTS: {
|
|
17
|
+
readonly databaseName: "libo11y-rum-retention";
|
|
18
|
+
readonly maxBytes: 2_097_152;
|
|
19
|
+
readonly maxAgeMillis: 900_000;
|
|
20
|
+
readonly maxEntries: 1000;
|
|
21
|
+
};
|
|
22
|
+
export interface RetentionBufferOptions {
|
|
23
|
+
readonly open: () => Promise<PersistentQueue>;
|
|
24
|
+
/** Epoch milliseconds. Default Date.now. */
|
|
25
|
+
readonly now?: () => number;
|
|
26
|
+
/** The longest one send can take, the transport timeout. Default 10000. Sets the claim lease. */
|
|
27
|
+
readonly sendTimeoutMillis?: number | undefined;
|
|
28
|
+
}
|
|
29
|
+
export declare function createRetentionBuffer(opts: RetentionBufferOptions): RetentionBuffer;
|
|
@@ -0,0 +1,130 @@
|
|
|
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
|
+
// Bumped by clear and close.
|
|
20
|
+
let epoch = 0;
|
|
21
|
+
/** Active hand-overs whose removals close() waits on before closing the queue. */
|
|
22
|
+
const handing = new Set();
|
|
23
|
+
const queue = () => {
|
|
24
|
+
opening ??= opts.open().catch((err) => {
|
|
25
|
+
diag.warn("o11y: rum: the retention buffer could not open", err);
|
|
26
|
+
return undefined;
|
|
27
|
+
});
|
|
28
|
+
return opening;
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
async put(batch) {
|
|
32
|
+
if (closed)
|
|
33
|
+
return;
|
|
34
|
+
try {
|
|
35
|
+
await (await queue())?.put(batch);
|
|
36
|
+
}
|
|
37
|
+
catch (err) {
|
|
38
|
+
diag.warn("o11y: rum: a retention buffer write failed", err);
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
async flush(delivery, keep, allowed) {
|
|
42
|
+
// A clear or close ends every flush begun before it: a batch it claimed before a revoke is
|
|
43
|
+
// never handed over, even under a grant that began since.
|
|
44
|
+
const e = epoch;
|
|
45
|
+
const ok = () => !closed && e === epoch && (allowed === undefined || allowed());
|
|
46
|
+
let sent = 0;
|
|
47
|
+
// A flush after close or before consent opens nothing.
|
|
48
|
+
if (!ok())
|
|
49
|
+
return sent;
|
|
50
|
+
try {
|
|
51
|
+
const q = await queue();
|
|
52
|
+
for (;;) {
|
|
53
|
+
if (q === undefined || !ok())
|
|
54
|
+
return sent;
|
|
55
|
+
// The queue leases only the batches keep accepts, in one transaction, so another session's
|
|
56
|
+
// batches stay claimable by that session's own flush while this one waits on the network.
|
|
57
|
+
const claimed = await q.claim(now(), CLAIM_BATCH, lease, keep);
|
|
58
|
+
if (claimed.length === 0)
|
|
59
|
+
return sent;
|
|
60
|
+
for (const b of claimed) {
|
|
61
|
+
if (!ok())
|
|
62
|
+
return sent;
|
|
63
|
+
// A queue that ignores match leaves a refused batch leased until its lease runs out, unsent.
|
|
64
|
+
if (keep !== undefined && !keep(b))
|
|
65
|
+
continue;
|
|
66
|
+
// The delivery keeps a retryable failure in its own retry queue, so the entry is done here,
|
|
67
|
+
// and a batch handed over is removed even when the flush ends meanwhile.
|
|
68
|
+
const handed = delivery.deliver({ signal: b.signal, body: b.body }).then(() => {
|
|
69
|
+
sent++;
|
|
70
|
+
return q.remove([b.id]);
|
|
71
|
+
});
|
|
72
|
+
const tracked = handed.then(() => {
|
|
73
|
+
handing.delete(tracked);
|
|
74
|
+
}, () => {
|
|
75
|
+
handing.delete(tracked);
|
|
76
|
+
});
|
|
77
|
+
handing.add(tracked);
|
|
78
|
+
await handed;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
diag.warn("o11y: rum: the retention flush failed", err);
|
|
84
|
+
return sent;
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
async discard(match) {
|
|
88
|
+
if (closed)
|
|
89
|
+
return 0;
|
|
90
|
+
try {
|
|
91
|
+
const q = await queue();
|
|
92
|
+
if (q === undefined)
|
|
93
|
+
return 0;
|
|
94
|
+
// A zero lease leaves every entry this claim reads claimable by other contexts at once.
|
|
95
|
+
const entries = await q.claim(now(), RETENTION_QUEUE_DEFAULTS.maxEntries, 0);
|
|
96
|
+
const ids = entries.filter((e) => match({ signal: e.signal, body: e.body })).map((e) => e.id);
|
|
97
|
+
if (ids.length > 0)
|
|
98
|
+
await q.remove(ids);
|
|
99
|
+
return ids.length;
|
|
100
|
+
}
|
|
101
|
+
catch (err) {
|
|
102
|
+
diag.warn("o11y: rum: discarding from the retention buffer failed", err);
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
async clear() {
|
|
107
|
+
if (closed)
|
|
108
|
+
return;
|
|
109
|
+
epoch++;
|
|
110
|
+
try {
|
|
111
|
+
// Opens the queue if needed: a previous page of the session may have left entries.
|
|
112
|
+
await (await queue())?.clear();
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
diag.warn("o11y: rum: clearing the retention buffer failed", err);
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
async size() {
|
|
119
|
+
const q = opening === undefined ? undefined : await opening;
|
|
120
|
+
return q === undefined ? { entries: 0, bytes: 0 } : q.size();
|
|
121
|
+
},
|
|
122
|
+
close() {
|
|
123
|
+
closed = true;
|
|
124
|
+
epoch++;
|
|
125
|
+
// The queue stays open until the batches already handed over are removed, so a later page
|
|
126
|
+
// never sends them again.
|
|
127
|
+
void Promise.all([...handing]).then(() => opening?.then((q) => q?.close()));
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The retention router. 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. holdingSpanExporter and holdingLogExporter
|
|
7
|
+
* route the records of an exporter the app injected, or of a console exporter, the same way, holding
|
|
8
|
+
* the current unkept session's in memory.
|
|
9
|
+
*/
|
|
10
|
+
import type { ExporterSet } from "@libo11y/core";
|
|
11
|
+
import type { LogRecordExporter } from "@opentelemetry/sdk-logs";
|
|
12
|
+
import type { SpanExporter } from "@opentelemetry/sdk-trace";
|
|
13
|
+
import type { RetentionRouting } from "../contracts/retention.ts";
|
|
14
|
+
import type { SessionDecision } from "../contracts/session.ts";
|
|
15
|
+
/** A SpanExporter that routes each span by its session.id. */
|
|
16
|
+
export declare function retainingSpanExporter(inner: SpanExporter, routing: RetentionRouting): SpanExporter;
|
|
17
|
+
/** The most spans holdingSpanExporter holds. Past it the oldest are dropped first. */
|
|
18
|
+
export declare const HELD_SPANS_MAX = 1000;
|
|
19
|
+
/** The most log records holdingLogExporter holds. Past it the oldest are dropped first. */
|
|
20
|
+
export declare const HELD_LOGS_MAX = 1000;
|
|
21
|
+
/** What a holding exporter adds to the exporter it wraps. */
|
|
22
|
+
export interface Holding {
|
|
23
|
+
/**
|
|
24
|
+
* Exports, in the order they were held, the held items of every session decide now sends, and
|
|
25
|
+
* drops those of every session it drops. The items of a session still to be buffered stay held.
|
|
26
|
+
* The export waits for any export in flight, so the inner exporter never exports two batches at
|
|
27
|
+
* once, and is dropped if allowed is false when its turn comes.
|
|
28
|
+
*/
|
|
29
|
+
release(): void;
|
|
30
|
+
/**
|
|
31
|
+
* Drops the held items of sessionId. Without it, as on a revoke, drops every held item and settles
|
|
32
|
+
* every queued export without exporting it, so none runs under a later grant.
|
|
33
|
+
*/
|
|
34
|
+
discard(sessionId?: string): void;
|
|
35
|
+
/**
|
|
36
|
+
* Stops for good: drops what is held and queued, ends a shutdown still waiting for a release, and
|
|
37
|
+
* stops the inner exporter if nothing has yet. Called once the caller's shutdown deadline passed.
|
|
38
|
+
*/
|
|
39
|
+
close(): Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
/** A SpanExporter that holds the spans of the current unkept session in memory. */
|
|
42
|
+
export interface HoldingSpanExporter extends SpanExporter, Holding {
|
|
43
|
+
}
|
|
44
|
+
/** A LogRecordExporter that holds the records of the current unkept session in memory. */
|
|
45
|
+
export interface HoldingLogExporter extends LogRecordExporter, Holding {
|
|
46
|
+
}
|
|
47
|
+
export interface HoldingOptions {
|
|
48
|
+
/** The most items held. Default HELD_SPANS_MAX or HELD_LOGS_MAX. */
|
|
49
|
+
readonly max?: number;
|
|
50
|
+
/** False while nothing may be exported, as after a revoke. A queued export that finds it false is dropped. Default always true. */
|
|
51
|
+
readonly allowed?: () => boolean;
|
|
52
|
+
/** How long one export may take. Default 30000. */
|
|
53
|
+
readonly timeoutMillis?: number;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A SpanExporter that routes each span by its session.id as retainingSpanExporter does, but holds
|
|
57
|
+
* the spans to be buffered in memory, at most max of them, instead of in the retention buffer. The
|
|
58
|
+
* retention buffer sends through the platform's delivery, so an exporter the app injected, or the
|
|
59
|
+
* console exporter, would never see a span that waited there. A held span without a session.id is
|
|
60
|
+
* never released.
|
|
61
|
+
*/
|
|
62
|
+
export declare function holdingSpanExporter(inner: SpanExporter, decide: (sessionId: string | undefined) => SessionDecision, o?: HoldingOptions): HoldingSpanExporter;
|
|
63
|
+
/**
|
|
64
|
+
* A LogRecordExporter that routes each record as holdingSpanExporter routes spans, sending every
|
|
65
|
+
* o11y.rum.view.summary record at once, as retainingLogExporter does.
|
|
66
|
+
*/
|
|
67
|
+
export declare function holdingLogExporter(inner: LogRecordExporter, decide: (sessionId: string | undefined) => SessionDecision, o?: HoldingOptions): HoldingLogExporter;
|
|
68
|
+
/** A LogRecordExporter that routes each record by its session.id, sending every view summary. */
|
|
69
|
+
export declare function retainingLogExporter(inner: LogRecordExporter, routing: RetentionRouting): LogRecordExporter;
|
|
70
|
+
/** The exporter set with traces and logs routed by session. The metric reader is unchanged. */
|
|
71
|
+
export declare function withRetention(set: ExporterSet, routing: RetentionRouting): ExporterSet;
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { EVENT_RUM_VIEW_SUMMARY } from "@libo11y/spec";
|
|
2
|
+
import { serializeLogs, serializeSpans } from "@libo11y/web/portable";
|
|
3
|
+
import { diag } from "@opentelemetry/api";
|
|
4
|
+
import { ExportResultCode } from "@opentelemetry/core";
|
|
5
|
+
import { ATTR_SESSION_ID } from "../attrs.js";
|
|
6
|
+
const SUCCESS = { code: ExportResultCode.SUCCESS };
|
|
7
|
+
function sessionOf(attrs) {
|
|
8
|
+
const v = attrs[ATTR_SESSION_ID];
|
|
9
|
+
return typeof v === "string" ? v : undefined;
|
|
10
|
+
}
|
|
11
|
+
function partition(items, route) {
|
|
12
|
+
const send = [];
|
|
13
|
+
const buffer = [];
|
|
14
|
+
for (const item of items) {
|
|
15
|
+
const r = route(item);
|
|
16
|
+
if (r === "send")
|
|
17
|
+
send.push(item);
|
|
18
|
+
else if (r === "buffer")
|
|
19
|
+
buffer.push(item);
|
|
20
|
+
}
|
|
21
|
+
return { send, buffer };
|
|
22
|
+
}
|
|
23
|
+
/** A SpanExporter that routes each span by its session.id. */
|
|
24
|
+
export function retainingSpanExporter(inner, routing) {
|
|
25
|
+
return {
|
|
26
|
+
export(spans, done) {
|
|
27
|
+
const { send, buffer } = partition(spans, (s) => routing.decide(sessionOf(s.attributes)));
|
|
28
|
+
if (buffer.length > 0)
|
|
29
|
+
routing.buffer({ signal: "traces", body: serializeSpans(buffer) });
|
|
30
|
+
if (send.length === 0)
|
|
31
|
+
done(SUCCESS);
|
|
32
|
+
else
|
|
33
|
+
inner.export(send, done);
|
|
34
|
+
},
|
|
35
|
+
shutdown: () => inner.shutdown(),
|
|
36
|
+
...(inner.forceFlush === undefined
|
|
37
|
+
? {}
|
|
38
|
+
: { forceFlush: () => inner.forceFlush?.() ?? Promise.resolve() }),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/** The most spans holdingSpanExporter holds. Past it the oldest are dropped first. */
|
|
42
|
+
export const HELD_SPANS_MAX = 1000;
|
|
43
|
+
/** The most log records holdingLogExporter holds. Past it the oldest are dropped first. */
|
|
44
|
+
export const HELD_LOGS_MAX = 1000;
|
|
45
|
+
/** How long one export the holding exporters start may take before it counts as failed, as upstream's batch processors wait. */
|
|
46
|
+
const HELD_EXPORT_TIMEOUT_MILLIS = 30_000;
|
|
47
|
+
function asError(err) {
|
|
48
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
49
|
+
}
|
|
50
|
+
function holding(inner, what, route, idOf, max, o) {
|
|
51
|
+
const allowed = o.allowed ?? (() => true);
|
|
52
|
+
const timeoutMillis = o.timeoutMillis ?? HELD_EXPORT_TIMEOUT_MILLIS;
|
|
53
|
+
let held = [];
|
|
54
|
+
let jobs = [];
|
|
55
|
+
/** An export whose caller is still waiting for it. */
|
|
56
|
+
let busy = false;
|
|
57
|
+
/** The inner exporter has not yet called back, even if the export timed out. */
|
|
58
|
+
let innerBusy = false;
|
|
59
|
+
let closed = false;
|
|
60
|
+
let epoch = 0;
|
|
61
|
+
/** The first release export that failed and was not yet reported by forceFlush or shutdown. */
|
|
62
|
+
let failure;
|
|
63
|
+
/** Waiting for every queued and in-flight export to finish. */
|
|
64
|
+
let idleWaiters = [];
|
|
65
|
+
let innerStopped;
|
|
66
|
+
/** Ends a shutdown that waits for a release, once close is called. */
|
|
67
|
+
let abort = () => { };
|
|
68
|
+
const aborted = new Promise((resolve) => {
|
|
69
|
+
abort = resolve;
|
|
70
|
+
});
|
|
71
|
+
const idle = () => !busy && jobs.length === 0 ? Promise.resolve() : new Promise((resolve) => idleWaiters.push(resolve));
|
|
72
|
+
const settleIdle = () => {
|
|
73
|
+
const waiters = idleWaiters;
|
|
74
|
+
idleWaiters = [];
|
|
75
|
+
for (const w of waiters)
|
|
76
|
+
w();
|
|
77
|
+
};
|
|
78
|
+
const stopInner = () => {
|
|
79
|
+
innerStopped ??= Promise.resolve().then(() => inner.shutdown());
|
|
80
|
+
return innerStopped;
|
|
81
|
+
};
|
|
82
|
+
const shutDown = () => ({
|
|
83
|
+
code: ExportResultCode.FAILED,
|
|
84
|
+
error: new Error(`o11y: rum: ${what} exporter is shut down`),
|
|
85
|
+
});
|
|
86
|
+
const timedOut = () => ({
|
|
87
|
+
code: ExportResultCode.FAILED,
|
|
88
|
+
error: new Error(`o11y: rum: exporting ${what} timed out`),
|
|
89
|
+
});
|
|
90
|
+
const pump = () => {
|
|
91
|
+
while (!busy) {
|
|
92
|
+
const job = jobs.shift();
|
|
93
|
+
if (job === undefined) {
|
|
94
|
+
settleIdle();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
// What waits for its turn after a revoke, or past a grant revoked since, exports nothing.
|
|
98
|
+
if (closed || !allowed() || job.epoch !== epoch) {
|
|
99
|
+
job.done(closed && !job.release ? shutDown() : SUCCESS);
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
// The inner exporter has yet to answer an export that timed out, and never exports two
|
|
103
|
+
// batches at once: what is queued meanwhile fails.
|
|
104
|
+
if (innerBusy) {
|
|
105
|
+
job.done(timedOut());
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
busy = true;
|
|
109
|
+
innerBusy = true;
|
|
110
|
+
let answered = false;
|
|
111
|
+
let finished = false;
|
|
112
|
+
const finish = (r) => {
|
|
113
|
+
if (finished)
|
|
114
|
+
return;
|
|
115
|
+
finished = true;
|
|
116
|
+
clearTimeout(timer);
|
|
117
|
+
busy = false;
|
|
118
|
+
job.done(r);
|
|
119
|
+
pump();
|
|
120
|
+
};
|
|
121
|
+
const timer = setTimeout(() => finish(timedOut()), timeoutMillis);
|
|
122
|
+
timer.unref?.();
|
|
123
|
+
const answer = (r) => {
|
|
124
|
+
if (answered)
|
|
125
|
+
return;
|
|
126
|
+
answered = true;
|
|
127
|
+
innerBusy = false;
|
|
128
|
+
finish(r);
|
|
129
|
+
};
|
|
130
|
+
try {
|
|
131
|
+
inner.export(job.items, answer);
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
answer({ code: ExportResultCode.FAILED, error: asError(err) });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
const enqueue = (items, done, release) => {
|
|
139
|
+
jobs.push({ items, done, release, epoch });
|
|
140
|
+
pump();
|
|
141
|
+
};
|
|
142
|
+
/** Settles every queued export with r without exporting it; a release settles as a success. */
|
|
143
|
+
const drain = (r) => {
|
|
144
|
+
const queued = jobs;
|
|
145
|
+
jobs = [];
|
|
146
|
+
for (const job of queued)
|
|
147
|
+
job.done(job.release ? SUCCESS : r);
|
|
148
|
+
if (!busy)
|
|
149
|
+
settleIdle();
|
|
150
|
+
};
|
|
151
|
+
const report = () => {
|
|
152
|
+
const err = failure;
|
|
153
|
+
failure = undefined;
|
|
154
|
+
if (err !== undefined)
|
|
155
|
+
throw err;
|
|
156
|
+
};
|
|
157
|
+
return {
|
|
158
|
+
export(items, done) {
|
|
159
|
+
if (closed) {
|
|
160
|
+
done({ code: ExportResultCode.FAILED, error: new Error(`o11y: rum: ${what} exporter is shut down`) });
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const send = [];
|
|
164
|
+
for (const item of items) {
|
|
165
|
+
const r = route(item);
|
|
166
|
+
if (r === "send")
|
|
167
|
+
send.push(item);
|
|
168
|
+
else if (r === "buffer")
|
|
169
|
+
held.push({ id: idOf(item), item });
|
|
170
|
+
}
|
|
171
|
+
if (held.length > max)
|
|
172
|
+
held = held.slice(held.length - max);
|
|
173
|
+
if (send.length === 0)
|
|
174
|
+
done(SUCCESS);
|
|
175
|
+
else
|
|
176
|
+
enqueue(send, done, false);
|
|
177
|
+
},
|
|
178
|
+
release() {
|
|
179
|
+
if (closed)
|
|
180
|
+
return;
|
|
181
|
+
const send = [];
|
|
182
|
+
const keep = [];
|
|
183
|
+
for (const h of held) {
|
|
184
|
+
const r = h.id === undefined ? "drop" : route(h.item);
|
|
185
|
+
if (r === "send")
|
|
186
|
+
send.push(h.item);
|
|
187
|
+
else if (r === "buffer")
|
|
188
|
+
keep.push(h);
|
|
189
|
+
}
|
|
190
|
+
held = keep;
|
|
191
|
+
if (send.length === 0)
|
|
192
|
+
return;
|
|
193
|
+
enqueue(send, (r) => {
|
|
194
|
+
if (r.code === ExportResultCode.SUCCESS)
|
|
195
|
+
return;
|
|
196
|
+
const err = r.error ?? new Error(`o11y: rum: exporting held ${what} failed`);
|
|
197
|
+
diag.warn(`o11y: rum: exporting held ${what} failed`, err);
|
|
198
|
+
failure ??= err;
|
|
199
|
+
}, true);
|
|
200
|
+
},
|
|
201
|
+
discard(sessionId) {
|
|
202
|
+
if (sessionId !== undefined) {
|
|
203
|
+
held = held.filter((h) => h.id !== sessionId);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
// A revoke: nothing held or queued under the grant it ends is exported, even after a new grant.
|
|
207
|
+
held = [];
|
|
208
|
+
epoch++;
|
|
209
|
+
drain(SUCCESS);
|
|
210
|
+
},
|
|
211
|
+
async forceFlush() {
|
|
212
|
+
await Promise.race([idle(), aborted]);
|
|
213
|
+
await inner.forceFlush?.();
|
|
214
|
+
report();
|
|
215
|
+
},
|
|
216
|
+
async shutdown() {
|
|
217
|
+
await Promise.race([idle(), aborted]);
|
|
218
|
+
await stopInner();
|
|
219
|
+
report();
|
|
220
|
+
},
|
|
221
|
+
async close() {
|
|
222
|
+
closed = true;
|
|
223
|
+
held = [];
|
|
224
|
+
abort();
|
|
225
|
+
// What still waits for its turn is not exported. A queued release is dropped as a revoke drops it.
|
|
226
|
+
drain(shutDown());
|
|
227
|
+
try {
|
|
228
|
+
await stopInner();
|
|
229
|
+
}
|
|
230
|
+
catch (err) {
|
|
231
|
+
diag.debug(`o11y: rum: stopping the ${what} exporter failed`, err);
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* A SpanExporter that routes each span by its session.id as retainingSpanExporter does, but holds
|
|
238
|
+
* the spans to be buffered in memory, at most max of them, instead of in the retention buffer. The
|
|
239
|
+
* retention buffer sends through the platform's delivery, so an exporter the app injected, or the
|
|
240
|
+
* console exporter, would never see a span that waited there. A held span without a session.id is
|
|
241
|
+
* never released.
|
|
242
|
+
*/
|
|
243
|
+
export function holdingSpanExporter(inner, decide, o = {}) {
|
|
244
|
+
return holding(inner, "spans", (s) => decide(sessionOf(s.attributes)), (s) => sessionOf(s.attributes), o.max ?? HELD_SPANS_MAX, o);
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* A LogRecordExporter that routes each record as holdingSpanExporter routes spans, sending every
|
|
248
|
+
* o11y.rum.view.summary record at once, as retainingLogExporter does.
|
|
249
|
+
*/
|
|
250
|
+
export function holdingLogExporter(inner, decide, o = {}) {
|
|
251
|
+
const h = holding(inner, "log records", (l) => (l.attributes["event.name"] === EVENT_RUM_VIEW_SUMMARY ? "send" : decide(sessionOf(l.attributes))), (l) => sessionOf(l.attributes), o.max ?? HELD_LOGS_MAX, o);
|
|
252
|
+
return { ...h, forceFlush: () => h.forceFlush?.() ?? Promise.resolve() };
|
|
253
|
+
}
|
|
254
|
+
/** A LogRecordExporter that routes each record by its session.id, sending every view summary. */
|
|
255
|
+
export function retainingLogExporter(inner, routing) {
|
|
256
|
+
return {
|
|
257
|
+
export(records, done) {
|
|
258
|
+
const { send, buffer } = partition(records, (l) => l.attributes["event.name"] === EVENT_RUM_VIEW_SUMMARY
|
|
259
|
+
? "send"
|
|
260
|
+
: routing.decide(sessionOf(l.attributes)));
|
|
261
|
+
if (buffer.length > 0)
|
|
262
|
+
routing.buffer({ signal: "logs", body: serializeLogs(buffer) });
|
|
263
|
+
if (send.length === 0)
|
|
264
|
+
done(SUCCESS);
|
|
265
|
+
else
|
|
266
|
+
inner.export(send, done);
|
|
267
|
+
},
|
|
268
|
+
shutdown: () => inner.shutdown(),
|
|
269
|
+
forceFlush: () => inner.forceFlush(),
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
/** The exporter set with traces and logs routed by session. The metric reader is unchanged. */
|
|
273
|
+
export function withRetention(set, routing) {
|
|
274
|
+
return {
|
|
275
|
+
...set,
|
|
276
|
+
...(set.spanExporter === undefined
|
|
277
|
+
? {}
|
|
278
|
+
: { spanExporter: retainingSpanExporter(set.spanExporter, routing) }),
|
|
279
|
+
...(set.logExporter === undefined ? {} : { logExporter: retainingLogExporter(set.logExporter, routing) }),
|
|
280
|
+
};
|
|
281
|
+
}
|
|
@@ -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;
|