tricache 1.0.2 → 2.0.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 (101) hide show
  1. package/README.md +78 -90
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/{cache-service-CWI4jkS7.d.cts → cache-service-BV5T8-20.d.cts} +122 -21
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-B108FzER.d.ts → cache-service-tpyrXvlH.d.ts} +122 -21
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-H4GFLQ26.js → chunk-KV7KISK2.js} +47 -1
  10. package/dist/{chunk-WYF7NOAT.js → chunk-MB3DMVWN.js} +2111 -543
  11. package/dist/{chunk-OYDU3SMI.js → chunk-RBJRTGFK.js} +5 -0
  12. package/dist/chunk-S5N65I45.js +17 -0
  13. package/dist/cli.cjs +2454 -572
  14. package/dist/cli.js +186 -11
  15. package/dist/dashboard/index.d.cts +2 -2
  16. package/dist/dashboard/index.d.ts +2 -2
  17. package/dist/drizzle/index.cjs +2335 -571
  18. package/dist/drizzle/index.d.cts +2 -2
  19. package/dist/drizzle/index.d.ts +2 -2
  20. package/dist/drizzle/index.js +6 -2
  21. package/dist/edge/index.cjs +145 -43
  22. package/dist/edge/index.d.cts +11 -4
  23. package/dist/edge/index.d.ts +11 -4
  24. package/dist/edge/index.js +118 -43
  25. package/dist/hono/index.cjs +2322 -569
  26. package/dist/hono/index.d.cts +2 -2
  27. package/dist/hono/index.d.ts +2 -2
  28. package/dist/hono/index.js +2 -2
  29. package/dist/{hono-C886ok3X.d.cts → hono-CMv2VdQ6.d.cts} +18 -5
  30. package/dist/{hono-3rDMYVtY.d.ts → hono-Dvq04kX9.d.ts} +18 -5
  31. package/dist/http/index.cjs +2323 -570
  32. package/dist/http/index.d.cts +3 -3
  33. package/dist/http/index.d.ts +3 -3
  34. package/dist/http/index.js +4 -4
  35. package/dist/index.cjs +2554 -620
  36. package/dist/index.d.cts +88 -23
  37. package/dist/index.d.ts +88 -23
  38. package/dist/index.js +873 -16
  39. package/dist/{murmur3-CMGw9PbV.d.cts → murmur3-DF8BFRnu.d.cts} +1 -0
  40. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.ts} +1 -0
  41. package/dist/nestjs/index.cjs +2292 -574
  42. package/dist/nestjs/index.d.cts +19 -5
  43. package/dist/nestjs/index.d.ts +19 -5
  44. package/dist/nestjs/index.js +25 -19
  45. package/dist/next/index.cjs +2306 -571
  46. package/dist/next/index.d.cts +8 -2
  47. package/dist/next/index.d.ts +8 -2
  48. package/dist/next/index.js +36 -9
  49. package/dist/prisma/index.cjs +26 -25
  50. package/dist/prisma/index.d.cts +2 -2
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +14 -25
  53. package/dist/serialize-worker.cjs +162 -39
  54. package/dist/serialize-worker.js +9 -7
  55. package/dist/{types-BA4pz1A0.d.cts → types-F8vRWMrE.d.cts} +162 -45
  56. package/dist/{types-BA4pz1A0.d.ts → types-F8vRWMrE.d.ts} +162 -45
  57. package/package.json +21 -2
  58. package/src/adapters/auto-pipeliner.ts +52 -11
  59. package/src/cache-service.ts +1537 -415
  60. package/src/cli.ts +2 -9
  61. package/src/codec.ts +3 -3
  62. package/src/compression.ts +39 -16
  63. package/src/cross-region.ts +1 -1
  64. package/src/disk-tier.ts +283 -43
  65. package/src/drizzle/index.ts +2 -1
  66. package/src/edge/adapters/cloudflare-do.ts +25 -10
  67. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  68. package/src/edge/adapters/upstash.ts +27 -11
  69. package/src/edge/cache.ts +59 -17
  70. package/src/edge/types.ts +15 -5
  71. package/src/encryption.ts +50 -18
  72. package/src/env.d.ts +1 -1
  73. package/src/errors.ts +12 -0
  74. package/src/http/utils.ts +6 -0
  75. package/src/index.ts +6 -0
  76. package/src/latency-watchdog.ts +5 -1
  77. package/src/nestjs/decorators.ts +11 -6
  78. package/src/nestjs/tricache.module.ts +2 -1
  79. package/src/nestjs/tricache.store.ts +21 -9
  80. package/src/nestjs/types.ts +1 -1
  81. package/src/next/cache-handler.ts +24 -4
  82. package/src/next/types.ts +4 -0
  83. package/src/origin-capacity.ts +134 -0
  84. package/src/prisma/index.ts +14 -32
  85. package/src/remote-snapshot.ts +37 -27
  86. package/src/serialize-worker.ts +8 -5
  87. package/src/sigv4-snapshot-adapter.ts +37 -27
  88. package/src/smart-memory-cache.ts +62 -22
  89. package/src/types.ts +92 -35
  90. package/src/utils/config-comparison.ts +29 -0
  91. package/src/utils/lz4-size.ts +74 -0
  92. package/src/utils/namespace-key.ts +48 -0
  93. package/src/utils/query-key.ts +13 -0
  94. package/src/utils/snapshot-transfer.ts +83 -0
  95. package/src/utils/work-limits.ts +73 -0
  96. package/src/utils/write-revision.ts +4 -0
  97. package/src/wasm/bloom-filter-wasm.ts +16 -1
  98. package/src/worker-pool.ts +28 -8
  99. package/src/wtiny-lfu.ts +62 -14
  100. package/dist/cache-service-GYPZFB7O.js +0 -12
  101. package/dist/chunk-VNRDL5RA.js +0 -666
