Skip to content

quasar ​

@c9up/quasar: Redis connections for a ream application: named connections opened on first use, pub/sub on a separate socket, health checks and a clean shutdown. Guide: Redis.

Installation ​

bash
pnpm add @c9up/quasar

ream configure @c9up/quasar registers the provider, writes config/redis.ts, adds REDIS_HOST, REDIS_PORT and REDIS_PASSWORD to .env and declares their validation rules.

Entry points ​

ImportContents
@c9up/quasardefineConfig, QuasarManager, QuasarConnection, health checks, tracing channels, errors, types
@c9up/quasar/providerQuasarProvider (default export)
@c9up/quasar/services/mainThe default manager (default export), setQuasar, getQuasar, clearQuasar
@c9up/quasar/configureconfigure(codemods), run by ream configure

Exports ​

@c9up/quasar ​

ExportKindDescription
defineConfigfunctionTypes config/redis.ts; throws when no connection is declared or the default one is not declared.
isClusterConfigfunctiontrue when a connection config is a cluster (clusters set).
QuasarManagerclassThe declared connections, opened on demand. Redis commands called on it run on the default connection.
QuasarConnectionclassOne connection: the ioredis commands, pub/sub, state and events.
QuasarCheckclassHealth check that PINGs a connection.
QuasarMemoryUsageCheckclassHealth check comparing the server's memory use with a warning and a failure threshold.
errorsnamespaceThe package's errors, one class per code, see Errors
tracingChannelsconstNamespace holding redisCommand, the quasar.redis.command tracing channel.
QuasarConfigtype{ connection: keyof Connections & string; connections: Connections }.
ConnectionConfigtypeStandaloneConnectionConfig | ClusterConnectionConfig.
StandaloneConnectionConfiginterfaceioredis RedisOptions, plus url?, port?: string | number, password? and sentinelPassword? as a Credential.
ClusterConnectionConfiginterface{ clusters: ClusterNode[]; clusterOptions?: QuasarClusterOptions }.
QuasarClusterOptionsinterfaceioredis ClusterOptions whose redisOptions passwords accept a Credential.
Credentialtypestring | SecretValue.
SecretValueinterface{ release(): string }: a secret as env.get() returns it for Env.schema.secret().
RedisClienttypeRedis | Cluster (ioredis).
QuasarServiceinterfaceThe manager seen structurally; the type of the service accessor.
QuasarManagerEventsinterface{ connection: QuasarConnection }.
QuasarConnectionEventsinterfaceEvery event a connection emits, with its payload.
ChannelHandlertype(message: string, channel: string) => void | Promise<void>.
PatternHandlertype(channel: string, message: string, pattern: string) => void | Promise<void>.
PubSubOptionsinterface{ onError?(error: unknown): void; onSubscription?(count: number): void }.
ScriptDefinitioninterface{ lua: string; numberOfKeys?: number; readOnly?: boolean }.
QuasarLoggerinterface{ error(message: string, data?: Record<string, unknown>): void }.
HealthResultinterface{ message: string; status: HealthStatus; finishedAt: Date; meta?: Record<string, unknown> }.
HealthStatustype'ok' | 'warning' | 'error'.
CheckedConnectioninterfaceWhat a health check reads off a connection; a QuasarConnection satisfies it.
RedisCommandTracingDatainterface{ command: string; connection: string }: the command name, never its arguments.

@c9up/quasar/provider ​

ExportKindDescription
default (QuasarProvider)providerregister() builds the manager from the redis config and binds it; boot() hands it the container's logger; shutdown() calls quitAll().
QuasarAppContextinterface{ container; config }: the host the provider needs.

@c9up/quasar/services/main ​

ExportKindDescription
defaultconstThe seated QuasarService. Importing it opens nothing; a member read before a manager is seated throws.
setQuasarfunctionsetQuasar(manager: QuasarService): void: seats a manager (the provider calls it).
getQuasarfunctiongetQuasar(): QuasarService | undefined.
clearQuasarfunctionclearQuasar(manager: QuasarService): void: drops the seated manager if it is this one.

QuasarManager ​

new QuasarManager(config: QuasarConfig<Connections>, logger?: QuasarLogger). Every ioredis command of the forwarded list is also a method of the manager and runs on the default connection (redis.get('key')).

