@vitrinka/web 0.3.3 → 0.3.4

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.
@@ -4,9 +4,9 @@
4
4
  *
5
5
  * - A synchronous KV store (./storage — localStorage by default, memory when
6
6
  * that is unavailable) holds the session record and the event buffer:
7
- * reads/writes complete in one JS tick, so no async mutex is needed. Only
8
- * flush() needs single-flight guarding (its POST is async) and it removes
9
- * exactly the sent seqs on return.
7
+ * seq allocation is serialized across tabs by the driver's lock, reading
8
+ * the shared watermark inside it. flush() is single-flight within each
9
+ * document and removes exactly the sent seqs on return.
10
10
  * - rrweb batches ride as CHUNKS the way the extension sends them: each batch
11
11
  * is serialized once, split under the server's chunk cap, uploaded to
12
12
  * `/chunk?seq=N` under a pre-allocated seq, and only then does its `rrweb`
@@ -97,6 +97,8 @@ export declare function setState(rec: SessionState | null): void;
97
97
  */
98
98
  export declare function markStopping(sessionId: string | null, activeMs?: number, renewMs?: number): void;
99
99
  export type StoredChange = 'joined' | 'updated' | 'ended' | 'unchanged';
100
+ export declare function onBeforeStop(fn: () => void): () => void;
101
+ export declare function runBeforeStopHooks(): void;
100
102
  /**
101
103
  * Another document of this origin (a second tab) wrote the session record.
102
104
  * The store is shared, this cache is not — a tab that joined a recording on
@@ -141,11 +143,10 @@ export declare function markSessionDead(reason: string): void;
141
143
  export declare function reconcile(): Promise<void>;
142
144
  export declare function armReconcile(): void;
143
145
  export declare function disarmReconcile(): void;
144
- /** Allocate `count` consecutive seqs without emitting events; null when not capturing. */
145
- export declare function allocSeq(count?: number): {
146
- seq: number;
147
- sessionId: string;
148
- } | null;
146
+ /** Document identity is not sessionStorage: duplicated tabs copy that store. */
147
+ export declare const RECORDER_DOCUMENT_KEY: string;
148
+ /** A departing document can be acknowledged by a helper only with a full journal. */
149
+ export declare function tailIsDurable(): boolean;
149
150
  export declare function trackCapture(p: Promise<void>): Promise<void>;
150
151
  export declare const CAPTURES_SETTLE_MS = 5000;
151
152
  /** Wait for in-flight captures, bounded; false when stragglers were abandoned. */
@@ -134,6 +134,21 @@ function renewStopping(sessionId) {
134
134
  if (live?.sessionId === sessionId)
135
135
  setState(live);
136
136
  }
137
+ const beforeStopHooks = new Set();
138
+ export function onBeforeStop(fn) {
139
+ beforeStopHooks.add(fn);
140
+ return () => beforeStopHooks.delete(fn);
141
+ }
142
+ export function runBeforeStopHooks() {
143
+ for (const fn of beforeStopHooks) {
144
+ try {
145
+ fn();
146
+ }
147
+ catch (error) {
148
+ console.warn('vitrinka: before-stop hook failed', error);
149
+ }
150
+ }
151
+ }
137
152
  /**
138
153
  * Another document of this origin (a second tab) wrote the session record.
139
154
  * The store is shared, this cache is not — a tab that joined a recording on
@@ -155,6 +170,10 @@ export function adoptStoredState(raw) {
155
170
  }
156
171
  }
157
172
  const cur = getState();
173
+ // Allocations also read storage before its notification arrives. Ship the
174
+ // already-captured DOM tail while the local cache still accepts it.
175
+ if (next?.stopping && next.sessionId === cur?.sessionId && !cur.paused && stoppingHere?.sessionId !== next.sessionId)
176
+ runBeforeStopHooks();
158
177
  if (!next) {
159
178
  if (!cur)
160
179
  return 'unchanged';
@@ -204,6 +223,10 @@ function getBuffer() {
204
223
  }
205
224
  /** Write the in-memory buffer (and the pending chunks) to storage NOW. */
206
225
  export function persistNow() {
226
+ for (const item of pendingAllocations) {
227
+ if (!item.persisted)
228
+ item.persisted = safeSet(item.key, JSON.stringify({ draft: item.draft, seq: item.seq }));
229
+ }
207
230
  persistBuffer();
208
231
  persistChunks();
209
232
  }
