Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,282 @@
# OpenSpec Change: enterprise-cache
- **Change ID**: enterprise-cache
- **Package**: `@suaveplan/cache`
- **Category**: universal
- **Target path**: `universal/database/cache`
- **Status**: PROPOSED
- **Date**: 2026-04-24
- **Reference spec**: `/mnt/s/web/suaveplan/enterprise/cache.md`
---
## Summary
Deliver `@suaveplan/cache` on the genesis branch from scratch at enterprise quality. The package provides a type-safe caching abstraction: an `AbstractCache` base class, a built-in LRU `MemoryCache`, a `CacheFactory` with module-augmentation-based provider registry, namespaced caches, TTL support, stale-while-revalidate, multi-get/set, lifecycle hooks via `@suaveplan/events`, and cache statistics. Genesis adds structured errors via `@suaveplan/error`, Zod schemas for all option types, OTel instrumentation, injectable clock and RNG (no `Date.now()` at module scope), `AbortSignal` on async operations, property-based tests (fast-check), and a mitata benchmark suite.
---
## Current-state audit (genesis)
The package does not exist on genesis yet — this is a fresh build. No prior source, no test results, no coverage data.
---
## Available workspace deps on genesis
| Package | Role |
|---|---|
| `@suaveplan/error` (`workspace:^`) | Base class for `CacheError`; `defineCodes` for `CACHE.*` codes |
| `@suaveplan/types` (`workspace:^`) | `Clock` (injectable for TTL expiry, `Date.now` replacement), `EventBusLike`, `LoggerLike` |
| `@suaveplan/events` (`workspace:^`) | `EventBus` for lifecycle hooks (hit, miss, set, evict, expire) |
| `zod` (`catalog:forms`) | Zod schemas for all public option types |
| `@opentelemetry/api` (`catalog:observability`) | Spans + counters on every public cache operation |
| `tslib` (`catalog:build`) | Runtime helpers |
Dev deps: `vitest`, `@vitest/coverage-istanbul`, `fast-check`, `mitata` (all `catalog:testing`), `@suaveplan/testing` (`workspace:^`).
---
## Preserved public API surface (from main branch)
### Abstract
```ts
abstract class AbstractCache<T = unknown> {
abstract get(key: string): Promise<T | undefined>
abstract set(key: string, value: T, options?: CacheSetOptions): Promise<void>
abstract delete(key: string): Promise<boolean>
abstract clear(): Promise<void>
abstract has(key: string): Promise<boolean>
abstract getStats(): CacheStats
abstract getMultiple(keys: string[]): Promise<CacheMultiGetResult<T>>
abstract setMultiple(entries: CacheMultiSetEntry<T>[]): Promise<void>
wrap(key: string, fn: () => Promise<T>, options?: CacheWrapOptions<T>): Promise<T>
}
class NamespacedCache<T = unknown> extends AbstractCache<T>
```
### Memory cache
```ts
class MemoryCache<T = unknown> extends AbstractCache<T> {
constructor(options?: CacheOptions)
get(key: string): Promise<T | undefined>
set(key: string, value: T, options?: CacheSetOptions): Promise<void>
delete(key: string): Promise<boolean>
clear(): Promise<void>
has(key: string): Promise<boolean>
getStats(): CacheStats
getMultiple(keys: string[]): Promise<CacheMultiGetResult<T>>
setMultiple(entries: CacheMultiSetEntry<T>[]): Promise<void>
}
```
### Factory
```ts
class CacheFactory {
static create<T>(type: CacheProviderType, config?: CacheProviderConfig): AbstractCache<T>
static register(type: string, impl: CacheProviderImplementation): void
static unregister(type: string): void
static has(type: string): boolean
static providers(): string[]
}
function createCache<T>(type: CacheProviderType, config?: CacheProviderConfig): AbstractCache<T>
function createCacheWithConfig<T>(config: CacheFactoryConfig): AbstractCache<T>
function registerCacheProvider(type: string, impl: CacheProviderImplementation): void
function unregisterCacheProvider(type: string): void
function hasCacheProvider(type: string): boolean
function getCacheProviders(): string[]
function clearCacheProviders(): void
```
### Types
```ts
interface CacheEntry<T = unknown> {
value: T
expiresAt: number
createdAt: number
lastAccessedAt: number
hitCount: number
}
interface CacheStats { hits: number; misses: number; size: number; hitRate: number; memoryUsage?: number }
type CacheEvictionPolicy = 'lru' | 'lfu' | 'fifo' | 'ttl'
interface CacheOptions {
maxSize?: number
defaultTTL?: number
evictionPolicy?: CacheEvictionPolicy
enableStats?: boolean
checkExpirationInterval?: number
}
interface CacheSetOptions { ttl?: number; staleWhileRevalidate?: boolean; staleThreshold?: number }
interface CacheWrapOptions<T> {
ttl?: number
staleWhileRevalidate?: boolean
staleThreshold?: number
forceRefresh?: boolean
shouldCache?: (value: T) => boolean
}
interface CacheTransformHook<T = unknown> { name: string; transform: (key: string, value: T) => Promise<T> | T; priority?: number }
interface CacheMultiGetResult<T = unknown> { found: Map<string, T>; missing: string[] }
interface CacheMultiSetEntry<T = unknown> { key: string; value: T; options?: CacheSetOptions }
type CacheProviderType = keyof CacheProviderRegistry
interface CacheProviderConfig extends CacheOptions { [key: string]: unknown }
type CacheProviderConfigFor<K extends keyof CacheProviderRegistry> = CacheProviderRegistry[K] extends new (opts: infer O) => unknown ? O : CacheProviderConfig
interface CacheProviderImplementation { new(options?: CacheProviderConfig): AbstractCache }
interface CacheFactoryConfig { type: CacheProviderType; options?: CacheProviderConfig }
interface CacheProviderRegistry { memory: typeof MemoryCache }
interface CacheEvents {
hit: { key: string }
miss: { key: string }
set: { key: string; ttl?: number }
delete: { key: string }
clear: {}
evict: { key: string; reason: 'ttl' | 'lru' | 'lfu' | 'manual' }
expire: { key: string }
}
```
### Error codes
```ts
type CacheErrorCode =
| 'CACHE_KEY_INVALID'
| 'CACHE_CAPACITY_EXCEEDED'
| 'CACHE_PROVIDER_NOT_FOUND'
| 'CACHE_SET_FAILED'
| 'CACHE_GET_FAILED'
| 'CACHE_SERIALIZATION_FAILED'
```
---
## New additions for genesis
### 1. Structured `CacheError`
`CacheError` extends `SuaveplanError` from `@suaveplan/error` carrying a `CacheErrorCode` discriminant. All internal throw sites use named factory helpers.
### 2. Zod option schemas
- `CacheOptionsSchema`
- `CacheSetOptionsSchema`
- `CacheWrapOptionsSchema`
- `CacheFactoryConfigSchema`
- `CacheTransformHookSchema`
### 3. Injectable clock
`CacheOptions` gains an optional `clock?: Clock` field (from `@suaveplan/types`). `MemoryCache` uses `clock.now()` for all TTL calculations instead of bare `Date.now()`. Defaults to `{ now: () => Date.now() }`.
### 4. Event bus integration
`CacheOptions` gains an optional `events?: EventBusLike` field. When provided, `MemoryCache` emits typed `CacheEvents` on every hit/miss/set/delete/evict/expire. Uses `@suaveplan/events` `EventBus` shape — no external event emitter library.
### 5. AbortSignal on `wrap`
`CacheWrapOptions` gains an optional `signal?: AbortSignal`. The background refresh in stale-while-revalidate is aborted when the signal fires.
### 6. OTel instrumentation
| Operation | Signal |
|---|---|
| `get` | counter `cache.get_total`, attribute `cache.hit` (bool), attribute `cache.namespace` |
| `set` | counter `cache.set_total`, attribute `cache.ttl_set` (bool) |
| `delete` | counter `cache.delete_total` |
| `clear` | counter `cache.clear_total` |
| `wrap` | span `cache.wrap`, histogram `cache.wrap_duration_ms` |
| `getStats` | gauge `cache.size`, gauge `cache.hit_rate` |
### 7. LFU eviction policy
The `lfu` eviction policy is fully implemented (main branch had the type but the implementation may have been a stub). `MemoryCache` uses a frequency map + linked-list for O(1) LFU eviction when `evictionPolicy: 'lfu'` is set.
### 8. Property-based tests (fast-check)
- **LRU eviction invariant**: after filling a cache of capacity N and setting N+1 items, assert the least-recently-used item is no longer present.
- **TTL expiry**: for items set with TTL T, after advancing the injectable clock by T+1 ms, assert `has()` returns false and `get()` returns `undefined`.
- **`getMultiple` completeness**: for M items set in cache and K random keys queried (K ≥ M), assert `found.size + missing.length === K` always.
- **Stats accuracy**: for N random get/set/miss sequences, assert `hits + misses === total get calls` and `hitRate ≈ hits / (hits + misses)`.
### 9. Benchmark suite
- `get_hot_1k`: 1000 `get()` calls, all hits, LRU cache of 500 items.
- `set_1k`: 1000 `set()` calls with TTL.
- `wrap_cold`: 100 `wrap()` calls where all miss (async factory call each time).
- `lru_eviction_pressure`: fill cache to 2x capacity, measure eviction throughput.
---
## File layout
```text
universal/database/cache/
package.json
tsconfig.json
vitest.config.ts
src/
index.ts # Public barrel
error-codes.ts # CACHE.* codes + registerCacheErrorCodes
constants/
index.ts # DEFAULT_MAX_SIZE, DEFAULT_TTL, DEFAULT_EVICTION_POLICY
types/
common.ts # All public TS interfaces and type aliases
common.md
schemas.ts # Zod schemas
schemas.md
abstract/
abstract-cache/
abstract-cache.ts # AbstractCache base class
abstract-cache.md
abstract-cache.types.ts
abstract-cache.test.ts
index.ts
namespaced-cache/
namespaced-cache.ts
namespaced-cache.md
namespaced-cache.test.ts
index.ts
memory/
memory-cache/
memory-cache.ts # LRU/LFU/FIFO/TTL MemoryCache
memory-cache.md
memory-cache.types.ts
memory-cache.test.ts
index.ts
factory/
cache-factory/
cache-factory.ts # CacheFactory class + free functions
cache-factory.md
cache-factory.types.ts
cache-factory.test.ts
index.ts
registry/
registry.ts # Built-in memory provider registration
registry.md
index.ts
__benchmarks__/
cache.bench.ts
tests/
integration.test.ts # Cross-cutting: namespaced + factory + wrap round-trip
property.test.ts # fast-check property tests
```
---
## Impact
**Downstream packages**: `@suaveplan/idempotency` and any server-side package that needs caching will depend on `@suaveplan/cache`. No existing genesis package currently requires it.
**Breaking changes from main-branch API**: none. New optional fields (`clock`, `events`, `signal`) are additive.
**Workspace dep prerequisites**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events` must be published to Verdaccio before this package can be built or tested.

View File

@@ -0,0 +1,169 @@
# Tasks: enterprise-cache
**Change ID**: enterprise-cache
**Package**: `@suaveplan/cache`
**Target path**: `universal/database/cache`
**Prerequisite packages on Verdaccio**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`
---
## 1. Scaffold
- [x] Create directory `universal/database/cache/` with `src/`, `tests/`, `src/__benchmarks__/`, and all feature subdirectories per the layout in `proposal.md`.
- [x] Write `package.json` at version `0.1.0` with:
- `"type": "module"`, `"sideEffects": false`
- `exports` map: top-level `"."` barrel plus subpaths `./abstract/abstract-cache`, `./abstract/namespaced-cache`, `./memory/memory-cache`, `./factory/cache-factory`, `./types/common`, `./types/schemas`
- `dependencies`: `@suaveplan/error workspace:^`, `@suaveplan/types workspace:^`, `@suaveplan/events workspace:^`, `zod catalog:forms`, `@opentelemetry/api catalog:observability`, `tslib catalog:build`
- `devDependencies`: `vitest catalog:testing`, `@vitest/coverage-istanbul catalog:testing`, `fast-check catalog:testing`, `mitata catalog:testing`, `@suaveplan/testing workspace:^`
- [x] Write `tsconfig.json` extending `@suaveplan/typescript-config/library.json`.
- [x] Write `vitest.config.ts` using `createTestConfig()` from `@suaveplan/testing/config` (pool: `forks`).
- [x] Add `lint`, `typecheck`, `test`, `test:coverage`, `build`, `docs:check`, `bench` scripts to `package.json`.
---
## 2. Types + errors
### 2a. Common types (`src/types/common.ts` + `src/types/common.md`)
- [x] Define all public TS interfaces: `CacheEntry`, `CacheStats`, `CacheEvictionPolicy`, `CacheOptions`, `CacheSetOptions`, `CacheWrapOptions`, `CacheTransformHook`, `CacheMultiGetResult`, `CacheMultiSetEntry`, `CacheProviderType`, `CacheProviderConfig`, `CacheProviderConfigFor`, `CacheProviderImplementation`, `CacheFactoryConfig`, `CacheProviderRegistry`, `CacheEvents`.
- [x] Add genesis-only optional fields to `CacheOptions`: `clock?: Clock` (from `@suaveplan/types`), `events?: EventBusLike` (from `@suaveplan/types`).
- [x] Add genesis-only optional field to `CacheWrapOptions`: `signal?: AbortSignal`.
- [x] Write `src/types/common.md` (≥200 words, both simple + advanced examples, API reference for every type).
### 2b. Error codes (`src/error-codes.ts`)
- [x] Import `CodeMetadata`, `ErrorCodes`, `SuaveplanError` from `@suaveplan/error`.
- [x] Define `CacheErrorCode` union — six codes: `CACHE_KEY_INVALID`, `CACHE_CAPACITY_EXCEEDED`, `CACHE_PROVIDER_NOT_FOUND`, `CACHE_SET_FAILED`, `CACHE_GET_FAILED`, `CACHE_SERIALIZATION_FAILED`.
- [x] Define `CACHE_ERROR_METADATA` with `httpStatus`, `severity`, `retryable`, `userMessageKey`, `category`, `description` for each code.
- [x] Export `registerCacheErrorCodes()` — calls `ErrorCodes.registerMany(CACHE_ERROR_METADATA)`. Idempotent.
- [x] Call `registerCacheErrorCodes()` as an eager side-effect at module scope.
- [x] Export `CacheError` extending `SuaveplanError` carrying `CacheErrorCode` discriminant.
### 2c. Zod schemas (`src/types/schemas.ts` + `src/types/schemas.md`)
- [x] Write `CacheOptionsSchema`, `CacheSetOptionsSchema`, `CacheWrapOptionsSchema`, `CacheFactoryConfigSchema`, `CacheTransformHookSchema`.
- [x] Export inferred TypeScript types as companions where they differ from hand-written types.
- [x] Write `src/types/schemas.md` (≥200 words).
---
## 3. Constants (`src/constants/index.ts`)
- [x] Export `DEFAULT_MAX_SIZE = 1000`, `DEFAULT_TTL_SECONDS = 3600`, `DEFAULT_EVICTION_POLICY: CacheEvictionPolicy = 'lru'`, `DEFAULT_EXPIRATION_INTERVAL_MS = 60_000`.
---
## 4. Abstract base (`src/abstract/abstract-cache/`)
- [x] Implement `AbstractCache<T>` abstract class:
- Abstract methods: `get`, `set`, `delete`, `clear`, `has`, `getStats`, `getMultiple`, `setMultiple`.
- Concrete `wrap(key, fn, options?)`:
- Check cache; if hit and not stale, return cached value.
- If stale-while-revalidate: return stale value, trigger background refresh (respects `options.signal`).
- If miss or expired: call `fn()`, store result if `shouldCache(value)` returns true.
- OTel: span `cache.wrap`, histogram `cache.wrap_duration_ms`.
- All methods protected by try/catch; on internal error throw `CacheError` with appropriate code.
- [x] Write `abstract-cache.test.ts` — test `wrap` logic via a concrete in-memory subclass stub (no vi.mock).
- [x] Write `abstract-cache.md` (≥200 words).
### 4b. NamespacedCache (`src/abstract/namespaced-cache/`)
- [x] Implement `NamespacedCache<T>` wrapping an `AbstractCache<T>`:
- Prefixes all keys with `"${namespace}:"`.
- Delegates all methods to the wrapped cache.
- `getStats()` returns stats scoped to the namespace where possible.
- [x] Write `namespaced-cache.test.ts`: key isolation between namespaces, clear only clears own namespace.
- [x] Write `namespaced-cache.md` (≥200 words).
---
## 5. Memory cache (`src/memory/memory-cache/`)
- [x] Implement `MemoryCache<T>` extending `AbstractCache<T>`:
- Internal store: `Map<string, CacheEntry<T>>`.
- Injectable `clock?: Clock` — default `{ now: () => Date.now() }`.
- Injectable `events?: EventBusLike` — emit `CacheEvents` on every operation.
- LRU eviction: doubly-linked list + map for O(1) evict-on-capacity.
- LFU eviction: frequency map + bucket list for O(1) evict-on-capacity.
- FIFO eviction: insertion-order queue.
- TTL eviction: periodic sweep via `setInterval` using injectable clock.
- `setInterval` is cleared on `clear()` and optionally on explicit `dispose()`.
- `getStats()` returns live counters (no `Date.now()` — use `clock.now()`).
- Stale-while-revalidate: tracked in `CacheEntry` metadata.
- OTel: counter `cache.get_total` (hit/miss), `cache.set_total`, `cache.delete_total`, `cache.clear_total`, gauge `cache.size`, gauge `cache.hit_rate`, counter `cache.evict_total` (with `reason` attribute).
- [x] Write `memory-cache.test.ts` (≤500 lines): get/set/delete/clear/has, TTL expiry (advance injectable clock), LRU eviction, LFU eviction, stats accuracy, multi-get/set, namespace isolation, event emission.
- [x] Write `memory-cache.md` (≥200 words, both basic + advanced example with injectable clock).
---
## 6. Factory (`src/factory/cache-factory/`)
- [x] Implement `CacheFactory` class with static methods: `create`, `register`, `unregister`, `has`, `providers`.
- [x] Implement free functions: `createCache`, `createCacheWithConfig`, `registerCacheProvider`, `unregisterCacheProvider`, `hasCacheProvider`, `getCacheProviders`, `clearCacheProviders`.
- [x] `CacheFactory.create` validates the type against the registry; throws `CacheError(CACHE_PROVIDER_NOT_FOUND)` for unknown types.
- [x] Write `cache-factory.test.ts`: register/unregister, create known + unknown type, `clearCacheProviders` resets state.
- [x] Write `cache-factory.md` (≥200 words).
### Registry (`src/factory/registry/`)
- [x] `registry.ts` — auto-registers `MemoryCache` as the `memory` provider on import (side-effect).
- [x] Write `registry.md` explaining the auto-registration side-effect and tree-shaking implications.
---
## 7. Public barrel (`src/index.ts`)
- [x] Re-export: `AbstractCache`, `NamespacedCache`, `MemoryCache`, `CacheFactory`, all free factory functions, all types, error-codes, constants.
- [x] Import `./factory/registry` to trigger built-in provider registration on package load.
---
## 8. Property-based tests (`tests/property.test.ts`)
Use `fast-check`. All timeouts: `{ timeout: 30000 }`.
- [x] **LRU eviction invariant**: fill cache of capacity N (N in 5–20), set N+1 items with sequential access order; assert LRU item is evicted.
- [x] **TTL expiry**: set items with TTL T (T in 1–100 ms), advance injectable clock by T+1; assert `has()` returns false.
- [x] **`getMultiple` completeness**: for M items set and K keys queried, assert `found.size + missing.length === K`.
- [x] **Stats accuracy**: for N random get/set sequences, assert `stats.hits + stats.misses === total get calls`.
---
## 9. Benchmarks (`src/__benchmarks__/cache.bench.ts`)
Use `mitata`.
- [x] `get_hot_1k`: 1000 `get()` on LRU cache of 500 pre-populated items (all hits).
- [x] `set_1k`: 1000 `set()` with TTL = 60s.
- [x] `wrap_cold_100`: 100 `wrap()` all misses, factory returns `Promise.resolve(1)`.
- [x] `lru_eviction_pressure`: fill 2x capacity, measure throughput of evictions.
- [x] Add `bench` script to `package.json`.
- [x] Add placeholder benchmark table to `README.md`.
---
## 10. Docs
- [x] `src/types/common.md`
- [x] `src/types/schemas.md`
- [x] `src/abstract/abstract-cache/abstract-cache.md`
- [x] `src/abstract/namespaced-cache/namespaced-cache.md`
- [x] `src/memory/memory-cache/memory-cache.md`
- [x] `src/factory/cache-factory/cache-factory.md`
- [x] `src/factory/registry/registry.md`
- [x] Root `universal/database/cache/README.md` — purpose, installation, quick-start, dep table, full API symbol list, benchmarks table.
---
## 11. Verify and publish
- [x] Run `bunx turbo lint --filter=@suaveplan/cache` — zero errors.
- [x] Run `bunx turbo typecheck --filter=@suaveplan/cache` — zero errors.
- [x] Run `bunx turbo test --filter=@suaveplan/cache` — all tests pass.
- [x] Run `bunx turbo test:coverage --filter=@suaveplan/cache` — 100% on all touched modules.
- [x] Run `bun run docs:check --filter=@suaveplan/cache` — zero errors.
- [x] Confirm no `TODO`, `FIXME`, `@deprecated`, untyped `any`, `ts-ignore`, or `.skip` in `src/` or `tests/`.
- [x] Confirm `"sideEffects": false` in `package.json`.
- [x] Run `bun scripts/publish.ts --package @suaveplan/cache`.
- [x] Update `CLAUDE.md` package listing to include `@suaveplan/cache`.
- [x] Archive: move `openspec/changes/enterprise-cache/` to `openspec/archive/2026-04-24-enterprise-cache/` and fold spec delta into `openspec/specs/database/spec.md`.