MemberSignatureDescription
connectionconnection(name?: keyof Connections & string): QuasarConnectionThe named connection (default one without a name), opened on first use and kept. Throws for an undeclared name.
defaultConnectionNameget defaultConnectionName(): keyof Connections & stringThe connection key of the config.
activeConnectionNamesget activeConnectionNames(): string[]Names of the open connections.
activeConnectionsget activeConnections(): Record<string, QuasarConnection>The open connections.
activeConnectionsCountget activeConnectionsCount(): numberHow many are open.
managerConfigreadonly managerConfig: QuasarConfig<Connections>The config; not enumerable, and toJSON() / util.inspect print it with credentials redacted.
subscribesubscribe(channel: string, handler: ChannelHandler, options?: PubSubOptions): voidSubscribe on the default connection. Failure goes to onError, never to a rejection.
subscribedsubscribed(channel: string, handler: ChannelHandler, options?: PubSubOptions): Promise<void>Same, resolved once the channel is live; rejects on failure.
unsubscribeunsubscribe(channel: string, handler?: ChannelHandler): Promise<void>Drop one handler, or every handler of the channel.
psubscribepsubscribe(pattern: string, handler: PatternHandler, options?: PubSubOptions): voidPattern subscription on the default connection.
psubscribedpsubscribed(pattern: string, handler: PatternHandler, options?: PubSubOptions): Promise<void>Awaitable form; rejects on failure.
punsubscribepunsubscribe(pattern: string, handler?: PatternHandler): Promise<void>Drop a pattern handler.
publishpublish(channel: string, message: string): Promise<number>Publish on the default connection; resolves to the receiver count.
defineCommanddefineCommand(name: string, definition: ScriptDefinition): thisRegister a LUA script on every open connection and on those opened later.
runCommandrunCommand(command: string, ...args: unknown[]): unknownRun a script registered with defineCommand on the default connection.
useLoggeruseLogger(logger: QuasarLogger): thisReport connection failures through this logger.
doNotLogErrorsdoNotLogErrors(): thisStop logging connection errors; the application handles the error event.
quitquit(name?: keyof Connections & string): Promise<void>QUIT one connection, the default one without a name.
disconnectdisconnect(name?: keyof Connections & string): Promise<void>Drop one connection without waiting for pending commands.
quitAllquitAll(): Promise<void>QUIT every open connection.
disconnectAlldisconnectAll(): Promise<void>Drop every open connection.
on / off / onceon('connection', listener): () => voidListen to each connection the manager opens; on returns the function that stops listening.

QuasarConnection ​

Every ioredis command of the forwarded list is a method of the connection (connection.set(...)).

MemberSignatureDescription
name / connectionNamereadonly name: stringThe declared connection name.
statusget status(): RedisClient['status']The command socket's ioredis status.
subscriberStatusget subscriberStatus(): RedisClient['status'] | undefinedThe pub/sub socket's status, undefined until the first subscription.
lastError / lastSubscriberErrorget lastError(): unknownLast error of each socket; its command keeps the name, not the arguments.
isConnecting / isReady / isClosedisReady(): booleanState of the command socket.
autoPipelineQueueSizeget autoPipelineQueueSize(): numberCommands waiting in the auto-pipeline.
ioConnectionget ioConnection(): RedisClientThe raw ioredis client.
ioSubscriberConnectionget ioSubscriberConnection(): RedisClient | undefinedThe raw pub/sub client, once opened.
mode / subscribeModeget mode(): Redis['mode'] | undefinedioredis mode of each socket.
slotsget slots(): Cluster['slots'] | undefinedCluster slot map; undefined on a standalone connection.
nodesnodes(role?: NodeRole): Redis[]A cluster's nodes, or one role's; throws on a standalone connection.
subscribe / subscribedas on the managerOpens the pub/sub socket on first use. Subscribing twice stacks the handlers.
psubscribe / psubscribedas on the managerPattern subscriptions.
unsubscribe / punsubscribeas on the managerDrop one handler, or all of a channel.
publishpublish(channel: string, message: string): Promise<number>Publish on the command socket.
defineCommand / runCommandas on the managerLUA scripts on this connection.
useLogger / doNotLogErrorsas on the managerError reporting for this connection.
quit / disconnectquit(): Promise<void>Close both sockets; handlers are dropped.
on / off / once / clearListeners / listenerCounton(event, listener): () => voidEvents of QuasarConnectionEvents: connect, wait, ready, error, close, reconnecting, end, the subscriber:* and node:* events, subscription:ready / subscription:error and their psubscription: twins.