@@ -262,7 +285,9 @@ function setChunks(chunks) {
262
285
  persistChunks();
263
286
  }
264
287
  export function queuedCount() {
265
- return getBuffer().length + getChunks().length;
288
+ recoverAllocations();
289
+ pruneAcknowledgedCaptures();
290
+ return getBuffer().length + getChunks().length + pendingAllocations.size;
266
291
  }
267
292
  // -- health + server reconciliation (extension D4/D5/D9) ---------------------
268
293
  let lastSyncAt = 0;
@@ -375,16 +400,203 @@ export function disarmReconcile() {
375
400
  clearInterval(reconcileTimer);
376
401
  reconcileTimer = null;
377
402
  }
378
- /** Allocate `count` consecutive seqs without emitting events; null when not capturing. */
379
- export function allocSeq(count = 1) {
403
+ /** Allocate inside the storage driver's lock; lifecycle writes cannot rewind its watermark. */
404
+ function allocSeq(count) {
380
405
  const rec = getState();
381
- if (!rec || rec.paused || rec.dead || count < 1)
406
+ if (!rec || rec.dead || count < 1)
382
407
  return null;
383
- const first = rec.seq + 1;
384
- rec.seq += count;
408
+ const watermark = readJson('seq', null);
409
+ const first = Math.max(rec.seq, watermark?.sessionId === rec.sessionId ? watermark.seq : 0) + 1;
410
+ // This write must succeed before a seq can be used in another document.
411
+ // On failure the capture stays pending and retries rather than colliding.
412
+ kv().set('seq', JSON.stringify({ sessionId: rec.sessionId, seq: first + count - 1 }));
413
+ rec.seq = first + count - 1;
385
414
  setState(rec);
386
415
  return { seq: first, sessionId: rec.sessionId };
387
416
  }
417
+ /** Document identity is not sessionStorage: duplicated tabs copy that store. */
418
+ export const RECORDER_DOCUMENT_KEY = `${Date.now().toString(36)}.${Math.random().toString(36).slice(2)}`;
419
+ const ALLOCATION_PREFIX = 'allocation.';
420
+ let captureNo = 0;
421
+ const pendingAllocations = new Set();
422
+ const MAX_ALLOCATION_BYTES = 16 * 1024 * 1024;
423
+ let allocationBytes = 0;
424
+ let allocationChunks = 0;
425
+ const allocatedCaptures = new Map();
426
+ let allocationsRecovered = false;
427
+ let allocationBusy = null;
428
+ function removeAllocation(item) {
429
+ if (!pendingAllocations.delete(item))
430
+ return;
431
+ allocationBytes -= item.bytes;
432
+ if (item.draft.kind === 'chunk')
433
+ allocationChunks--;
434
+ }
435
+ function addAllocation(item) {
436
+ pendingAllocations.add(item);
437
+ allocationBytes += item.bytes;
438
+ if (item.draft.kind === 'chunk')
439
+ allocationChunks++;
440
+ while (pendingAllocations.size > MAX_BUFFER || allocationBytes > MAX_ALLOCATION_BYTES || allocationChunks > MAX_PENDING) {
441
+ const oldest = pendingAllocations.values().next().value;
442
+ removeAllocation(oldest);
443
+ kv().remove(oldest.key);
444
+ const error = new Error('vitrinka: pending allocation budget full — oldest capture dropped');
445
+ noteFailure(error);
446
+ console.warn(error.message);
447
+ }
448
+ }
449
+ /** Journals survive pagehide and are safe for another document to help drain. */
450
+ function recoverAllocations(refresh = false) {
451
+ if (allocationsRecovered && !refresh)
452
+ return;
453
+ allocationsRecovered = true;
454
+ const storage = kv();
455
+ if (!storage.withLock)
456
+ return;
457
+ const queuedKeys = new Set([...pendingAllocations].map((item) => item.key));
458
+ for (const key of storage.keys?.() ?? []) {
459
+ if (!key.startsWith(ALLOCATION_PREFIX) || queuedKeys.has(key) || allocatedCaptures.has(key))
460
+ continue;
461
+ const item = readJson(key, null);
462
+ if (item && item.draft && item.draft.sessionId === getState()?.sessionId)
463
+ addAllocation({ ...item, key, persisted: true, bytes: utf8Bytes(JSON.stringify(item)) });
464
+ }
465
+ }
466
+ function appendCapture(draft, seq) {
467
+ const { ts, tabId, tabHost, sessionId } = draft;
468
+ if (draft.kind === 'event') {
469
+ const buffer = getBuffer();
470
+ if (!buffer.some((event) => event.seq === seq))
471
+ buffer.push({ seq, ts, tabId, tabHost, ...draft.event });
472
+ if (buffer.length > MAX_BUFFER) {
473
+ const dropped = buffer.splice(0, buffer.length - MAX_BUFFER);
474
+ clearStoredCaptures(sessionId, new Set(dropped.map((event) => event.seq)));
475
+ console.warn(`vitrinka: retry buffer full — dropped ${dropped.length} oldest events`);
476
+ }
477
+ }
478
+ else {
479
+ const chunks = getChunks();
480
+ if (!chunks.some((chunk) => chunk.seq === seq) && !getBuffer().some((event) => event.seq === seq)) {
481
+ chunks.push({ seq, ts, tabId, tabHost, sessionId, ...draft.part });
482
+ chunkBytes += draft.part.body.length;
483
+ }
484
+ while (chunks.length > MAX_PENDING) {
485
+ const dropped = chunks.shift();
486
+ chunkBytes -= dropped.body.length;
487
+ clearStoredCaptures(sessionId, new Set([dropped.seq]));
488
+ console.warn(`vitrinka: pending chunk queue full — dropped rrweb chunk seq ${dropped.seq}`);
489
+ }
490
+ }
491
+ schedulePersist();
492
+ scheduleFlush();
493
+ }
494
+ function clearStoredCaptures(sessionId, seqs) {
495
+ for (const [key, item] of allocatedCaptures) {
496
+ if (item.sessionId === sessionId && seqs.has(item.seq)) {
497
+ kv().remove(key);
498
+ allocatedCaptures.delete(key);
499
+ const documentKey = key.slice(ALLOCATION_PREFIX.length, key.lastIndexOf('.'));
500
+ const peerKey = `tab.${documentKey}`;
501
+ const peer = readJson(peerKey, null);
502
+ if (peer?.departed && peer.recoverable && !kv().keys?.().some((k) => k.startsWith(`${ALLOCATION_PREFIX}${documentKey}.`)))
503
+ kv().remove(peerKey);
504
+ }
505
+ }
506
+ }
507
+ /** Helpers remove a journal only after ack; the original tab may still cache its retry. */
508
+ function pruneAcknowledgedCaptures() {
509
+ const delivered = new Set();
510
+ for (const [key, item] of allocatedCaptures) {
511
+ if (item.persisted && !kv().getString(key)) {
512
+ delivered.add(item.seq);
513
+ allocatedCaptures.delete(key);
514
+ }
515
+ }
516
+ if (!delivered.size)
517
+ return;
518
+ setBuffer(getBuffer().filter((event) => !delivered.has(event.seq)));
519
+ setChunks(getChunks().filter((chunk) => !delivered.has(chunk.seq)));
520
+ }
521
+ /** A departing document can be acknowledged by a helper only with a full journal. */
522
+ export function tailIsDurable() {
523
+ if (!kv().keys)
524
+ return false;
525
+ const durableSeqs = new Set([...allocatedCaptures].filter(([key]) => kv().getString(key)).map(([, item]) => item.seq));
526
+ for (const item of pendingAllocations) {
527
+ if (item.persisted && item.seq !== undefined && kv().getString(item.key))
528
+ durableSeqs.add(item.seq);
529
+ }
530
+ return [...pendingAllocations].every((item) => item.persisted && !!kv().getString(item.key))
531
+ && getBuffer().every((event) => durableSeqs.has(event.seq))
532
+ && getChunks().every((chunk) => durableSeqs.has(chunk.seq));
533
+ }
534
+ /** One worker per document: evicted drafts cannot stay held by queued lock callbacks. */
535
+ function allocatePending() {
536
+ if (allocationBusy)
537
+ return allocationBusy;
538
+ const storage = kv();
539
+ allocationBusy = trackCapture(Promise.resolve().then(async () => {
540
+ for (const item of pendingAllocations) {
541
+ await storage.withLock('seq', () => {
542
+ if (!pendingAllocations.has(item))
543
+ return;
544
+ if (item.persisted) {
545
+ const saved = readJson(item.key, null);
546
+ // Another tab already delivered this journal; never allocate it twice.
547
+ if (!saved) {
548
+ removeAllocation(item);
549
+ return;
550
+ }
551
+ item.seq = saved.seq;
552
+ }
553
+ adoptStoredState(storage.getString(REC_KEY) ?? null);
554
+ if (getState()?.sessionId !== item.draft.sessionId) {
555
+ removeAllocation(item);
556
+ return;
557
+ }
558
+ const seq = item.seq ?? allocSeq(1)?.seq;
559
+ if (seq === undefined)
560
+ return;
561
+ item.seq = seq;
562
+ // Keep the payload AND its identity until the server acknowledges it.
563
+ // A recovering document reuses this seq even when the old tab is alive.
564
+ if (item.persisted)
565
+ storage.set(item.key, JSON.stringify({ draft: item.draft, seq }));
566
+ allocatedCaptures.set(item.key, { sessionId: item.draft.sessionId, seq, persisted: item.persisted });
567
+ appendCapture(item.draft, seq);
568
+ removeAllocation(item);
569
+ });
570
+ }
571
+ }).catch((error) => {
572
+ noteFailure(error);
573
+ console.warn('vitrinka: seq allocation failed — capture kept for retry', error);
574
+ scheduleFlush();
575
+ notify();
576
+ throw error;
577
+ })).finally(() => { allocationBusy = null; });
578
+ return allocationBusy;
579
+ }
580
+ /** Accept now, persist now, stamp under the shared lock later. */
581
+ function queueCapture(draft) {
582
+ const accepted = getState();
583
+ if (!accepted || accepted.paused || accepted.dead)
584
+ return false;
585
+ recoverAllocations();
586
+ if (kv().withLock) {
587
+ const key = `${ALLOCATION_PREFIX}${RECORDER_DOCUMENT_KEY}.${++captureNo}`;
588
+ const raw = JSON.stringify({ draft });
589
+ const item = { key, draft, persisted: safeSet(key, raw), bytes: utf8Bytes(raw) };
590
+ addAllocation(item);
591
+ void allocatePending();
592
+ }
593
+ else {
594
+ const allocation = allocSeq(1);
595
+ if (allocation)
596
+ appendCapture(draft, allocation.seq);
597
+ }
598
+ return true;
599
+ }
388
600
  /**
389
601
  * In-flight CAPTURES (async network body reads) that have not yet appended
390
602
  * their event. Stop must settle these before draining.
@@ -445,19 +657,10 @@ export function pushEvent(kind, payload, route) {
445
657
  return pushFlightEvent(kind, payload, route);
446
658
  if (rec.paused || rec.dead)
447
659
  return null;
448
- rec.seq++;
449
660
  const ts = new Date().toISOString();
450
- const buffer = getBuffer();
451
- buffer.push({ seq: rec.seq, ts, tabId: route.tabId, tabHost: route.tabHost, kind, payload });
452
- if (buffer.length > MAX_BUFFER) {
453
- const dropped = buffer.length - MAX_BUFFER;
454
- buffer.splice(0, dropped);
455
- console.warn(`vitrinka: retry buffer full — dropped ${dropped} oldest events`);
456
- }
661
+ const { tabId, tabHost } = route;
662
+ queueCapture({ sessionId: rec.sessionId, ts, tabId, tabHost, kind: 'event', event: { kind, payload } });
457
663
  noteActivity();
458
- schedulePersist();
459
- setState(rec);
460
- scheduleFlush();
461
664
  return ts;
462
665
  }
463
666
  /** Push a fully-formed event (chunk rows carry a pre-allocated seq). */
@@ -534,32 +737,13 @@ export function pushRRWebBatch(events, route) {
534
737
  text: `⚠ rrweb event dropped (${(b / 1048576).toFixed(1)} MiB > chunk cap) — replay may be incomplete from here`,
535
738
  }, route);
