@nagoorkani/session-capture-core 0.1.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 +25 -0
- package/README.md +42 -0
- package/dist/batcher.d.ts +58 -0
- package/dist/batcher.js +106 -0
- package/dist/breadcrumbs.d.ts +22 -0
- package/dist/breadcrumbs.js +45 -0
- package/dist/config.d.ts +60 -0
- package/dist/config.js +134 -0
- package/dist/container.d.ts +33 -0
- package/dist/container.js +48 -0
- package/dist/core.d.ts +175 -0
- package/dist/core.js +414 -0
- package/dist/dispatcher.d.ts +43 -0
- package/dist/dispatcher.js +74 -0
- package/dist/errors.d.ts +40 -0
- package/dist/errors.js +186 -0
- package/dist/ids.d.ts +29 -0
- package/dist/ids.js +58 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.js +39 -0
- package/dist/network.d.ts +123 -0
- package/dist/network.js +510 -0
- package/dist/performance.d.ts +33 -0
- package/dist/performance.js +54 -0
- package/dist/queue.d.ts +70 -0
- package/dist/queue.js +105 -0
- package/dist/redact.d.ts +19 -0
- package/dist/redact.js +61 -0
- package/dist/replay-gate.d.ts +69 -0
- package/dist/replay-gate.js +78 -0
- package/dist/safe.d.ts +26 -0
- package/dist/safe.js +88 -0
- package/dist/session.d.ts +80 -0
- package/dist/session.js +111 -0
- package/dist/store.d.ts +44 -0
- package/dist/store.js +49 -0
- package/dist/transport.d.ts +62 -0
- package/dist/transport.js +84 -0
- package/dist/types.d.ts +92 -0
- package/dist/types.js +26 -0
- package/package.json +45 -0
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SDK core.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately contains no React Native imports. The platform glue lives in
|
|
5
|
+
* `lifecycle.ts` and is injected, so this logic is testable in plain Node and
|
|
6
|
+
* so a bug here cannot be hidden behind a mock of the whole SDK.
|
|
7
|
+
*/
|
|
8
|
+
import { type CapturedError } from './errors.ts';
|
|
9
|
+
import type { NetworkEvent } from './network.ts';
|
|
10
|
+
import { type SessionState } from './session.ts';
|
|
11
|
+
import { type CaptureEvent, type EventBatch, type EventType, type InitOptions, type RemoteConfig } from './types.ts';
|
|
12
|
+
export declare const SDK_VERSION = "0.1.0";
|
|
13
|
+
/**
|
|
14
|
+
* Idle bound. Nothing for this long and the next event opens a new session.
|
|
15
|
+
*
|
|
16
|
+
* There is deliberately no wall-clock ceiling. A continuously used app is
|
|
17
|
+
* one continuously useful session whether it lasts five minutes or an hour.
|
|
18
|
+
* The backend waits beyond this idle bound before finalizing sessions that
|
|
19
|
+
* never deliver `session_end` (section 20).
|
|
20
|
+
*/
|
|
21
|
+
export declare const SESSION_TIMEOUT_MS: number;
|
|
22
|
+
/** Receives a fully-formed batch, ready to send. */
|
|
23
|
+
export type BatchHandler = (batch: EventBatch) => void | Promise<void>;
|
|
24
|
+
export interface CoreDeps {
|
|
25
|
+
now?: () => number;
|
|
26
|
+
onFlush?: BatchHandler;
|
|
27
|
+
/**
|
|
28
|
+
* Supplies platform and OS details for `session_start`.
|
|
29
|
+
*
|
|
30
|
+
* Injected rather than imported so this module never touches
|
|
31
|
+
* `react-native` — that keeps it testable in Node, and keeps the
|
|
32
|
+
* device-only import isolated in `index.ts` where it belongs.
|
|
33
|
+
*/
|
|
34
|
+
deviceContext?: () => Record<string, unknown>;
|
|
35
|
+
/**
|
|
36
|
+
* Supplies a session to resume instead of starting a new one.
|
|
37
|
+
*
|
|
38
|
+
* A browser tab outlives its JavaScript context: a reload is the same visit,
|
|
39
|
+
* and treating it as a new session would cut every timeline at every
|
|
40
|
+
* navigation. Native apps have no equivalent — an app that is killed really
|
|
41
|
+
* has ended — so this is unset there and the SDK starts fresh.
|
|
42
|
+
*/
|
|
43
|
+
restoreSession?: () => SessionState | null;
|
|
44
|
+
}
|
|
45
|
+
export declare class SdkCore {
|
|
46
|
+
private options;
|
|
47
|
+
private config;
|
|
48
|
+
private sessions;
|
|
49
|
+
private batcher;
|
|
50
|
+
private enabled;
|
|
51
|
+
private started;
|
|
52
|
+
private readonly now;
|
|
53
|
+
private readonly onFlush;
|
|
54
|
+
private readonly deviceContext;
|
|
55
|
+
private readonly restoreSession;
|
|
56
|
+
/**
|
|
57
|
+
* Notified after an error is captured.
|
|
58
|
+
*
|
|
59
|
+
* The seam the optional replay package hangs off (section 23). Core does not
|
|
60
|
+
* know what replay is and must not: this is a list of callbacks, and if the
|
|
61
|
+
* package is not installed the list is empty.
|
|
62
|
+
*/
|
|
63
|
+
private readonly errorListeners;
|
|
64
|
+
/**
|
|
65
|
+
* Notified as each session begins.
|
|
66
|
+
*
|
|
67
|
+
* The same seam as `errorListeners`, for the thing replay cannot get from
|
|
68
|
+
* `onError`: continuous recording needs the session id at every flush, and
|
|
69
|
+
* needs the start boundary to decide whether this session is sampled.
|
|
70
|
+
*/
|
|
71
|
+
private readonly sessionListeners;
|
|
72
|
+
constructor(deps?: CoreDeps);
|
|
73
|
+
/**
|
|
74
|
+
* The live session, for a platform that has to persist it.
|
|
75
|
+
*
|
|
76
|
+
* Read-only by convention — it is the manager's own object, and mutating it
|
|
77
|
+
* from outside would desynchronize the sequence counter from the events
|
|
78
|
+
* already sent.
|
|
79
|
+
*/
|
|
80
|
+
session(): SessionState | null;
|
|
81
|
+
init(options: InitOptions): void;
|
|
82
|
+
/**
|
|
83
|
+
* Whether capture is currently active.
|
|
84
|
+
*
|
|
85
|
+
* Three independent gates: initialized, locally enabled (consent), and
|
|
86
|
+
* remotely enabled (the kill switch). Any one of them off means nothing is
|
|
87
|
+
* captured and nothing is buffered.
|
|
88
|
+
*/
|
|
89
|
+
isEnabled(): boolean;
|
|
90
|
+
setEnabled(enabled: boolean): void;
|
|
91
|
+
/**
|
|
92
|
+
* Apply remote configuration (section 39).
|
|
93
|
+
*
|
|
94
|
+
* Takes effect on a running SDK, not just at startup — that is the whole
|
|
95
|
+
* point of the kill switch. `isEnabled()` re-reads `config.enabled` on every
|
|
96
|
+
* capture, so `enabled: false` stops collection mid-session.
|
|
97
|
+
*
|
|
98
|
+
* Sampling is the one thing that cannot be retrofitted: it is decided once
|
|
99
|
+
* at session start and must stay that way, or a timeline ends up half
|
|
100
|
+
* captured while looking complete. A new rate therefore applies from the
|
|
101
|
+
* next session.
|
|
102
|
+
*/
|
|
103
|
+
applyConfig(config: RemoteConfig): void;
|
|
104
|
+
/** Events discarded because remote config disabled capture. Diagnostics. */
|
|
105
|
+
private dropOnKill;
|
|
106
|
+
get droppedOnKill(): number;
|
|
107
|
+
/** The config currently in force. */
|
|
108
|
+
get remoteConfig(): RemoteConfig;
|
|
109
|
+
capture(type: EventType, data?: Record<string, unknown>): CaptureEvent | null;
|
|
110
|
+
/**
|
|
111
|
+
* Capture an error with its breadcrumb trail.
|
|
112
|
+
*
|
|
113
|
+
* Bypasses sampling: errors are rare and are the reason people install this.
|
|
114
|
+
*/
|
|
115
|
+
captureError(value: unknown, handled: boolean, extra?: Record<string, unknown>): void;
|
|
116
|
+
/**
|
|
117
|
+
* Capture an error the global handler has already described.
|
|
118
|
+
*
|
|
119
|
+
* Separate from `captureError` because `describeError` cannot usefully
|
|
120
|
+
* re-describe its own output: a `CapturedError` is a plain object, so it
|
|
121
|
+
* took the object branch and came out as `UnknownError` with the real type,
|
|
122
|
+
* message and stack JSON-stringified inside the message. Every *uncaught*
|
|
123
|
+
* error — the ones that matter most — arrived that way, and the `fatal`
|
|
124
|
+
* flag was lost with them.
|
|
125
|
+
*/
|
|
126
|
+
captureCrash(described: CapturedError): void;
|
|
127
|
+
private report;
|
|
128
|
+
/**
|
|
129
|
+
* Subscribe to errors. Returns an unsubscribe.
|
|
130
|
+
*
|
|
131
|
+
* The session id is passed rather than left for the subscriber to look up:
|
|
132
|
+
* by the time a listener runs the session could have rolled over, and a
|
|
133
|
+
* recording filed against the wrong session is worse than none.
|
|
134
|
+
*/
|
|
135
|
+
/**
|
|
136
|
+
* Count ongoing work as activity, without emitting an event for it.
|
|
137
|
+
*
|
|
138
|
+
* Recording is activity even when no analytics event happens, so replay
|
|
139
|
+
* calls this as it cuts segments. That keeps an actively recorded session
|
|
140
|
+
* alive; after thirty minutes without either kind of work, the next touch
|
|
141
|
+
* rotates through the ordinary inactivity boundary.
|
|
142
|
+
*/
|
|
143
|
+
keepAlive(): void;
|
|
144
|
+
/** The config in force right now, including anything remote config changed. */
|
|
145
|
+
currentConfig(): RemoteConfig;
|
|
146
|
+
onSession(listener: (sessionId: string) => void): () => void;
|
|
147
|
+
onError(listener: (sessionId: string) => void): () => void;
|
|
148
|
+
captureNetwork(event: NetworkEvent): void;
|
|
149
|
+
/** Close a named mark and record its duration. */
|
|
150
|
+
measure(name: string): void;
|
|
151
|
+
mark(name: string): void;
|
|
152
|
+
/** Record time from SDK load to app-ready. */
|
|
153
|
+
markReady(): void;
|
|
154
|
+
screen(name: string): void;
|
|
155
|
+
/** Called by the platform lifecycle glue. */
|
|
156
|
+
onAppStateChange(state: 'active' | 'background'): void;
|
|
157
|
+
flush(): Promise<void>;
|
|
158
|
+
shutdown(): void;
|
|
159
|
+
private startSessionIfNeeded;
|
|
160
|
+
/**
|
|
161
|
+
* Announce a session that has just begun.
|
|
162
|
+
*
|
|
163
|
+
* Called from inside `SessionManager.start()`, which is reachable from
|
|
164
|
+
* inside `capture()` — so this re-enters `capture()`. That is safe and is
|
|
165
|
+
* what gives the right ordering: `this.state` is already set, so the nested
|
|
166
|
+
* `touch()` finds a live session rather than rotating again, and
|
|
167
|
+
* `session_start` takes sequence 0 while the event that triggered the
|
|
168
|
+
* rotation takes 1.
|
|
169
|
+
*/
|
|
170
|
+
private announce;
|
|
171
|
+
/** Test accessors. */
|
|
172
|
+
get currentSession(): SessionState | null;
|
|
173
|
+
get buffered(): number;
|
|
174
|
+
private deliver;
|
|
175
|
+
}
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SDK core.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately contains no React Native imports. The platform glue lives in
|
|
5
|
+
* `lifecycle.ts` and is injected, so this logic is testable in plain Node and
|
|
6
|
+
* so a bug here cannot be hidden behind a mock of the whole SDK.
|
|
7
|
+
*/
|
|
8
|
+
import { Batcher } from "./batcher.js";
|
|
9
|
+
import { addBreadcrumb, clearBreadcrumbs, snapshotBreadcrumbs } from "./breadcrumbs.js";
|
|
10
|
+
import { describeError } from "./errors.js";
|
|
11
|
+
import { createId } from "./ids.js";
|
|
12
|
+
import { measure, timeToReady, mark } from "./performance.js";
|
|
13
|
+
import { redact } from "./redact.js";
|
|
14
|
+
import { SessionManager } from "./session.js";
|
|
15
|
+
import { DEFAULT_CONFIG, SCHEMA_VERSION, } from "./types.js";
|
|
16
|
+
export const SDK_VERSION = '0.1.0';
|
|
17
|
+
/**
|
|
18
|
+
* Idle bound. Nothing for this long and the next event opens a new session.
|
|
19
|
+
*
|
|
20
|
+
* There is deliberately no wall-clock ceiling. A continuously used app is
|
|
21
|
+
* one continuously useful session whether it lasts five minutes or an hour.
|
|
22
|
+
* The backend waits beyond this idle bound before finalizing sessions that
|
|
23
|
+
* never deliver `session_end` (section 20).
|
|
24
|
+
*/
|
|
25
|
+
export const SESSION_TIMEOUT_MS = 30 * 60 * 1000;
|
|
26
|
+
/** Event types that bypass sampling entirely. */
|
|
27
|
+
const ALWAYS_CAPTURED = new Set([
|
|
28
|
+
'error',
|
|
29
|
+
]);
|
|
30
|
+
export class SdkCore {
|
|
31
|
+
constructor(deps = {}) {
|
|
32
|
+
this.options = null;
|
|
33
|
+
this.config = DEFAULT_CONFIG;
|
|
34
|
+
this.sessions = null;
|
|
35
|
+
this.batcher = null;
|
|
36
|
+
this.enabled = false;
|
|
37
|
+
this.started = false;
|
|
38
|
+
/**
|
|
39
|
+
* Notified after an error is captured.
|
|
40
|
+
*
|
|
41
|
+
* The seam the optional replay package hangs off (section 23). Core does not
|
|
42
|
+
* know what replay is and must not: this is a list of callbacks, and if the
|
|
43
|
+
* package is not installed the list is empty.
|
|
44
|
+
*/
|
|
45
|
+
this.errorListeners = new Set();
|
|
46
|
+
/**
|
|
47
|
+
* Notified as each session begins.
|
|
48
|
+
*
|
|
49
|
+
* The same seam as `errorListeners`, for the thing replay cannot get from
|
|
50
|
+
* `onError`: continuous recording needs the session id at every flush, and
|
|
51
|
+
* needs the start boundary to decide whether this session is sampled.
|
|
52
|
+
*/
|
|
53
|
+
this.sessionListeners = new Set();
|
|
54
|
+
/** Events discarded because remote config disabled capture. Diagnostics. */
|
|
55
|
+
this.dropOnKill = 0;
|
|
56
|
+
this.now = deps.now ?? Date.now;
|
|
57
|
+
this.onFlush = deps.onFlush ?? (() => { });
|
|
58
|
+
this.deviceContext = deps.deviceContext ?? (() => ({}));
|
|
59
|
+
this.restoreSession = deps.restoreSession ?? (() => null);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The live session, for a platform that has to persist it.
|
|
63
|
+
*
|
|
64
|
+
* Read-only by convention — it is the manager's own object, and mutating it
|
|
65
|
+
* from outside would desynchronize the sequence counter from the events
|
|
66
|
+
* already sent.
|
|
67
|
+
*/
|
|
68
|
+
session() {
|
|
69
|
+
return this.sessions?.current() ?? null;
|
|
70
|
+
}
|
|
71
|
+
init(options) {
|
|
72
|
+
if (this.started) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
this.options = options;
|
|
76
|
+
this.enabled = options.enabled ?? true;
|
|
77
|
+
this.started = true;
|
|
78
|
+
this.sessions = new SessionManager({
|
|
79
|
+
timeoutMs: SESSION_TIMEOUT_MS,
|
|
80
|
+
initial: this.restoreSession(),
|
|
81
|
+
sampleRate: this.config.sampleRate,
|
|
82
|
+
now: this.now,
|
|
83
|
+
onStart: (session) => this.announce(session.sessionId),
|
|
84
|
+
// Close the outgoing side of an inactivity rotation immediately. The
|
|
85
|
+
// backend finalizer remains the fallback for force-quits and OS kills.
|
|
86
|
+
onEnd: () => this.capture('session_end'),
|
|
87
|
+
});
|
|
88
|
+
this.batcher = new Batcher({
|
|
89
|
+
maxSize: this.config.batchSize,
|
|
90
|
+
flushIntervalMs: this.config.flushIntervalMs,
|
|
91
|
+
onFlush: (events) => this.deliver(events),
|
|
92
|
+
});
|
|
93
|
+
// Open the session immediately when consent allows. The backend creates
|
|
94
|
+
// its session row from this event (section 20); without it the first
|
|
95
|
+
// screen view would arrive for a session nothing has announced.
|
|
96
|
+
this.startSessionIfNeeded();
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Whether capture is currently active.
|
|
100
|
+
*
|
|
101
|
+
* Three independent gates: initialized, locally enabled (consent), and
|
|
102
|
+
* remotely enabled (the kill switch). Any one of them off means nothing is
|
|
103
|
+
* captured and nothing is buffered.
|
|
104
|
+
*/
|
|
105
|
+
isEnabled() {
|
|
106
|
+
return this.started && this.enabled && this.config.enabled;
|
|
107
|
+
}
|
|
108
|
+
setEnabled(enabled) {
|
|
109
|
+
this.enabled = enabled;
|
|
110
|
+
if (enabled) {
|
|
111
|
+
// Consent just arrived — this is the real start of the session.
|
|
112
|
+
this.startSessionIfNeeded();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
// Disabling drops what is buffered rather than flushing it. Consent was
|
|
116
|
+
// withdrawn; sending anyway would be the exact violation the gate exists
|
|
117
|
+
// to prevent.
|
|
118
|
+
if (!enabled) {
|
|
119
|
+
this.batcher?.drop();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Apply remote configuration (section 39).
|
|
124
|
+
*
|
|
125
|
+
* Takes effect on a running SDK, not just at startup — that is the whole
|
|
126
|
+
* point of the kill switch. `isEnabled()` re-reads `config.enabled` on every
|
|
127
|
+
* capture, so `enabled: false` stops collection mid-session.
|
|
128
|
+
*
|
|
129
|
+
* Sampling is the one thing that cannot be retrofitted: it is decided once
|
|
130
|
+
* at session start and must stay that way, or a timeline ends up half
|
|
131
|
+
* captured while looking complete. A new rate therefore applies from the
|
|
132
|
+
* next session.
|
|
133
|
+
*/
|
|
134
|
+
applyConfig(config) {
|
|
135
|
+
const wasEnabled = this.config.enabled;
|
|
136
|
+
this.config = config;
|
|
137
|
+
this.sessions?.setSampleRate(config.sampleRate);
|
|
138
|
+
// The kill switch has to take the buffer with it.
|
|
139
|
+
//
|
|
140
|
+
// Config arrives a moment after `init`, and the SDK captures from the
|
|
141
|
+
// first line of the app's mount — session_start, foreground, the first
|
|
142
|
+
// screen. Gating future captures is not enough: on a real device those
|
|
143
|
+
// early events sat in the buffer and the flush timer sent them anyway,
|
|
144
|
+
// so a "killed" SDK still delivered four events on every launch.
|
|
145
|
+
if (wasEnabled && !config.enabled) {
|
|
146
|
+
const dropped = this.batcher?.drop() ?? 0;
|
|
147
|
+
if (dropped > 0) {
|
|
148
|
+
this.dropOnKill = dropped;
|
|
149
|
+
}
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
this.batcher?.reconfigure({
|
|
153
|
+
maxSize: config.batchSize,
|
|
154
|
+
flushIntervalMs: config.flushIntervalMs,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
get droppedOnKill() {
|
|
158
|
+
return this.dropOnKill;
|
|
159
|
+
}
|
|
160
|
+
/** The config currently in force. */
|
|
161
|
+
get remoteConfig() {
|
|
162
|
+
return this.config;
|
|
163
|
+
}
|
|
164
|
+
capture(type, data) {
|
|
165
|
+
if (!this.isEnabled() || !this.sessions || !this.batcher) {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
// A goodbye must never create the thing it says goodbye to. `session_end`
|
|
169
|
+
// used to route through `touch()` like everything else, so one arriving
|
|
170
|
+
// on an expired session rotated it — emitting a `session_end` for the old
|
|
171
|
+
// session, a `session_start` for a brand new one, and then filing the
|
|
172
|
+
// original farewell against *that*. The result was a phantom session one
|
|
173
|
+
// millisecond long, containing nothing but hello and goodbye.
|
|
174
|
+
const session = type === 'session_end' ? this.sessions.current() : this.sessions.touch();
|
|
175
|
+
if (!session)
|
|
176
|
+
return null;
|
|
177
|
+
// Sampling is per session, so an unsampled session captures nothing —
|
|
178
|
+
// except errors and crashes, which are rare and are the reason people
|
|
179
|
+
// install this at all.
|
|
180
|
+
if (!session.sampled && !ALWAYS_CAPTURED.has(type)) {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
const event = {
|
|
184
|
+
id: createId('evt'),
|
|
185
|
+
type,
|
|
186
|
+
sessionId: session.sessionId,
|
|
187
|
+
sequence: this.sessions.takeSequence(session),
|
|
188
|
+
timestamp: this.now(),
|
|
189
|
+
// Redact before the event reaches the buffer, never on the way out.
|
|
190
|
+
...(data ? { data: redact(data, this.config.maskedKeys) } : {}),
|
|
191
|
+
};
|
|
192
|
+
this.batcher.add(event);
|
|
193
|
+
// Every captured event is also context for a future error. Errors are
|
|
194
|
+
// excluded: an error carries its own breadcrumbs, and including them
|
|
195
|
+
// would nest the buffer inside itself.
|
|
196
|
+
if (type !== 'error') {
|
|
197
|
+
addBreadcrumb(type, undefined, data, this.config.maskedKeys, event.timestamp);
|
|
198
|
+
}
|
|
199
|
+
return event;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Capture an error with its breadcrumb trail.
|
|
203
|
+
*
|
|
204
|
+
* Bypasses sampling: errors are rare and are the reason people install this.
|
|
205
|
+
*/
|
|
206
|
+
captureError(value, handled, extra) {
|
|
207
|
+
this.report(describeError(value, handled), extra);
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Capture an error the global handler has already described.
|
|
211
|
+
*
|
|
212
|
+
* Separate from `captureError` because `describeError` cannot usefully
|
|
213
|
+
* re-describe its own output: a `CapturedError` is a plain object, so it
|
|
214
|
+
* took the object branch and came out as `UnknownError` with the real type,
|
|
215
|
+
* message and stack JSON-stringified inside the message. Every *uncaught*
|
|
216
|
+
* error — the ones that matter most — arrived that way, and the `fatal`
|
|
217
|
+
* flag was lost with them.
|
|
218
|
+
*/
|
|
219
|
+
captureCrash(described) {
|
|
220
|
+
this.report(described);
|
|
221
|
+
}
|
|
222
|
+
report(described, extra) {
|
|
223
|
+
if (!this.isEnabled())
|
|
224
|
+
return;
|
|
225
|
+
this.capture('error', {
|
|
226
|
+
...described,
|
|
227
|
+
...extra,
|
|
228
|
+
breadcrumbs: snapshotBreadcrumbs(this.now()),
|
|
229
|
+
});
|
|
230
|
+
// Listeners are wrapped individually: a subscriber that throws must not
|
|
231
|
+
// take the error path down with it, and the error path is the one that
|
|
232
|
+
// matters most.
|
|
233
|
+
//
|
|
234
|
+
// Notified before the session is closed below, so replay still files its
|
|
235
|
+
// frames against the session they were recorded in.
|
|
236
|
+
const sessionId = this.sessions?.current()?.sessionId ?? '';
|
|
237
|
+
for (const listener of this.errorListeners) {
|
|
238
|
+
try {
|
|
239
|
+
listener(sessionId);
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
// Deliberately swallowed. See above.
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
// A fatal error is the end of the session, and the platform is about to
|
|
246
|
+
// stop running our code — so say so now rather than leaving the session
|
|
247
|
+
// looking live until the sweeper closes it half an hour later.
|
|
248
|
+
//
|
|
249
|
+
// Only what the platform calls fatal. A handled exception is a bad
|
|
250
|
+
// moment, not the end of a session.
|
|
251
|
+
if (described.fatal) {
|
|
252
|
+
this.capture('session_end', { reason: 'crash' });
|
|
253
|
+
this.sessions?.end();
|
|
254
|
+
}
|
|
255
|
+
// An error flushes immediately — after the session_end, so both travel in
|
|
256
|
+
// the same batch. Waiting for a full batch risks losing the one event that
|
|
257
|
+
// mattered if the app is about to die.
|
|
258
|
+
void this.batcher?.flush();
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Subscribe to errors. Returns an unsubscribe.
|
|
262
|
+
*
|
|
263
|
+
* The session id is passed rather than left for the subscriber to look up:
|
|
264
|
+
* by the time a listener runs the session could have rolled over, and a
|
|
265
|
+
* recording filed against the wrong session is worse than none.
|
|
266
|
+
*/
|
|
267
|
+
/**
|
|
268
|
+
* Count ongoing work as activity, without emitting an event for it.
|
|
269
|
+
*
|
|
270
|
+
* Recording is activity even when no analytics event happens, so replay
|
|
271
|
+
* calls this as it cuts segments. That keeps an actively recorded session
|
|
272
|
+
* alive; after thirty minutes without either kind of work, the next touch
|
|
273
|
+
* rotates through the ordinary inactivity boundary.
|
|
274
|
+
*/
|
|
275
|
+
keepAlive() {
|
|
276
|
+
if (!this.isEnabled())
|
|
277
|
+
return;
|
|
278
|
+
this.sessions?.touch();
|
|
279
|
+
}
|
|
280
|
+
/** The config in force right now, including anything remote config changed. */
|
|
281
|
+
currentConfig() {
|
|
282
|
+
return this.config;
|
|
283
|
+
}
|
|
284
|
+
onSession(listener) {
|
|
285
|
+
this.sessionListeners.add(listener);
|
|
286
|
+
// A session may already be open — `init()` starts one — and a subscriber
|
|
287
|
+
// that arrives a tick later would otherwise wait for the next rotation.
|
|
288
|
+
const open = this.sessions?.current();
|
|
289
|
+
if (open) {
|
|
290
|
+
try {
|
|
291
|
+
listener(open.sessionId);
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
// As above.
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return () => {
|
|
298
|
+
this.sessionListeners.delete(listener);
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
onError(listener) {
|
|
302
|
+
this.errorListeners.add(listener);
|
|
303
|
+
return () => {
|
|
304
|
+
this.errorListeners.delete(listener);
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
captureNetwork(event) {
|
|
308
|
+
this.capture('network_request', { ...event });
|
|
309
|
+
}
|
|
310
|
+
/** Close a named mark and record its duration. */
|
|
311
|
+
measure(name) {
|
|
312
|
+
const result = measure(name, this.now());
|
|
313
|
+
if (result) {
|
|
314
|
+
this.capture('performance', { ...result });
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
mark(name) {
|
|
318
|
+
mark(name, this.now());
|
|
319
|
+
}
|
|
320
|
+
/** Record time from SDK load to app-ready. */
|
|
321
|
+
markReady() {
|
|
322
|
+
this.capture('performance', { ...timeToReady(this.now()) });
|
|
323
|
+
}
|
|
324
|
+
screen(name) {
|
|
325
|
+
if (!this.isEnabled() || !this.sessions)
|
|
326
|
+
return;
|
|
327
|
+
this.sessions.setScreen(name);
|
|
328
|
+
this.capture('screen_view', { screen: name });
|
|
329
|
+
}
|
|
330
|
+
/** Called by the platform lifecycle glue. */
|
|
331
|
+
onAppStateChange(state) {
|
|
332
|
+
if (!this.isEnabled())
|
|
333
|
+
return;
|
|
334
|
+
if (state === 'background') {
|
|
335
|
+
this.capture('lifecycle', { state: 'background' });
|
|
336
|
+
// Flush on the way out. The OS may never schedule this app again.
|
|
337
|
+
void this.batcher?.flush();
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
// `touch` rotates the session if the app sat in the background longer
|
|
341
|
+
// than the timeout (section 20).
|
|
342
|
+
this.sessions?.touch();
|
|
343
|
+
this.capture('lifecycle', { state: 'active' });
|
|
344
|
+
}
|
|
345
|
+
async flush() {
|
|
346
|
+
await this.batcher?.flush();
|
|
347
|
+
}
|
|
348
|
+
shutdown() {
|
|
349
|
+
clearBreadcrumbs();
|
|
350
|
+
// Best effort. A clean shutdown is the one case where session_end
|
|
351
|
+
// actually arrives — most sessions are closed by the backend sweeper
|
|
352
|
+
// because the app was force-quit or OS-killed (section 20).
|
|
353
|
+
if (this.isEnabled() && this.sessions?.current()) {
|
|
354
|
+
this.capture('session_end');
|
|
355
|
+
void this.batcher?.flush();
|
|
356
|
+
}
|
|
357
|
+
this.batcher?.stop();
|
|
358
|
+
this.sessions?.end();
|
|
359
|
+
this.started = false;
|
|
360
|
+
}
|
|
361
|
+
startSessionIfNeeded() {
|
|
362
|
+
if (!this.isEnabled() || !this.sessions)
|
|
363
|
+
return;
|
|
364
|
+
if (this.sessions.current())
|
|
365
|
+
return;
|
|
366
|
+
// `session_start` is emitted by `announce`, not here. Sessions also begin
|
|
367
|
+
// by rotation, in the middle of a `capture()`, and those used to get no
|
|
368
|
+
// `session_start` at all — leaving the worker with no device context for
|
|
369
|
+
// them (`a_session_without_session_start_has_no_context`).
|
|
370
|
+
this.sessions.touch();
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Announce a session that has just begun.
|
|
374
|
+
*
|
|
375
|
+
* Called from inside `SessionManager.start()`, which is reachable from
|
|
376
|
+
* inside `capture()` — so this re-enters `capture()`. That is safe and is
|
|
377
|
+
* what gives the right ordering: `this.state` is already set, so the nested
|
|
378
|
+
* `touch()` finds a live session rather than rotating again, and
|
|
379
|
+
* `session_start` takes sequence 0 while the event that triggered the
|
|
380
|
+
* rotation takes 1.
|
|
381
|
+
*/
|
|
382
|
+
announce(sessionId) {
|
|
383
|
+
// Device context rides on session_start — it is the only event the worker
|
|
384
|
+
// reads it from, and every field is optional there.
|
|
385
|
+
this.capture('session_start', { ...this.deviceContext() });
|
|
386
|
+
for (const listener of this.sessionListeners) {
|
|
387
|
+
try {
|
|
388
|
+
listener(sessionId);
|
|
389
|
+
}
|
|
390
|
+
catch {
|
|
391
|
+
// A listener must not be able to break session rotation.
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
/** Test accessors. */
|
|
396
|
+
get currentSession() {
|
|
397
|
+
return this.sessions?.current() ?? null;
|
|
398
|
+
}
|
|
399
|
+
get buffered() {
|
|
400
|
+
return this.batcher?.size ?? 0;
|
|
401
|
+
}
|
|
402
|
+
deliver(events) {
|
|
403
|
+
if (!this.options)
|
|
404
|
+
return;
|
|
405
|
+
const batch = {
|
|
406
|
+
schemaVersion: SCHEMA_VERSION,
|
|
407
|
+
projectId: this.options.projectId,
|
|
408
|
+
sdkVersion: SDK_VERSION,
|
|
409
|
+
sentAt: this.now(),
|
|
410
|
+
events,
|
|
411
|
+
};
|
|
412
|
+
return this.onFlush(batch);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Drains the queue.
|
|
3
|
+
*
|
|
4
|
+
* Single-flight on purpose: only one drain runs at a time. Two concurrent
|
|
5
|
+
* drains would read the same oldest batches and deliver them twice — the
|
|
6
|
+
* backend deduplicates, but spending a user's data plan to send events the
|
|
7
|
+
* server will throw away is not something to rely on.
|
|
8
|
+
*/
|
|
9
|
+
import { SendQueue, type QueuedBatch } from './queue.ts';
|
|
10
|
+
import { type SendOutcome, type TransportOptions } from './transport.ts';
|
|
11
|
+
export interface DispatcherOptions {
|
|
12
|
+
queue: SendQueue;
|
|
13
|
+
transport: TransportOptions;
|
|
14
|
+
/** Batches per drain. Keeps one pass bounded on a large backlog. */
|
|
15
|
+
batchesPerDrain?: number;
|
|
16
|
+
now?: () => number;
|
|
17
|
+
onOutcome?: (outcome: SendOutcome, entry: QueuedBatch) => void;
|
|
18
|
+
}
|
|
19
|
+
export declare class Dispatcher {
|
|
20
|
+
private readonly queue;
|
|
21
|
+
private readonly transport;
|
|
22
|
+
private readonly batchesPerDrain;
|
|
23
|
+
private readonly now;
|
|
24
|
+
private readonly onOutcome?;
|
|
25
|
+
private draining;
|
|
26
|
+
/** Wall-clock time before which no send should be attempted. */
|
|
27
|
+
private pausedUntil;
|
|
28
|
+
constructor(options: DispatcherOptions);
|
|
29
|
+
/** True while backpressure is in effect. */
|
|
30
|
+
get paused(): boolean;
|
|
31
|
+
get pausedForMs(): number;
|
|
32
|
+
/**
|
|
33
|
+
* Send what is queued.
|
|
34
|
+
*
|
|
35
|
+
* Returns the number of batches delivered. Stops early on the first batch
|
|
36
|
+
* that needs retrying: the queue is ordered, and a failure almost always
|
|
37
|
+
* means the network or the server is unavailable for the next one too.
|
|
38
|
+
* Continuing would just burn attempts on every queued batch at once.
|
|
39
|
+
*/
|
|
40
|
+
drain(): Promise<number>;
|
|
41
|
+
/** Clear backpressure, e.g. when the app returns to the foreground. */
|
|
42
|
+
resume(): void;
|
|
43
|
+
}
|