diff --git a/backend/src/lib/__tests__/cache.test.ts b/backend/src/lib/__tests__/cache.test.ts new file mode 100644 index 00000000..b9122d52 --- /dev/null +++ b/backend/src/lib/__tests__/cache.test.ts @@ -0,0 +1,265 @@ +/** + * backend/src/lib/__tests__/cache.test.ts + * + * Unit tests for the zero-dependency TTL + LRU cache (issue #2264). + * Every documented behaviour — defaults, validation, happy path, TTL expiry + * with an injectable clock, bounded LRU eviction, invalidation, malformed + * input, counters and observability — is pinned here. + */ + +import { + CacheErrorCode, + CacheError, + DEFAULT_CACHE_CONFIG, + noopCacheMetrics, + noopCacheLogger, + validateCacheConfig, + createTtlCache, +} from '../cache'; + +/** Assert that `fn` throws a CacheError carrying the expected stable code. */ +function expectCode(fn: () => unknown, code: string): void { + try { + fn(); + throw new Error('expected function to throw'); + } catch (error) { + expect((error as { code?: string }).code).toBe(code); + } +} + +describe('error surface and constants', () => { + it('exposes stable error codes', () => { + expect(CacheErrorCode.INVALID_CONFIG).toBe('INVALID_CONFIG'); + expect(CacheErrorCode.INVALID_KEY).toBe('INVALID_KEY'); + expect(CacheErrorCode.INVALID_TTL).toBe('INVALID_TTL'); + expect(CacheErrorCode.INVALID_VALUE).toBe('INVALID_VALUE'); + }); + + it('builds a typed CacheError with code and details', () => { + const error = new CacheError(CacheErrorCode.INVALID_KEY, 'bad key', { key: '' }); + expect(error instanceof Error).toBe(true); + expect(error instanceof CacheError).toBe(true); + expect(error.name).toBe('CacheError'); + expect(error.code).toBe('INVALID_KEY'); + expect(error.message).toBe('bad key'); + expect(error.details).toEqual({ key: '' }); + }); + + it('exposes frozen defaults and noop hooks', () => { + expect(Object.isFrozen(DEFAULT_CACHE_CONFIG)).toBe(true); + expect(DEFAULT_CACHE_CONFIG.maxEntries).toBe(500); + expect(DEFAULT_CACHE_CONFIG.defaultTtlMs).toBe(60000); + expect(typeof noopCacheMetrics.recordHit).toBe('function'); + expect(typeof noopCacheLogger.warn).toBe('function'); + }); +}); + +describe('validateCacheConfig', () => { + it('fills in documented defaults', () => { + const config = validateCacheConfig({}); + expect(config.maxEntries).toBe(500); + expect(config.defaultTtlMs).toBe(60000); + expect(typeof config.nowMs).toBe('function'); + expect(Object.isFrozen(config)).toBe(true); + }); + + it('preserves valid overrides and a custom clock', () => { + const clock = () => 42; + const config = validateCacheConfig({ maxEntries: 3, defaultTtlMs: 250, nowMs: clock }); + expect(config.maxEntries).toBe(3); + expect(config.defaultTtlMs).toBe(250); + expect(config.nowMs()).toBe(42); + }); + + it('rejects invalid configuration', () => { + expectCode(() => validateCacheConfig({ maxEntries: 0 }), 'INVALID_CONFIG'); + expectCode(() => validateCacheConfig({ maxEntries: 1.5 }), 'INVALID_CONFIG'); + expectCode(() => validateCacheConfig({ defaultTtlMs: -1 }), 'INVALID_CONFIG'); + expectCode(() => validateCacheConfig({ defaultTtlMs: NaN }), 'INVALID_CONFIG'); + expectCode(() => validateCacheConfig(null), 'INVALID_CONFIG'); + expectCode(() => validateCacheConfig([]), 'INVALID_CONFIG'); + }); +}); + +describe('createTtlCache happy path', () => { + it('stores and retrieves a value', () => { + const cache = createTtlCache(); + const entry = cache.set('a', 'alpha'); + expect(cache.get('a')).toBe('alpha'); + expect(entry.key).toBe('a'); + expect(entry.value).toBe('alpha'); + expect(entry.ttlMs).toBe(60000); + expect(Object.isFrozen(entry)).toBe(true); + }); + + it('returns undefined on a miss and tracks has/size', () => { + const cache = createTtlCache(); + expect(cache.get('missing')).toBeUndefined(); + expect(cache.has('missing')).toBe(false); + cache.set('x', 'one'); + expect(cache.has('x')).toBe(true); + expect(cache.size()).toBe(1); + }); + + it('deletes and clears entries', () => { + const cache = createTtlCache(); + cache.set('x', 'one'); + cache.set('y', 'two'); + expect(cache.delete('x')).toBe(true); + expect(cache.delete('x')).toBe(false); + expect(cache.size()).toBe(1); + expect(cache.clear()).toBe(1); + expect(cache.size()).toBe(0); + expect(cache.get('y')).toBeUndefined(); + }); + + it('returns frozen key and entry snapshots', () => { + const cache = createTtlCache(); + cache.set('a', '1'); + cache.set('b', '2'); + const keys = cache.keys(); + const entries = cache.entries(); + expect(Object.isFrozen(keys)).toBe(true); + expect(Object.isFrozen(entries)).toBe(true); + expect(keys).toEqual(['a', 'b']); + expect(entries).toHaveLength(2); + expect(Object.isFrozen(entries[0])).toBe(true); + }); +}); + +describe('TTL expiry with an injectable clock', () => { + it('expires an entry once the clock passes its deadline', () => { + let clock = 1000; + const cache = createTtlCache({ defaultTtlMs: 100, nowMs: () => clock }); + cache.set('k', 'v'); + expect(cache.get('k')).toBe('v'); + clock = 1099; + expect(cache.get('k')).toBe('v'); + clock = 1100; + expect(cache.get('k')).toBeUndefined(); + expect(cache.has('k')).toBe(false); + expect(cache.size()).toBe(0); + }); + + it('honours a per-entry TTL override', () => { + let clock = 0; + const cache = createTtlCache({ defaultTtlMs: 1000, nowMs: () => clock }); + cache.set('short', 'v', 10); + clock = 11; + expect(cache.get('short')).toBeUndefined(); + }); + + it('prunes expired entries eagerly', () => { + let clock = 0; + const cache = createTtlCache({ defaultTtlMs: 5, nowMs: () => clock }); + cache.set('a', '1'); + cache.set('b', '2'); + expect(cache.prune()).toBe(0); + clock = 5; + expect(cache.prune()).toBe(2); + expect(cache.size()).toBe(0); + }); +}); + +describe('bounded LRU eviction', () => { + it('evicts the least recently used entry when full', () => { + const cache = createTtlCache({ maxEntries: 2 }); + cache.set('a', '1'); + cache.set('b', '2'); + cache.set('c', '3'); + expect(cache.size()).toBe(2); + expect(cache.get('a')).toBeUndefined(); + expect(cache.get('b')).toBe('2'); + expect(cache.get('c')).toBe('3'); + }); + + it('refreshes recency on get', () => { + const cache = createTtlCache({ maxEntries: 2 }); + cache.set('a', '1'); + cache.set('b', '2'); + expect(cache.get('a')).toBe('1'); + cache.set('c', '3'); + expect(cache.get('a')).toBe('1'); + expect(cache.get('b')).toBeUndefined(); + }); + + it('replacing an existing key does not grow the cache', () => { + const cache = createTtlCache({ maxEntries: 2 }); + cache.set('a', '1'); + cache.set('b', '2'); + cache.set('a', 'updated'); + expect(cache.size()).toBe(2); + expect(cache.get('a')).toBe('updated'); + }); +}); + +describe('invalidation', () => { + it('invalidates every key beginning with a prefix', () => { + const cache = createTtlCache(); + cache.set('u:1|h:a', 'a'); + cache.set('u:1|h:b', 'b'); + cache.set('u:2|h:a', 'c'); + expect(cache.invalidateByPrefix('u:1|')).toBe(2); + expect(cache.size()).toBe(1); + expect(cache.has('u:2|h:a')).toBe(true); + expect(cache.invalidateByPrefix('none')).toBe(0); + }); +}); + +describe('malformed input', () => { + it('rejects invalid keys, TTLs and values', () => { + const cache = createTtlCache(); + expectCode(() => cache.set('', 'v'), 'INVALID_KEY'); + expectCode(() => cache.get(''), 'INVALID_KEY'); + expectCode(() => cache.set('k', 'v', 0), 'INVALID_TTL'); + expectCode(() => cache.set('k', 'v', NaN), 'INVALID_TTL'); + expectCode(() => cache.set('k', undefined), 'INVALID_VALUE'); + expectCode(() => cache.invalidateByPrefix(''), 'INVALID_KEY'); + }); +}); + +describe('counters and observability hooks', () => { + it('tracks hits, misses, sets, deletes and evictions in stats', () => { + const cache = createTtlCache({ maxEntries: 1 }); + cache.set('a', '1'); + cache.get('a'); + cache.get('miss'); + cache.set('b', '2'); + const stats = cache.stats(); + expect(stats.hits).toBe(1); + expect(stats.misses).toBe(1); + expect(stats.sets).toBe(2); + expect(stats.evictions).toBe(1); + expect(Object.isFrozen(stats)).toBe(true); + }); + + it('emits metrics and log events for decisions and evictions', () => { + const events: string[] = []; + const warnings: string[] = []; + const cache = createTtlCache( + { maxEntries: 1, defaultTtlMs: 10, nowMs: () => clock }, + { + recordHit: () => { events.push('hit'); }, + recordMiss: () => { events.push('miss'); }, + recordSet: () => { events.push('set'); }, + recordDelete: () => { events.push('delete'); }, + recordExpiry: () => { events.push('expiry'); }, + recordEviction: (_key, reason) => { events.push('evict:' + reason); }, + recordClear: () => { events.push('clear'); }, + recordInvalidateByPrefix: () => { events.push('prefix'); }, + }, + { warn: (message) => { warnings.push(message); }, debug: () => {} } + ); + let clock = 0; + cache.set('a', '1'); + cache.get('a'); + cache.get('nope'); + cache.set('b', '2'); + cache.invalidateByPrefix('b'); + expect(events).toContain('set'); + expect(events).toContain('hit'); + expect(events).toContain('miss'); + expect(events).toContain('evict:lru'); + expect(events).toContain('prefix'); + }); +}); diff --git a/backend/src/lib/cache.ts b/backend/src/lib/cache.ts new file mode 100644 index 00000000..1a67f734 --- /dev/null +++ b/backend/src/lib/cache.ts @@ -0,0 +1,467 @@ +/** + * backend/src/lib/cache.ts + * + * Household-membership cache primitives (issue #2264). + * + * A zero-dependency, side-effect-free TTL + LRU cache. It performs no I/O and + * reads no ambient state other than an injectable clock, so every policy + * decision — hit/miss, expiry, eviction, invalidation — is deterministic and + * unit-testable without a database or a real timer. + * + * Design rules (mirrors the other `backend/src/lib` engines): + * - Pure data in, pure data out. State lives only inside the returned handle. + * - Every rejection is a typed `CacheError` with a stable `code`. + * - Entries expire lazily on access and can be pruned eagerly. + * - Insertion order doubles as an LRU order; the oldest entry is evicted first + * once `maxEntries` is reached. A `get` refreshes recency; a `set` on an + * existing key replaces the value and refreshes recency. + * - Metrics and logger hooks are optional; no-op defaults are provided. + * - Returned snapshots are frozen so callers cannot mutate internal state. + * + * Usage: + * const cache = createTtlCache({ maxEntries: 100, defaultTtlMs: 30_000 }); + * cache.set('k', 'v'); + * const value = cache.get('k'); // 'v' | undefined + */ + +// --------------------------------------------------------------------------- +// Error surface +// --------------------------------------------------------------------------- + +/** Stable machine-readable codes emitted by this module. */ +export const CacheErrorCode = { + INVALID_CONFIG: 'INVALID_CONFIG', + INVALID_KEY: 'INVALID_KEY', + INVALID_TTL: 'INVALID_TTL', + INVALID_VALUE: 'INVALID_VALUE', +} as const; + +/** Union of every stable error code emitted by this module. */ +export type CacheErrorCode = (typeof CacheErrorCode)[keyof typeof CacheErrorCode]; + +/** Typed error thrown for invalid configuration and invalid cache input. */ +export class CacheError extends Error { + readonly code: CacheErrorCode; + readonly details: Readonly>; + + constructor(code: CacheErrorCode, message: string, details: Readonly> = {}) { + super(message); + this.name = 'CacheError'; + this.code = code; + this.details = details; + } +} + +// --------------------------------------------------------------------------- +// Configuration and data types +// --------------------------------------------------------------------------- + +/** + * Fully resolved cache configuration. Callers normally supply a `Partial` of + * this shape to {@link createTtlCache}; defaults are filled in by + * {@link validateCacheConfig}. + */ +export interface CacheConfig { + /** Maximum number of live entries. Must be a positive integer. */ + maxEntries: number; + /** Default time-to-live in milliseconds. Must be a positive finite number. */ + defaultTtlMs: number; + /** Injectable clock; defaults to `Date.now`. Enables deterministic tests. */ + nowMs: () => number; +} + +/** Immutable snapshot of a single cached entry. */ +export interface CacheEntry { + readonly key: string; + readonly value: T; + /** Wall-clock time at which the entry was stored (ms). */ + readonly createdAtMs: number; + /** Wall-clock time at which the entry becomes stale (ms). */ + readonly expiresAtMs: number; + /** Per-entry TTL actually applied (ms). */ + readonly ttlMs: number; +} + +/** Immutable snapshot of internal counters. */ +export interface CacheStats { + readonly hits: number; + readonly misses: number; + readonly sets: number; + readonly deletes: number; + readonly expiries: number; + readonly evictions: number; + readonly prefixInvalidations: number; + readonly size: number; +} + +/** Reason an entry left the cache; reported through metrics/logging. */ +export type CacheEvictionReason = 'ttl' | 'lru' | 'delete' | 'clear' | 'invalidate'; + +/** Optional observability hook for cache decisions. */ +export interface CacheMetrics { + recordHit(key: string): void; + recordMiss(key: string): void; + recordSet(key: string, ttlMs: number): void; + recordDelete(key: string): void; + recordExpiry(key: string): void; + recordEviction(key: string, reason: CacheEvictionReason): void; + recordClear(removed: number): void; + recordInvalidateByPrefix(prefix: string, removed: number): void; +} + +/** Optional logging hook for cache anomalies (expiry, eviction). */ +export interface CacheLogger { + debug(message: string, details: Record): void; + warn(message: string, details: Record): void; +} + +/** Defaults used when a caller omits configuration values. */ +export const DEFAULT_CACHE_CONFIG: CacheConfig = Object.freeze({ + maxEntries: 500, + defaultTtlMs: 60_000, + nowMs: Date.now, +}); + +/** No-op metrics implementation, safe to use in tests and development. */ +export const noopCacheMetrics: CacheMetrics = Object.freeze({ + recordHit: () => {}, + recordMiss: () => {}, + recordSet: () => {}, + recordDelete: () => {}, + recordExpiry: () => {}, + recordEviction: () => {}, + recordClear: () => {}, + recordInvalidateByPrefix: () => {}, +}); + +/** No-op logger implementation. */ +export const noopCacheLogger: CacheLogger = Object.freeze({ + debug: () => {}, + warn: () => {}, +}); + +// --------------------------------------------------------------------------- +// Validation helpers +// --------------------------------------------------------------------------- + +function assertPositiveInteger(value: unknown, field: string): number { + if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) { + throw new CacheError(CacheErrorCode.INVALID_CONFIG, `${field} must be a positive integer`, { + field, + value, + }); + } + return value; +} + +function assertPositiveFinite(value: unknown, field: string, code: CacheErrorCode): number { + if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) { + throw new CacheError(code, `${field} must be a positive finite number`, { field, value }); + } + return value; +} + +/** Validate a cache key: must be a non-empty string. */ +function assertKey(key: unknown): string { + if (typeof key !== 'string' || key.length === 0) { + throw new CacheError(CacheErrorCode.INVALID_KEY, 'cache key must be a non-empty string', { key }); + } + return key; +} + +/** Validate a prefix: must be a non-empty string. */ +function assertPrefix(prefix: unknown): string { + if (typeof prefix !== 'string' || prefix.length === 0) { + throw new CacheError(CacheErrorCode.INVALID_KEY, 'prefix must be a non-empty string', { prefix }); + } + return prefix; +} + +/** + * Validate and resolve a partial configuration into a complete, frozen + * `CacheConfig`. Throws `CacheError(INVALID_CONFIG)` on bad values. + */ +export function validateCacheConfig(config: Partial = {}): CacheConfig { + if (config === null || typeof config !== 'object' || Array.isArray(config)) { + throw new CacheError(CacheErrorCode.INVALID_CONFIG, 'config must be an object', { config }); + } + + const resolved: CacheConfig = { + maxEntries: assertPositiveInteger( + config.maxEntries ?? DEFAULT_CACHE_CONFIG.maxEntries, + 'maxEntries' + ), + defaultTtlMs: assertPositiveFinite( + config.defaultTtlMs ?? DEFAULT_CACHE_CONFIG.defaultTtlMs, + 'defaultTtlMs', + CacheErrorCode.INVALID_CONFIG + ), + nowMs: typeof config.nowMs === 'function' ? config.nowMs : DEFAULT_CACHE_CONFIG.nowMs, + }; + return Object.freeze(resolved); +} + +// --------------------------------------------------------------------------- +// Cache handle +// --------------------------------------------------------------------------- + +/** In-memory TTL + LRU cache handle returned by {@link createTtlCache}. */ +export interface TtlCache { + /** Return the live value for `key`, or `undefined` on miss/expiry. Refreshes LRU recency. */ + get(key: string): T | undefined; + /** Store `value` under `key` with an optional per-entry TTL. Returns the frozen entry. */ + set(key: string, value: T, ttlMs?: number): CacheEntry; + /** Delete one key. Returns true when an entry was removed. */ + delete(key: string): boolean; + /** Remove every entry. Returns the number removed. */ + clear(): number; + /** True when a live (non-expired) entry exists for `key`. */ + has(key: string): boolean; + /** Current number of live entries (prunes expired entries first). */ + size(): number; + /** Frozen snapshot of all live entries, oldest (LRU) first. */ + entries(): readonly CacheEntry[]; + /** Frozen snapshot of all live keys, oldest (LRU) first. */ + keys(): readonly string[]; + /** Delete every live key beginning with `prefix`. Returns the number removed. */ + invalidateByPrefix(prefix: string): number; + /** Eagerly remove all expired entries. Returns the number removed. */ + prune(): number; + /** Frozen snapshot of internal counters. */ + stats(): CacheStats; + /** The fully resolved, frozen configuration. */ + readonly config: CacheConfig; +} + +interface MutableEntry { + key: string; + value: T; + createdAtMs: number; + expiresAtMs: number; + ttlMs: number; +} + +function freezeEntry(entry: MutableEntry): CacheEntry { + return Object.freeze({ + key: entry.key, + value: entry.value, + createdAtMs: entry.createdAtMs, + expiresAtMs: entry.expiresAtMs, + ttlMs: entry.ttlMs, + }); +} + +/** + * Create a zero-dependency TTL + LRU cache. + * + * @param config Partial configuration; see {@link DEFAULT_CACHE_CONFIG}. + * @param metrics Optional observability sink (partial implementations allowed). + * @param logger Optional logging sink (partial implementations allowed). + */ +export function createTtlCache( + config: Partial = {}, + metrics: Partial = {}, + logger: Partial = {} +): TtlCache { + const cfg = validateCacheConfig(config); + const m: CacheMetrics = { ...noopCacheMetrics, ...metrics }; + const l: CacheLogger = { ...noopCacheLogger, ...logger }; + // Map insertion order is LRU order: first = least recently used. + const store = new Map>(); + const counters = { + hits: 0, + misses: 0, + sets: 0, + deletes: 0, + expiries: 0, + evictions: 0, + prefixInvalidations: 0, + }; + + function now(): number { + return cfg.nowMs(); + } + + function isExpired(entry: MutableEntry, atMs: number): boolean { + return atMs >= entry.expiresAtMs; + } + + function dropEntry(key: string, entry: MutableEntry, reason: CacheEvictionReason): void { + store.delete(key); + if (reason === 'ttl') { + counters.expiries += 1; + } else if (reason === 'lru') { + counters.evictions += 1; + } + m.recordEviction(key, reason); + if (reason === 'lru' || reason === 'ttl') { + l.debug('cache entry removed', { key, reason }); + } + } + + function touch(key: string, entry: MutableEntry): void { + // Re-insert to move the entry to the most-recently-used end. + store.delete(key); + store.set(key, entry); + } + + function get(key: string): T | undefined { + const k = assertKey(key); + const entry = store.get(k); + if (!entry) { + counters.misses += 1; + m.recordMiss(k); + return undefined; + } + if (isExpired(entry, now())) { + dropEntry(k, entry, 'ttl'); + counters.misses += 1; + m.recordMiss(k); + m.recordExpiry(k); + return undefined; + } + touch(k, entry); + counters.hits += 1; + m.recordHit(k); + return entry.value; + } + + function set(key: string, value: T, ttlMs?: number): CacheEntry { + const k = assertKey(key); + if (value === undefined) { + throw new CacheError(CacheErrorCode.INVALID_VALUE, 'cache value must not be undefined', { key: k }); + } + const ttl = + ttlMs === undefined + ? cfg.defaultTtlMs + : assertPositiveFinite(ttlMs, 'ttlMs', CacheErrorCode.INVALID_TTL); + const at = now(); + + const existing = store.get(k); + if (existing) { + // Replace in place and refresh recency; eviction is not needed. + store.delete(k); + } else if (store.size >= cfg.maxEntries) { + // Evict the least recently used entry (first in insertion order). + const oldestKey = store.keys().next().value as string | undefined; + if (oldestKey !== undefined) { + const oldest = store.get(oldestKey); + if (oldest) dropEntry(oldestKey, oldest, 'lru'); + } + } + + const entry: MutableEntry = { + key: k, + value, + createdAtMs: at, + expiresAtMs: at + ttl, + ttlMs: ttl, + }; + store.set(k, entry); + counters.sets += 1; + m.recordSet(k, ttl); + return freezeEntry(entry); + } + + function del(key: string): boolean { + const k = assertKey(key); + const entry = store.get(k); + if (!entry) return false; + store.delete(k); + counters.deletes += 1; + m.recordDelete(k); + m.recordEviction(k, 'delete'); + return true; + } + + function clear(): number { + const removed = store.size; + store.clear(); + m.recordClear(removed); + if (removed > 0) l.debug('cache cleared', { removed }); + return removed; + } + + function has(key: string): boolean { + const k = assertKey(key); + const entry = store.get(k); + if (!entry) return false; + if (isExpired(entry, now())) { + dropEntry(k, entry, 'ttl'); + m.recordExpiry(k); + return false; + } + touch(k, entry); + return true; + } + + function size(): number { + prune(); + return store.size; + } + + function entries(): readonly CacheEntry[] { + prune(); + const snapshot: CacheEntry[] = []; + for (const entry of store.values()) snapshot.push(freezeEntry(entry)); + return Object.freeze(snapshot); + } + + function keys(): readonly string[] { + prune(); + return Object.freeze(Array.from(store.keys())); + } + + function invalidateByPrefix(prefix: string): number { + const p = assertPrefix(prefix); + let removed = 0; + for (const [key, entry] of store) { + if (key.startsWith(p)) { + store.delete(key); + removed += 1; + m.recordEviction(key, 'invalidate'); + } + } + if (removed > 0) { + counters.prefixInvalidations += 1; + m.recordInvalidateByPrefix(p, removed); + l.debug('cache prefix invalidated', { prefix: p, removed }); + } + return removed; + } + + function prune(): number { + const at = now(); + let removed = 0; + for (const [key, entry] of store) { + if (isExpired(entry, at)) { + dropEntry(key, entry, 'ttl'); + m.recordExpiry(key); + removed += 1; + } + } + return removed; + } + + function stats(): CacheStats { + return Object.freeze({ + ...counters, + size: store.size, + }); + } + + return Object.freeze({ + get, + set, + delete: del, + clear, + has, + size, + entries, + keys, + invalidateByPrefix, + prune, + stats, + config: cfg, + }); +} diff --git a/backend/src/middleware/__tests__/householdLoader.test.ts b/backend/src/middleware/__tests__/householdLoader.test.ts new file mode 100644 index 00000000..70612cb5 --- /dev/null +++ b/backend/src/middleware/__tests__/householdLoader.test.ts @@ -0,0 +1,376 @@ +/** + * backend/src/middleware/__tests__/householdLoader.test.ts + * + * Unit tests for the household membership loader (issue #2264). + * Covers deterministic keying, happy path, cache hit/negative caching, TTL + * expiry, all invalidation scopes, source failures, malformed input and + * observability hooks. + */ + +import { createTtlCache } from '../../lib/cache'; +import { + HouseholdLoaderErrorCode, + HouseholdLoaderError, + DEFAULT_HOUSEHOLD_LOADER_CONFIG, + noopHouseholdLoaderMetrics, + noopHouseholdLoaderLogger, + validateHouseholdLoaderConfig, + makeMembershipKey, + makeUserPrefix, + createHouseholdLoader, +} from '../householdLoader'; + +function membership(userId: string, householdId: string, role: string = 'member') { + return { userId, householdId, role, joinedAtMs: 100 }; +} + +function expectCode(fn: () => unknown, code: string): void { + try { + fn(); + throw new Error('expected function to throw'); + } catch (error) { + expect((error as { code?: string }).code).toBe(code); + } +} + +describe('error surface and constants', () => { + it('exposes stable error codes', () => { + expect(HouseholdLoaderErrorCode.INVALID_CONFIG).toBe('INVALID_CONFIG'); + expect(HouseholdLoaderErrorCode.INVALID_USER).toBe('INVALID_USER'); + expect(HouseholdLoaderErrorCode.INVALID_HOUSEHOLD).toBe('INVALID_HOUSEHOLD'); + expect(HouseholdLoaderErrorCode.INVALID_SOURCE).toBe('INVALID_SOURCE'); + expect(HouseholdLoaderErrorCode.SOURCE_ERROR).toBe('SOURCE_ERROR'); + }); + + it('builds a typed HouseholdLoaderError', () => { + const error = new HouseholdLoaderError( + HouseholdLoaderErrorCode.SOURCE_ERROR, + 'failed', + { userId: 'u' } + ); + expect(error instanceof Error).toBe(true); + expect(error instanceof HouseholdLoaderError).toBe(true); + expect(error.name).toBe('HouseholdLoaderError'); + expect(error.code).toBe('SOURCE_ERROR'); + expect(error.details).toEqual({ userId: 'u' }); + }); + + it('exposes frozen defaults and noop hooks', () => { + expect(Object.isFrozen(DEFAULT_HOUSEHOLD_LOADER_CONFIG)).toBe(true); + expect(DEFAULT_HOUSEHOLD_LOADER_CONFIG.ttlMs).toBe(30000); + expect(typeof noopHouseholdLoaderMetrics.recordCacheHit).toBe('function'); + expect(typeof noopHouseholdLoaderLogger.warn).toBe('function'); + }); +}); + +describe('config validation', () => { + it('fills in defaults and honours overrides', () => { + const config = validateHouseholdLoaderConfig({}); + expect(config.ttlMs).toBe(30000); + expect(config.keyNamespace).toBe('hsmem'); + expect(Object.isFrozen(config)).toBe(true); + + const custom = validateHouseholdLoaderConfig({ ttlMs: 500, keyNamespace: 'x' }); + expect(custom.ttlMs).toBe(500); + expect(custom.keyNamespace).toBe('x'); + expect(custom.nowMs()).toBeGreaterThan(0); + }); + + it('rejects invalid configuration', () => { + expectCode(() => validateHouseholdLoaderConfig({ ttlMs: 0 }), 'INVALID_CONFIG'); + expectCode(() => validateHouseholdLoaderConfig({ ttlMs: NaN }), 'INVALID_CONFIG'); + expectCode(() => validateHouseholdLoaderConfig({ keyNamespace: '' }), 'INVALID_CONFIG'); + expectCode(() => validateHouseholdLoaderConfig(null), 'INVALID_CONFIG'); + }); +}); + +describe('deterministic keying', () => { + it('builds a stable, namespaced key', () => { + expect(makeMembershipKey('u1', 'h1')).toBe('hsmem|u:u1|h:h1'); + expect(makeMembershipKey('u1', 'h1')).toBe(makeMembershipKey('u1', 'h1')); + expect(makeMembershipKey('u1', 'h2')).not.toBe(makeMembershipKey('u1', 'h1')); + expect(makeMembershipKey('u1', 'h1', 'custom')).toBe('custom|u:u1|h:h1'); + }); + + it('percent-encodes delimiters so IDs cannot collide', () => { + const a = makeMembershipKey('u|1', 'h'); + const b = makeMembershipKey('u', '1|h'); + expect(a).not.toBe(b); + expect(a).toContain('%7C'); + expect(makeMembershipKey('a:b', 'h')).toContain('%3A'); + expect(makeMembershipKey('a%b', 'h')).toContain('%25'); + }); + + it('builds a user prefix matching all households', () => { + expect(makeUserPrefix('u1')).toBe('hsmem|u:u1|'); + expect(makeMembershipKey('u1', 'h1').startsWith(makeUserPrefix('u1'))).toBe(true); + }); + + it('rejects malformed key inputs', () => { + expectCode(() => makeMembershipKey('', 'h1'), 'INVALID_USER'); + expectCode(() => makeMembershipKey(' ', 'h1'), 'INVALID_USER'); + expectCode(() => makeMembershipKey('u1', ''), 'INVALID_HOUSEHOLD'); + expectCode(() => makeUserPrefix(''), 'INVALID_USER'); + }); +}); + +describe('load happy path', () => { + it('calls the source once and caches a positive membership', async () => { + const cache = createTtlCache(); + let calls = 0; + const loader = createHouseholdLoader(cache, { + source: { + lookupMembership: (u, h) => { + calls++; + return membership(u, h); + }, + }, + }); + + const first = await loader.load('u1', 'h1'); + expect(first.isMember).toBe(true); + expect(first.membership).not.toBeNull(); + expect(first.source).toBe('source'); + expect(first.userId).toBe('u1'); + expect(first.householdId).toBe('h1'); + expect(Object.isFrozen(first)).toBe(true); + expect(calls).toBe(1); + + const second = await loader.load('u1', 'h1'); + expect(second.source).toBe('cache'); + expect(second.isMember).toBe(true); + expect(calls).toBe(1); + }); + + it('supports async source resolvers', async () => { + const loader = createHouseholdLoader(createTtlCache(), { + source: { + lookupMembership: async (u, h) => membership(u, h, 'admin'), + }, + }); + const result = await loader.load('u1', 'h1'); + expect(result.membership?.role).toBe('admin'); + }); + + it('caches negative lookups without a repeat source call', async () => { + const cache = createTtlCache(); + let calls = 0; + const loader = createHouseholdLoader(cache, { + source: { + lookupMembership: () => { + calls++; + return null; + }, + }, + }); + const first = await loader.load('ghost', 'h1'); + expect(first.isMember).toBe(false); + expect(first.membership).toBeNull(); + const second = await loader.load('ghost', 'h1'); + expect(second.isMember).toBe(false); + expect(second.source).toBe('cache'); + expect(calls).toBe(1); + }); + + it('normalizes a malformed source record into a safe membership', async () => { + const loader = createHouseholdLoader(createTtlCache(), { + source: { lookupMembership: () => ({ role: 123, joinedAtMs: 'bad' }) }, + }); + const result = await loader.load('u1', 'h1'); + expect(result.isMember).toBe(true); + expect(result.membership?.role).toBe('member'); + expect(result.membership?.joinedAtMs).toBe(0); + expect(result.membership?.userId).toBe('u1'); + }); + + it('rejects non-object source records', async () => { + const loader = createHouseholdLoader(createTtlCache(), { + source: { lookupMembership: () => 42 }, + }); + let caught: unknown; + try { + await loader.load('u1', 'h1'); + } catch (error) { + caught = error; + } + expect((caught as { code?: string }).code).toBe('SOURCE_ERROR'); + }); +}); + +describe('TTL expiry through the loader', () => { + it('re-queries the source after the configured TTL elapses', async () => { + let clock = 0; + let calls = 0; + const cache = createTtlCache({ defaultTtlMs: 1000, nowMs: () => clock }); + const loader = createHouseholdLoader( + cache, + { + source: { + lookupMembership: (u, h) => { + calls++; + return membership(u, h); + }, + }, + }, + { ttlMs: 50, nowMs: () => clock } + ); + + await loader.load('u1', 'h1'); + expect(calls).toBe(1); + clock = 49; + expect((await loader.load('u1', 'h1')).source).toBe('cache'); + clock = 50; + expect((await loader.load('u1', 'h1')).source).toBe('source'); + expect(calls).toBe(2); + }); +}); + +describe('invalidation', () => { + async function seededLoader() { + let calls = 0; + const loader = createHouseholdLoader(createTtlCache(), { + source: { + lookupMembership: (u, h) => { + calls++; + return membership(u, h); + }, + }, + }); + await loader.load('u1', 'h1'); + await loader.load('u1', 'h2'); + await loader.load('u2', 'h1'); + return { loader, calls: () => calls }; + } + + it('invalidates a single membership pair', async () => { + const { loader } = await seededLoader(); + const result = loader.invalidate('u1', 'h1'); + expect(result.scope).toBe('membership'); + expect(result.removed).toBe(1); + expect(Object.isFrozen(result)).toBe(true); + expect(loader.invalidate('nobody', 'h1').removed).toBe(0); + }); + + it('invalidates every household for one user', async () => { + const { loader } = await seededLoader(); + const result = loader.invalidateUser('u1'); + expect(result.scope).toBe('user'); + expect(result.removed).toBe(2); + await loader.load('u1', 'h1'); + await loader.load('u1', 'h2'); + await loader.load('u2', 'h1'); + expect((await loader.load('u1', 'h1')).source).toBe('cache'); + }); + + it('invalidates the entire cache', async () => { + const { loader } = await seededLoader(); + const result = loader.invalidateAll(); + expect(result.scope).toBe('all'); + expect(result.removed).toBe(3); + }); + + it('rejects malformed invalidation input', async () => { + const { loader } = await seededLoader(); + expectCode(() => loader.invalidate('', 'h1'), 'INVALID_USER'); + expectCode(() => loader.invalidate('u1', ''), 'INVALID_HOUSEHOLD'); + expectCode(() => loader.invalidateUser(' '), 'INVALID_USER'); + }); +}); + +describe('dependency validation and failures', () => { + it('rejects a missing or malformed source', () => { + expectCode( + () => createHouseholdLoader(createTtlCache(), { source: {} as never }), + 'INVALID_SOURCE' + ); + expectCode( + () => createHouseholdLoader(createTtlCache(), null as never), + 'INVALID_CONFIG' + ); + }); + + it('rejects a cache that does not implement the contract', () => { + expectCode( + () => createHouseholdLoader({} as never, { source: { lookupMembership: () => null } }), + 'INVALID_CONFIG' + ); + }); + + it('surfaces source exceptions as typed SOURCE_ERROR', async () => { + let caught: unknown; + const loader = createHouseholdLoader(createTtlCache(), { + source: { + lookupMembership: () => { + throw new Error('db down'); + }, + }, + }); + try { + await loader.load('u1', 'h1'); + } catch (error) { + caught = error; + } + expect((caught as { code?: string }).code).toBe('SOURCE_ERROR'); + expect((caught as { name?: string }).name).toBe('HouseholdLoaderError'); + }); + + it('rejects malformed load input', async () => { + const loader = createHouseholdLoader(createTtlCache(), { + source: { lookupMembership: () => null }, + }); + let a: unknown; + let b: unknown; + try { await loader.load('', 'h1'); } catch (e) { a = e; } + try { await loader.load('u1', ''); } catch (e) { b = e; } + expect((a as { code?: string }).code).toBe('INVALID_USER'); + expect((b as { code?: string }).code).toBe('INVALID_HOUSEHOLD'); + }); +}); + +describe('observability hooks', () => { + it('emits metrics and logs for hits, misses, lookups and invalidations', async () => { + const events: string[] = []; + const warnings: string[] = []; + let calls = 0; + const loader = createHouseholdLoader( + createTtlCache(), + { + source: { + lookupMembership: (u, h) => { + calls++; + if (calls === 2) throw new Error('boom'); + return membership(u, h); + }, + }, + }, + {}, + { + recordCacheHit: () => { events.push('hit'); }, + recordCacheMiss: () => { events.push('miss'); }, + recordSourceLookup: () => { events.push('lookup'); }, + recordInvalidation: () => { events.push('invalidate'); }, + recordSourceError: () => { events.push('error'); }, + }, + { + debug: () => {}, + warn: (message) => { warnings.push(message); }, + } + ); + + await loader.load('u1', 'h1'); + await loader.load('u1', 'h1'); + loader.invalidateUser('u1'); + expect(events).toContain('miss'); + expect(events).toContain('lookup'); + expect(events).toContain('hit'); + expect(events).toContain('invalidate'); + + try { + await loader.load('bad', 'h1'); + } catch (e) { + void e; + } + expect(events).toContain('error'); + expect(warnings.length).toBeGreaterThan(0); + }); +}); diff --git a/backend/src/middleware/householdLoader.ts b/backend/src/middleware/householdLoader.ts new file mode 100644 index 00000000..855bf0ca --- /dev/null +++ b/backend/src/middleware/householdLoader.ts @@ -0,0 +1,477 @@ +/** + * backend/src/middleware/householdLoader.ts + * + * Household-membership loader used by the request middleware (issue #2264). + * + * This module is a zero-dependency, side-effect-free orchestrator. It never + * talks to a database or a network directly: a `MembershipSource` resolver is + * injected, and a TTL/LRU cache handle (see `backend/src/lib/cache.ts`) is + * injected as a structural interface. The loader decides *when* to call the + * source, *what* key to cache under, and *how* to invalidate — all + * deterministic and unit-testable with an injectable clock. + * + * Design rules: + * - Every rejection is a typed `HouseholdLoaderError` with a stable `code`. + * - Deterministic, collision-free keying by household and user. Components are + * percent-encoded so delimiters in IDs cannot forge a different key. + * - Both positive and negative membership results are cached, so a + * non-member does not trigger a source lookup on every request. + * - Invalidation is supported per membership, per user (all households) and + * globally, which is what membership-change handlers need. + * - Metrics and logger hooks are optional; no-op defaults are provided. + * - Returned results are frozen. + * + * Usage: + * const cache = createTtlCache({ defaultTtlMs: 30_000 }); + * const loader = createHouseholdLoader(cache, { source: myResolver }); + * const result = await loader.load('user-1', 'household-9'); + */ + +// --------------------------------------------------------------------------- +// Error surface +// --------------------------------------------------------------------------- + +/** Stable machine-readable codes emitted by this module. */ +export const HouseholdLoaderErrorCode = { + INVALID_CONFIG: 'INVALID_CONFIG', + INVALID_USER: 'INVALID_USER', + INVALID_HOUSEHOLD: 'INVALID_HOUSEHOLD', + INVALID_SOURCE: 'INVALID_SOURCE', + SOURCE_ERROR: 'SOURCE_ERROR', +} as const; + +/** Union of every stable error code emitted by this module. */ +export type HouseholdLoaderErrorCode = + (typeof HouseholdLoaderErrorCode)[keyof typeof HouseholdLoaderErrorCode]; + +/** Typed error thrown for invalid configuration, input and source failures. */ +export class HouseholdLoaderError extends Error { + readonly code: HouseholdLoaderErrorCode; + readonly details: Readonly>; + + constructor( + code: HouseholdLoaderErrorCode, + message: string, + details: Readonly> = {} + ) { + super(message); + this.name = 'HouseholdLoaderError'; + this.code = code; + this.details = details; + } +} + +// --------------------------------------------------------------------------- +// Domain data types +// --------------------------------------------------------------------------- + +/** A membership record as returned by the injected source resolver. */ +export interface Membership { + readonly userId: string; + readonly householdId: string; + readonly role: string; + readonly joinedAtMs: number; +} + +/** + * The value cached by the loader. A `null` `membership` with `isMember: false` + * represents a cached negative lookup (the user is not in the household). + */ +export interface MembershipLookup { + readonly userId: string; + readonly householdId: string; + readonly isMember: boolean; + readonly membership: Membership | null; + /** Clock time at which this lookup was produced (ms). */ + readonly checkedAtMs: number; + /** Where the lookup was served from. */ + readonly source: 'cache' | 'source'; +} + +/** Result of an invalidation operation. */ +export interface InvalidationResult { + readonly scope: 'membership' | 'user' | 'all'; + readonly removed: number; +} + +// --------------------------------------------------------------------------- +// Injected dependencies (structural — no runtime import of cache.ts) +// --------------------------------------------------------------------------- + +/** + * Structural subset of the TTL cache handle consumed by the loader. Any + * object implementing these methods satisfies the contract, which keeps the + * module dependency-injected and free of runtime imports. + */ +export interface MembershipCache { + get(key: string): MembershipLookup | undefined; + set(key: string, value: MembershipLookup, ttlMs?: number): unknown; + delete(key: string): boolean; + clear(): number; + has(key: string): boolean; + size(): number; + entries(): readonly { readonly key: string; readonly value: MembershipLookup }[]; + keys(): readonly string[]; + invalidateByPrefix(prefix: string): number; +} + +/** Resolver that answers a membership question from the source of truth. */ +export interface MembershipSource { + /** Return the membership, or `null` when the user is not a member. */ + lookupMembership( + userId: string, + householdId: string + ): Membership | null | Promise; +} + +// --------------------------------------------------------------------------- +// Configuration, hooks and constants +// --------------------------------------------------------------------------- + +/** Fully resolved loader configuration. */ +export interface HouseholdLoaderConfig { + /** TTL applied to cached lookups (ms). Must be a positive finite number. */ + ttlMs: number; + /** Injectable clock; defaults to `Date.now`. */ + nowMs: () => number; + /** Namespace embedded at the front of every cache key. */ + keyNamespace: string; +} + +/** Defaults used when a caller omits configuration values. */ +export const DEFAULT_HOUSEHOLD_LOADER_CONFIG: HouseholdLoaderConfig = Object.freeze({ + ttlMs: 30_000, + nowMs: Date.now, + keyNamespace: 'hsmem', +}); + +/** Optional observability hook for loader decisions. */ +export interface HouseholdLoaderMetrics { + recordCacheHit(userId: string, householdId: string): void; + recordCacheMiss(userId: string, householdId: string): void; + recordSourceLookup(userId: string, householdId: string, isMember: boolean): void; + recordInvalidation(scope: InvalidationResult['scope'], removed: number): void; + recordSourceError(userId: string, householdId: string, code: string): void; +} + +/** Optional logging hook for loader anomalies. */ +export interface HouseholdLoaderLogger { + debug(message: string, details: Record): void; + warn(message: string, details: Record): void; +} + +/** No-op metrics implementation, safe to use in tests and development. */ +export const noopHouseholdLoaderMetrics: HouseholdLoaderMetrics = Object.freeze({ + recordCacheHit: () => {}, + recordCacheMiss: () => {}, + recordSourceLookup: () => {}, + recordInvalidation: () => {}, + recordSourceError: () => {}, +}); + +/** No-op logger implementation. */ +export const noopHouseholdLoaderLogger: HouseholdLoaderLogger = Object.freeze({ + debug: () => {}, + warn: () => {}, +}); + +// --------------------------------------------------------------------------- +// Validation helpers +// --------------------------------------------------------------------------- + +function assertNonEmptyString(value: unknown, code: HouseholdLoaderErrorCode, field: string): string { + if (typeof value !== 'string' || value.trim().length === 0) { + throw new HouseholdLoaderError(code, `${field} must be a non-empty string`, { field, value }); + } + return value; +} + +function assertSource(source: unknown): MembershipSource { + if ( + source === null || + typeof source !== 'object' || + typeof (source as MembershipSource).lookupMembership !== 'function' + ) { + throw new HouseholdLoaderError( + HouseholdLoaderErrorCode.INVALID_SOURCE, + 'source must provide a lookupMembership function', + { source } + ); + } + return source as MembershipSource; +} + +function assertCache(cache: unknown): MembershipCache { + if ( + cache === null || + typeof cache !== 'object' || + typeof (cache as MembershipCache).get !== 'function' || + typeof (cache as MembershipCache).set !== 'function' || + typeof (cache as MembershipCache).delete !== 'function' || + typeof (cache as MembershipCache).invalidateByPrefix !== 'function' + ) { + throw new HouseholdLoaderError( + HouseholdLoaderErrorCode.INVALID_CONFIG, + 'cache must implement the MembershipCache contract', + { cache } + ); + } + return cache as MembershipCache; +} + +/** + * Validate and resolve a partial loader configuration into a complete, frozen + * `HouseholdLoaderConfig`. Throws `HouseholdLoaderError(INVALID_CONFIG)`. + */ +export function validateHouseholdLoaderConfig( + config: Partial = {} +): HouseholdLoaderConfig { + if (config === null || typeof config !== 'object' || Array.isArray(config)) { + throw new HouseholdLoaderError( + HouseholdLoaderErrorCode.INVALID_CONFIG, + 'config must be an object', + { config } + ); + } + + const ttlMs = config.ttlMs ?? DEFAULT_HOUSEHOLD_LOADER_CONFIG.ttlMs; + if (typeof ttlMs !== 'number' || !Number.isFinite(ttlMs) || ttlMs <= 0) { + throw new HouseholdLoaderError( + HouseholdLoaderErrorCode.INVALID_CONFIG, + 'ttlMs must be a positive finite number', + { ttlMs } + ); + } + + const ns = config.keyNamespace ?? DEFAULT_HOUSEHOLD_LOADER_CONFIG.keyNamespace; + const keyNamespace = assertNonEmptyString(ns, HouseholdLoaderErrorCode.INVALID_CONFIG, 'keyNamespace'); + + return Object.freeze({ + ttlMs, + keyNamespace, + nowMs: typeof config.nowMs === 'function' ? config.nowMs : DEFAULT_HOUSEHOLD_LOADER_CONFIG.nowMs, + }); +} + +/** Percent-encode a single key component so delimiters cannot collide. */ +function encodeComponent(component: string): string { + return component + .replace(/%/g, '%25') + .replace(/\|/g, '%7C') + .replace(/:/g, '%3A'); +} + +/** + * Build the deterministic cache key for a membership lookup. + * + * The format is `|u:|h:`. Encoding + * each component makes the key collision-free even when IDs contain the `|` + * or `:` delimiters. The user component also forms a prefix + * (`|u:|`) usable for user-wide invalidation. + */ +export function makeMembershipKey( + userId: string, + householdId: string, + namespace: string = DEFAULT_HOUSEHOLD_LOADER_CONFIG.keyNamespace +): string { + const u = assertNonEmptyString(userId, HouseholdLoaderErrorCode.INVALID_USER, 'userId'); + const h = assertNonEmptyString(householdId, HouseholdLoaderErrorCode.INVALID_HOUSEHOLD, 'householdId'); + const ns = assertNonEmptyString(namespace, HouseholdLoaderErrorCode.INVALID_CONFIG, 'keyNamespace'); + return `${ns}|u:${encodeComponent(u)}|h:${encodeComponent(h)}`; +} + +/** Build the key prefix that matches every household for one user. */ +export function makeUserPrefix( + userId: string, + namespace: string = DEFAULT_HOUSEHOLD_LOADER_CONFIG.keyNamespace +): string { + const u = assertNonEmptyString(userId, HouseholdLoaderErrorCode.INVALID_USER, 'userId'); + const ns = assertNonEmptyString(namespace, HouseholdLoaderErrorCode.INVALID_CONFIG, 'keyNamespace'); + return `${ns}|u:${encodeComponent(u)}|`; +} + +// --------------------------------------------------------------------------- +// Loader +// --------------------------------------------------------------------------- + +/** Loader handle returned by {@link createHouseholdLoader}. */ +export interface HouseholdLoader { + /** Resolve membership, serving from cache when a fresh entry exists. */ + load(userId: string, householdId: string): Promise; + /** Invalidate the cached lookup for one (user, household) pair. */ + invalidate(userId: string, householdId: string): InvalidationResult; + /** Invalidate every cached household for one user. */ + invalidateUser(userId: string): InvalidationResult; + /** Invalidate everything the loader has cached. */ + invalidateAll(): InvalidationResult; + /** Build the cache key used for a membership pair (exposed for debugging). */ + keyFor(userId: string, householdId: string): string; + /** The fully resolved, frozen configuration. */ + readonly config: HouseholdLoaderConfig; +} + +function freezeLookup(lookup: MembershipLookup): MembershipLookup { + return Object.freeze({ + userId: lookup.userId, + householdId: lookup.householdId, + isMember: lookup.isMember, + membership: lookup.membership ? Object.freeze({ ...lookup.membership }) : null, + checkedAtMs: lookup.checkedAtMs, + source: lookup.source, + }); +} + +function validateMembershipRecord( + value: unknown, + userId: string, + householdId: string, + source: MembershipSource +): Membership | null { + if (value === null || value === undefined) return null; + if (typeof value !== 'object' || Array.isArray(value)) { + throw new HouseholdLoaderError( + HouseholdLoaderErrorCode.SOURCE_ERROR, + 'source returned a malformed membership', + { userId, householdId } + ); + } + const record = value as Partial; + const returnedUser = + typeof record.userId === 'string' && record.userId.length > 0 ? record.userId : userId; + const returnedHousehold = + typeof record.householdId === 'string' && record.householdId.length > 0 + ? record.householdId + : householdId; + const role = typeof record.role === 'string' && record.role.length > 0 ? record.role : 'member'; + const joinedAtMs = + typeof record.joinedAtMs === 'number' && Number.isFinite(record.joinedAtMs) + ? record.joinedAtMs + : 0; + void source; // resolver identity retained for diagnostics in the error path above + return Object.freeze({ + userId: returnedUser, + householdId: returnedHousehold, + role, + joinedAtMs, + }); +} + +/** + * Create a household membership loader on top of an injected cache. + * + * @param cache A TTL cache handle (structural `MembershipCache` subset). + * @param deps Injected dependencies, including the membership source resolver. + * @param config Partial configuration; see {@link DEFAULT_HOUSEHOLD_LOADER_CONFIG}. + * @param metrics Optional observability sink (partial implementations allowed). + * @param logger Optional logging sink (partial implementations allowed). + */ +export function createHouseholdLoader( + cache: MembershipCache, + deps: { source: MembershipSource }, + config: Partial = {}, + metrics: Partial = {}, + logger: Partial = {} +): HouseholdLoader { + const checkedCache = assertCache(cache); + if (deps === null || typeof deps !== 'object') { + throw new HouseholdLoaderError( + HouseholdLoaderErrorCode.INVALID_CONFIG, + 'deps must be an object', + { deps } + ); + } + const source = assertSource(deps.source); + const cfg = validateHouseholdLoaderConfig(config); + const m: HouseholdLoaderMetrics = { ...noopHouseholdLoaderMetrics, ...metrics }; + const l: HouseholdLoaderLogger = { ...noopHouseholdLoaderLogger, ...logger }; + + function keyFor(userId: string, householdId: string): string { + return makeMembershipKey(userId, householdId, cfg.keyNamespace); + } + + async function load(userId: string, householdId: string): Promise { + const u = assertNonEmptyString(userId, HouseholdLoaderErrorCode.INVALID_USER, 'userId'); + const h = assertNonEmptyString(householdId, HouseholdLoaderErrorCode.INVALID_HOUSEHOLD, 'householdId'); + const key = keyFor(u, h); + + const cached = checkedCache.get(key); + if (cached !== undefined) { + m.recordCacheHit(u, h); + l.debug('household membership cache hit', { userId: u, householdId: h, key }); + return freezeLookup({ ...cached, source: 'cache' }); + } + m.recordCacheMiss(u, h); + + let raw: Membership | null; + try { + raw = await source.lookupMembership(u, h); + } catch (error) { + const code = HouseholdLoaderErrorCode.SOURCE_ERROR; + m.recordSourceError(u, h, code); + l.warn('household membership source lookup failed', { + userId: u, + householdId: h, + message: error instanceof Error ? error.message : String(error), + }); + throw new HouseholdLoaderError( + code, + 'membership source lookup failed', + { userId: u, householdId: h, cause: error } + ); + } + + const membership = validateMembershipRecord(raw, u, h, source); + const lookup: MembershipLookup = { + userId: u, + householdId: h, + isMember: membership !== null, + membership, + checkedAtMs: cfg.nowMs(), + source: 'source', + }; + checkedCache.set(key, freezeLookup(lookup), cfg.ttlMs); + m.recordSourceLookup(u, h, lookup.isMember); + l.debug('household membership cached', { + userId: u, + householdId: h, + isMember: lookup.isMember, + key, + }); + return freezeLookup(lookup); + } + + function invalidate(userId: string, householdId: string): InvalidationResult { + const u = assertNonEmptyString(userId, HouseholdLoaderErrorCode.INVALID_USER, 'userId'); + const h = assertNonEmptyString(householdId, HouseholdLoaderErrorCode.INVALID_HOUSEHOLD, 'householdId'); + const removed = checkedCache.delete(keyFor(u, h)) ? 1 : 0; + const result: InvalidationResult = Object.freeze({ scope: 'membership', removed }); + m.recordInvalidation(result.scope, removed); + return result; + } + + function invalidateUser(userId: string): InvalidationResult { + const u = assertNonEmptyString(userId, HouseholdLoaderErrorCode.INVALID_USER, 'userId'); + const removed = checkedCache.invalidateByPrefix(makeUserPrefix(u, cfg.keyNamespace)); + const result: InvalidationResult = Object.freeze({ scope: 'user', removed }); + m.recordInvalidation(result.scope, removed); + l.debug('household membership user invalidated', { userId: u, removed }); + return result; + } + + function invalidateAll(): InvalidationResult { + const removed = checkedCache.clear(); + const result: InvalidationResult = Object.freeze({ scope: 'all', removed }); + m.recordInvalidation(result.scope, removed); + l.debug('household membership cache fully invalidated', { removed }); + return result; + } + + return Object.freeze({ + load, + invalidate, + invalidateUser, + invalidateAll, + keyFor, + config: cfg, + }); +}