Health checks ​

MemberSignatureDescription
new QuasarChecknew QuasarCheck(connection: CheckedConnection)Named Redis health check (<connection>).
new QuasarMemoryUsageChecknew QuasarMemoryUsageCheck(connection: Connection)Named Redis memory consumption health check (<connection>).
warnWhenExceedswarnWhenExceeds(value: string | number): thisWarning threshold in bytes or as a size ('100 mb'). Default 100 MB.
failWhenExceedsfailWhenExceeds(value: string | number): thisFailure threshold. Default 120 MB.
computecompute(callback: (connection: Connection) => Promise<number | null>): thisMeasure memory another way; null means unreadable.
asas(name: string): thisRename the check.
cacheForcacheFor(duration: string | number): thisReuse a result for seconds or a duration ('1 minute').
runrun(): Promise<HealthResult>Never throws; a connection that is not ready is not sent a command.

Configuration ​

config/redis.ts, read under the redis key.

OptionTypeDefaultDescription
connectionkeyof Connections & string—The connection redis.connection() returns without a name. Must be declared.
connectionsRecord<string, ConnectionConfig>—At least one connection.
connections.<name>.urlstring—redis:// or rediss:// URL; takes precedence over host and port.
connections.<name>.portstring | number—A string is converted; a value that is not a port number is refused.
connections.<name>.passwordCredential—A plain string or a Secret, released as the client is built.
connections.<name>.<option>ioredis RedisOptionsioredis defaultsAny other ioredis option (host, db, keyPrefix, retryStrategy…).
connections.<name>.clustersClusterNode[]—Seed nodes; makes the connection a cluster.
connections.<name>.clusterOptionsQuasarClusterOptions—ioredis cluster options.

The generated config/redis.ts reads REDIS_HOST, REDIS_PORT and REDIS_PASSWORD, uses db: 0, and gives up reconnecting after ten attempts.

Container bindings ​

TokenResolves to
'quasar.redis'QuasarManager<Record<string, ConnectionConfig>>
'redis'The same manager

Both tokens are typed on ContainerBindings once @c9up/quasar is imported.

Errors ​

CodeRaised when
E_INVALID_BYTES_VALUEA memory threshold of QuasarMemoryUsageCheck cannot be read as a size.
E_QUASAR_MISSING_CONFIGQuasarProvider registers and config/redis.ts does not exist.
E_QUASAR_INVALID_CONFIGdefineConfig declares no connection, or names a default connection it does not declare.
E_QUASAR_INVALID_PORTA connection's port is not a whole number between 0 and 65535.
E_QUASAR_UNKNOWN_CONNECTIONconnection(name) names a connection the config does not declare.
E_QUASAR_UNKNOWN_COMMANDrunCommand() names a command never defined with defineCommand(), or the connection lacks a forwarded command.
E_QUASAR_NOT_A_CLUSTERnodes() is called on a standalone connection.
E_QUASAR_INVALID_DURATIONcacheFor() on a health check is given a duration it cannot read.
E_QUASAR_NOT_BOOTEDA member of services/main is read before QuasarProvider seated a manager, or before setQuasar().

Each one is a class of the errors namespace and a @c9up/flare Exception with status 500: branch on error.code or on error instanceof errors.E_*. The messages of the E_QUASAR_ refusals start with [redis].

Migration ​

  • QuasarError is gone: test error.code, or error instanceof errors.E_QUASAR_* with import { errors } from '@c9up/quasar'.
  • InvalidBytesValueError is no longer exported: use errors.E_INVALID_BYTES_VALUE, which was already its alias.
  • An error from a connection or a rejected command no longer carries error.command.args; error.command.name stays. Log the arguments yourself where you need them and know they are safe.
  • A failed health check now reports a fixed message and meta.error: { name, code } instead of the error's message and the error object. Read the connection's log for the full error.

See also ​