Skip to content

echo ​

@c9up/echo: a cache with named stores, one or two layers (memory, Redis), grace periods, timeouts, single-flight factories and tags. Guide: Cache.

Installation ​

bash
pnpm add @c9up/echo
ream configure @c9up/echo

ream configure @c9up/echo adds CACHE_STORE=memory to the environment, registers the provider and the @c9up/echo/commands module, and writes config/cache.ts. A Redis store needs @c9up/quasar, an optional peer dependency.

Entry points ​

ImportContents
@c9up/echoCacheManager, the store builder, the drivers, defineConfig, the duration helpers, the errors and the types.
@c9up/echo/providerEchoProvider (default export).
@c9up/echo/services/mainThe booted CacheManager (default export), plus setCache, getCache, clearCache. Reading it before boot throws E_ECHO_NOT_BOOTED.
@c9up/echo/configureconfigure(codemods), run by ream configure @c9up/echo.
@c9up/echo/commandsThe cache:clear, cache:delete and cache:prune commands (getMetaData, getCommand).
@c9up/echo/testingcreateTestCache for unit tests.

Exports ​

@c9up/echo ​

ExportKindDescription
defineConfigfunctiondefineConfig<T extends EchoProviderConfig | MultiStoreConfig>(config: T): T. Returns the config unchanged.
storefunctionstore(options?: Omit<StoreConfig, 'driver'>): Store: starts describing a store.
StoreclassStore builder: useL1Layer, useL2Layer, useBus.
driversconstDriver factories: memory, redis, redisBus, tiered.
CacheManagerclassOne store: reads, writes, getOrSet, tags, namespaces, events.
CacheStoreManagerclassEvery store of a { default, stores } config, built on first use.
MemoryDriverclassIn-process driver with TTL, grace, tags and LRU bounds.
RedisDriverclassRedis driver with tags.
TieredDriverclassL1 in front of L2, with an optional bus.
isBusMessagefunctionisBusMessage(value: unknown): value is BusMessage.
parseDurationfunctionparseDuration(value: string): number: '5m', '300s', '500ms' to seconds; a bare number is seconds.
resolveTtlSecondsfunctionresolveTtlSeconds(ttl: Duration | undefined, defaultSeconds: number): number. null, 0 and Infinity mean no expiry (0); a negative TTL stays negative (already expired).
errorsnamespaceThe package's errors, one class per code, see Errors. Upstream's errors.E_FACTORY_ERROR, E_FACTORY_SOFT_TIMEOUT, E_FACTORY_HARD_TIMEOUT, E_UNDEFINED_VALUE, E_L2_CACHE_ERROR keep their names and messages. E_FACTORY_ERROR carries key and isBackgroundFactory, E_FACTORY_SOFT_TIMEOUT, E_FACTORY_HARD_TIMEOUT and E_ECHO_LOCK_TIMEOUT carry key, E_L2_CACHE_ERROR carries operation.
CacheConfiginterfaceOptions of one CacheManager; see Configuration.
EchoProviderConfiginterfaceCacheConfig plus driver?: 'memory': the single-store form of config/cache.ts.
MultiStoreConfiginterface{ default: string; ttl?: Duration; stores: Record<string, StoreConfig | Store>; emitter?: CacheEmitter }.
StoreConfiginterface{ driver: DriverFactory } plus the store options.
DriverFactorytype(context?: DriverContext) => CacheDriver.
DriverContextinterface{ store: string }, the store's key in the config.
CacheDriverinterfaceThe driver contract: get, set, delete, flush(prefix?), has, and optional getEntry, setEntry, connect, prune, disconnect.
TaggableDriverinterfaceCacheDriver plus setWithTags, deleteByTag, flushTags.
CacheEntryinterface{ value: T; stale: boolean; expiresAt?: number; tags?: string[] }.
MemoryDriverOptionsinterfaceSee Drivers.
RedisClientinterfaceThe Redis commands the driver calls (get, set, del, exists, keys, sadd, srem, smembers, expire, persist, ttl, optional scan).
TieredDriverOptionsinterface{ l1: CacheDriver; l2: CacheDriver; bus?: CacheBus; suppressL2Errors?: boolean; l2CircuitBreakerDuration?: Duration; store?: string }.
CacheBusinterfacepublish(message), subscribe(handler), optional unsubscribe(handler).
BusMessageinterface{ type: 'delete' | 'clear'; keys: string[]; … }.
Durationtypenumber | string | null: seconds, or '30s', '10m', '1h', '2d', '1w'.
Factorytype() => T | Promise<T>.
DefaultValuetypeT | (() => T).
GetOptionsinterface{ key: string; defaultValue?: DefaultValue<T>; grace?: Duration }.
SetOptionsinterface{ key: string; value: unknown; ttl?: Duration; grace?: Duration; tags?: string[] }.
GetOrSetOptionsinterfaceSee getOrSet.
GetOrSetForeverOptionstypeOmit<GetOrSetOptions<T>, 'ttl'>.
DeleteOptions, HasOptions, ExpireOptionsinterface{ key: string }.
DeleteManyOptionsinterface{ keys: string[] }.
DeleteByTagOptionsinterface{ tags: string[] }.
CacheEventMapinterfacePayload of each event; see Events.
CacheEmitterinterface{ emit(event: string, payload: unknown): unknown }: any emitter fits.

