core package

Redis-backed message queue engine for the @imqueue framework — the transport shared by @imqueue/rpc and the job packages.

Start from IMQ.create(), which picks a queue adapter from the options and returns an unstarted IMessageQueue. The two concrete adapters are RedisQueue (a single Redis server) and ClusteredRedisQueue (several servers, with sends distributed between them), and either can also be constructed directly.

Remarks

Every queue follows the same lifecycle: construct, start(), then either consume message events or send(), and finally destroy() to release the connections. start() is required before publish() or subscribe(); send() starts the queue implicitly. stop() only stops consuming — it keeps the writer, the watcher lock and the maintenance timers alive, so destroy() is what actually releases resources.

Delivery is at-least-once, so message handlers must be idempotent. Within a single process, writer and watcher connections are shared per host:port and reference-counted, and exactly one queue per key prefix is elected as the watcher that releases delayed messages and performs maintenance.

Example

import IMQ, { IMQMode, type IMessageQueue } from '@imqueue/core';

const queue: IMessageQueue = IMQ.create('my-queue', {
    host: 'localhost',
    port: 6379,
});

queue.on('message', (message, id, from) => {
    console.log(`got ${id} from ${from}`, message);
});

await queue.start();
await queue.send('my-queue', { hello: 'world' });

Classes

Class

Description

ClusteredRedisQueue

Scales a single logical queue horizontally across several redis instances. This is what IMQ.create() returns when IMQOptions.cluster or IMQOptions.clusterManagers is supplied.

IMQ

Message queue factory. This is also the default export of @imqueue/core.

RedisQueue

Redis-backed message queue with at-least-once delivery — the default IMessageQueue implementation, and what IMQ.create() returns for a single-server configuration.

UDPClusterManager

Cluster manager that discovers redis cluster members from UDP broadcast announcements. Supply instances through IMQOptions.clusterManagers.

Abstract Classes

Abstract Class

Description

ClusterManager

Abstract base for cluster-membership discovery. A manager tracks the clusters it feeds and pushes server add/remove events into each of them, so several clustered queues can share one discovery mechanism.

Supply instances through IMQOptions.clusterManagers. UDPClusterManager is the implementation shipped with the framework.

Enumerations

Enumeration

Description

IMQMode

Operating mode of a queue instance, selecting which halves of the queue are active. Passed as the third constructor argument and defaults to IMQMode.BOTH.

All modes still open a writer connection and take part in watcher election; the mode only controls whether a reader is created and whether sending is allowed.

LogLevel

Logger method to which profiling output is dispatched. Each value is the literal name of the corresponding ILogger method, so the level is used as a property lookup on the logger.

Functions

Function

Description

logDebugInfo(input)

Emits the profiling output for a single call: the elapsed time computed from input.start, and/or the call arguments serialized as indented JSON.

profile(options)

Wraps a class method so that its execution time and/or its call arguments are logged through the logger property of the decorated instance.

verifyLogLevel(level)

Normalizes an arbitrary value into a LogLevel.

Interfaces

Interface

Description

ClusterServer

A server registered in a ClusteredRedisQueue: its address, plus the RedisQueue instance serving that host.

Returned by ClusteredRedisQueue.addServer() so callers can address or inspect one specific host of the cluster.

DebugInfoOptions

Fully-resolved description of a single profiled call, as passed to logDebugInfo().

Normally constructed by the profile() decorator; supply it directly only to emit profiling output by hand. Every field except logger is required.

EventMap

Typed event map for a queue's EventEmitter base, giving compile-time signatures for the only two events a queue emits.

ICluster

Membership callbacks a clustered queue hands to a ClusterManager so the manager can add and remove servers as it discovers them.

Implement this to feed a clustered queue from your own discovery mechanism; ClusteredRedisQueue supplies an implementation of its own.

ILogger

Minimal logging contract the framework writes diagnostics through. The global console satisfies it, and it is the default.

Pass an implementation as IMQOptions.logger to redirect queue output, or a no-op implementation to silence it. The method names match the members of LogLevel, so a level can be used as a property lookup on a logger.

IMessage

Internal envelope of a queued message as it is stored in Redis: a generated id, the caller's payload, and the name of the queue that sent it.

IMessageQueue

