@vitrinka/web 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +77 -5
  3. package/build/hud.d.ts +1 -1
  4. package/build/hud.iife.js +46 -9
  5. package/build/protocol/index.d.ts +55 -4
  6. package/build/protocol/index.js +4 -2
  7. package/build/recorder/api.d.ts +25 -5
  8. package/build/recorder/api.js +21 -9
  9. package/build/recorder/attachments.d.ts +19 -0
  10. package/build/recorder/attachments.js +31 -0
  11. package/build/recorder/hud/Hud.d.ts +1 -1
  12. package/build/recorder/hud/Hud.js +43 -10
  13. package/build/recorder/hud/Sheet.d.ts +40 -5
  14. package/build/recorder/hud/Sheet.js +134 -8
  15. package/build/recorder/hud/attach.d.ts +26 -0
  16. package/build/recorder/hud/attach.js +136 -0
  17. package/build/recorder/hud/controller.d.ts +31 -3
  18. package/build/recorder/hud/controller.js +1 -1
  19. package/build/recorder/hud/host.js +2 -0
  20. package/build/recorder/hud/icons.d.ts +3 -0
  21. package/build/recorder/hud/icons.js +7 -0
  22. package/build/recorder/hud/layer.d.ts +4 -1
  23. package/build/recorder/hud/layer.js +11 -3
  24. package/build/recorder/hud/resize.d.ts +83 -0
  25. package/build/recorder/hud/resize.js +236 -0
  26. package/build/recorder/hud/styles.d.ts +1 -1
  27. package/build/recorder/hud/styles.js +38 -1
  28. package/build/recorder/link.d.ts +4 -1
  29. package/build/recorder/link.js +6 -2
  30. package/build/recorder/me.d.ts +7 -0
  31. package/build/recorder/me.js +62 -12
  32. package/build/recorder/page-controller.js +4 -3
  33. package/build/recorder/queue.d.ts +42 -11
  34. package/build/recorder/queue.js +640 -47
  35. package/build/recorder/report.d.ts +9 -0
  36. package/build/recorder/report.js +46 -4
  37. package/build/recorder/session.d.ts +18 -6
  38. package/build/recorder/session.js +59 -29
  39. package/build/recorder/storage/blobs.d.ts +32 -0
  40. package/build/recorder/storage/blobs.js +83 -0
  41. package/build/recorder/storage/index.d.ts +4 -13
  42. package/build/recorder/storage/index.js +12 -6
  43. package/build/recorder/storage/lock.d.ts +2 -0
  44. package/build/recorder/storage/lock.js +48 -0
  45. package/build/recorder/tabs.d.ts +8 -0
  46. package/build/recorder/tabs.js +137 -0
  47. package/package.json +1 -1
@@ -1,7 +1,8 @@
1
- import { api, permanentStatus, uploadChunk, VitrinkaApiError } from './api';
1
+ import { api, permanentStatus, uploadChunk, uploadImage, VitrinkaApiError } from './api';
2
2
  import { pushFlightEvent } from './flight';
3
3
  import { notify } from './state';
4
4
  import { getRecorderStorage } from './storage';
5
+ import { getRecorderBlobStore } from './storage/blobs';
5
6
  const FLUSH_MS = 2000;
6
7
  const MAX_BUFFER = 20000;
7
8
  const MAX_PENDING = 200; // rrweb chunks in memory; oldest evicted loudly
@@ -134,6 +135,21 @@ function renewStopping(sessionId) {
134
135
  if (live?.sessionId === sessionId)
135
136
  setState(live);
136
137
  }
138
+ const beforeStopHooks = new Set();
139
+ export function onBeforeStop(fn) {
140
+ beforeStopHooks.add(fn);
141
+ return () => beforeStopHooks.delete(fn);
142
+ }
143
+ export function runBeforeStopHooks() {
144
+ for (const fn of beforeStopHooks) {
145
+ try {
146
+ fn();
147
+ }
148
+ catch (error) {
149
+ console.warn('vitrinka: before-stop hook failed', error);
150
+ }
151
+ }
152
+ }
137
153
  /**
138
154
  * Another document of this origin (a second tab) wrote the session record.
139
155
  * The store is shared, this cache is not — a tab that joined a recording on
@@ -155,6 +171,10 @@ export function adoptStoredState(raw) {
155
171
  }
156
172
  }
157
173
  const cur = getState();
174
+ // Allocations also read storage before its notification arrives. Ship the
175
+ // already-captured DOM tail while the local cache still accepts it.
176
+ if (next?.stopping && next.sessionId === cur?.sessionId && !cur.paused && stoppingHere?.sessionId !== next.sessionId)
177
+ runBeforeStopHooks();
158
178
  if (!next) {
159
179
  if (!cur)
160
180
  return 'unchanged';
@@ -168,6 +188,8 @@ export function adoptStoredState(raw) {
168
188
  // A policy this tab already holds outlives a record written before it.
169
189
  if (next.policy === undefined && cur.policy !== undefined)
170
190
  next.policy = cur.policy;
191
+ if (next.attachments === undefined && cur.attachments !== undefined)
192
+ next.attachments = cur.attachments;
171
193
  // A session this tab is stopping comes back as the frozen copy it wrote
172
194
  // (another tab wrote its cache back): this tab's clock and capture stay live.
173
195
  if (stoppingHere?.sessionId === next.sessionId) {
@@ -204,8 +226,13 @@ function getBuffer() {
204
226
  }
205
227
  /** Write the in-memory buffer (and the pending chunks) to storage NOW. */
