2.2 KiB
replay
Purpose
Per-client LRU of (driveId, nonce) tuples used to reject replayed templates (DTP-06). The cache holds at most LRU_CAPACITY entries (default 1024); inserting a new entry that exceeds the cap evicts the least-recently-used one. The LRU is kept in-memory only; the spec calls out that Drive.initialize() rebuilds it from the FileLocationIndex.
Features
TemplateNonceLru— bounded LRU keyed on(driveId, nonce-hex).has(driveId, nonce)— query without mutation.remember(driveId, nonce)— insert; auto-evicts oldest past the cap.clear()/size/capacity— utility surface for tests + persistence hooks.TEMPLATE_NONCE_LRU_DEFAULT_CAPACITY— pinned at 1024 per DTP-06.
Usage: Basic Example
import { TemplateNonceLru } from "@suaveplan/drive-template";
const lru = new TemplateNonceLru();
lru.remember("drive-1", new Uint8Array(16).fill(7));
console.log(lru.has("drive-1", new Uint8Array(16).fill(7))); // true
Usage: Advanced Example
import {
TEMPLATE_NONCE_LRU_DEFAULT_CAPACITY,
TemplateNonceLru,
} from "@suaveplan/drive-template";
const lru = new TemplateNonceLru(TEMPLATE_NONCE_LRU_DEFAULT_CAPACITY);
async function rebuildFromFileLocationIndex(seen: Iterable<{ driveId: string; nonce: Uint8Array }>) {
lru.clear();
for (const entry of seen) {
lru.remember(entry.driveId, entry.nonce);
}
return lru.size;
}
API Reference
class TemplateNonceLru—has,remember,clear,size,capacity.TEMPLATE_NONCE_LRU_DEFAULT_CAPACITY: 1024.
Implementation Notes
The implementation uses an insertion-ordered Map and re-inserts duplicates on remember to refresh recency. The keys are <driveId>:<nonce-hex> strings rather than tuple objects so Map's === equality works without needing a custom key class. The capacity check fires AFTER the insert so the eviction policy is "drop the actual oldest", not "drop the entry we're about to overwrite" — this matters when a template re-uses the same (driveId, nonce) shortly after another distribution. Persistence support lives in Drive.initialize() rather than this module: the LRU rebuilds from the FileLocationIndex on startup so a process restart does not open a replay window.