536
739
  }
537
- const alloc = parts.length ? allocSeq(parts.length) : null;
538
- if (!alloc)
539
- return 0;
540
- const chunks = getChunks();
541
740
  const ts = new Date().toISOString();
542
- parts.forEach((p, i) => {
543
- chunks.push({
544
- seq: alloc.seq + i,
545
- ts,
546
- tabId: route.tabId,
547
- tabHost: route.tabHost,
548
- sessionId: alloc.sessionId,
549
- count: p.count,
550
- body: p.body,
551
- });
552
- chunkBytes += p.body.length;
553
- });
554
- while (chunks.length > MAX_PENDING) {
555
- const drop = chunks.shift();
556
- if (drop)
557
- chunkBytes -= drop.body.length;
558
- console.warn(`vitrinka: pending chunk queue full — dropped rrweb chunk seq ${drop?.seq}`);
741
+ const { tabId, tabHost } = route;
742
+ for (const part of parts) {
743
+ if (!queueCapture({ sessionId: rec.sessionId, ts, tabId, tabHost, kind: 'chunk', part }))
744
+ return 0;
559
745
  }
560
746
  noteActivity();
561
- schedulePersist();
562
- scheduleFlush();
563
747
  return parts.length;
564
748
  }
565
749
  /**
@@ -608,6 +792,7 @@ async function drainPending(limit = 5) {
608
792
  return getChunks().length === 0;
609
793
  if (e instanceof VitrinkaApiError && permanentStatus(e.status)) {
610
794
  console.warn(`vitrinka: rrweb chunk seq ${item.seq} rejected permanently (${e.status}) — dropped`);
795
+ clearStoredCaptures(item.sessionId, new Set([item.seq]));
611
796
  gone.add(item.seq);
612
797
  continue;
613
798
  }
@@ -645,6 +830,11 @@ export async function flush(opts = {}) {
645
830
  async function flushInner(opts) {
646
831
  if (getState()?.dead)
647
832
  return false;
833
+ recoverAllocations(true);
834
+ if (pendingAllocations.size)
835
+ await allocatePending();
836
+ if (pendingAllocations.size)
837
+ return false;
648
838
  const pendingClear = await drainPending();
649
839
  if (!pendingClear)
650
840
  scheduleFlush();
@@ -681,6 +871,7 @@ async function flushInner(opts) {
681
871
  batchBytes += b;
682
872
  }
683
873
  if (oversized.size) {
874
+ clearStoredCaptures(rec.sessionId, oversized);
684
875
  setBuffer(getBuffer().filter((ev) => !oversized.has(ev.seq)));
685
876
  if (!batch.length) {
686
877
  scheduleFlush();
@@ -711,10 +902,11 @@ async function flushInner(opts) {
711
902
  if (movedOn(rec))
712
903
  return true;
713
904
  noteSync();
714
- serverMaxSeq = Math.max(serverMaxSeq, batch[batch.length - 1]?.seq ?? serverMaxSeq);
905
+ serverMaxSeq = Math.max(serverMaxSeq, ...batch.map((event) => event.seq));
715
906
  notify();
716
907
  // Remove EXACTLY the sent seqs — events pushed during the in-flight POST survive.
717
908
  const sent = new Set(batch.map((e) => e.seq));
909
+ clearStoredCaptures(rec.sessionId, sent);
718
910
  const rest = getBuffer().filter((e) => !sent.has(e.seq));
719
911
  setBuffer(rest);
720
912
  if (rest.length)
@@ -725,7 +917,9 @@ async function flushInner(opts) {
725
917
  export async function drainBuffer(deadlineMs = 60000) {
726
918
  const t0 = Date.now();
727
919
  while (Date.now() - t0 < deadlineMs) {
728
- if (getBuffer().length === 0 && getChunks().length === 0)
920
+ // A peer may journal its departure after an already-running flush scanned storage.
921
+ recoverAllocations(true);
922
+ if (queuedCount() === 0)
729
923
  return true;
730
924
  const sent = await flush();
731
925
  if (getState()?.dead)
@@ -738,6 +932,13 @@ export async function drainBuffer(deadlineMs = 60000) {
738
932
  }
739
933
  /** Reset buffers for a fresh session. */