CacheManager ​

MemberSignatureDescription
constructornew CacheManager(driver: CacheDriver, config?: CacheConfig)
nameget name(): stringThe store name events report.
getget<T = unknown>(key: string): Promise<T | undefined>Also get(options: GetOptions<T>). defaultValue answers a miss; grace lets a stale value answer.
setset(key: string, value: unknown, ttlSeconds?: number): Promise<void>Also set(options: SetOptions). null and undefined are refused.
setForeversetForever(options: Omit<SetOptions, 'ttl'>): Promise<void>Never expires.
getOrSetgetOrSet<T>(key: string, ttlSeconds: number, factory: Factory<T>): Promise<T>Also getOrSet(options: GetOrSetOptions<T>). One factory runs per key; concurrent callers wait for it.
getOrSetForevergetOrSetForever<T>(options: GetOrSetForeverOptions<T>): Promise<T>
has / missinghas(key: string): Promise<boolean>Also take HasOptions.
pullpull<T = unknown>(key: string): Promise<T | undefined>Reads and deletes.
deletedelete(key: string): Promise<boolean>Also delete(options: DeleteOptions).
deleteManydeleteMany(keysOrOptions: string[] | DeleteManyOptions): Promise<boolean>
expireexpire(keyOrOptions: string | ExpireOptions): Promise<boolean>Marks the key stale now and keeps it for its grace period; without grace, deletes it.
clearclear(): Promise<void>Clears the store, or only this namespace.
setWithTagssetWithTags(key: string, value: unknown, tags: string[], ttlSeconds?: number): Promise<void>
deleteByTagdeleteByTag(tags: string[]): Promise<void>Also deleteByTag(options: DeleteByTagOptions). flushTags(tags) is a deprecated alias.
namespacenamespace(ns: string): CacheManagerA view under an extra key prefix; shares the driver, the defaults and the single-flight state. Throws E_ECHO_INVALID_ARGUMENT when ns is not a non-empty string, so a missing tenant id never gives back the whole store.
useuse(name?: string): CacheManagerA named store of the config. Throws when the manager owns a single store and a name is given.
on / onceon<E extends keyof CacheEventMap>(event: E, listener: (payload: CacheEventMap[E]) => void): thisA listener that throws is ignored.
offoff<E extends keyof CacheEventMap>(event: E, listener?: (payload: CacheEventMap[E]) => void): thisWithout a listener, drops them all.
pruneprune(): Promise<void>Drops expired entries, for drivers that do not evict on their own.
connect / connectAllconnect(): Promise<void>Opens what the driver needs outside the process (a bus subscription); connectAll covers every store.
disconnect / disconnectAlldisconnect(): Promise<void>Releases what the driver owns. An injected Redis client is not closed.

getOrSet ​

GetOrSetOptionsTypeDescription
keystring
factoryFactory<T>Computes the value on a miss.
ttlDurationFreshness of the value.
graceDurationHow long a stale value is kept to answer when the factory fails or is slow.
graceBackoffDurationAfter a failed factory, how long the stale value counts as fresh. '10s' by default; 0 or null retries on the next call.
timeoutDurationSoft timeout: on a stale hit, answer the stale value if the factory is slower, and refresh in the background.
hardTimeoutDurationReject with E_FACTORY_HARD_TIMEOUT past it.
lockTimeoutDurationHow long to wait for another caller's factory of the same key; then the stale value, or E_ECHO_LOCK_TIMEOUT.
tagsstring[]
onFactoryError(error: errors.E_FACTORY_ERROR) => voidTold of every factory failure, foreground and background.

CacheStoreManager ​

