/**
* Disk-backed offline buffer queue — TypeScript parallel of
* `edge-client/src/buffer/queue.rs` (in-memory queue with the disk-persist
* half) and `edge-client/src/buffer/disk_dump.rs` (AES-256-GCM envelope).
*
* This is the OFFLINE RESILIENCE LAYER: when the WS connection is down,
* stream frames are durably written to disk; on reconnect they replay in
* order; no frames lost on crash.
*
* ## On-disk format (mirrors Rust `DiskDumper`)
*
* [KEY_VERSION: 1 byte][AES-256-GCM nonce: 12 bytes][ciphertext + auth tag: 16 bytes]
*
* The plaintext is a JSON-encoded array of {@link QueueEntry} objects
* (`{ msg_id, timestamp, bytes }`), where `bytes` is base64-encoded.
*
* ## Atomic-write invariant (the project's hardest-won guarantee)
*
* 1. Serialize entries → encrypt → write to `
/.buffer.queue.enc.tmp`
* 2. `fsync` the temp file
* 3. `rename` tmp → `/buffer.queue.enc`
*
* Crash safety: a tmp file left on disk after a crash is half-written; we
* delete it on next lazy-load. The main file is either fully written or
* absent (the rename is atomic on POSIX and on Windows since Node 14+).
*
* ## Concurrency
*
* In-process serialization via a Promise-chain mutex. Cross-process locking
* is intentionally NOT implemented (would require `proper-lockfile` or
* similar; omitted to keep the dependency surface minimal — the in-process
* case is the common path).
*
* ## Dedup
*
* `append` silently skips when an entry with the same `msg_id` is already
* buffered. The Rust `BufferQueue::push` does not dedup, but the disk queue
* MUST dedup to avoid sending the same `msg_id` twice to the relay on
* reconnect (relay-side ACKs would otherwise race).
*/
import { KEY_VERSION } from '../crypto/aes-gcm.js';
/** One queued message awaiting replay. */
export interface QueueEntry {
/** Stable identifier used for dedup. */
msg_id: string;
/** Unix epoch milliseconds (sender-side ordering hint). */
timestamp: number;
/** Wire payload — encrypted at rest in the on-disk file. */
bytes: Uint8Array;
}
export interface DiskBufferQueueOptions {
/** Directory where the encrypted queue file lives. Created if missing. */
readonly dir: string;
/** 32-byte AES-256-GCM key (typically from `loadBufferKey(settings)`). */
readonly key: Uint8Array;
/**
* Soft cap on the serialized JSON envelope (plaintext bytes).
* Mirrors Rust `BufferConfig.max_memory_mb` (default 50 MiB).
*/
readonly maxBytes?: number;
}
/**
* Default cap — 50 MiB. Matches Rust `BufferConfig::default().max_memory_mb`.
*
* Eviction behavior (FIX 2026-07-14, F-21): when `append()` would push
* the buffer past this cap, the queue evicts the OLDEST entries (FIFO)
* to make room for new ones. This is intentional — the offline buffer
* is a lossy cache of inbound events that should never grow unbounded,
* but the operator can still see recent activity once the relay
* reconnects. Operators pushing high-frequency frames (>2 MiB at
* >10 Hz) should lower `maxBytes` via `buffer.max_memory_mb` in
* config.toml to reduce eviction churn.
*/
export declare const DEFAULT_MAX_BYTES: number;
/** Filename of the encrypted queue blob (relative to `dir`). */
export declare const QUEUE_FILE_NAME = "buffer.queue.enc";
/** Filename of the atomic-write temp file (relative to `dir`). */
export declare const QUEUE_TMP_NAME = ".buffer.queue.enc.tmp";
/** Thrown by {@link DiskBufferQueue.append} when the cap would be exceeded. */
export declare class BufferFullError extends Error {
readonly currentBytes: number;
readonly maxBytes: number;
constructor(currentBytes: number, maxBytes: number);
}
/**
* Single-file, AES-256-GCM-encrypted, FIFO buffer queue.
*
* Append-only on the hot path. `drain()` consumes every entry in FIFO order,
* hands each to a handler, and deletes the on-disk file when the handler
* completes successfully. `peek()` and `size()` are non-mutating.
*/
export declare class DiskBufferQueue {
private readonly dir;
private readonly filePath;
private readonly tmpPath;
private readonly key;
private readonly maxBytes;
/** In-memory cache. Loaded lazily on first op. */
private entries;
private loaded;
/** Promise-chain mutex for in-process serialization. */
private mutex;
constructor(opts: DiskBufferQueueOptions);
/**
* Append an entry to the queue. Skips silently when `entry.msg_id` is
* already buffered (dedup invariant). Throws {@link BufferFullError} when
* the serialized envelope would exceed `maxBytes`.
*/
append(entry: QueueEntry): Promise;
/**
* Return up to `limit` entries (FIFO order) without removing them.
* Defensive copy — callers may freely mutate the returned bytes.
*/
peek(limit: number): Promise;
/** Return the number of entries currently buffered. */
size(): Promise;
/**
* Delete all entries and the on-disk file. Idempotent — succeeds whether
* the file exists or not.
*/
clear(): Promise;
/**
* Invoke `handler(entry)` for every entry in FIFO order, then delete the
* on-disk file. Returns the number of entries processed. If the handler
* throws, the entries remain on disk for a future `drain()` retry
* (at-least-once semantics — matches the Rust offline-queue contract).
*/
drain(handler: (entry: QueueEntry) => Promise | void): Promise;
/**
* Lazily create the dir, recover from a prior crash (delete tmp), and
* load existing entries. Runs at most once per queue instance.
*/
private ensureLoaded;
/**
* Encrypt + atomic-write the in-memory entry list to disk.
*
* Sequence (mirrors Rust `atomic_write` in `disk_dump.rs:159-186`):
* 1. encrypt(plaintext) → `[version][nonce][ciphertext][tag]`
* 2. open tmp with mode 0600 (defense in depth — encryption protects
* contents either way)
* 3. write blob + fsync the file (force kernel buffers to disk)
* 4. rename tmp → final path (atomic on POSIX, atomic on Win since Node 14+)
*/
private persist;
private projectedBytesAfterAppend;
/** Serialize operations via a Promise chain (in-process mutex). */
private withLock;
private assertValidEntry;
private unlinkIfExists;
}
export { KEY_VERSION };