Contract every messaging queue implementation fulfils. Implement it to add a transport of your own, or program against it to stay adapter-agnostic.

A queue is an EventEmitter typed by EventMap, so it emits exactly two events: message, with the payload, the message id and the sending queue's name; and error, with the error and the name of the internal routine that caught it. The error event fires only when a listener is attached — attach one if background failures must be observed.

IMessageQueueAuthConnection

Optional credentials for a queue host, forwarded to the Redis client as username and password.

Supply both for a Redis ACL user, or just password for a requirepass-only server. Omit both to connect unauthenticated, which is the default.

IMessageQueueConnection

A single queue-host endpoint: where to connect and, optionally, how to authenticate.

IMQOptions

Options accepted by every queue implementation.

Anything omitted falls back to DEFAULT_IMQ_OPTIONSlocalhost:6379, prefix imq, cleanup off, safe delivery off, gzip off, a 5000 ms watcher check and safe-delivery TTL, and signal handling on.

InitializedCluster

A cluster that has been registered with a ClusterManager, carrying the generated id that identifies it for ClusterManager.remove().

IRedisClient

The ioredis Redis client type augmented with the two internal bookkeeping flags imq stamps onto the connections it creates. Not intended for use as an option or parameter type by consumers.

IServerInput

Address of a cluster server, as supplied to the cluster membership operations ICluster.add, ICluster.remove and ICluster.find.

JsonArray

Represents JSON-serializable array

JsonObject

Represents JSON serializable object

ProfileDecoratorOptions

Options accepted by the profile() decorator.

Every field is optional; omitted fields fall back to the IMQ_LOG_TIME, IMQ_LOG_ARGS and IMQ_LOG_LEVEL environment defaults.

UDPClusterManagerOptions

Configuration for UDPClusterManager.

Pass any subset to the constructor; unspecified values come from DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS.

Variables

Variable

Description

DEFAULT_IMQ_OPTIONS

Default option values applied to every queue instance: localhost:6379, prefix imq, console as the logger, cleanup off with filter '*', safe delivery off with a 5000 ms lease TTL, gzip off, a 5000 ms watcher check interval, and process signal handling on.

DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS

Default options applied to every UDPClusterManager unless overridden: broadcast address 255.255.255.255 on port 63000, a 5000 ms alive-timeout correction, liveness checking enabled, process signal handling enabled, and console as the logger.

IMQ_CONNECTION_QUIT_TIMEOUT

Grace period (ms) for a graceful QUIT to complete before a channel is forcibly disconnected. A reader blocked on an infinite BRPOP/BLMOVE can never let QUIT through, so without this the socket would leak and keep the process alive.

IMQ_LOG_ARGS

Whether call-argument profiling is on by default, from the IMQ_LOG_ARGS environment variable.

IMQ_LOG_LEVEL

Default logger method for profiling output, from the IMQ_LOG_LEVEL environment variable.

Accepts log, info, warn or error; any other or missing value resolves to info without warning.

IMQ_LOG_TIME_FORMAT

Unit used when rendering profiled execution time, from the IMQ_LOG_TIME_FORMAT environment variable. Accepts microseconds, milliseconds or seconds, and defaults to microseconds.

IMQ_LOG_TIME

Whether execution-time profiling is on by default, from the IMQ_LOG_TIME environment variable.

IMQ_SHUTDOWN_TIMEOUT

Time in milliseconds allowed for releasing watcher locks when a shutdown signal is received, before the process is force-exited. Defaults to 1000; override with the IMQ_SHUTDOWN_TIMEOUT environment variable.

Type Aliases

Type Alias

Description

AllowedTimeFormat

Units in which profiled execution time can be rendered.

AnyJson

Any JSON value.

IMessageQueueConstructor

Constructor contract every queue adapter must satisfy: it takes the queue name, optional partial options and an optional IMQMode, and yields an IMessageQueue.

IMQ.create() resolves an adapter of this shape from the registered vendor adapters and instantiates it.

UDPWorkerOptions

The options actually handed to the UDP worker thread: everything except the logger, which is not structured-cloneable, and the signal-handling flag, which the main thread owns.

Read this page as plain markdown — no HTML, no navigation. For pasting into an LLM, or for an agent to fetch.