MemberSignatureDescription
constructornew CacheStoreManager(config: MultiStoreConfig)
defaultStoreNameget defaultStoreName(): string
useuse(name?: string): CacheManagerA store by name, or the default; built once.
on / once / offas on CacheManagerAcross every store, including ones not built yet.
clearAllclearAll(): Promise<void>Clears every configured store.
pruneprune(): Promise<void>Prunes every configured store.
connectAll / disconnectAllconnectAll(): Promise<void>Every built store.

Store ​

MemberSignatureDescription
constructornew Store(options?: Omit<StoreConfig, 'driver'>)
useL1LayeruseL1Layer(driver: DriverFactory): thisThe fast layer, usually memory.
useL2LayeruseL2Layer(driver: DriverFactory): thisThe shared layer, usually Redis.
useBususeBus(bus: CacheBus): thisKeeps every instance's L1 in step after a write; needs two layers.
entryentry(): StoreConfigThe { driver, …options } the manager reads. Throws E_ECHO_INVALID_CONFIG without a layer, or with a bus on one layer.

Drivers ​

FactorySignatureDescription
drivers.memorymemory(options?: MemoryDriverOptions): DriverFactory
drivers.redisredis(options: { client: RedisClient; prefix?: string } | { connection?: string; prefix?: string }): DriverFactoryA client, or a quasar connection name, loaded on the first command. clear() honours the connection's keyPrefix and scans every master of a cluster.
drivers.redisBusredisBus(options?: { connection?: string; channel?: string }): CacheBusRedis pub/sub as the bus.
drivers.tieredtiered(options: { l1: DriverFactory; l2: DriverFactory } & Omit<TieredDriverOptions, 'l1' | 'l2'>): DriverFactoryWhat Store builds from two layers.
MemoryDriverOptionsTypeDefaultDescription
sweepIntervalMsnumber60000How often expired entries are swept.
maxItemsnumber1000Entries held before the least recently used goes; 0 or Infinity for no ceiling.
maxSizenumber | stringnoneTotal size of the values (bytes or '10mb'); needs serialize.
maxEntrySizenumber | stringmaxSizeLargest single value; a bigger one is not stored and the key's old value goes.
serializebooleantrueStore JSON and return copies; false keeps references.

new MemoryDriver(options?), new RedisDriver(source: RedisClient \| (() => RedisClient \| Promise<RedisClient>), prefix?: string) and new TieredDriver(options: TieredDriverOptions) build a driver directly. MemoryDriver#destroy() stops the sweep timer. In a two-layer store, suppressL2Errors (default true) turns a failed L2 read into a miss and a failed L2 write into a skip; invalidations report a failed L2 either way. l2CircuitBreakerDuration skips a failing L2 for that long.

Events ​

EventPayload
cache:hit{ key, value, store, graced: boolean, duration }
cache:miss{ key, store, duration }
cache:written{ key, value, store, ttl: number | null, duration }
cache:deleted{ key, store, duration }
cache:cleared{ store, duration }
cache:expire{ key, store, duration }

duration is in milliseconds. The provider sends the events through the container's emitter binding when there is one.

@c9up/echo/testing ​

ExportKindDescription
createTestCachefunctioncreateTestCache(options?: CreateTestCacheOptions): TestCache: an isolated memory cache that records its events.
CreateTestCacheOptionsinterface{ prefix?: string; ttl?: number; grace?: Duration; name?: string }; name is 'test' by default.
TestCacheinterface{ cache: CacheManager; driver: MemoryDriver; events: RecordedEvent[]; dispose(): void }. Call dispose() after each test.
RecordedEventinterface{ event: string; payload: unknown }.

Commands ​

CommandArguments and flagsDescription
cache:clear[store], --namespace (-n), --tags (-t), --forceClears a store, a namespace or tags. Asks for confirmation in production unless --force. Fails on an empty --namespace.
cache:delete<key> [store]Deletes one entry. Asks for confirmation in production.
cache:prune[store]Removes expired entries, for stores without native TTL.

Configuration ​

config/cache.ts exports defineConfig({ default, stores }); the single-store form { prefix, ttl, … } builds one memory store. Stores are built on first use, so a Redis store that is never used opens no connection.

OptionTypeDefaultDescription
defaultstring(required)The store cache resolves to.
storesRecord<string, StoreConfig | Store>(required)store() builders, or { driver: drivers.memory(), … }.
ttlDuration3600 (seconds)TTL every store inherits.
emitterCacheEmitterthe container's emitterShared emitter for every store's events.

Options of a store (store(options)) and of a CacheConfig:

OptionTypeDefaultDescription
prefixstring''Prefix of every key.
ttlDuration3600 (seconds)Freshness of an entry.
graceDurationnoneDefault grace period.
graceBackoffDuration'10s'See getOrSet.
timeoutDurationnoneDefault soft timeout of getOrSet.
hardTimeoutDurationnoneDefault hard timeout of getOrSet.
lockTimeoutDurationnoneDefault single-flight wait.
suppressL2ErrorsbooleantrueTwo-layer stores only.
l2CircuitBreakerDurationDurationoffTwo-layer stores only.
namestring'default'CacheConfig only: the store name events report.

Container bindings ​

TokenResolves to
CacheManager (class), 'echo.cache', 'cache'The default store's CacheManager; use(name) reaches the others.

The string tokens are declared on ContainerBindings. The provider publishes the cache on services/main at boot and opens the drivers' connections (a bus subscription) when the application is ready.

Errors ​

CodeRaised when
E_FACTORY_ERRORThe factory of getOrSet() threw; cause holds its error.
E_FACTORY_SOFT_TIMEOUTNot raised: at the soft timeout echo serves the stale value. Exported for code that tests it.
E_FACTORY_HARD_TIMEOUTThe factory did not finish within its hard timeout.
E_UNDEFINED_VALUEA null or undefined value was written (null is refused too, on purpose).
E_L2_CACHE_ERRORA two-layer store's L2 failed and the failure is not suppressed.
E_ECHO_LOCK_TIMEOUTA caller waited too long for another caller's factory of the same key, with no stale value.
E_ECHO_INVALID_ARGUMENTA method was given an argument it cannot work with.
E_ECHO_INVALID_DURATIONA duration is neither a number nor a readable string.
E_ECHO_INVALID_CONFIGA config value cannot be read, or a store has no layer, or a Redis connection's keyPrefix is not a string when clear() needs it.
E_ECHO_UNKNOWN_STOREA store name, or the default store, is not declared in stores.
E_ECHO_UNSUPPORTED_DRIVERThe single-store config names a driver other than memory.
E_ECHO_NOT_TAGGABLETag invalidation on a driver without tags.
E_ECHO_SCAN_UNSUPPORTEDflush() on a Redis client, or on a cluster master, without scan().
E_ECHO_UNSERIALIZABLE_VALUEThe memory driver stores JSON and the value has none; pass serialize: false.
E_ECHO_QUASAR_MISSINGA Redis store was configured and @c9up/quasar is not installed.
E_ECHO_INCOMPLETE_CONNECTIONThe quasar connection lacks publish() or subscribe().
E_ECHO_NOT_BOOTEDservices/main was used before EchoProvider.boot() or setCache().
E_ECHO_BUS_SUBSCRIBE_FAILEDThe quasar cache bus reported a subscribe failure that is not an Error; cause holds what it reported.

Each one is a class of errors, a flare Exception: read error.code, or test error instanceof errors.E_ECHO_LOCK_TIMEOUT.

Migration ​

  • EchoError is gone: test error.code, or instanceof a class of errors.
  • The classes are named by their code: FactoryError is errors.E_FACTORY_ERROR, TimeoutError is errors.E_FACTORY_HARD_TIMEOUT, LockTimeoutError is errors.E_ECHO_LOCK_TIMEOUT, L2CacheError is errors.E_L2_CACHE_ERROR, UndefinedValueError is errors.E_UNDEFINED_VALUE, InvalidArgumentError is errors.E_ECHO_INVALID_ARGUMENT, InvalidDurationError is errors.E_ECHO_INVALID_DURATION.
  • None of them extends TypeError any more: replace instanceof TypeError with the code.
  • E_FACTORY_ERROR, E_FACTORY_HARD_TIMEOUT, E_UNDEFINED_VALUE and E_L2_CACHE_ERROR now carry the cache module's messages ("Factory has thrown an error", "Factory has timed out after waiting for hard timeout", "Cannot set undefined value in the cache, key: <key>", "An error occurred while interacting with the L2 cache"): read cause, key and operation instead of parsing the message. Their constructors are (key, cause, isBackground?), (key), (key) and (cause, { operation }?).
  • errors.E_FACTORY_SOFT_TIMEOUT is new.
  • namespace('') now throws E_ECHO_INVALID_ARGUMENT; so do undefined and null. It used to return the root view, whose clear() emptied the whole store. Check the name before you call it, and use the root cache to work on the whole store.
  • cache:clear --namespace= with an empty value now fails. Leave --namespace out to clear the whole store.

See also ​