740
934
  export function resetQueues() {
935
+ for (const key of allocatedCaptures.keys())
936
+ kv().remove(key);
937
+ for (const item of pendingAllocations)
938
+ kv().remove(item.key);
939
+ allocatedCaptures.clear();
940
+ pendingAllocations.clear();
941
+ allocationBytes = allocationChunks = 0;
741
942
  setBuffer([]);
742
943
  setChunks([]);
743
944
  }
@@ -753,6 +954,9 @@ function dropLocalTail() {
753
954
  bufferCache = [];
754
955
  chunkCache = [];
755
956
  chunkBytes = 0;
957
+ pendingAllocations.clear();
958
+ allocationBytes = allocationChunks = 0;
959
+ allocatedCaptures.clear();
756
960
  tailDropped = true;
757
961
  }
758
962
  /** Test-only: drop all module state so suites cannot leak into each other. */
@@ -762,6 +966,10 @@ export function __resetForTests() {
762
966
  kv().remove('rec');
763
967
  kv().remove('buffer');
764
968
  kv().remove('chunks');
969
+ kv().remove('seq');
970
+ for (const key of kv().keys?.() ?? [])
971
+ if (key.startsWith(ALLOCATION_PREFIX))
972
+ kv().remove(key);
765
973
  resetIdle();
766
974
  }