package/src/disk-tier.ts CHANGED
@@ -21,6 +21,8 @@ import os from 'os';
21
21
  import { CacheCodec, defaultCodec } from './codec.js';
22
22
  import type { DiskCacheEntry, ILogger, DiskBackpressureStats } from './types.js';
23
23
  import type { CacheEncryption } from './encryption.js';
24
+ import { encodeNamespaceSegment } from './utils/namespace-key.js';
25
+ import { isWriteRevision } from './utils/write-revision.js';
24
26
  import {
25
27
  compressWithHeader,
26
28
  decompressWithHeader,
@@ -44,6 +46,7 @@ export class BoundedDiskQueue {
44
46
  private consecutiveFailures = 0;
45
47
  private circuitState: 'closed' | 'open' | 'half-open' = 'closed';
46
48
  private lastStateChangeMonotonic = performance.now();
49
+ private readonly idleWaiters = new Set<() => void>();
47
50
 
48
51
  constructor(
49
52
  private readonly maxConcurrent: number = Math.min(4, Math.max(1, Math.floor((os?.availableParallelism?.() ?? 4) / 4))),
@@ -71,6 +74,30 @@ export class BoundedDiskQueue {
71
74
  // Transfer the reservation so newly arriving calls cannot steal a queued slot.
72
75
  if (next) next(true);
73
76
  else this.active--;
77
+ if (this.active === 0 && this.queue.length === 0) {
78
+ for (const resolve of this.idleWaiters) resolve();
79
+ this.idleWaiters.clear();
80
+ }
81
+ }
82
+
83
+ /** Wait for physical work, not caller promises that may already have timed out. */
84
+ async drain(timeoutMs = 8_000): Promise<boolean> {
85
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) throw new Error('Drain timeout must be finite and non-negative');
86
+ if (this.active === 0 && this.queue.length === 0) return true;
87
+ return new Promise<boolean>(resolve => {
88
+ let settled = false;
89
+ const finish = (idle: boolean) => {
90
+ if (settled) return;
91
+ settled = true;
92
+ clearTimeout(timer);
93
+ this.idleWaiters.delete(onIdle);
94
+ resolve(idle);
95
+ };
96
+ const onIdle = () => finish(true);
97
+ const timer = setTimeout(() => finish(false), timeoutMs);
98
+ this.idleWaiters.add(onIdle);
99
+ if (this.active === 0 && this.queue.length === 0) onIdle();
100
+ });
74
101
  }
75
102
 
76
103
  public async schedule<T>(task: () => Promise<T>): Promise<T | null> {
@@ -157,6 +184,19 @@ export class BoundedDiskQueue {
157
184
  };
158
185
  }
159
186
 
187
+ /** Resolve when every admitted physical task, including timed-out callers, settles. */
188
+ public whenIdle(): Promise<void> {
189
+ if (this.active === 0 && this.queue.length === 0) return Promise.resolve();
190
+ return new Promise(resolve => {
191
+ const onIdle = () => {
192
+ this.idleWaiters.delete(onIdle);
193
+ resolve();
194
+ };
195
+ this.idleWaiters.add(onIdle);
196
+ if (this.active === 0 && this.queue.length === 0) onIdle();
197
+ });
198
+ }
199
+
160
200
  public reset(): void {
161
201
  this.consecutiveFailures = 0;
162
202
  this.circuitState = 'closed';
@@ -227,7 +267,7 @@ const DISK_TIER_VERSION = 1;
227
267
  */
228
268
  export function resolveDefaultDiskDir(namespace?: string, logger?: ILogger): { dir: string; isShm: boolean } {
229
269
  const ns = namespace?.trim() ?? '';
230
- const nsDir = ns ? `tricache-disk-${ns}` : 'tricache-disk';
270
+ const nsDir = `tricache-disk-v3-${encodeNamespaceSegment(ns)}`;
231
271
 
232
272
  if (process.platform === 'linux') {
233
273
  const shmPath = '/dev/shm';
@@ -297,9 +337,12 @@ export class DiskTier {
297
337
  private reservedFiles = 0;
298
338
  private saveSequence = 0;
299
339
  private epoch = 0;
300
- private readonly pendingSaves = new Map<string, { token: symbol; setAt: number }>();
340
+ private readonly pendingSaves = new Map<string, { token: symbol; setAt: number; revision?: string }>();
301
341
  private closed = false;
302
342
  private readonly invalidatedKeys = new Set<string>();
343
+ /** Hash buckets are bounded to 256; successful creation can be reused between spills. */
344
+ private readonly readyBuckets = new Set<string>();
345
+ private readonly pendingBuckets = new Map<string, Promise<void>>();
303
346
  /** Next bucket index (0–255) for the staggered janitor wheel. */
304
347
  private _nextJanitorBucket = 0;
305
348
 
@@ -349,6 +392,21 @@ export class DiskTier {
349
392
  }
350
393
  }
351
394
 
395
+ private ensureBucket(hash: string): Promise<void> {
396
+ const bucket = hash.slice(0, 2);
397
+ if (this.readyBuckets.has(bucket)) return Promise.resolve();
398
+ const pending = this.pendingBuckets.get(bucket);
399
+ if (pending) return pending;
400
+ const creation = Promise.resolve().then(async () => {
401
+ await fs.promises.mkdir(path.join(this.opts.dir, bucket), { recursive: true });
402
+ if (!this.closed) this.readyBuckets.add(bucket);
403
+ }).finally(() => {
404
+ if (this.pendingBuckets.get(bucket) === creation) this.pendingBuckets.delete(bucket);
405
+ });
406
+ this.pendingBuckets.set(bucket, creation);
407
+ return creation;
408
+ }
409
+
352
410
  /**
353
411
  * Initialise the SQLite metadata index. Called once after the cache directory
354
412
  * is confirmed to exist. On any failure the instance silently falls back to
@@ -461,12 +519,18 @@ export class DiskTier {
461
519
  *
462
520
  * 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
463
521
  */
464
- private hashToWritePath(hash: string, expiresAt: number, setAt?: number): string {
522
+ private hashToWritePath(hash: string, expiresAt: number, setAt?: number, revision?: string): string {
465
523
  const expiry = Math.floor(expiresAt).toString(16).padStart(12, '0');
466
524
  if (setAt === undefined) return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}`);
467
525
  const written = Math.floor(setAt).toString(16).padStart(12, '0');
468
526
  const sequence = (++this.saveSequence).toString(16).padStart(12, '0');
469
- return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${crypto.randomBytes(6).toString('hex')}`);
527
+ const identity = revision ? this.revisionSuffix(revision) : '';
528
+ return path.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiry}_${written}_${sequence}_${crypto.randomBytes(6).toString('hex')}${identity}`);
529
+ }
530
+
531
+ /** Fixed, path-safe suffix lets cleanup select a revision without decoding its payload. */
532
+ private revisionSuffix(revision: string): string {
533
+ return `_r${crypto.createHash('sha256').update(revision).digest('hex')}`;
470
534
  }
471
535
 
472
536
  private findFilePaths(hash: string): string[] {
@@ -558,9 +622,9 @@ export class DiskTier {
558
622
  * magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
559
623
  * Returns the buffer unchanged when no encryption instance is configured.
560
624
  */
561
- private encryptV2(data: Buffer): Buffer {
625
+ private encryptV2(data: Buffer, key: string): Buffer {
562
626
  if (!this.opts.encryption) return data;
563
- return this.opts.encryption.encryptBuffer(data);
627
+ return this.opts.encryption.encryptBuffer(data, JSON.stringify(['tricache-disk-v2', key]));
564
628
  }
565
629
 
566
630
  /**
@@ -569,9 +633,9 @@ export class DiskTier {
569
633
  * CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
570
634
  * without one the payload is raw msgpack.
571
635
  */
572
- private decryptV2(inner: Buffer): Buffer {
636
+ private decryptV2(inner: Buffer, key: string): Buffer {
573
637
  if (!this.opts.encryption) return inner;
574
- return this.opts.encryption.decryptBuffer(inner);
638
+ return this.opts.encryption.decryptBuffer(inner, JSON.stringify(['tricache-disk-v2', key]));
575
639
  }
576
640
 
577
641
  // ── Public API ────────────────────────────────────────────────────────────
@@ -579,19 +643,20 @@ export class DiskTier {
579
643
  /**
580
644
  * Spill an evicted L1 entry to disk.
581
645
  *
582
- * Returns a Promise that resolves when the file is durably written. Callers
646
+ * Returns after the queue caller completes or times out; this is not an fsync
647
+ * durability guarantee. drain() separately waits for physical work. Callers
583
648
  * that treat the spill as fire-and-forget should do:
584
649
  * `void disk.save(key, entry)`
585
650
  *
586
651
  * Implementation notes:
587
- * - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
588
- * sub-millisecond for entries up to diskEntryMaxBytes, and do not block
589
- * on any external resource.
590
- * - The actual write syscall (mkdir + writeFile) is async via fs.promises,
591
- * so the Node.js event loop is never stalled waiting for disk I/O.
652
+ * - Serialization/compression/encryption run synchronously; CPU cost depends
653
+ * on payload shape and size. Index and version-cleanup work can also block.
654
+ * - Staging writes and rename use fs.promises. Bucket creation is coalesced,
655
+ * and failed staging cleanup has one owner in the physical task's finally.
592
656
  */
593
657
  async save(key: string, entry: DiskCacheEntry): Promise<void> {
594
658
  if (this.closed || this.diskQueue.isSaturated) return;
659
+ if (entry.revision !== undefined && !isWriteRevision(entry.revision)) return;
595
660
  if (this.isForbidden(key)) return;
596
661
  if (entry.expiresAt <= Date.now()) return;
597
662
 
@@ -642,7 +707,7 @@ export class DiskTier {
642
707
  const header = Buffer.allocUnsafe(V2_HEADER_LEN);
643
708
  DISK_MAGIC_V2.copy(header, 0);
644
709
  header.writeBigUInt64LE(BigInt(Math.floor(entry.expiresAt)), 8);
645
- final = Buffer.concat([header, this.encryptV2(toEncrypt)]);
710
+ final = Buffer.concat([header, this.encryptV2(toEncrypt, key)]);
646
711
  if (final.length > this.opts.entryMaxBytes || this.diskUsageBytes + this.reservedBytes + final.length > this.opts.maxBytes) return;
647
712
  } catch (err) {
648
713
  this.opts.logger.debug('DiskTier: pack/encrypt failed', { key: key.slice(0, 50), error: (err as Error).message });
@@ -653,11 +718,11 @@ export class DiskTier {
653
718
  const hash = this.keyToHash(key);
654
719
  const setAt = entry.setAt ?? Date.now();
655
720
  if ((this.pendingSaves.get(key)?.setAt ?? 0) > setAt) return;
656
- const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt);
721
+ const filePath = this.hashToWritePath(hash, entry.expiresAt, setAt, entry.revision);
657
722
  const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`;
658
723
  const token = Symbol(key);
659
724
  const epoch = this.epoch;
660
- this.pendingSaves.set(key, { token, setAt });
725
+ this.pendingSaves.set(key, { token, setAt, revision: entry.revision });
661
726
  const current = () => !this.closed && this.epoch === epoch && this.pendingSaves.get(key)?.token === token;
662
727
  let started = false;
663
728
  let released = false;
@@ -680,12 +745,25 @@ export class DiskTier {
680
745
 
681
746
  const result = await this.diskQueue.schedule(async () => {
682
747
  started = true;
748
+ let cleanupTemporary = false;
683
749
  try {
684
750
  if (!current()) return false;
685
751
  const previous = this.findFilePath(hash);
686
752
  if (previous && this.fileWrittenAt(previous) > setAt) return false;
687
- await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
688
- await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
753
+ await this.ensureBucket(hash);
754
+ if (!current()) return false;
755
+ cleanupTemporary = true; // A failed write can still leave a partial staging file.
756
+ try {
757
+ await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
758
+ } catch (writeError: unknown) {
759
+ // Another process/operator may remove a known bucket. Retry once after
760
+ // invalidating its cached readiness; do not retry other filesystem errors.
761
+ if ((writeError as { code?: string })?.code !== 'ENOENT' || !current()) throw writeError;
762
+ this.readyBuckets.delete(hash.slice(0, 2));
763
+ await this.ensureBucket(hash);
764
+ if (!current()) return false;
765
+ await fs.promises.writeFile(tmpPath, final, { mode: 0o600 });
766
+ }
689
767
  if (!current()) return false;
690
768
 
691
769
  // Atomic rename with micro-retry loop for Windows NTFS handle release
@@ -700,6 +778,7 @@ export class DiskTier {
700
778
  throw renameErr;
701
779
  }
702
780
  }
781
+ cleanupTemporary = false; // Successful rename consumed the staging path.
703
782
 
704
783
  if (!current()) {
705
784
  try { await fs.promises.unlink(filePath); } catch { /* already removed */ }
@@ -723,12 +802,13 @@ export class DiskTier {
723
802
  this.opts.logger.debug('DiskTier: entry saved', { key: key.slice(0, 50), bytes: final.length });
724
803
  return true;
725
804
  } catch (err) {
726
- try { await fs.promises.unlink(tmpPath); } catch { /* ignore if already gone/failed */ }
727
805
  if (accounted) this.removeFile(filePath);
728
806
  this.opts.logger.debug('DiskTier: save failed', { key: key.slice(0, 50), error: (err as Error).message });
729
807
  throw err;
730
808
  } finally {
731
- try { await fs.promises.unlink(tmpPath); } catch { /* renamed, removed, or never created */ }
809
+ if (cleanupTemporary) {
810
+ try { await fs.promises.unlink(tmpPath); } catch { /* removed, partially created, or never created */ }
811
+ }
732
812
  releaseReservation();
733
813
  if (this.invalidatedKeys.has(key) && !this.pendingSaves.has(key)) this.delete(key, true);
734
814
  }
@@ -793,6 +873,7 @@ export class DiskTier {
793
873
  if (stat.size > this.opts.entryMaxBytes) {
794
874
  fs.unlinkSync(filePath);
795
875
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
876
+ this.fileCount = Math.max(0, this.fileCount - 1);
796
877
  if (this._db) this._stmtDelete!.run(hash);
797
878
  return null;
798
879
  }
@@ -801,41 +882,162 @@ export class DiskTier {
801
882
  // Delete immediately — entry will be promoted back to L1
802
883
  for (const storedPath of this.findFilePaths(hash)) this.removeFile(storedPath);
803
884
  if (this._db) this._stmtDelete!.run(hash);
885
+ return this.decodeLoadedPayload(key, raw);
886
+ } catch (err) {
887
+ if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
888
+ this.opts.logger.debug('DiskTier: load failed', { key: key.slice(0, 50), error: (err as Error).message });
889
+ return null;
890
+ }
891
+ }
804
892
 
805
- let decrypted: Buffer;
806
- if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
807
- // V2/V3: quick expiry guard from plaintext header before paying decrypt cost
808
- const expiresAt = Number(raw.readBigUInt64LE(8));
809
- if (expiresAt <= Date.now()) return null;
810
- try { decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN)); } catch { return null; }
811
- } else {
812
- // V1 / legacy unencrypted — backward compat
813
- try { decrypted = this.decrypt(raw); } catch { return null; }
893
+ /**
894
+ * Async variant of load() for the SQLite-indexed path.
895
+ *
896
+ * Disk hits sit directly on the request path in front of Redis. The sync
897
+ * load() above blocks the event loop for readdir/stat/read/unlink; under
898
+ * concurrent pressure those small stalls add up to tail latency. This
899
+ * variant keeps the same consume-on-read and validation semantics but uses
900
+ * fs.promises, and only removes the indexed file instead of scanning the
901
+ * whole bucket. Superseded files remain unreachable through the index and
902
+ * are removed by the existing expiry janitor.
903
+ *
904
+ * File-only mode (no node:sqlite) falls back to the synchronous path.
905
+ */
906
+ async loadAsync(key: string): Promise<DiskCacheEntry | null> {
907
+ if (this.invalidatedKeys.has(key) || this.closed) return null;
908
+ if (this.isForbidden(key)) return null;
909
+ this.ensureDir();
910
+ if (!this.dirReady) return null;
911
+ if (!this._db) return this.load(key);
912
+
913
+ const hash = this.keyToHash(key);
914
+ let row: { file_path: string; expires_at: number } | undefined;
915
+ try {
916
+ row = this._stmtSelect!.get(hash) as { file_path: string; expires_at: number } | undefined;
917
+ } catch { return null; }
918
+ if (!row) return null;
919
+
920
+ if (row.expires_at <= Date.now()) {
921
+ if (this.deleteIndexRowIfCurrent(hash, row.file_path)) {
922
+ try {
923
+ const stat = await fs.promises.stat(row.file_path);
924
+ await fs.promises.unlink(row.file_path);
925
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - stat.size);
926
+ this.fileCount = Math.max(0, this.fileCount - 1);
927
+ } catch { /* already gone */ }
814
928
  }
929
+ return null;
930
+ }
815
931
 
816
- const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? 'brotli');
817
- const payload = this.codec.decode(uncompressed) as DiskPayload;
818
- if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
819
- if (payload.entry.expiresAt <= Date.now()) return null;
932
+ let raw: Buffer;
933
+ try {
934
+ // Match the synchronous loader's admission check before allocating the payload.
935
+ const stat = await fs.promises.stat(row.file_path);
936
+ if (stat.size > this.opts.entryMaxBytes) {
937
+ if (this.deleteIndexRowIfCurrent(hash, row.file_path)) {
938
+ try {
939
+ await fs.promises.unlink(row.file_path);
940
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - stat.size);
941
+ this.fileCount = Math.max(0, this.fileCount - 1);
942
+ } catch { /* already removed by another path */ }
943
+ }
944
+ return null;
945
+ }
946
+ raw = await fs.promises.readFile(row.file_path);
947
+ } catch {
948
+ // A newer spill may have replaced the row while readFile() ran. Only
949
+ // remove the row when it still describes the file that failed to read.
950
+ this.deleteIndexRowIfCurrent(hash, row.file_path);
951
+ return null;
952
+ }
953
+
954
+ // Consume the indexed file. Only the caller that still owns the row removes
955
+ // the file and adjusts accounting; a newer spill may have replaced it while
956
+ // readFile() ran, and that newer entry must remain readable.
957
+ if (this.deleteIndexRowIfCurrent(hash, row.file_path)) {
958
+ try {
959
+ await fs.promises.unlink(row.file_path);
960
+ this.diskUsageBytes = Math.max(0, this.diskUsageBytes - raw.length);
961
+ this.fileCount = Math.max(0, this.fileCount - 1);
962
+ } catch { /* already removed by another path */ }
963
+ }
820
964
 
821
- const entry = payload.entry;
822
- if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
965
+ // Recheck in case the file grew after stat() or the limit changed while reading.
966
+ if (raw.length > this.opts.entryMaxBytes) return null;
823
967
 
824
- this.opts.logger.debug('DiskTier: hit (→L1)', { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
825
- return entry;
968
+ try {
969
+ return this.decodeLoadedPayload(key, raw);
826
970
  } catch (err) {
827
- if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
828
971
  this.opts.logger.debug('DiskTier: load failed', { key: key.slice(0, 50), error: (err as Error).message });
829
972
  return null;
830
973
  }
831
974
  }
832
975
 
976
+ /**
977
+ * Delete the index row for `hash` only if it still points at `filePath`.
978
+ * The check and delete are synchronous, so a newer spill cannot slip between
979
+ * them. Returns true when this caller removed the row.
980
+ */
981
+ private deleteIndexRowIfCurrent(hash: string, filePath: string): boolean {
982
+ try {
983
+ const latest = this._stmtSelect!.get(hash) as { file_path: string } | undefined;
984
+ if (latest?.file_path !== filePath) return false;
985
+ this._stmtDelete!.run(hash);
986
+ return true;
987
+ } catch {
988
+ return false;
989
+ }
990
+ }
991
+
992
+ /** Decode and validate a raw disk payload. Callers own file cleanup. */
993
+ private decodeLoadedPayload(key: string, raw: Buffer): DiskCacheEntry | null {
994
+ let decrypted: Buffer;
995
+ if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
996
+ // V2/V3: quick expiry guard from plaintext header before paying decrypt cost
997
+ const expiresAt = Number(raw.readBigUInt64LE(8));
998
+ if (expiresAt <= Date.now()) return null;
999
+ try { decrypted = this.decryptV2(raw.subarray(V2_HEADER_LEN), key); } catch { return null; }
1000
+ } else {
1001
+ // V1 / legacy unencrypted — backward compat
1002
+ try { decrypted = this.decrypt(raw); } catch { return null; }
1003
+ }
1004
+
1005
+ const uncompressed = decompressWithHeader(decrypted, this.opts.compression ?? 'brotli');
1006
+ const payload = this.codec.decode(uncompressed) as DiskPayload;
1007
+ if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
1008
+ if (payload.entry.revision !== undefined && !isWriteRevision(payload.entry.revision)) return null;
1009
+ if (payload.entry.expiresAt <= Date.now()) return null;
1010
+
1011
+ const entry = payload.entry;
1012
+ if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
1013
+
1014
+ this.opts.logger.debug('DiskTier: hit (→L1)', { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
1015
+ return entry;
1016
+ }
1017
+
833
1018
  /** Synchronously fence queued/running saves while leaving filesystem cleanup deferred. */
834
1019
  invalidate(key: string): void {
835
1020
  this.pendingSaves.delete(key);
836
1021
  this.invalidatedKeys.add(key);
837
1022
  }
838
1023
 
1024
+ /** Cancel and remove only the observed write; newer pending or stored spills survive. */
1025
+ deleteIfRevision(key: string, revision: string): void {
1026
+ if (this.closed || !isWriteRevision(revision)) return;
1027
+ if (this.pendingSaves.get(key)?.revision === revision) this.pendingSaves.delete(key);
1028
+ const hash = this.keyToHash(key);
1029
+ const suffix = this.revisionSuffix(revision);
1030
+ const files = new Set(this.findFilePaths(hash));
1031
+ if (this._db) {
1032
+ const row = this._stmtSelect!.get(hash) as { file_path: string } | undefined;
1033
+ if (row?.file_path.endsWith(suffix)) {
1034
+ files.add(row.file_path);
1035
+ this._stmtDelete!.run(hash);
1036
+ }
1037
+ }
1038
+ for (const file of files) if (file.endsWith(suffix)) this.removeFile(file);
1039
+ }
1040
+
839
1041
  /** Delete all versions; deferred cleanup must not cancel a newer save. */
840
1042
  delete(key: string, invalidatedOnly = false): void {
841
1043
  if (invalidatedOnly && (!this.invalidatedKeys.has(key) || this.pendingSaves.has(key))) return;
@@ -1199,20 +1401,28 @@ export class DiskTier {
1199
1401
  while (!this.closed && this.diskUsageBytes > targetBytes) {
1200
1402
  const rows = this._stmtPruneChunk.all() as Array<{ key_hash: string; file_path: string; size: number }>;
1201
1403
  if (!rows || rows.length === 0) break;
1404
+ let progress = 0;
1202
1405
 
1203
1406
  for (const row of rows) {
1407
+ let removed = false;
1204
1408
  try {
1205
1409
  fs.unlinkSync(row.file_path);
1206
- } catch { /* already gone */ }
1410
+ removed = true;
1411
+ } catch (error) {
1412
+ // Only ENOENT proves the indexed file no longer occupies storage.
1413
+ if ((error as { code?: string }).code !== 'ENOENT') continue;
1414
+ }
1415
+ try { this._stmtDelete!.run(row.key_hash); }
1416
+ catch { continue; } // Keep conservative accounting if index cleanup fails.
1207
1417
  this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
1208
1418
  this.fileCount = Math.max(0, this.fileCount - 1);
1209
- this._entriesPruned++;
1210
- prunedInThisRound++;
1211
- try { this._stmtDelete!.run(row.key_hash); } catch { /* ok */ }
1419
+ progress++;
1420
+ if (removed) { this._entriesPruned++; prunedInThisRound++; }
1212
1421
 
1213
1422
  if (this.diskUsageBytes <= targetBytes) break;
1214
1423
  }
1215
1424
 
1425
+ if (progress === 0) break; // Permission/read-only errors must not create a retry loop.
1216
1426
  if (this.diskUsageBytes > targetBytes) {
1217
1427
  await new Promise<void>(resolve => setImmediate(resolve));
1218
1428
  }
@@ -1222,6 +1432,7 @@ export class DiskTier {
1222
1432
  const files = this.walkCacheFiles();
1223
1433
  if (files.length === 0) break;
1224
1434
  const chunk = files.slice(0, 500);
1435
+ let progress = 0;
1225
1436
 
1226
1437
  for (const filePath of chunk) {
1227
1438
  try {
@@ -1231,11 +1442,13 @@ export class DiskTier {
1231
1442
  this.fileCount = Math.max(0, this.fileCount - 1);
1232
1443
  this._entriesPruned++;
1233
1444
  prunedInThisRound++;
1445
+ progress++;
1234
1446
  } catch { /* already gone */ }
1235
1447
 
1236
1448
  if (this.diskUsageBytes <= targetBytes) break;
1237
1449
  }
1238
1450
 
1451
+ if (progress === 0) break;
1239
1452
  if (this.diskUsageBytes > targetBytes) {
1240
1453
  await new Promise<void>(resolve => setImmediate(resolve));
1241
1454
  }
@@ -1309,6 +1522,31 @@ export class DiskTier {
1309
1522
  return this.diskQueue;
1310
1523
  }
1311
1524
 
1525
+ /** Wait for admitted physical spill tasks, including work past its caller timeout. */
1526
+ async drain(timeoutMs = 8_000): Promise<boolean> {
1527
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) throw new Error('Drain timeout must be finite and non-negative');
1528
+ const deadline = performance.now() + timeoutMs;
1529
+ while (true) {
1530
+ const remaining = Math.max(0, deadline - performance.now());
1531
+ if (!await this.diskQueue.drain(remaining)) return false;
1532
+ // Slot release precedes save() reservation cleanup in its continuation.
1533
+ if (this.pendingSaves.size === 0 && this.diskQueue.getStats().activeWrites === 0 &&
1534
+ this.diskQueue.getStats().pendingWrites === 0) return true;
1535
+ if (performance.now() >= deadline) return false;
1536
+ await new Promise<void>(resolve => setImmediate(resolve));
1537
+ }
1538
+ }
1539
+
1540
+ /** Wait unboundedly for physical writes and their reservation cleanup before closing the index. */
1541
+ async whenIdle(): Promise<void> {
1542
+ while (true) {
1543
+ await this.diskQueue.whenIdle();
1544
+ await new Promise<void>(resolve => setImmediate(resolve));
1545
+ if (this.pendingSaves.size === 0 && this.pendingBuckets.size === 0 &&
1546
+ this.diskQueue.getStats().activeWrites === 0 && this.diskQueue.getStats().pendingWrites === 0) return;
1547
+ }
1548
+ }
1549
+
1312
1550
  /** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
1313
1551
  get indexMode(): 'sqlite' | 'file-only' {
1314
1552
  return this._db ? 'sqlite' : 'file-only';
@@ -1320,6 +1558,8 @@ export class DiskTier {
1320
1558
  this.epoch++;
1321
1559
  this.pendingSaves.clear();
1322
1560
  this.invalidatedKeys.clear();
1561
+ this.readyBuckets.clear();
1562
+ this.pendingBuckets.clear();
1323
1563
  if (this._db) {
1324
1564
  try { this._db.close(); } catch { /* ok */ }
1325
1565
  this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =
@@ -13,6 +13,7 @@
13
13
  import type { CacheService } from '../cache-service.js';
14
14
  import type { WrapOptions } from '../types.js';
15
15
  import crypto from 'crypto';
16
+ import { deterministicStringify } from '../utils/query-key.js';
16
17
 
17
18
  export interface DrizzleCacheOptions extends WrapOptions {
18
19
  /** TriCache instance to use. If omitted, uses process-level singleton `CacheService.create()`. */
@@ -31,7 +32,7 @@ export interface DrizzleExecutableQuery<T> {
31
32
  * Generate a deterministic SHA-256 hash key for a Drizzle query based on its compiled SQL and parameters.
32
33
  */
33
34
  export function generateDrizzleCacheKey(sqlInfo: { sql: string; params: unknown[] }): string {
34
- const normalized = JSON.stringify(sqlInfo);
35
+ const normalized = deterministicStringify({ sql: sqlInfo.sql, params: sqlInfo.params });
35
36
  const hash = crypto.createHash('sha256').update(normalized, 'utf8').digest('hex').slice(0, 32);
36
37
  return `drizzle:${hash}`;
37
38
  }
@@ -10,6 +10,7 @@ interface DOEntry {
10
10
  * Enables strongly-consistent edge caching and coordination across edge isolates.
11
11
  */
12
12
  export class CloudflareDOStorageAdapter implements IEdgeRemoteStorage {
13
+ readonly tagConsistency = 'atomic' as const;
13
14
  private readonly storage: CloudflareDOStorage;
14
15
 
15
16
  constructor(storage: CloudflareDOStorage) {
@@ -84,18 +85,32 @@ export class CloudflareDOStorageAdapter implements IEdgeRemoteStorage {
84
85
  await this.storage.put(record);
85
86
  }
86
87
 
87
- async clear(prefix?: string): Promise<void> {
88
- if (!this.storage.list) return;
88
+ async *scanKeys(prefix: string): AsyncIterable<string> {
89
+ if (!this.storage.list) throw new Error('Durable Object storage does not support list');
90
+ let startAfter: string | undefined;
91
+ while (true) {
92
+ const page = await this.storage.list({ prefix, startAfter, limit: 256 });
93
+ if (page.size === 0) return;
94
+ const keys = [...page.keys()];
95
+ for (const key of keys) if (key.startsWith(prefix)) yield key;
96
+ const next = keys[keys.length - 1];
97
+ if (next === startAfter) throw new Error('Durable Object list did not advance');
98
+ startAfter = next;
99
+ if (page.size < 256) return;
100
+ }
101
+ }
89
102
 
90
- const map = await this.storage.list({ prefix });
91
- const keysToDelete = Array.from(map.keys());
92
- if (keysToDelete.length > 0) {
93
- await this.storage.delete(keysToDelete);
103
+ async clear(prefix = ''): Promise<void> {
104
+ let keys: string[] = [];
105
+ for await (const key of this.scanKeys(prefix)) {
106
+ keys.push(key);
107
+ if (keys.length === 256) { await this.storage.delete(keys); keys = []; }
94
108
  }
109
+ if (keys.length) await this.storage.delete(keys);
95
110
  }
96
111
 
97
112
  async incrementTagVersion(tag: string): Promise<number> {
98
- const key = `tag_ver:${tag}`;
113
+ const key = tag;
99
114
  const raw = await this.storage.get<DOEntry>(key);
100
115
  const prev = (raw && typeof raw === 'object' && 'val' in raw)
101
116
  ? parseInt(raw.val, 10) || 0
@@ -106,7 +121,7 @@ export class CloudflareDOStorageAdapter implements IEdgeRemoteStorage {
106
121
  }
107
122
 
108
123
  async getTagVersion(tag: string): Promise<number> {
109
- const raw = await this.storage.get<DOEntry>(`tag_ver:${tag}`);
124
+ const raw = await this.storage.get<DOEntry>(tag);
110
125
  if (raw && typeof raw === 'object' && 'val' in raw) {
111
126
  return parseInt(raw.val, 10) || 1;
112
127
  }
@@ -114,11 +129,11 @@ export class CloudflareDOStorageAdapter implements IEdgeRemoteStorage {
114
129
  }
115
130
 
116
131
  async batchGetTagVersions(tags: string[]): Promise<Record<string, number>> {
117
- const keys = tags.map(t => `tag_ver:${t}`);
132
+ const keys = tags;
118
133
  const map = await this.storage.get<DOEntry>(keys);
119
134
  const result: Record<string, number> = {};
120
135
  for (const tag of tags) {
121
- const entry = map.get(`tag_ver:${tag}`);
136
+ const entry = map.get(tag);
122
137
  if (entry && typeof entry === 'object' && 'val' in entry) {
123
138
  result[tag] = parseInt(entry.val, 10) || 1;
124
139
  } else {