@libo11y/rum-replay 0.4.0 → 0.7.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/README.md CHANGED
@@ -1,27 +1,24 @@
1
1
  # @libo11y/rum-replay
2
2
 
3
3
  Privacy-first session replay for
4
- [`@libo11y/rum`](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/rum).
4
+ [`@libo11y/rum`](https://github.com/libo11y/libo11y/tree/main/ts/packages/rum).
5
5
  It records the page with rrweb's recorder
6
6
  ([`@rrweb/record`](https://www.npmjs.com/package/@rrweb/record) 2.2.2,
7
7
  pinned exactly) and passes every event through libo11y's own scrubber
8
8
  before anything is buffered. Text is masked by default, and input values
9
9
  are never recorded.
10
10
 
11
- ## Status
12
-
13
- The package first ships in `ts/v0.4.0`, and it releases with
14
- `@libo11y/rum` at the same version. Neither is on npm yet. Until their
15
- first npm publish, install both from the tarballs attached to the
16
- [`ts/v0.4.0` GitHub Release](https://github.com/jamesainslie/libo11y/releases/tag/ts/v0.4.0),
17
- whose notes list the exact URLs:
18
-
19
11
  ```sh
20
- npm install \
21
- https://github.com/jamesainslie/libo11y/releases/download/ts/v0.4.0/libo11y-rum-0.4.0.tgz \
22
- https://github.com/jamesainslie/libo11y/releases/download/ts/v0.4.0/libo11y-rum-replay-0.4.0.tgz
12
+ npm install @libo11y/rum @libo11y/rum-replay
23
13
  ```
24
14
 
15
+ ## Status
16
+
17
+ The package first ships in `ts/v0.4.0`, releases with `@libo11y/rum` at
18
+ the same version, and is published on npm at `0.7.0` (also attached as a
19
+ tarball to the
20
+ [`ts/v0.7.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.7.0)).
21
+
25
22
  The RUM gateway stores what it uploads from `go/o11yrum/v0.2.0` on, once
26
23
  an app enables replay; see
27
24
  [Session replay](../../../go/o11yrum/README.md#session-replay) in the
@@ -83,9 +80,11 @@ option.
83
80
  `POST <url>?service=&session=&segment=&sent_at=&client_token=`, without
84
81
  credentials and uninstrumented, one at a time and in order. Segment
85
82
  numbers count per session across tabs, under a Web Lock. `429` and `503`
86
- retry after `Retry-After`, at most three attempts, and any other `4xx`
87
- drops the segment. At most 4 segments and 4 MiB wait to upload; the
88
- oldest goes first past either bound.
83
+ retry after `Retry-After` and a network error retries after 5 seconds,
84
+ for at most three attempts. Each attempt is aborted after 10 seconds and
85
+ counts as a network error. Any other non-2xx status drops the segment.
86
+ At most 4 segments and 4 MiB wait to upload; the oldest goes first past
87
+ either bound.
89
88
  - **Errors point at the replay.** While a session uploads, its
90
89
  `o11y.rum.error` and `o11y.rum.frustration` events carry
91
90
  `o11y.rum.replay.segment`, the number of the segment being sent or last
@@ -94,8 +93,9 @@ option.
94
93
  yet sent and removes the shared segment counter.
95
94
  - **Where it runs.** Replay records pages and extension pages. It refuses
96
95
  to start, with one warning, in an extension content script, which must
97
- not record the host page, and in a browser without Web Locks or
98
- `CompressionStream`.
96
+ not record the host page, in a browser without Web Locks,
97
+ `CompressionStream` or `localStorage`, and when the telemetry has no
98
+ `service.name`.
99
99
 
100
100
  ## Privacy model
101
101
 
package/dist/clamp.js CHANGED
@@ -1,6 +1,5 @@
1
1
  /**
2
- * Remote configuration of replay (design decision P3). The gateway's configuration document (R3d's
3
- * GET /_o11y/v1/config) may carry an optional replay object:
2
+ * Remote configuration of replay. The gateway's configuration document (GET /_o11y/v1/config) may carry an optional replay object:
4
3
  * { enabled?: false, sampleRate?: number, onRetain?: false, mask?: string[], block?: string[], unmask?: string[] }.
5
4
  *
6
5
  * Remote configuration can only make replay stricter:
@@ -13,7 +12,7 @@
13
12
  * - A selector that is not a string, is empty or fails validSelector is dropped, and so is every
14
13
  * unknown field.
15
14
  *
16
- * The clamped settings are pinned for the session by the collector, like the rest of R3d's
15
+ * The clamped settings are pinned for the session by the collector, like the rest of
17
16
  * document.
18
17
  */
19
18
  import { O11yError } from "@libo11y/core";
package/dist/collector.js CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
- * replay(): the session replay collector for @libo11y/rum (design decisions P4 to P9). Installing it
2
+ * replay(): the session replay collector for @libo11y/rum. Installing it
3
3
  * is the opt-in. RUM starts it only while consent is granted, and stops it on revoke, shutdown and
4
4
  * the remote kill switch.
5
5
  *
6
6
  * - It refuses to start, logging once, in an extension content script (it must not record the host
7
- * page), without Web Locks or CompressionStream, and without a service name.
7
+ * page), without Web Locks, CompressionStream or localStorage, and without a service name.
8
8
  * - Each session is configured once, when it starts: the code settings clamped by the replay object
9
9
  * of the remote document the session started under, which can only make replay stricter. A
10
10
  * session records when replay is on and fnv1a32("replay:" + session.id) / 2^32 is below the
@@ -21,7 +21,9 @@
21
21
  * - o11y.rum.error and o11y.rum.frustration events carry o11y.rum.replay.segment, the number of the
22
22
  * session's segment being sent or last sent, once one has been numbered.
23
23
  * - The stop drops everything not sent. On a revoke it also removes the shared segment counter; a
24
- * stop while consent holds (shutdown, kill switch) leaves it for the session's other tabs.
24
+ * stop while consent holds (shutdown, kill switch) leaves it for the session's other tabs. RUM's
25
+ * erasure (a denied start, a revoke) removes the counter through clear, even if replay never
26
+ * started in this page.
25
27
  */
26
28
  import { O11yError } from "@libo11y/core";
27
29
  import { fnv1a32, randomUuid } from "@libo11y/rum/internal";
@@ -126,6 +128,13 @@ export function replayWith(deps, options = {}) {
126
128
  let loadFailed = false;
127
129
  return {
128
130
  name: "replay",
131
+ // RUM erases its storage on a denied start and a revoke even when replay never started here.
132
+ // A content script's storage is the host page's, which replay never wrote, so it is left alone.
133
+ clear() {
134
+ const d = typeof deps === "function" ? deps() : deps;
135
+ if (!d.contentScript && d.storage !== undefined)
136
+ clearSequence(d.storage);
137
+ },
129
138
  start(rt) {
130
139
  const d = typeof deps === "function" ? deps() : deps;
131
140
  const service = rt.telemetry.resource?.attributes["service.name"];
@@ -157,7 +166,9 @@ export function replayWith(deps, options = {}) {
157
166
  service,
158
167
  ...(rt.settings().clientToken === undefined ? {} : { clientToken: rt.settings().clientToken }),
159
168
  fetch: d.fetch ?? globalThis.fetch,
160
- allocate: (id) => allocateSegment(id, storage, locks, () => rt.gate.recording()),
169
+ // proceed runs inside the lock: an uploader cleared since (a revoke, even one a grant
170
+ // followed) or a session no longer kept writes no counter.
171
+ allocate: (id, proceed) => allocateSegment(id, storage, locks, proceed),
161
172
  now: d.now,
162
173
  allowed: (id) => rt.gate.recording() && rt.session.decide(id) === "send",
163
174
  timers: d.timers,
@@ -186,7 +197,10 @@ export function replayWith(deps, options = {}) {
186
197
  stopRecording(false);
187
198
  if (loadFailed || session === undefined || !rt.gate.recording())
188
199
  return;
189
- const s = clampReplay(code, resolved.limits, parseReplayRemote(rt.remoteDocument()?.replay, d.validSelector));
200
+ const remoteDoc = rt.remoteDocument();
201
+ if (session.configVersion !== undefined && remoteDoc?.version !== session.configVersion)
202
+ return;
203
+ const s = clampReplay(code, resolved.limits, parseReplayRemote(remoteDoc?.replay, d.validSelector));
190
204
  if (!s.enabled || fnv1a32(`replay:${session.id}`) / 2 ** 32 >= s.sampleRate)
191
205
  return;
192
206
  if (!session.sampled && !s.onRetain)
@@ -281,6 +295,12 @@ export function replayWith(deps, options = {}) {
281
295
  if (e.type !== "end")
282
296
  recording?.segmenter.view(viewOf(rt, rt.views.current() ?? e.view));
283
297
  }),
298
+ // The document a resumed session started under may arrive after it, and replay then starts
299
+ // under it. A recording already running keeps the settings it started with.
300
+ rt.bus.subscribe((s) => {
301
+ if (s.type === "config" && recording === undefined)
302
+ begin(rt.session.current());
303
+ }),
284
304
  rt.onRequestStart((span) => {
285
305
  const sc = span.spanContext();
286
306
  recording?.segmenter.request({ trace_id: sc.traceId, span_id: sc.spanId, at: d.now() });
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The DOM-backed ScrubContext: what the scrubber needs to know about a node it cannot see in the
3
- * event itself, read from the live page through rrweb's mirror (R6b wires getNode to
3
+ * event itself, read from the live page through rrweb's mirror (getNode is wired to
4
4
  * record.mirror.getNode). The collector must scrub synchronously inside rrweb's emit callback,
5
5
  * while the DOM still matches the event: a node read later may have moved or been detached.
6
6
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The segment envelope: what one upload carries (design decisions P5 and P7). A segment is
2
+ * The segment envelope: what one upload carries. A segment is
3
3
  * self-contained, starting with a Meta event and a full snapshot, so a player can start at any
4
4
  * segment and a lost upload loses only its own time. The gateway (POST /_o11y/v1/replay) accepts
5
5
  * these fields and no others.
@@ -23,9 +23,9 @@ export interface SegmentEnvelope {
23
23
  readonly format: 1;
24
24
  /** One per tab and session: the segments of one recording continue one DOM. */
25
25
  readonly recording: string;
26
- /** Epoch milliseconds of the first event. */
26
+ /** Earliest event timestamp, in epoch milliseconds. */
27
27
  readonly start: number;
28
- /** Epoch milliseconds of the last event. */
28
+ /** Latest event timestamp, in epoch milliseconds. */
29
29
  readonly end: number;
30
30
  readonly views: readonly SegmentView[];
31
31
  readonly requests: readonly SegmentRequest[];
package/dist/policy.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The privacy policy of a recording (design decision P2). Code options are the ceiling: remote
2
+ * The privacy policy of a recording. Code options are the ceiling: remote
3
3
  * configuration can only add to the mask and block lists and remove from the unmask list
4
4
  * (clamp.ts). The fixed rules here apply whatever the options say.
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The only module that names rrweb (design decision P1), and it loads it lazily: replay() bundles
2
+ * The only module that names rrweb, and it loads it lazily: replay() bundles
3
3
  * no recorder. loadRecorder imports @rrweb/record the first time a session will actually record,
4
4
  * so a page that never records never downloads it. Until it has loaded nothing is recorded. A failed
5
5
  * import is kept, so replay stays off for the page rather than retrying.
package/dist/scrub.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The event scrubber: libo11y's own, authoritative pass over every rrweb event before it is
3
- * buffered (design decision P2). rrweb's options are a first line only; nothing here trusts them.
3
+ * buffered. rrweb's options are a first line only; nothing here trusts them.
4
4
  * Everything is an allow-list, so a field, attribute, event type or source rrweb adds later is
5
5
  * dropped rather than leaked. The gateway runs the same rules in Go from the shared vectors in
6
6
  * conformance/rum-replay.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Cuts the scrubbed event stream into self-contained segments (design decision P5).
2
+ * Cuts the scrubbed event stream into self-contained segments.
3
3
  *
4
4
  * - A segment opens with a Meta event (type 4), which rrweb emits before every full snapshot. A
5
5
  * Meta event while a segment is open closes it and opens the next, so every segment starts with
package/dist/segmenter.js CHANGED
@@ -21,13 +21,22 @@ export function createSegmenter(o) {
21
21
  if (!s.incremental && !isFirst)
22
22
  return;
23
23
  const events = s.events;
24
+ const firstEvent = events[0];
25
+ let start = firstEvent?.timestamp ?? 0;
26
+ let end = start;
27
+ for (const e of events) {
28
+ if (e.timestamp < start)
29
+ start = e.timestamp;
30
+ if (e.timestamp > end)
31
+ end = e.timestamp;
32
+ }
24
33
  o.onClose({
25
34
  first: isFirst,
26
35
  envelope: {
27
36
  format: 1,
28
37
  recording: o.recording,
29
- start: events[0]?.timestamp ?? 0,
30
- end: events[events.length - 1]?.timestamp ?? 0,
38
+ start,
39
+ end,
31
40
  views: s.views,
32
41
  requests: s.requests,
33
42
  events,
@@ -1,15 +1,18 @@
1
1
  /**
2
- * Segment numbers shared by every tab of a session (design decision P6). o11y.rum.replay.segment is
3
- * the index of a segment in its session, and tabs share a session, so the next index lives in
4
- * localStorage under SEQUENCE_KEY as { "session": "<id>", "next": <n> } and is read and written
5
- * inside a Web Lock (navigator.locks) of the same name, so two tabs never take the same index. A
6
- * counter of another session, or one that does not parse, starts again at 0.
2
+ * Segment numbers shared by every tab of a session. o11y.rum.replay.segment is
3
+ * the index of a segment in its session, and tabs share a session, so the next index per session
4
+ * lives in localStorage under SEQUENCE_KEY as { "sessions": [["<id>", <n>], ...] } (bounded to
5
+ * MAX_TRACKED_SESSIONS most recent sessions, while still reading the legacy
6
+ * { "session": "<id>", "next": <n> } shape) and is read and written inside a Web Lock
7
+ * (navigator.locks) of the same name, so two tabs never take the same index. A session not tracked
8
+ * yet, or an unreadable payload, starts at 0.
7
9
  *
8
10
  * Where storage throws (blocked site data), the counter falls back to this tab's memory, so the tab
9
11
  * still numbers its own segments without reusing one.
10
12
  */
11
13
  export declare const SEQUENCE_KEY = "libo11y.rum.replay.seq";
12
14
  export declare const SEQUENCE_LOCK = "libo11y.rum.replay.seq";
15
+ export declare const MAX_TRACKED_SESSIONS = 16;
13
16
  /** The part of navigator.locks the counter uses. */
14
17
  export interface LockManagerLike {
15
18
  request<T>(name: string, cb: () => Promise<T> | T): Promise<T>;
package/dist/sequence.js CHANGED
@@ -1,33 +1,72 @@
1
1
  /**
2
- * Segment numbers shared by every tab of a session (design decision P6). o11y.rum.replay.segment is
3
- * the index of a segment in its session, and tabs share a session, so the next index lives in
4
- * localStorage under SEQUENCE_KEY as { "session": "<id>", "next": <n> } and is read and written
5
- * inside a Web Lock (navigator.locks) of the same name, so two tabs never take the same index. A
6
- * counter of another session, or one that does not parse, starts again at 0.
2
+ * Segment numbers shared by every tab of a session. o11y.rum.replay.segment is
3
+ * the index of a segment in its session, and tabs share a session, so the next index per session
4
+ * lives in localStorage under SEQUENCE_KEY as { "sessions": [["<id>", <n>], ...] } (bounded to
5
+ * MAX_TRACKED_SESSIONS most recent sessions, while still reading the legacy
6
+ * { "session": "<id>", "next": <n> } shape) and is read and written inside a Web Lock
7
+ * (navigator.locks) of the same name, so two tabs never take the same index. A session not tracked
8
+ * yet, or an unreadable payload, starts at 0.
7
9
  *
8
10
  * Where storage throws (blocked site data), the counter falls back to this tab's memory, so the tab
9
11
  * still numbers its own segments without reusing one.
10
12
  */
11
13
  export const SEQUENCE_KEY = "libo11y.rum.replay.seq";
12
14
  export const SEQUENCE_LOCK = "libo11y.rum.replay.seq";
13
- /** The counter of a storage that throws, kept per storage object. */
15
+ export const MAX_TRACKED_SESSIONS = 16;
16
+ /** Per-storage high-water counters per session, so mid-session storage failures and recoveries never reuse an index. */
14
17
  const memory = new WeakMap();
15
- function read(raw, sessionId) {
18
+ function validNext(n) {
19
+ return typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
20
+ }
21
+ function prune(map) {
22
+ while (map.size > MAX_TRACKED_SESSIONS) {
23
+ const oldest = map.keys().next().value;
24
+ if (oldest === undefined)
25
+ break;
26
+ map.delete(oldest);
27
+ }
28
+ }
29
+ function setBounded(map, sessionId, next) {
30
+ map.delete(sessionId);
31
+ map.set(sessionId, next);
32
+ prune(map);
33
+ }
34
+ function memoryMap(storage) {
35
+ let map = memory.get(storage);
36
+ if (map === undefined) {
37
+ map = new Map();
38
+ memory.set(storage, map);
39
+ }
40
+ return map;
41
+ }
42
+ function readAll(raw) {
43
+ const map = new Map();
16
44
  try {
17
45
  const v = JSON.parse(raw ?? "null");
18
- if (typeof v === "object" &&
19
- v !== null &&
20
- v.session === sessionId &&
21
- typeof v.next === "number" &&
22
- Number.isInteger(v.next) &&
23
- v.next >= 0) {
24
- return v.next;
46
+ if (typeof v !== "object" || v === null || Array.isArray(v))
47
+ return map;
48
+ if (Array.isArray(v.sessions)) {
49
+ for (const entry of v.sessions) {
50
+ if (Array.isArray(entry) &&
51
+ entry.length >= 2 &&
52
+ typeof entry[0] === "string" &&
53
+ entry[0] !== "" &&
54
+ validNext(entry[1])) {
55
+ const prev = map.get(entry[0]) ?? 0;
56
+ map.delete(entry[0]);
57
+ map.set(entry[0], Math.max(prev, entry[1]));
58
+ }
59
+ }
60
+ }
61
+ else if (typeof v.session === "string" && v.session !== "" && validNext(v.next)) {
62
+ map.set(v.session, v.next);
25
63
  }
26
64
  }
27
65
  catch {
28
66
  // unreadable: start again
29
67
  }
30
- return 0;
68
+ prune(map);
69
+ return map;
31
70
  }
32
71
  /**
33
72
  * Takes the next segment index of sessionId under the lock. proceed is checked once the lock is
@@ -39,16 +78,27 @@ export function allocateSegment(sessionId, storage, locks, proceed = () => true)
39
78
  return locks.request(SEQUENCE_LOCK, () => {
40
79
  if (!proceed())
41
80
  throw new Error("rum-replay: segment numbering is no longer allowed");
42
- const counter = { session: sessionId, next: 0 };
81
+ const kept = memoryMap(storage);
82
+ const floor = kept.get(sessionId) ?? 0;
83
+ let storedIfRead = 0;
43
84
  let next;
44
85
  try {
45
- next = read(storage.getItem(SEQUENCE_KEY), sessionId);
46
- storage.setItem(SEQUENCE_KEY, JSON.stringify({ ...counter, next: next + 1 }));
86
+ const map = readAll(storage.getItem(SEQUENCE_KEY));
87
+ for (const [id, val] of map) {
88
+ const k = kept.get(id);
89
+ if (k !== undefined && k > val)
90
+ map.set(id, k);
91
+ }
92
+ const stored = map.get(sessionId) ?? 0;
93
+ storedIfRead = stored;
94
+ next = Math.max(stored, floor);
95
+ setBounded(map, sessionId, next + 1);
96
+ storage.setItem(SEQUENCE_KEY, JSON.stringify({ sessions: [...map] }));
97
+ setBounded(kept, sessionId, next + 1);
47
98
  }
48
99
  catch {
49
- const kept = memory.get(storage);
50
- next = kept?.session === sessionId ? kept.next : 0;
51
- memory.set(storage, { ...counter, next: next + 1 });
100
+ next = Math.max(storedIfRead, floor);
101
+ setBounded(kept, sessionId, next + 1);
52
102
  }
53
103
  return next;
54
104
  });
package/dist/upload.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Compression and upload of closed segments (design decision P8). Each segment is gzipped with
2
+ * Compression and upload of closed segments. Each segment is gzipped with
3
3
  * CompressionStream and posted to the gateway's POST /_o11y/v1/replay as
4
4
  * ?service=&session=&segment=&sent_at=&client_token= (the client token only when the app has one,
5
5
  * sent_at taken per attempt so the gateway can correct clock skew), with credentials omitted and
@@ -12,8 +12,11 @@
12
12
  * - 2xx is done. 429 and 503 retry after Retry-After (seconds or an HTTP date; default 5 s, at
13
13
  * most 60 s), and a network error after 5 s, for at most MAX_ATTEMPTS attempts. Anything else
14
14
  * drops the segment.
15
- * - The queue, the segment in flight included, holds at most maxQueue segments and maxQueueBytes
16
- * of compressed bodies; past either bound the oldest segment not in flight is dropped.
15
+ * - The queue holds at most maxQueue segments in all: those waiting for compression, the one
16
+ * compressing, the compressed ones and the one in flight. Past it the oldest segment not in flight
17
+ * is dropped, and a new segment is dropped when every place is taken by one compressing or in
18
+ * flight. The compressed bodies, the one in flight included, take at most maxQueueBytes; past it
19
+ * the oldest compressed segment not in flight is dropped.
17
20
  */
18
21
  /** The keepalive quota is 64 KiB for every keepalive request of a page; this leaves room for the rest. */
19
22
  export declare const KEEPALIVE_MAX_BYTES = 61440;
@@ -34,7 +37,12 @@ export interface UploaderOptions {
34
37
  readonly service: string;
35
38
  readonly clientToken?: string;
36
39
  readonly fetch: typeof fetch;
37
- readonly allocate: (sessionId: string) => Promise<number>;
40
+ /**
41
+ * Takes the next segment number of sessionId. proceed is checked once the number may be taken,
42
+ * which can be long after the call: false (a clear, a revoke, a session no longer kept) means no
43
+ * number is taken, and the promise rejects.
44
+ */
45
+ readonly allocate: (sessionId: string, proceed: () => boolean) => Promise<number>;
38
46
  /** Epoch milliseconds, for sent_at. */
39
47
  readonly now: () => number;
40
48
  /** Whether a segment of sessionId may go out now: consent granted and the session kept. */
@@ -45,5 +53,7 @@ export interface UploaderOptions {
45
53
  };
46
54
  readonly maxQueue: number;
47
55
  readonly maxQueueBytes: number;
56
+ /** Per-attempt request timeout in milliseconds. Default 10000. */
57
+ readonly timeoutMillis?: number;
48
58
  }
49
59
  export declare function createUploader(o: UploaderOptions): Uploader;
package/dist/upload.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Compression and upload of closed segments (design decision P8). Each segment is gzipped with
2
+ * Compression and upload of closed segments. Each segment is gzipped with
3
3
  * CompressionStream and posted to the gateway's POST /_o11y/v1/replay as
4
4
  * ?service=&session=&segment=&sent_at=&client_token= (the client token only when the app has one,
5
5
  * sent_at taken per attempt so the gateway can correct clock skew), with credentials omitted and
@@ -12,8 +12,11 @@
12
12
  * - 2xx is done. 429 and 503 retry after Retry-After (seconds or an HTTP date; default 5 s, at
13
13
  * most 60 s), and a network error after 5 s, for at most MAX_ATTEMPTS attempts. Anything else
14
14
  * drops the segment.
15
- * - The queue, the segment in flight included, holds at most maxQueue segments and maxQueueBytes
16
- * of compressed bodies; past either bound the oldest segment not in flight is dropped.
15
+ * - The queue holds at most maxQueue segments in all: those waiting for compression, the one
16
+ * compressing, the compressed ones and the one in flight. Past it the oldest segment not in flight
17
+ * is dropped, and a new segment is dropped when every place is taken by one compressing or in
18
+ * flight. The compressed bodies, the one in flight included, take at most maxQueueBytes; past it
19
+ * the oldest compressed segment not in flight is dropped.
17
20
  */
18
21
  /** The keepalive quota is 64 KiB for every keepalive request of a page; this leaves room for the rest. */
19
22
  export const KEEPALIVE_MAX_BYTES = 61440;
@@ -21,6 +24,7 @@ export const KEEPALIVE_MAX_BYTES = 61440;
21
24
  export const MAX_ATTEMPTS = 3;
22
25
  const DEFAULT_RETRY_MILLIS = 5000;
23
26
  const MAX_RETRY_MILLIS = 60_000;
27
+ const DEFAULT_TIMEOUT_MILLIS = 10_000;
24
28
  /** value as JSON, gzip-compressed with CompressionStream. */
25
29
  export async function gzipJson(value) {
26
30
  const stream = new Blob([JSON.stringify(value)]).stream().pipeThrough(new CompressionStream("gzip"));
@@ -44,17 +48,28 @@ function retryAfter(header, now) {
44
48
  export function createUploader(o) {
45
49
  let pending = [];
46
50
  let active;
51
+ let activeAbort;
52
+ let activeTimer;
47
53
  let retryTimer;
54
+ const timeoutMillis = o.timeoutMillis ?? DEFAULT_TIMEOUT_MILLIS;
48
55
  /** Bumped by clear, so work that started before it does nothing after. */
49
56
  let generation = 0;
50
- /** Compression keeps queue order: each segment is queued after the one before it. */
51
- let compressing = Promise.resolve();
57
+ /** Bounded pre-compression FIFO queue, drained one segment at a time to preserve order. */
58
+ let uncompressed = [];
59
+ let compressing = false;
60
+ /** The generation of the envelope being compressed now; one from before a clear counts for nothing. */
61
+ let squeezing;
52
62
  let last;
53
- /** Drops the oldest segments not in flight past either bound, never the newest. */
63
+ /** Every segment held: waiting, compressing, compressed and in flight. */
64
+ const held = () => uncompressed.length +
65
+ (squeezing === generation ? 1 : 0) +
66
+ pending.length +
67
+ (active === undefined ? 0 : 1);
68
+ /** Drops the oldest compressed segments not in flight past either bound. */
54
69
  const bound = () => {
55
70
  const total = () => pending.length + (active === undefined ? 0 : 1);
56
- const bytes = () => pending.reduce((n, i) => n + i.body.byteLength, 0);
57
- while (pending.length > 1 && (total() > o.maxQueue || bytes() > o.maxQueueBytes))
71
+ const bytes = () => pending.reduce((n, i) => n + i.body.byteLength, active?.body.byteLength ?? 0);
72
+ while (pending.length > 0 && (total() > o.maxQueue || bytes() > o.maxQueueBytes))
58
73
  pending.shift();
59
74
  };
60
75
  const finish = (gen) => {
@@ -66,6 +81,11 @@ export function createUploader(o) {
66
81
  const attempt = async (item, gen) => {
67
82
  if (gen !== generation)
68
83
  return;
84
+ // Checked on every attempt: a session that left the eligible set during a retry wait sends no more.
85
+ if (!o.allowed(item.sessionId)) {
86
+ finish(gen);
87
+ return;
88
+ }
69
89
  item.attempts++;
70
90
  const params = new URLSearchParams({
71
91
  service: o.service,
@@ -76,6 +96,10 @@ export function createUploader(o) {
76
96
  if (o.clientToken !== undefined)
77
97
  params.set("client_token", o.clientToken);
78
98
  const url = `${o.url}${o.url.includes("?") ? "&" : "?"}${params.toString()}`;
99
+ const controller = new AbortController();
100
+ activeAbort = controller;
101
+ const timeoutTimer = o.timers.setTimeout(() => controller.abort(), timeoutMillis);
102
+ activeTimer = timeoutTimer;
79
103
  let wait;
80
104
  try {
81
105
  const res = await o.fetch(url, {
@@ -86,6 +110,7 @@ export function createUploader(o) {
86
110
  cache: "no-store",
87
111
  referrerPolicy: "no-referrer",
88
112
  keepalive: item.body.byteLength <= KEEPALIVE_MAX_BYTES,
113
+ signal: controller.signal,
89
114
  });
90
115
  if (res.status === 429 || res.status === 503)
91
116
  wait = retryAfter(res.headers.get("Retry-After"), o.now());
@@ -93,6 +118,13 @@ export function createUploader(o) {
93
118
  catch {
94
119
  wait = DEFAULT_RETRY_MILLIS;
95
120
  }
121
+ finally {
122
+ o.timers.clearTimeout(timeoutTimer);
123
+ if (activeTimer === timeoutTimer)
124
+ activeTimer = undefined;
125
+ if (activeAbort === controller)
126
+ activeAbort = undefined;
127
+ }
96
128
  if (gen !== generation)
97
129
  return;
98
130
  if (wait === undefined || item.attempts >= MAX_ATTEMPTS) {
@@ -116,7 +148,7 @@ export function createUploader(o) {
116
148
  }
117
149
  active = item;
118
150
  const gen = generation;
119
- o.allocate(item.sessionId).then((segment) => {
151
+ o.allocate(item.sessionId, () => gen === generation && o.allowed(item.sessionId)).then((segment) => {
120
152
  if (gen !== generation)
121
153
  return;
122
154
  item.segment = segment;
@@ -124,24 +156,64 @@ export function createUploader(o) {
124
156
  void attempt(item, gen);
125
157
  }, () => finish(gen));
126
158
  };
159
+ const drainCompression = async () => {
160
+ if (compressing)
161
+ return;
162
+ compressing = true;
163
+ try {
164
+ while (uncompressed.length > 0) {
165
+ const next = uncompressed.shift();
166
+ if (next === undefined || next.gen !== generation)
167
+ continue;
168
+ let body;
169
+ squeezing = next.gen;
170
+ try {
171
+ body = await gzipJson(next.envelope);
172
+ }
173
+ catch {
174
+ continue;
175
+ }
176
+ finally {
177
+ squeezing = undefined;
178
+ }
179
+ if (next.gen !== generation)
180
+ continue;
181
+ pending.push({ sessionId: next.sessionId, body, attempts: 0 });
182
+ bound();
183
+ pump();
184
+ }
185
+ }
186
+ finally {
187
+ compressing = false;
188
+ }
189
+ };
127
190
  return {
128
191
  enqueue(sessionId, envelope) {
129
- const gen = generation;
130
- compressing = compressing
131
- .then(() => gzipJson(envelope))
132
- .then((body) => {
133
- if (gen !== generation)
192
+ if (o.maxQueue <= 0 || o.maxQueueBytes <= 0)
193
+ return;
194
+ while (held() >= o.maxQueue) {
195
+ if (pending.length > 0)
196
+ pending.shift();
197
+ else if (uncompressed.length > 0)
198
+ uncompressed.shift();
199
+ // Every place is taken by a segment compressing or in flight.
200
+ else
134
201
  return;
135
- pending.push({ sessionId, body, attempts: 0 });
136
- bound();
137
- pump();
138
- }, () => { });
202
+ }
203
+ uncompressed.push({ sessionId, envelope, gen: generation });
204
+ void drainCompression();
139
205
  },
140
206
  clear() {
141
207
  generation++;
208
+ uncompressed = [];
142
209
  pending = [];
143
210
  active = undefined;
144
211
  last = undefined;
212
+ if (activeTimer !== undefined)
213
+ o.timers.clearTimeout(activeTimer);
214
+ activeTimer = undefined;
215
+ activeAbort?.abort();
216
+ activeAbort = undefined;
145
217
  if (retryTimer !== undefined)
146
218
  o.timers.clearTimeout(retryTimer);
147
219
  retryTimer = undefined;
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The `@libo11y/rum-replay` package version. scripts/release.ts keeps it equal to package.json. */
2
- export declare const VERSION = "0.4.0";
2
+ export declare const VERSION = "0.7.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The `@libo11y/rum-replay` package version. scripts/release.ts keeps it equal to package.json. */
2
- export const VERSION = "0.4.0";
2
+ export const VERSION = "0.7.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libo11y/rum-replay",
3
- "version": "0.4.0",
3
+ "version": "0.7.0",
4
4
  "description": "Privacy-first session replay for @libo11y/rum: text masked by default, inputs never recorded, every event scrubbed against an attribute allow-list before it is buffered.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -13,21 +13,21 @@
13
13
  },
14
14
  "repository": {
15
15
  "type": "git",
16
- "url": "git+https://github.com/jamesainslie/libo11y.git",
16
+ "url": "git+https://github.com/libo11y/libo11y.git",
17
17
  "directory": "ts/packages/rum-replay"
18
18
  },
19
19
  "dependencies": {
20
- "@libo11y/core": "0.4.0",
21
- "@libo11y/spec": "0.4.0",
22
- "@libo11y/web": "0.4.0",
20
+ "@libo11y/core": "0.7.0",
21
+ "@libo11y/spec": "0.7.0",
22
+ "@libo11y/web": "0.7.0",
23
23
  "@rrweb/record": "2.2.2",
24
24
  "@rrweb/types": "2.2.2"
25
25
  },
26
26
  "peerDependencies": {
27
- "@libo11y/rum": "0.4.0"
27
+ "@libo11y/rum": "0.7.0"
28
28
  },
29
29
  "devDependencies": {
30
- "@libo11y/rum": "0.4.0",
30
+ "@libo11y/rum": "0.7.0",
31
31
  "@rrweb/replay": "2.2.2"
32
32
  },
33
33
  "files": [