767
975
  /** Test-only: the recorded events currently buffered (in order). */
@@ -774,6 +982,11 @@ export function __chunksForTests() {
774
982
  }
775
983
  /** Test-only: drop the in-memory caches while LEAVING storage intact (a reload). */
776
984
  export function __dropCachesForTests() {
985
+ pendingAllocations.clear();
986
+ allocationBytes = allocationChunks = 0;
987
+ allocatedCaptures.clear();
988
+ allocationsRecovered = false;
989
+ allocationBusy = null;
777
990
  if (persistTimer) {
778
991
  clearTimeout(persistTimer);
779
992
  persistTimer = null;
@@ -15,10 +15,11 @@ import type { RedactionPolicy } from '@vitrinka/redact';
15
15
  import type { SessionDone } from '../protocol';
16
16
  import { type SessionState } from './queue';
17
17
  export { currentRoute, notify, subscribe } from './state';
18
+ export { onBeforeStop } from './queue';
18
19
  export type { SessionDone } from '../protocol';
19
20
  /** Sent as `meta.recorder`; bumped with the package version. */
20
- export declare const RECORDER_VERSION = "0.3.3";
21
- export declare const RECORDER_ID = "web/0.3.3";
21
+ export declare const RECORDER_VERSION = "0.3.4";
22
+ export declare const RECORDER_ID = "web/0.3.4";
22
23
  /** What `POST /api/v1/sessions` answers (the fields this recorder keeps). */
23
24
  export interface SessionOut {
24
25
  id: string;
@@ -81,7 +82,10 @@ export declare function imagePixels(r: ViewRect): ViewRect;
81
82
  export declare function addAnnotation(text: string, rect: ViewRect, selector: string, opts?: {
82
83
  task?: boolean;
83
84
  }): void;
84
- export declare function onBeforeStop(fn: () => void): () => void;
85
+ /**
86
+ * Hooks that run at the top of Stop, before the drain snapshot — the rrweb
87
+ * lane ships its sub-2s tail here so the last DOM events make the session.
88
+ */
85
89
  /**
86
90
  * Stop the session. Throws with the queued-item count when the server is
87
91
  * unreachable — the durable tail is NEVER deleted; capture freezes paused and
@@ -1,13 +1,15 @@
1
1
  import { api, fetchPolicy, permanentStatus, VitrinkaApiError } from './api';
2
2
  import { redactUrl, setRedactionPolicy } from './capture/redact';
3
3
  import { recorderConfig } from './config';
4
- import { adoptStoredState, armReconcile, capturesSettled, disarmReconcile, drainBuffer, getState, markStopping, pushEvent, queuedCount, REC_KEY, resetHealth, resetIdle, resetQueues, setState, stoppingElsewhere, } from './queue';
4
+ import { adoptStoredState, armReconcile, capturesSettled, disarmReconcile, drainBuffer, getState, markStopping, persistNow, pushEvent, queuedCount, REC_KEY, resetHealth, resetIdle, resetQueues, runBeforeStopHooks, setState, stoppingElsewhere, } from './queue';
5
5
  import { awaitBoard, boardUrlOf, forgetRecents, noteRecent, RECENTS_KEY, updateRecent } from './recents';
6
6
  import { currentRoute, notify } from './state';
7
7
  import { getRecorderStorage } from './storage';
8
+ import { recorderPeers, registerRecorderTab, waitForRecorderPeers } from './tabs';
8
9
  export { currentRoute, notify, subscribe } from './state';
10
+ export { onBeforeStop } from './queue';
9
11
  /** Sent as `meta.recorder`; bumped with the package version. */
10
- export const RECORDER_VERSION = '0.3.3';
12
+ export const RECORDER_VERSION = '0.3.4';
11
13
  export const RECORDER_ID = `web/${RECORDER_VERSION}`;
12
14
  /**
13
15
  * Re-apply a RECOVERED session's redaction policy after a reload — and
@@ -47,11 +49,13 @@ export function recoverRedactionPolicy() {
47
49
  */
48
50
  export function followOtherTabs() {
49
51
  const storage = getRecorderStorage();
52
+ const participant = registerRecorderTab();
50
53
  const offRec = storage.watch?.(REC_KEY, (raw) => {
51
54
  const had = getState()?.policy;
52
55
  const change = adoptStoredState(raw);
53
56
  if (change === 'unchanged')
54
57
  return;
58
+ participant?.sync();
55
59
  if (change === 'ended')
56
60
  setRedactionPolicy(null);
57
61
  if (change === 'joined') {
@@ -64,11 +68,16 @@ export function followOtherTabs() {
64
68
  if (change === 'updated' && had === undefined && policy !== undefined)
65
69
  setRedactionPolicy(policy);
66
70
  notify();
71
+ if (getState()?.stopping)
72
+ void participant?.settle().catch((error) => {
73
+ console.warn('vitrinka: cross-tab Stop remains unsaved', error);
74
+ });
67
75
  });
68
76
  const offRecents = storage.watch?.(RECENTS_KEY, forgetRecents);
69
77
  return () => {
70
78
  offRec?.();
71
79
  offRecents?.();
80
+ participant?.dispose();
72
81
  };
73
82
  }
74
83
  export function elapsedOf(rec) {
@@ -231,11 +240,6 @@ export function addAnnotation(text, rect, selector, opts = {}) {
231
240
  * Hooks that run at the top of Stop, before the drain snapshot — the rrweb
232
241
  * lane ships its sub-2s tail here so the last DOM events make the session.
233
242
  */
234
- const beforeStopHooks = new Set();
235
- export function onBeforeStop(fn) {
236
- beforeStopHooks.add(fn);
237
- return () => beforeStopHooks.delete(fn);
238
- }
239
243
  /**
240
244
  * Stop the session. Throws with the queued-item count when the server is
241
245
  * unreachable — the durable tail is NEVER deleted; capture freezes paused and
@@ -247,26 +251,20 @@ export async function stopSession() {
247
251
  return null;
248
252
  // The recording's length is what the tester saw at Stop, not Stop + drain.
249
253
  const durationMs = elapsedOf(rec);
254
+ const peers = recorderPeers(rec.sessionId);
250
255
  // The other tabs leave rec at the Stop, not when the save ends; a stop
251
256
  // that keeps the session hands it back to them as it now is.
252
257
  markStopping(rec.sessionId, durationMs);
253
258
  try {
254
- return await finishStop(rec, durationMs);
259
+ return await finishStop(rec, durationMs, peers);
255
260
  }
256
261
  finally {
257
262
  markStopping(null);
258
263
  }
259
264
  }
260
- async function finishStop(rec, durationMs) {
265
+ async function finishStop(rec, durationMs, peers) {
261
266
  disarmReconcile();
262
- for (const fn of beforeStopHooks) {
263
- try {
264
- fn();
265
- }
266
- catch (e) {
267
- console.warn('vitrinka: before-stop hook failed', e);
268
- }
269
- }
267
+ runBeforeStopHooks();
270
268
  const completeDeadStop = (reason) => {
271
269
  const kept = queuedCount();
272
270
  updateRecent(rec.sessionId, { status: 'unsaved', durationMs });
@@ -282,7 +280,8 @@ async function finishStop(rec, durationMs) {
282
280
  if (!(await capturesSettled())) {
283
281
  console.warn('vitrinka: stopping with unsettled captures — a late event may not make this session');
284
282
  }
285
- if (!(await drainBuffer())) {
283
+ const peersSaved = await waitForRecorderPeers(peers, rec.sessionId);
284
+ if (!peersSaved || !(await drainBuffer())) {
286
285
  const live = getState();
287
286
  // Another tab may have moved on to a session of its own meanwhile — never this stop's to hold.
288
287
  const held = live?.sessionId === rec.sessionId ? live : null;
@@ -294,9 +293,10 @@ async function finishStop(rec, durationMs) {
294
293
  held.resumeAt = null;
295
294
  setState(held);
296
295
  }
296
+ persistNow();
297
297
  armReconcile();
298
298
  notify();
299
- throw new Error(`server unreachable — ${queuedCount()} item(s) kept; stop again once online`);
299
+ throw new Error(`${peersSaved ? 'server unreachable' : 'another tab has undelivered captures'} — ${queuedCount()} local item(s) kept; stop again once online`);
300
300
  }
301
301
  let done = null;
302
302
  try {
@@ -1,16 +1,3 @@
1
- /**
2
- * Pluggable durable KV storage for the recorder's queue and session state.
3
- *
4
- * The queue's correctness leans on SYNCHRONOUS reads/writes: every
5
- * read-modify-write completes in one JS tick, so no async mutex is needed and
6
- * delivery-ack bookkeeping stays race-free. Any driver plugged in here MUST be
7
- * synchronous — which is why the default is `localStorage` and not IndexedDB.
8
- *
9
- * When `localStorage` is unavailable or throws on first touch (Safari private
10
- * mode, a sandboxed iframe, a storage-disabled profile) the recorder falls
11
- * back to the in-memory driver: capture still works for the life of the
12
- * document, only the reload-survival guarantee is lost — and it says so once.
13
- */
14
1
  export interface RecorderStorage {
15
2
  /** Read a value; null/undefined when the key was never written. */
16
3
  getString(key: string): string | null | undefined;
@@ -24,6 +11,10 @@ export interface RecorderStorage {
24
11
  * shares (memory) has nothing to hear.
25
12
  */
26
13
  watch?(key: string, onChange: (value: string | null) => void): () => void;
14
+ /** Run synchronously inside an exclusive cross-document lock. Required when shared across tabs. */
15
+ withLock?(name: string, run: () => void): Promise<void>;
16
+ /** Enumerate this driver's namespaced keys (cross-tab Stop participants). */
17
+ keys?(): string[];
27
18
  }
28
19
  /**
29
20
  * Install a storage driver. Call before the recorder mounts; calling after
@@ -1,16 +1,16 @@
1
1
  /**
2
2
  * Pluggable durable KV storage for the recorder's queue and session state.
3
3
  *
4
- * The queue's correctness leans on SYNCHRONOUS reads/writes: every
5
- * read-modify-write completes in one JS tick, so no async mutex is needed and
6
- * delivery-ack bookkeeping stays race-free. Any driver plugged in here MUST be
7
- * synchronous — which is why the default is `localStorage` and not IndexedDB.
4
+ * Reads/writes are synchronous for queue bookkeeping within one document.
5
+ * A driver shared across documents must also serialize seq allocations:
6
+ * one JS tick in one tab does not exclude a second tab's read-modify-write.
8
7
  *
9
8
  * When `localStorage` is unavailable or throws on first touch (Safari private
10
9
  * mode, a sandboxed iframe, a storage-disabled profile) the recorder falls
11
10
  * back to the in-memory driver: capture still works for the life of the
12
11
  * document, only the reload-survival guarantee is lost — and it says so once.
13
12
  */
13
+ import { withRecorderLock } from './lock';
14
14
  // Keys land as `vitrinka.recorder.<key>`: rec · buffer · chunks · link (the
15
15
  // recorder) and dock · prefs · me · recents (the HUD).
16
16
  const PREFIX = 'vitrinka.recorder.';
@@ -47,6 +47,10 @@ export function localRecorderStorage() {
47
47
  getString: (k) => ls.getItem(PREFIX + k),
48
48
  set: (k, v) => ls.setItem(PREFIX + k, v),
49
49
  remove: (k) => ls.removeItem(PREFIX + k),
50
+ withLock: withRecorderLock,
51
+ keys: () => Array.from({ length: ls.length }, (_, i) => ls.key(i))
52
+ .filter((key) => key !== null && key.startsWith(PREFIX))
53
+ .map((key) => key.slice(PREFIX.length)),
50
54
  // localStorage is shared by every tab of the origin; its `storage`
51
55
  // event reaches the OTHER documents only. A clear() (key null) is not
52
56
  // a write of `k` and is ignored.
@@ -72,6 +76,7 @@ export function memoryRecorderStorage() {
72
76
  getString: (k) => m.get(k) ?? null,
73
77
  set: (k, v) => void m.set(k, v),
74
78
  remove: (k) => void m.delete(k),
79
+ keys: () => [...m.keys()],
75
80
  };
76
81
  }
77
82
  /** Test-only: forget the configured driver and the first-use latch. */
@@ -0,0 +1,2 @@
1
+ /** Cross-document exclusion for the shared localStorage driver's seq allocator. */
2
+ export declare function withRecorderLock(name: string, run: () => void): Promise<void>;