@cool-ai/beach-session-store
v0.2.0
Published
Per-key Redis session-data primitive for stateful Beach consumers — namespaced storage with hash-typed fields, INCR-allocated ids, WATCH/MULTI/EXEC CAS.
Readme
@cool-ai/beach-session-store
Home: cool-ai.org · Documentation: cool-ai.org/docs
Per-key Redis session-data primitive for stateful Beach consumers. Sibling to @cool-ai/beach-missives (the conversation log) and @cool-ai/beach-session (turn coordination); distinct from both.
Why
Every stateful Beach consumer needs to store domain-specific data alongside sessions — basket items, trip context, booking state, partial form data. The naive approach (one Redis key, one JSON blob) loses writes under concurrent load: two browser tabs, two server instances, two webhook deliveries arriving in the same second all trample each other. This package solves the pattern once: per-concept Redis keys, hash-typed fields for concurrent writers, INCR-allocated unique ids, and WATCH/MULTI/EXEC compare-and-swap with bounded retry.
Optional utility — not folded into core. Take it when you need it.
Install
npm install @cool-ai/beach-session-store ioredisioredis is a peer dependency. Tests can use the bundled InMemoryClient instead.
Quick start
import { SessionStore } from '@cool-ai/beach-session-store';
import Redis from 'ioredis';
const store = new SessionStore({
client: new Redis(process.env.REDIS_URL),
prefix: 'ta',
defaultTtlSeconds: 86_400, // 24h
});
// Per request: cheap to construct, do not cache.
const ns = store.namespace(sessionId);
// Scalar
await ns.set('basket-id', '7');
const basketId = await ns.get('basket-id');
// Hash — for fields that get concurrent partial updates
await ns.hset('basket', 'item-1', JSON.stringify({ sku: 'SKU-A', qty: 2 }));
const items = await ns.hgetAll('basket');
// Unique id allocator
const newItemId = await ns.incr('item-id-counter');
// Compare-and-swap for compound mutations
await ns.withCas('basket', async (snap, ops) => {
const items = await snap.hgetAll('basket');
const total = computeTotal(items);
ops.set('basket-total', String(total));
});
// End-of-session cleanup
await ns.purge();Key design
| Component | Role |
|---|---|
| SessionStore | Holds the Redis client + prefix + default TTL. Hands out cheap Namespace wrappers. |
| Namespace | Per-session handle. All operations live here. Construct fresh per request — no caching. |
| Key shape | <prefix>:<namespace>:<slot> — e.g. ta:user-42:basket. The prefix scopes the whole consumer; the namespace scopes a session; the slot is the field name. |
| TTL discipline | Every write applies a TTL. There is no "no expiry". touch() refreshes; purge() deletes. |
API
Construction
const store = new SessionStore({
client, // RedisClient — ioredis or InMemoryClient
prefix: 'app', // alphanumeric+dashes; no colons or whitespace
defaultTtlSeconds: 3600, // applied to every write that does not override
logger, // optional Logger — defaults to no-op
});Namespace handle
const ns = store.namespace(sessionId);Cheap. Make a fresh one per request rather than caching.
Scalar
await ns.get(slot): Promise<string | null>
await ns.set(slot, value, opts?: { ttlSeconds?: number }): Promise<void>
await ns.del(slot): Promise<void>Hash
await ns.hget(slot, field): Promise<string | null>
await ns.hset(slot, field, value, opts?: { ttlSeconds?: number }): Promise<void>
await ns.hdel(slot, field): Promise<void>
await ns.hgetAll(slot): Promise<Map<string, string>>
await ns.hkeys(slot): Promise<string[]>hset issues HSET then EXPIRE as two operations. A crash between the two leaves the hash without a TTL; the next hset / set / touch re-applies one. Inside withCas the same sequence runs atomically through MULTI.
Counter
await ns.incr(slot): Promise<number>INCR has no TTL effect. Pair with explicit set / touch if the counter should expire alongside the rest of the namespace.
Lifecycle
await ns.touch(): Promise<void> // refresh TTL on every namespace key
await ns.purge(): Promise<void> // delete every namespace key; audit-loggedBoth SCAN MATCH <prefix>:<namespace>:*. O(n) in the number of keys for the namespace; not hot-path.
CAS
await ns.withCas<T>(
watchedSlot: string,
fn: (snap: CasSnapshot, ops: CasOps) => Promise<T>,
opts?: { maxRetries?: number }, // default: 3
): Promise<T>Wraps WATCH/MULTI/EXEC with bounded retry. Reads inside fn go through snap and reflect the state at WATCH time; writes go through ops and are deferred into the MULTI pipeline.
The closure may run multiple times. Caller side effects must be advisory and idempotent until EXEC commits. The return value of the committing invocation is the function's return value.
incr is not in CasOps — MULTI cannot return mid-transaction values, so allocate via ns.incr() before withCas. Wasted ids on retry are acceptable.
You cannot read your own writes inside fn — snap reflects WATCH-time state, not the queued ops.
On exhaustion, throws CasContentionError with the contended key and total attempt count.
In-memory backend for tests
import { SessionStore, InMemoryClient } from '@cool-ai/beach-session-store';
const store = new SessionStore({
client: new InMemoryClient(),
prefix: 'test',
defaultTtlSeconds: 60,
});InMemoryClient implements the same RedisClient interface as ioredis. Single-threaded — WATCH/EXEC always commits on first attempt because tests do not have concurrent mutation. Tests that need to simulate contention call client.simulateConcurrentChange(key) between WATCH and EXEC.
Logger
interface Logger {
info(msg: string, data?: Record<string, unknown>): void;
warn(msg: string, data?: Record<string, unknown>): void;
error(msg: string, data?: Record<string, unknown>): void;
}Pino, Winston, and any consumer-built logger satisfy it. The default is a silent no-op.
The store emits these audit-shaped entries:
| Level | Message | Data |
|---|---|---|
| info | session-store: purge | { namespace, keyCount, ts } |
| info | session-store: touch | { namespace, keyCount, ts } |
| warn | session-store: cas-contention-retry | { key, attempt, ts } |
| warn | session-store: cas-contention-exhausted | { key, attempts, ts } |
No PII reaches the logger. Slot values, hash field contents, and CAS closure return values are never logged.
What this package is not
- Not the Beach event log. Use
@cool-ai/beach-missivesfor inbound/outbound message persistence. - Not turn coordination. Use
@cool-ai/beach-sessionfor turn lifecycle, slot keys, and the orchestrator's settlement contract. - Not multi-tenanted authorisation. The store has no notion of "who owns this namespace"; that's the consumer's job at the request edge.
- Not a queue. Durable jobs, retries, dead-letters belong to the eventual
@cool-ai/beach-jobspackage.
Related
@cool-ai/beach-missivesREADME — conversation-log storage.@cool-ai/beach-sessionREADME — turn coordination.
