/** * SQLite Key-Value Store * * Core KV store built on better-sqlite3 with Redis-compatible interface. * Supports TTL expiration, optional encryption, and WAL mode. */ import type Database from 'better-sqlite3'; import { decryptValue, deriveEncryptionKey, encryptValue } from './encryption'; import { withBusyRetry } from './open-database'; import { acquireConnection, type SqliteConnection } from './sqlite-connection'; import type { SqliteDatabase, SqliteStatement } from './sqlite-driver'; import type { SqliteStorageOptions } from './sqlite.options'; /** Bundled prepared statements - all-or-nothing initialization. */ interface KvPreparedStatements { get: SqliteStatement; set: SqliteStatement; del: SqliteStatement; delExpired: SqliteStatement; has: SqliteStatement; keys: SqliteStatement; keysInRange: SqliteStatement; cleanup: SqliteStatement; ttl: SqliteStatement; expire: SqliteStatement; } /** One character of a LIKE pattern, with the `\` before it when there is one. */ const LIKE_TOKEN = /\\?./gsu; const ANY_CHARACTERS = Symbol('%'); const ONE_CHARACTER = Symbol('_'); /** A `\` that ends the pattern matches nothing, as in SQLite. */ const NO_CHARACTER = Symbol('\\'); const LAST_CODE_POINT = 0x10ffff; const FIRST_SURROGATE = 0xd800; const FIRST_AFTER_SURROGATES = 0xe000; /** A wildcard of a LIKE pattern, or the character a literal stands for. */ type LikeToken = string | typeof ANY_CHARACTERS | typeof ONE_CHARACTER | typeof NO_CHARACTER; /** One token of a LIKE pattern: a wildcard, or the character it matches. */ function parseLikeToken(token: string): LikeToken { if (token === '%') return ANY_CHARACTERS; if (token === '_') return ONE_CHARACTER; if (token === '\\') return NO_CHARACTER; return token.replace(/^\\/, ''); } /** A LIKE pattern (`%`, `_`, `\` before a literal character) as the text every match starts with, and its tokens. */ function parseLikePattern(pattern: string): { prefix: string; tokens: LikeToken[] } { const tokens = (pattern.match(LIKE_TOKEN) ?? []).map(parseLikeToken); const prefixLength = tokens.findIndex((token) => typeof token !== 'string'); const prefixTokens = prefixLength === -1 ? tokens : tokens.slice(0, prefixLength); return { prefix: prefixTokens.join(''), tokens }; } /** Whether `key` matches the tokens: a walk that returns to the last `%` on a mismatch, so key length times pattern length at worst. */ function matchesLikeTokens(tokens: LikeToken[], key: string): boolean { const characters = Array.from(key); let tokenIndex = 0; let characterIndex = 0; let lastAnyIndex = -1; let charactersLastAnyTook = 0; while (characterIndex < characters.length) { const token = tokens[tokenIndex]; if (token === ANY_CHARACTERS) { lastAnyIndex = tokenIndex++; charactersLastAnyTook = characterIndex; } else if (token === ONE_CHARACTER || token === characters[characterIndex]) { tokenIndex++; characterIndex++; } else if (lastAnyIndex === -1) { return false; } else { tokenIndex = lastAnyIndex + 1; characterIndex = ++charactersLastAnyTook; } } while (tokens[tokenIndex] === ANY_CHARACTERS) tokenIndex++; return tokenIndex === tokens.length; } /** The first string that sorts after every key starting with `prefix` (SQLite sorts UTF-8 text by code point), if any. */ function upperBoundOf(prefix: string): string | undefined { const codePoints = Array.from(prefix, (character) => character.codePointAt(0) ?? 0); while (codePoints.at(-1) === LAST_CODE_POINT) codePoints.pop(); const last = codePoints.pop(); if (last === undefined) return undefined; const next = last + 1 === FIRST_SURROGATE ? FIRST_AFTER_SURROGATES : last + 1; return String.fromCodePoint(...codePoints, next); } /** * SQLite-backed key-value store with TTL support and optional encryption. * * Schema: * ```sql * CREATE TABLE IF NOT EXISTS kv ( * key TEXT PRIMARY KEY, * value TEXT NOT NULL, * expires_at INTEGER -- Unix timestamp ms, NULL = no expiry * ); * ``` */ export class SqliteKvStore { private readonly connection: SqliteConnection; private readonly db: SqliteDatabase; private encryptionKey: Uint8Array | null = null; private cleanupTimer: ReturnType | null = null; private stmts: KvPreparedStatements | null = null; constructor(options: SqliteStorageOptions) { this.connection = acquireConnection(options.path, 'SqliteKvStore', { busyTimeoutMs: options.busyTimeoutMs, walMode: options.walMode !== false, }); this.db = this.connection.db; // Derive encryption key if secret provided if (options.encryption?.secret) { this.encryptionKey = deriveEncryptionKey(options.encryption.secret); } try { withBusyRetry(() => this.initSchema()); this.prepareStatements(); } catch (error) { this.connection.release(); throw error; } // Start periodic TTL cleanup const cleanupInterval = options.ttlCleanupIntervalMs ?? 60000; if (cleanupInterval > 0) { // Queued, so a lock held by another process neither blocks the event loop nor throws from the timer. this.cleanupTimer = setInterval( () => void this.connection.write(() => this.purgeExpired()).catch(() => undefined), cleanupInterval, ); // Allow the process to exit even if timer is running if (this.cleanupTimer.unref) { this.cleanupTimer.unref(); } } } private initSchema(): void { this.db.exec(` CREATE TABLE IF NOT EXISTS kv ( key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at INTEGER ); CREATE INDEX IF NOT EXISTS idx_kv_expires ON kv(expires_at) WHERE expires_at IS NOT NULL; `); } private prepareStatements(): void { this.stmts = { get: this.db.prepare('SELECT value, expires_at FROM kv WHERE key = ?'), set: this.db.prepare('INSERT OR REPLACE INTO kv (key, value, expires_at) VALUES (?, ?, ?)'), del: this.db.prepare('DELETE FROM kv WHERE key = ?'), delExpired: this.db.prepare('DELETE FROM kv WHERE key = ? AND expires_at IS NOT NULL AND expires_at <= ?'), has: this.db.prepare('SELECT 1 FROM kv WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)'), keys: this.db.prepare('SELECT key FROM kv WHERE (expires_at IS NULL OR expires_at > ?)'), keysInRange: this.db.prepare( 'SELECT key FROM kv WHERE key >= ? AND key < ? AND (expires_at IS NULL OR expires_at > ?)', ), cleanup: this.db.prepare('DELETE FROM kv WHERE expires_at IS NOT NULL AND expires_at <= ?'), ttl: this.db.prepare('SELECT expires_at FROM kv WHERE key = ?'), expire: this.db.prepare('UPDATE kv SET expires_at = ? WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)'), }; } /** * Return prepared statements, throwing if not yet initialized. */ private prepared(): KvPreparedStatements { if (!this.stmts) { throw new Error('SqliteKvStore: prepared statements not initialized. Was prepareStatements() called?'); } return this.stmts; } /** * Get a value by key. * Returns null if key doesn't exist or is expired. */ get(key: string): string | null { const stmts = this.prepared(); const row = stmts.get.get(key) as { value: string; expires_at: number | null } | undefined; if (!row) return null; // Check TTL const now = Date.now(); if (row.expires_at !== null && row.expires_at <= now) { stmts.delExpired.run(key, now); return null; } // Decrypt if encryption is enabled if (this.encryptionKey) { return decryptValue(this.encryptionKey, row.value); } return row.value; } /** * Get a value and parse it as JSON. */ getJSON(key: string): T | null { const value = this.get(key); if (value === null) return null; try { return JSON.parse(value) as T; } catch { // Return null if stored value is not valid JSON (e.g., corrupted or non-JSON string) return null; } } /** * Set a key-value pair with optional TTL. * * @param key - The key * @param value - The value to store * @param ttlMs - Time to live in milliseconds (optional) */ set(key: string, value: string, ttlMs?: number): void { const expiresAt = ttlMs !== undefined ? Date.now() + ttlMs : null; // Encrypt value if encryption is enabled const storedValue = this.encryptionKey ? encryptValue(this.encryptionKey, value) : value; this.prepared().set.run(key, storedValue, expiresAt); } /** * Set a key-value pair with JSON serialization and optional TTL. */ setJSON(key: string, value: unknown, ttlMs?: number): void { this.set(key, JSON.stringify(value), ttlMs); } /** * Delete a key. */ del(key: string): void { this.prepared().del.run(key); } /** * Check if a key exists (and is not expired). */ has(key: string): boolean { const row = this.prepared().has.get(key, Date.now()) as { 1: number } | undefined; return row !== undefined; } /** * List keys matching an optional glob-like pattern. * Pattern uses SQL LIKE syntax: `%` for any characters, `_` for single character, and `\` before a * character to match it literally. Letter case matters. No LIKE query is sent: the keys are selected * by the text the pattern starts with, through the primary key, and the pattern is applied here. * * @param pattern - Optional pattern (uses SQL LIKE syntax). Without pattern, returns all keys. * @returns Array of matching key strings */ keys(pattern?: string): string[] { const stmts = this.prepared(); const now = Date.now(); if (!pattern) return (stmts.keys.all(now) as { key: string }[]).map((r) => r.key); const { prefix, tokens } = parseLikePattern(pattern); const upperBound = upperBoundOf(prefix); const rows = upperBound === undefined ? stmts.keys.all(now) : stmts.keysInRange.all(prefix, upperBound, now); return (rows as { key: string }[]).map((r) => r.key).filter((key) => matchesLikeTokens(tokens, key)); } /** * Set TTL on an existing key. * * @param key - The key to set expiry on * @param ttlMs - Time to live in milliseconds * @returns true if key exists and TTL was set, false if key doesn't exist or has expired */ expire(key: string, ttlMs: number): boolean { const now = Date.now(); const result = this.prepared().expire.run(now + ttlMs, key, now); return result.changes > 0; } /** * Get remaining TTL for a key in milliseconds. * * @returns TTL in ms, -1 if no expiry, -2 if key doesn't exist */ ttl(key: string): number { const stmts = this.prepared(); const row = stmts.ttl.get(key) as { expires_at: number | null } | undefined; if (!row) return -2; if (row.expires_at === null) return -1; const now = Date.now(); const remaining = row.expires_at - now; if (remaining <= 0) { stmts.delExpired.run(key, now); return -2; } return remaining; } /** * Purge all expired keys. * Called periodically by the cleanup timer. */ purgeExpired(): number { const result = this.prepared().cleanup.run(Date.now()); return result.changes; } /** * Stop the cleanup timer and release the connection, which closes once no other store on the file uses it. */ close(): void { if (this.cleanupTimer) { clearInterval(this.cleanupTimer); this.cleanupTimer = null; } this.connection.release(); } /** * Get the underlying database instance (for advanced use cases / testing). * Other stores on the same file share it, so do not close it directly. * With a driver set by `useSqliteDriver()` it is the driver's database, which has the members of * `SqliteDatabase` only. */ getDatabase(): Database.Database { return this.db as Database.Database; } /** The connection this store shares with the other stores on its file, with its queue of operations. */ getConnection(): SqliteConnection { return this.connection; } }