206
228
  export function persistNow() {
229
+ for (const item of pendingAllocations) {
230
+ if (!item.persisted)
231
+ item.persisted = safeSet(item.key, JSON.stringify({ draft: item.draft, seq: item.seq }));
232
+ }
207
233
  persistBuffer();
208
234
  persistChunks();
235
+ persistImages();
209
236
  }
210
237
  function persistBuffer() {
211
238
  if (persistTimer) {
@@ -261,8 +288,139 @@ function setChunks(chunks) {
261
288
  tailDropped = false;
262
289
  persistChunks();
263
290
  }
291
+ // -- attached images ---------------------------------------------------------
292
+ /** The pending images' metadata (small: their bytes are in the blob journal). */
293
+ let imageCache;
294
+ /** Bytes this document holds itself, by journal key — no journal read to upload them. */
295
+ const imageBlobs = new Map();
296
+ /** Journal keys whose bytes are not (yet) known to be in a durable journal. */
297
+ const unjournaled = new Set();
298
+ /** Uploaded images whose row awaits the server's ack: row seq → journal key, deleted on ack. */
299
+ const rowBlobs = new Map();
300
+ /** Journal reads refused in a row, by key: a journal that never answers must not hold Stop forever. */
301
+ const readFailures = new Map();
302
+ const READ_ATTEMPTS = 5;
303
+ /**
304
+ * The queued images' budget across notes (one note holds ≤ 10): past either
305
+ * bound the oldest goes loudly and its note lands without it — a tester
306
+ * attaching on while offline never grows memory and the journal unbounded.
307
+ */
308
+ const MAX_IMAGES = 200;
309
+ const MAX_IMAGE_BYTES = 64 * 1024 * 1024;
310
+ let imageNo = 0;
311
+ let volatileWarned = false;
312
+ /** KV mark: the blob journal may hold something (spares IndexedDB for testers who never attach). */
313
+ const BLOBS_KEY = 'blobs';
314
+ function getImages() {
315
+ imageCache ??= readJson('images', []);
316
+ return imageCache;
317
+ }
318
+ /**
319
+ * Always persisted: metadata only — and only of images whose bytes are in
320
+ * the blob journal, the one place the next document can read them from.
321
+ */
322
+ function persistImages() {
323
+ if (tailDropped)
324
+ return;
325
+ const images = getImages().filter((image) => !unjournaled.has(image.blob));
326
+ if (images.length === 0)
327
+ kv().remove('images');
328
+ else
329
+ safeSet('images', JSON.stringify(images));
330
+ }
331
+ function setImages(images) {
332
+ imageCache = images;
333
+ tailDropped = false;
334
+ persistImages();
335
+ }
336
+ /**
337
+ * Hold a note's images for the queue: their bytes in memory for this
338
+ * document and in the blob journal for a reload or another tab. Returns
339
+ * the drafts the capture journal records (journal key + payload), and
340
+ * `journaled` — true once every image's bytes are durably in the journal:
341
+ * only then may anything outside this document be told about them.
342
+ */
343
+ function stageImages(sessionId, images) {
344
+ const store = getRecorderBlobStore();
345
+ if (!store.durable && !volatileWarned) {
346
+ volatileWarned = true;
347
+ console.warn('vitrinka: no IndexedDB — an attached image will not survive a reload');
348
+ }
349
+ safeSet(BLOBS_KEY, '1');
350
+ const writes = [];
351
+ const drafts = images.map(({ blob, payload }) => {
352
+ const key = `${sessionId}/${RECORDER_DOCUMENT_KEY}.${++imageNo}`;
353
+ imageBlobs.set(key, blob);
354
+ unjournaled.add(key);
355
+ writes.push(store.put(key, blob).then(() => {
356
+ // Released (or acknowledged) while the write was out: nothing will read it back.
357
+ const needed = imageBlobs.has(key) || getImages().some((image) => image.blob === key) || [...rowBlobs.values()].includes(key);
358
+ if (!needed) {
359
+ unjournaled.delete(key);
360
+ forgetBlob(key);
361
+ return false;
362
+ }
363
+ if (!store.durable)
364
+ return false;
365
+ unjournaled.delete(key);
366
+ if (getImages().some((image) => image.blob === key))
367
+ persistImages();
368
+ return true;
369
+ }, (error) => {
370
+ console.warn('vitrinka: an attached image could not be journaled — it will not survive a reload', error);
371
+ return false;
372
+ }));
373
+ return { blob: key, payload };
374
+ });
375
+ return { drafts, journaled: Promise.all(writes).then((durable) => durable.every(Boolean)) };
376
+ }
377
+ /** Delete one image's bytes from the blob journal. */
378
+ function forgetBlob(key) {
379
+ void getRecorderBlobStore()
380
+ .delete(key)
381
+ .catch((error) => console.warn('vitrinka: blob journal delete failed', error));
382
+ }
383
+ /** Let go of images nothing here will upload; `journal` also deletes their bytes there. */
384
+ function releaseImages(keys, journal) {
385
+ for (const key of keys) {
386
+ imageBlobs.delete(key);
387
+ unjournaled.delete(key);
388
+ readFailures.delete(key);
389
+ if (journal)
390
+ forgetBlob(key);
391
+ }
392
+ }
393
+ const draftImageKeys = (draft) => (draft.kind === 'event' ? (draft.images ?? []).map((i) => i.blob) : []);
394
+ /**
395
+ * Delete journaled images nothing will upload: `ended`'s (a session just
396
+ * stopped), or, without it, every session's but the live one.
397
+ */
398
+ export async function pruneBlobJournal(ended) {
399
+ if (!kv().getString(BLOBS_KEY))
400
+ return;
401
+ const store = getRecorderBlobStore();
402
+ const live = getState()?.sessionId;
403
+ try {
404
+ const keys = await store.keys();
405
+ let kept = 0;
406
+ for (const key of keys) {
407
+ const drop = ended ? key.startsWith(`${ended}/`) : !live || !key.startsWith(`${live}/`);
408
+ if (drop)
409
+ await store.delete(key);
410
+ else
411
+ kept++;
412
+ }
413
+ if (kept === 0 && !getState())
414
+ kv().remove(BLOBS_KEY);
415
+ }
416
+ catch (error) {
417
+ console.warn('vitrinka: blob journal cleanup failed', error);
418
+ }
419
+ }
264
420
  export function queuedCount() {
265
- return getBuffer().length + getChunks().length;
421
+ recoverAllocations();
422
+ pruneAcknowledgedCaptures();
423
+ return getBuffer().length + getChunks().length + getImages().length + pendingAllocations.size;
266
424
  }
267
425
  // -- health + server reconciliation (extension D4/D5/D9) ---------------------
268
426
  let lastSyncAt = 0;
@@ -375,16 +533,310 @@ export function disarmReconcile() {
375
533
  clearInterval(reconcileTimer);
376
534
  reconcileTimer = null;
377
535
  }
378
- /** Allocate `count` consecutive seqs without emitting events; null when not capturing. */
379
- export function allocSeq(count = 1) {
536
+ /** Allocate inside the storage driver's lock; lifecycle writes cannot rewind its watermark. */
537
+ function allocSeq(count) {
380
538
  const rec = getState();
381
- if (!rec || rec.paused || rec.dead || count < 1)
539
+ if (!rec || rec.dead || count < 1)
382
540
  return null;
383
- const first = rec.seq + 1;
384
- rec.seq += count;
541
+ const watermark = readJson('seq', null);
542
+ const first = Math.max(rec.seq, watermark?.sessionId === rec.sessionId ? watermark.seq : 0) + 1;
543
+ // This write must succeed before a seq can be used in another document.
544
+ // On failure the capture stays pending and retries rather than colliding.
545
+ kv().set('seq', JSON.stringify({ sessionId: rec.sessionId, seq: first + count - 1 }));
546
+ rec.seq = first + count - 1;
385
547
  setState(rec);
386
548
  return { seq: first, sessionId: rec.sessionId };
387
549
  }
550
+ /** Document identity is not sessionStorage: duplicated tabs copy that store. */
551
+ export const RECORDER_DOCUMENT_KEY = `${Date.now().toString(36)}.${Math.random().toString(36).slice(2)}`;
552
+ const ALLOCATION_PREFIX = 'allocation.';
553
+ let captureNo = 0;
554
+ const pendingAllocations = new Set();
555
+ const MAX_ALLOCATION_BYTES = 16 * 1024 * 1024;
556
+ let allocationBytes = 0;
557
+ let allocationChunks = 0;
558
+ /** Per capture journal: the seqs it still waits on; the journal goes once none is left. */
559
+ const allocatedCaptures = new Map();
560
+ /** How many seqs a capture takes: one, or a note's images + the note. */
561
+ function seqCount(draft) {
562
+ return draft.kind === 'event' ? 1 + (draft.images?.length ?? 0) : 1;
563
+ }
564
+ function seqsFrom(first, draft) {
565
+ return new Set(Array.from({ length: seqCount(draft) }, (_, i) => first + i));
566
+ }
567
+ /** A capture journal as stored: with `left` once some of its seqs settled. */
568
+ function journalJson(draft, seq, left) {
569
+ return JSON.stringify(left && left.size < seqCount(draft) ? { draft, seq, left: [...left] } : { draft, seq });
570
+ }
571
+ let allocationsRecovered = false;
572
+ let allocationBusy = null;
573
+ function removeAllocation(item) {
574
+ if (!pendingAllocations.delete(item))
575
+ return;
576
+ allocationBytes -= item.bytes;
577
+ if (item.draft.kind === 'chunk')
578
+ allocationChunks--;
579
+ }
580
+ function addAllocation(item) {
581
+ pendingAllocations.add(item);
582
+ allocationBytes += item.bytes;
583
+ if (item.draft.kind === 'chunk')
584
+ allocationChunks++;
585
+ while (pendingAllocations.size > MAX_BUFFER || allocationBytes > MAX_ALLOCATION_BYTES || allocationChunks > MAX_PENDING) {
586
+ const oldest = pendingAllocations.values().next().value;
587
+ removeAllocation(oldest);
588
+ kv().remove(oldest.key);
589
+ releaseImages(draftImageKeys(oldest.draft), true);
590
+ const error = new Error('vitrinka: pending allocation budget full — oldest capture dropped');
591
+ noteFailure(error);
592
+ console.warn(error.message);
593
+ }
594
+ }
595
+ /** Journals survive pagehide and are safe for another document to help drain. */
596
+ function recoverAllocations(refresh = false) {
597
+ if (allocationsRecovered && !refresh)
598
+ return;
599
+ allocationsRecovered = true;
600
+ const storage = kv();
601
+ if (!storage.withLock)
602
+ return;
603
+ const queuedKeys = new Set([...pendingAllocations].map((item) => item.key));
604
+ for (const key of storage.keys?.() ?? []) {
605
+ if (!key.startsWith(ALLOCATION_PREFIX) || queuedKeys.has(key) || allocatedCaptures.has(key))
606
+ continue;
607
+ const item = readJson(key, null);
608
+ if (item && item.draft && item.draft.sessionId === getState()?.sessionId)
609
+ addAllocation({ ...item, key, persisted: true, bytes: utf8Bytes(JSON.stringify(item)) });
610
+ }
611
+ }
612
+ /**
613
+ * `seq` is the capture's first: a note's images take it and the next ones,
614
+ * the note the last. `left` (its journal's) restores only the seqs still
615
+ * waited on — a settled image never re-queues to crowd out a live one.
616
+ */
617
+ function appendCapture(draft, seq, left) {
618
+ const { ts, tabId, tabHost, sessionId } = draft;
619
+ const awaited = (at) => !left || left.has(at);
620
+ if (draft.kind === 'event') {
621
+ const images = draft.images ?? [];
622
+ const own = seq + images.length;
623
+ const event = images.length
624
+ ? { ...draft.event, payload: { ...draft.event.payload, attachments: images.map((_, i) => seq + i) } }
625
+ : draft.event;
626
+ const buffer = getBuffer();
627
+ if (awaited(own) && !buffer.some((e) => e.seq === own))
628
+ buffer.push({ seq: own, ts, tabId, tabHost, ...event });
629
+ if (images.length) {
630
+ const pending = getImages();
631
+ images.forEach((image, i) => {
632
+ const at = seq + i;
633
+ if (!awaited(at) || pending.some((p) => p.seq === at))
634
+ return;
635
+ // Already uploaded, its row waits in the buffer (a reload restored it):
636
+ // its bytes still leave the journal on that row's ack.
637
+ if (buffer.some((e) => e.seq === at)) {
638
+ rowBlobs.set(at, image.blob);
639
+ return;
640
+ }
641
+ pending.push({ seq: at, ts, tabId, tabHost, sessionId, blob: image.blob, payload: image.payload });
642
+ });
643
+ let bytes = pending.reduce((sum, p) => sum + p.payload.bytes, 0);
644
+ while (pending.length > MAX_IMAGES || bytes > MAX_IMAGE_BYTES) {
645
+ const dropped = pending.shift();
646
+ bytes -= dropped.payload.bytes;
647
+ clearStoredCaptures(dropped.sessionId, new Set([dropped.seq]));
648
+ releaseImages([dropped.blob], true);
649
+ console.warn(`vitrinka: attached image queue full — dropped ${dropped.payload.name} (seq ${dropped.seq}); its note lands without it`);
650
+ }
651
+ setImages(pending);
652
+ }
653
+ if (buffer.length > MAX_BUFFER) {
654
+ const dropped = buffer.splice(0, buffer.length - MAX_BUFFER);
655
+ clearStoredCaptures(sessionId, new Set(dropped.map((event) => event.seq)));
656
+ console.warn(`vitrinka: retry buffer full — dropped ${dropped.length} oldest events`);
657
+ }
658
+ }
659
+ else {
660
+ const chunks = getChunks();
661
+ if (!chunks.some((chunk) => chunk.seq === seq) && !getBuffer().some((event) => event.seq === seq)) {
662
+ chunks.push({ seq, ts, tabId, tabHost, sessionId, ...draft.part });
663
+ chunkBytes += draft.part.body.length;
664
+ }
665
+ while (chunks.length > MAX_PENDING) {
666
+ const dropped = chunks.shift();
667
+ chunkBytes -= dropped.body.length;
668
+ clearStoredCaptures(sessionId, new Set([dropped.seq]));
669
+ console.warn(`vitrinka: pending chunk queue full — dropped rrweb chunk seq ${dropped.seq}`);
670
+ }
671
+ }
672
+ schedulePersist();
673
+ scheduleFlush();
674
+ }
675
+ /**
676
+ * `seqs` were acknowledged (or dropped): a journal none of whose seqs is
677
+ * left goes; one with some left records which (merged with another tab's
678
+ * record — `left` only shrinks).
679
+ */
680
+ function clearStoredCaptures(sessionId, seqs) {
681
+ for (const [key, item] of allocatedCaptures) {
682
+ if (item.sessionId !== sessionId)
683
+ continue;
684
+ // A journal holds one seq, or a note's few: walk its own, never the batch.
685
+ const before = item.seqs.size;
686
+ for (const seq of item.seqs)
687
+ if (seqs.has(seq))
688
+ item.seqs.delete(seq);
689
+ const saved = item.seqs.size && item.seqs.size < before && item.persisted ? readJson(key, null) : null;
690
+ if (saved) {
691
+ const left = new Set([...item.seqs].filter((seq) => !saved.left || saved.left.includes(seq)));
692
+ if (left.size)
693
+ safeSet(key, journalJson(saved.draft, saved.seq, left));
694
+ else
695
+ item.seqs.clear(); // another tab settled the rest
696
+ }
697
+ if (item.seqs.size === 0) {
698
+ kv().remove(key);
699
+ allocatedCaptures.delete(key);
700
+ const documentKey = key.slice(ALLOCATION_PREFIX.length, key.lastIndexOf('.'));
701
+ const peerKey = `tab.${documentKey}`;
702
+ const peer = readJson(peerKey, null);
703
+ if (peer?.departed && peer.recoverable && !kv().keys?.().some((k) => k.startsWith(`${ALLOCATION_PREFIX}${documentKey}.`)))
704
+ kv().remove(peerKey);
705
+ }
706
+ }
707
+ }
708
+ /** Helpers remove a journal only after ack; the original tab may still cache its retry. */
709
+ function pruneAcknowledgedCaptures() {
710
+ const delivered = new Set();
711
+ for (const [key, item] of allocatedCaptures) {
712
+ if (item.persisted && !kv().getString(key)) {
713
+ for (const seq of item.seqs)
714
+ delivered.add(seq);
715
+ allocatedCaptures.delete(key);
716
+ }
717
+ }
718
+ if (!delivered.size)
719
+ return;
720
+ setBuffer(getBuffer().filter((event) => !delivered.has(event.seq)));
721
+ setChunks(getChunks().filter((chunk) => !delivered.has(chunk.seq)));
722
+ const images = getImages();
723
+ if (images.some((image) => delivered.has(image.seq))) {
724
+ // The helper uploaded them and deletes their bytes on its own ack.
725
+ releaseImages(images.filter((image) => delivered.has(image.seq)).map((image) => image.blob), false);
726
+ setImages(images.filter((image) => !delivered.has(image.seq)));
727
+ }
728
+ }
729
+ /** A departing document can be acknowledged by a helper only with a full journal. */
730
+ export function tailIsDurable() {
731
+ if (!kv().keys)
732
+ return false;
733
+ const durableSeqs = new Set([...allocatedCaptures].filter(([key]) => kv().getString(key)).flatMap(([, item]) => [...item.seqs]));
734
+ for (const item of pendingAllocations) {
735
+ if (item.persisted && item.seq !== undefined && kv().getString(item.key))
736
+ for (const seq of seqsFrom(item.seq, item.draft))
737
+ durableSeqs.add(seq);
738
+ }
739
+ // An image's bytes must be in the blob journal too, or a helper has nothing to upload.
740
+ const bytesDurable = (key) => !unjournaled.has(key);
741
+ return [...pendingAllocations].every((item) => item.persisted && !!kv().getString(item.key) && draftImageKeys(item.draft).every(bytesDurable))
742
+ && getBuffer().every((event) => durableSeqs.has(event.seq))
743
+ && getChunks().every((chunk) => durableSeqs.has(chunk.seq))
744
+ && getImages().every((image) => durableSeqs.has(image.seq) && bytesDurable(image.blob));
745
+ }
746
+ /** One worker per document: evicted drafts cannot stay held by queued lock callbacks. */
747
+ function allocatePending() {
748
+ if (allocationBusy)
749
+ return allocationBusy;
750
+ const storage = kv();
751
+ allocationBusy = trackCapture(Promise.resolve().then(async () => {
752
+ for (const item of pendingAllocations) {
753
+ await storage.withLock('seq', () => {
754
+ if (!pendingAllocations.has(item))
755
+ return;
756
+ if (item.persisted) {
757
+ const saved = readJson(item.key, null);
758
+ // Another tab already delivered this journal; never allocate it twice.
759
+ if (!saved) {
760
+ removeAllocation(item);
761
+ releaseImages(draftImageKeys(item.draft), false);
762
+ return;
763
+ }
764
+ item.seq = saved.seq;
765
+ item.left = saved.left;
766
+ }
767
+ adoptStoredState(storage.getString(REC_KEY) ?? null);
768
+ if (getState()?.sessionId !== item.draft.sessionId) {
769
+ removeAllocation(item);
770
+ releaseImages(draftImageKeys(item.draft), true);
771
+ return;
772
+ }
773
+ const seq = item.seq ?? allocSeq(seqCount(item.draft))?.seq;
774
+ if (seq === undefined)
775
+ return;
776
+ item.seq = seq;
777
+ const seqs = item.left ? new Set(item.left) : seqsFrom(seq, item.draft);
778
+ // Keep the payload AND its identity until the server acknowledges it.
779
+ // A recovering document reuses this seq even when the old tab is alive.
780
+ if (item.persisted)
781
+ storage.set(item.key, journalJson(item.draft, seq, seqs));
782
+ allocatedCaptures.set(item.key, { sessionId: item.draft.sessionId, seqs, persisted: item.persisted });
783
+ appendCapture(item.draft, seq, seqs);
784
+ removeAllocation(item);
785
+ });
786
+ }
787
+ }).catch((error) => {
788
+ noteFailure(error);
789
+ console.warn('vitrinka: seq allocation failed — capture kept for retry', error);
790
+ scheduleFlush();
791
+ notify();
792
+ throw error;
793
+ })).finally(() => { allocationBusy = null; });
794
+ return allocationBusy;
795
+ }
796
+ /**
797
+ * Accept now, persist now, stamp under the shared lock later. A note with
798
+ * images (`journaled`) persists its journal only once their bytes are in
799
+ * the blob journal: another tab recovering it sooner would read no bytes
800
+ * and drop them as lost. Until then (for good, when the bytes never get
801
+ * there) only this document can deliver it.
802
+ */
803
+ function queueCapture(draft, journaled) {
804
+ const accepted = getState();
805
+ if (!accepted || accepted.paused || accepted.dead)
806
+ return false;
807
+ recoverAllocations();
808
+ if (kv().withLock) {
809
+ const key = `${ALLOCATION_PREFIX}${RECORDER_DOCUMENT_KEY}.${++captureNo}`;
810
+ const raw = JSON.stringify({ draft });
811
+ const item = { key, draft, persisted: !journaled && safeSet(key, raw), bytes: utf8Bytes(raw) };
812
+ addAllocation(item);
813
+ void allocatePending();
814
+ void journaled?.then((durable) => {
815
+ if (durable)
816
+ publishAllocation(item);
817
+ });
818
+ }
819
+ else {
820
+ const allocation = allocSeq(seqCount(draft));
821
+ if (allocation)
822
+ appendCapture(draft, allocation.seq);
823
+ else
824
+ releaseImages(draftImageKeys(draft), true);
825
+ }
826
+ return true;
827
+ }
828
+ /**
829
+ * Persist a capture's journal late (its images' bytes just landed), with
830
+ * its seq when it has one. A capture delivered, dropped or reset meanwhile
831
+ * is no longer held here, and nothing is written.
832
+ */
833
+ function publishAllocation(item) {
834
+ const allocated = allocatedCaptures.get(item.key);
835
+ if (allocated)
836
+ allocated.persisted = safeSet(item.key, journalJson(item.draft, item.seq, allocated.seqs));
837
+ else if (pendingAllocations.has(item))
838
+ item.persisted = safeSet(item.key, JSON.stringify({ draft: item.draft }));
839
+ }
388
840
  /**
389
841
  * In-flight CAPTURES (async network body reads) that have not yet appended
390
842
  * their event. Stop must settle these before draining.
@@ -437,27 +889,28 @@ export function isSessionLive(id) {
437
889
  * kind+payload plus the route they observed. With no session the event goes
438
890
  * to the flight recorder when the idle pill keeps one (memory only — never
439
891
  * storage, never the network), else it is dropped. Returns the stamped ts
440
- * (null when dropped).
892
+ * (null when dropped). `images` (a note's attachments, live sessions only)
893
+ * take the seqs just before the event's, which lists them as `attachments`.
441
894
  */
442
- export function pushEvent(kind, payload, route) {
895
+ export function pushEvent(kind, payload, route, images = []) {
443
896
  const rec = getState();
444
897
  if (!rec)
445
898
  return pushFlightEvent(kind, payload, route);
446
899
  if (rec.paused || rec.dead)
447
900
  return null;
448
- rec.seq++;
449
901
  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
- }
902
+ const { tabId, tabHost } = route;
903
+ const staged = images.length ? stageImages(rec.sessionId, images) : null;
904
+ queueCapture({
905
+ sessionId: rec.sessionId,
906
+ ts,
907
+ tabId,
908
+ tabHost,
909
+ kind: 'event',
910
+ event: { kind, payload },
911
+ ...(staged ? { images: staged.drafts } : {}),
912
+ }, staged?.journaled);
457
913
  noteActivity();
458
- schedulePersist();
459
- setState(rec);
460
- scheduleFlush();
461
914
  return ts;
462
915
  }
463
916
  /** Push a fully-formed event (chunk rows carry a pre-allocated seq). */
@@ -534,32 +987,13 @@ export function pushRRWebBatch(events, route) {
534
987
  text: `⚠ rrweb event dropped (${(b / 1048576).toFixed(1)} MiB > chunk cap) — replay may be incomplete from here`,
535
988
  }, route);
536
989
  }
537
- const alloc = parts.length ? allocSeq(parts.length) : null;
538
- if (!alloc)
539
- return 0;
540
- const chunks = getChunks();
541
990
  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}`);
991
+ const { tabId, tabHost } = route;
992
+ for (const part of parts) {
993
+ if (!queueCapture({ sessionId: rec.sessionId, ts, tabId, tabHost, kind: 'chunk', part }))
994
+ return 0;
559
995
  }
560
996
  noteActivity();
561
- schedulePersist();
562
- scheduleFlush();
563
997
  return parts.length;
564
998
  }
565
999
  /**
@@ -608,6 +1042,7 @@ async function drainPending(limit = 5) {
608
1042
  return getChunks().length === 0;
609
1043
  if (e instanceof VitrinkaApiError && permanentStatus(e.status)) {
610
1044
  console.warn(`vitrinka: rrweb chunk seq ${item.seq} rejected permanently (${e.status}) — dropped`);
1045
+ clearStoredCaptures(item.sessionId, new Set([item.seq]));
611
1046
  gone.add(item.seq);
612
1047
  continue;
613
1048
  }
@@ -620,6 +1055,103 @@ async function drainPending(limit = 5) {
620
1055
  setChunks(getChunks().filter((c) => !gone.has(c.seq)));
621
1056
  return getChunks().length === 0;
622
1057
  }
1058
+ /**
1059
+ * Upload queued images oldest-first, the chunks' way: `/shot?seq=N` with the
1060
+ * bytes this document holds, else the blob journal's; only then does the
1061
+ * `attachment` row (payload, blobKey) join the stream under its original seq.
1062
+ * An image whose bytes are gone (never journaled before a reload) or that the
1063
+ * server refuses for good is dropped loudly — its note lands without it. A
1064
+ * refused journal READ is not gone bytes: it stops the pass like a transient
1065
+ * upload failure, and only READ_ATTEMPTS refusals in a row give the image up.
1066
+ * Returns true when no image is left.
1067
+ */
1068
+ async function drainImages(limit = 4) {
1069
+ const images = getImages();
1070
+ if (images.length === 0)
1071
+ return true;
1072
+ const rec = getState();
1073
+ let done = 0;
1074
+ const gone = new Set();
1075
+ const lost = [];
1076
+ for (const item of images) {
1077
+ if (done >= limit)
1078
+ break;
1079
+ done++;
1080
+ if (!rec || item.sessionId !== rec.sessionId) {
1081
+ console.warn(`vitrinka: dropping attachment seq ${item.seq} from ended session ${item.sessionId}`);
1082
+ gone.add(item.seq);
1083
+ lost.push(item.blob);
1084
+ continue;
1085
+ }
1086
+ let blob = imageBlobs.get(item.blob) ?? null;
1087
+ if (!blob) {
1088
+ try {
1089
+ blob = await getRecorderBlobStore().get(item.blob);
1090
+ readFailures.delete(item.blob);
1091
+ }
1092
+ catch (e) {
1093
+ if (movedOn(rec))
1094
+ return getImages().length === 0;
1095
+ const tries = (readFailures.get(item.blob) ?? 0) + 1;
1096
+ console.warn(`vitrinka: blob journal read failed (${tries}/${READ_ATTEMPTS})`, e);
1097
+ if (tries < READ_ATTEMPTS) {
1098
+ readFailures.set(item.blob, tries);
1099
+ noteFailure(e);
1100
+ break; // transient — the bytes stay queued and journaled, the next flush retries
1101
+ }
1102
+ }
1103
+ if (movedOn(rec))
1104
+ return getImages().length === 0;
1105
+ }
1106
+ if (!blob) {
1107
+ console.warn(`vitrinka: attachment seq ${item.seq} (${item.payload.name}) lost its bytes — its note lands without it`);
1108
+ clearStoredCaptures(item.sessionId, new Set([item.seq]));
1109
+ gone.add(item.seq);
1110
+ lost.push(item.blob);
1111
+ continue;
1112
+ }
1113
+ try {
1114
+ const up = await uploadImage(rec.sessionId, item.seq, blob);
1115
+ if (movedOn(rec))
1116
+ return getImages().length === 0;
1117
+ pushRawEvent({
1118
+ seq: item.seq,
1119
+ ts: item.ts,
1120
+ tabId: item.tabId,
1121
+ tabHost: item.tabHost,
1122
+ kind: 'attachment',
1123
+ payload: { ...item.payload },
1124
+ blobKey: up.blobKey,
1125
+ });
1126
+ // The bytes stay journaled until the row is acknowledged (a helper tab may still need them).
1127
+ imageBlobs.delete(item.blob);
1128
+ rowBlobs.set(item.seq, item.blob);
1129
+ noteSync();
1130
+ gone.add(item.seq);
1131
+ }
1132
+ catch (e) {
1133
+ if (movedOn(rec))
1134
+ return getImages().length === 0;
1135
+ if (e instanceof VitrinkaApiError && permanentStatus(e.status)) {
1136
+ console.warn(`vitrinka: attachment seq ${item.seq} rejected permanently (${e.status}) — dropped`);
1137
+ clearStoredCaptures(item.sessionId, new Set([item.seq]));
1138
+ gone.add(item.seq);
1139
+ lost.push(item.blob);
1140
+ continue;
1141
+ }
1142
+ noteFailure(e);
1143
+ console.warn('vitrinka: attachment upload failed', e);
1144
+ break; // transient — stop the pass, the next flush retries
1145
+ }
1146
+ }
1147
+ if (gone.size) {
1148
+ // The rows land in storage before the pending entries leave it.
1149
+ persistBuffer();
1150
+ setImages(getImages().filter((image) => !gone.has(image.seq)));
1151
+ }
1152
+ releaseImages(lost, true);
1153
+ return getImages().length === 0;
1154
+ }
623
1155
  let flushTimer = null;
624
1156
  export function scheduleFlush() {
625
1157
  if (flushTimer)
@@ -645,7 +1177,15 @@ export async function flush(opts = {}) {
645
1177
  async function flushInner(opts) {
646
1178
  if (getState()?.dead)
647
1179
  return false;
648
- const pendingClear = await drainPending();
1180
+ recoverAllocations(true);
1181
+ if (pendingAllocations.size)
1182
+ await allocatePending();
1183
+ if (pendingAllocations.size)
1184
+ return false;
1185
+ const chunksClear = await drainPending();
1186
+ // A leaving page cannot finish an image upload; the blob journal keeps it for the next document.
1187
+ const imagesClear = opts.keepalive ? getImages().length === 0 : await drainImages();
1188
+ const pendingClear = chunksClear && imagesClear;
649
1189
  if (!pendingClear)
650
1190
  scheduleFlush();
651
1191
  const rec = getState();
@@ -681,6 +1221,7 @@ async function flushInner(opts) {
681
1221
  batchBytes += b;
682
1222
  }
683
1223
  if (oversized.size) {
1224
+ clearStoredCaptures(rec.sessionId, oversized);
684
1225
  setBuffer(getBuffer().filter((ev) => !oversized.has(ev.seq)));
685
1226
  if (!batch.length) {
686
1227
  scheduleFlush();
@@ -711,21 +1252,32 @@ async function flushInner(opts) {
711
1252
  if (movedOn(rec))
712
1253
  return true;
713
1254
  noteSync();
714
- serverMaxSeq = Math.max(serverMaxSeq, batch[batch.length - 1]?.seq ?? serverMaxSeq);
1255
+ serverMaxSeq = Math.max(serverMaxSeq, ...batch.map((event) => event.seq));
715
1256
  notify();
716
1257
  // Remove EXACTLY the sent seqs — events pushed during the in-flight POST survive.
717
1258
  const sent = new Set(batch.map((e) => e.seq));
1259
+ clearStoredCaptures(rec.sessionId, sent);
718
1260
  const rest = getBuffer().filter((e) => !sent.has(e.seq));
719
1261
  setBuffer(rest);
1262
+ // An acknowledged attachment row: its bytes are the server's now.
1263
+ for (const seq of sent) {
1264
+ const key = rowBlobs.get(seq);
1265
+ if (key === undefined)
1266
+ continue;
1267
+ rowBlobs.delete(seq);
1268
+ forgetBlob(key);
1269
+ }
720
1270
  if (rest.length)
721
1271
  scheduleFlush();
722
1272
  return true;
723
1273
  }
724
- /** Drain until buffer + chunks are empty or the deadline passes. */
1274
+ /** Drain until buffer, chunks and images are empty or the deadline passes. */
725
1275
  export async function drainBuffer(deadlineMs = 60000) {
726
1276
  const t0 = Date.now();
727
1277
  while (Date.now() - t0 < deadlineMs) {
728
- if (getBuffer().length === 0 && getChunks().length === 0)
1278
+ // A peer may journal its departure after an already-running flush scanned storage.
1279
+ recoverAllocations(true);
1280
+ if (queuedCount() === 0)
729
1281
  return true;
730
1282
  const sent = await flush();
731
1283
  if (getState()?.dead)
@@ -738,8 +1290,21 @@ export async function drainBuffer(deadlineMs = 60000) {
738
1290
  }
739
1291
  /** Reset buffers for a fresh session. */
740
1292
  export function resetQueues() {
1293
+ for (const key of allocatedCaptures.keys())
1294
+ kv().remove(key);
1295
+ for (const item of pendingAllocations)
1296
+ kv().remove(item.key);
1297
+ allocatedCaptures.clear();
1298
+ pendingAllocations.clear();
1299
+ allocationBytes = allocationChunks = 0;
741
1300
  setBuffer([]);
742
1301
  setChunks([]);
1302
+ // The journaled bytes go with pruneBlobJournal (the lifecycle knows which session ended).
1303
+ imageBlobs.clear();
1304
+ unjournaled.clear();
1305
+ rowBlobs.clear();
1306
+ readFailures.clear();
1307
+ setImages([]);
743
1308
  }
744
1309
  /**
745
1310
  * Forget this tab's buffers WITHOUT writing storage: another tab owns the
@@ -753,6 +1318,13 @@ function dropLocalTail() {
753
1318
  bufferCache = [];
754
1319
  chunkCache = [];
755
1320
  chunkBytes = 0;
1321
+ imageCache = [];
1322
+ imageBlobs.clear();
1323
+ unjournaled.clear();
1324
+ rowBlobs.clear();
1325
+ pendingAllocations.clear();
1326
+ allocationBytes = allocationChunks = 0;
1327
+ allocatedCaptures.clear();
756
1328
  tailDropped = true;
757
1329
  }
758
1330
  /** Test-only: drop all module state so suites cannot leak into each other. */
@@ -762,6 +1334,12 @@ export function __resetForTests() {
762
1334
  kv().remove('rec');
763
1335
  kv().remove('buffer');
764
1336
  kv().remove('chunks');
1337
+ kv().remove('images');
1338
+ kv().remove(BLOBS_KEY);
1339
+ kv().remove('seq');
1340
+ for (const key of kv().keys?.() ?? [])
1341
+ if (key.startsWith(ALLOCATION_PREFIX))
1342
+ kv().remove(key);
765
1343
  resetIdle();
766
1344
  }
767
1345
  /** Test-only: the recorded events currently buffered (in order). */
@@ -772,8 +1350,17 @@ export function __bufferForTests() {
772
1350
  export function __chunksForTests() {
773
1351
  return getChunks().map((c) => ({ seq: c.seq, count: c.count, sessionId: c.sessionId }));
774
1352
  }
1353
+ /** Test-only: the images waiting for upload (in order), with their blob journal keys. */
1354
+ export function __imagesForTests() {
1355
+ return getImages().map((i) => ({ seq: i.seq, sessionId: i.sessionId, blob: i.blob, name: i.payload.name }));
1356
+ }
775
1357
  /** Test-only: drop the in-memory caches while LEAVING storage intact (a reload). */
776
1358
  export function __dropCachesForTests() {
1359
+ pendingAllocations.clear();
1360
+ allocationBytes = allocationChunks = 0;
1361
+ allocatedCaptures.clear();
1362
+ allocationsRecovered = false;
1363
+ allocationBusy = null;
777
1364
  if (persistTimer) {
778
1365
  clearTimeout(persistTimer);
779
1366
  persistTimer = null;
@@ -792,6 +1379,12 @@ export function __dropCachesForTests() {
792
1379
  bufferCache = undefined;
793
1380
  chunkCache = undefined;
794
1381
  chunkBytes = 0;
1382
+ // A reload keeps only what storage and the blob journal hold.
1383
+ imageCache = undefined;
1384
+ imageBlobs.clear();
1385
+ unjournaled.clear();
1386
+ rowBlobs.clear();
1387
+ readFailures.clear();
795
1388
  disarmReconcile();
796
1389
  lastSyncAt = 0;
797
1390
  lastError = '';