Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ not add these specs to a runner that CI invokes.
server that is removed is drained first:
`RedisQueue.drain()` releases the blocked reader with `CLIENT UNBLOCK` from
the writer, so a reply it already took reaches the listeners before teardown
removes them and drops the socket.
removes them and drops the socket. `RedisQueue.stop()` drains the same way before
it drops the reader, and clears the drain so a later `start()` reads again:
every graceful shutdown (`@imqueue/rpc` on `SIGTERM`) goes through it.

## Using this package correctly (for consumer-facing code an agent writes)

Expand Down
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,23 @@ queue does has an entry.

This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [3.10.2] - 2026-11-30

### Fixed

- **`stop()` no longer loses a message the broker already handed the
reader.** It dropped the reader's socket at once. A reader blocked in
`BRPOP` or `BLMOVE` whose message the broker had just popped and written
to the socket lost it with the socket: a request nobody answered, its
caller waiting out its whole timeout. Every graceful shutdown goes through
`stop()` — `@imqueue/rpc` stops the queue on `SIGTERM` — so each
scale-down or rollout could drop requests in flight. Now `stop()` drains
the reader first, as a broker removed from a cluster already was: the
reader is released by `CLIENT UNBLOCK` sent on the writer, what it already
took reaches the `message` listeners, and only then is the socket dropped.
The wait is bounded by `IMQ_CONNECTION_QUIT_TIMEOUT` (1 s by default) and
never rejects. A stopped queue reads again when started, as before.

## [3.10.1] - 2026-11-30

### Fixed
Expand Down
3 changes: 2 additions & 1 deletion src/IMessageQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -757,7 +757,8 @@ export interface IMessageQueue extends EventEmitter<EventMap> {
* @returns this queue instance
*
* @remarks
* Only the reader is torn down. The writer connection, the watcher lock and
* A message the reader already took from the broker is handed to the
* `message` listeners before it stops. Only the reader is torn down. The writer connection, the watcher lock and
* the watcher/maintenance timers all stay active, and
* {@link IMessageQueue.send} and {@link IMessageQueue.publish} keep working —
* call {@link IMessageQueue.destroy} to release those. Safe to call when not
Expand Down
26 changes: 19 additions & 7 deletions src/RedisQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,9 @@ export const IMQ_SHUTDOWN_TIMEOUT = envInt('IMQ_SHUTDOWN_TIMEOUT', 1000);
* @remarks
* Defaults to 1000; override with the `IMQ_CONNECTION_QUIT_TIMEOUT` environment
* variable, which is read once when the module is loaded. Applies to the writer,
* watcher and subscription channels — the reader is disconnected immediately
* without attempting `QUIT`.
* watcher and subscription channels. The reader is never sent `QUIT`: it is
* disconnected once {@link RedisQueue.stop} has released it from its blocking
* read, which this also bounds.
*/
export const IMQ_CONNECTION_QUIT_TIMEOUT = envInt(
'IMQ_CONNECTION_QUIT_TIMEOUT',
Expand Down Expand Up @@ -1197,8 +1198,8 @@ export class RedisQueue
}

/**
* Stops consuming messages by tearing down this instance's reader
* connection.
* Stops consuming messages: releases the reader from its blocking read,
* hands on what it already took, then tears down its connection.
*
* @returns this queue instance
*
Expand All @@ -1211,21 +1212,32 @@ export class RedisQueue
* stopped stays registered in a process-wide registry and is not
* garbage-collected.
*
* The reader socket is dropped immediately rather than closed with a graceful
* `QUIT`, so Redis stops treating it as a consumer at once and cannot hand it
* a message the torn-down read loop would drop.
* The reader is first drained, as {@link RedisQueue.drain} does: a message
* the broker already handed it is in its socket, and dropping the socket
* at once lost it, leaving its caller to wait out its whole timeout. Once
* the read loop has stopped, the socket is dropped rather than closed with
* a graceful `QUIT`. A broker that does not release the reader within
* `IMQ_CONNECTION_QUIT_TIMEOUT` is given up on and the socket dropped all
* the same, so the wait is bounded and never rejects.
*/
@profile()
public async stop(): Promise<RedisQueue> {
this.verbose('Stopping queue...');

if (this.reader) {
await this.drain(IMQ_CONNECTION_QUIT_TIMEOUT);
}

if (this.reader) {
this.verbose('Destroying reader...');
this.destroyChannel('reader');

delete this.reader;
}

delete this.readerId;
delete this.reading;
this.draining = false;
this.initialized = false;

this.verbose('Queue stopped!');
Expand Down
82 changes: 82 additions & 0 deletions test/unit/RedisQueue.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,88 @@ describe('RedisQueue', () => {
assert.ok(!rq.reader);
await rq.destroy();
});

it('hands on a message the broker gave the reader as it stops', async () => {
const rq: any = new RedisQueue(`StopInFlight${Date.now()}`, {
logger,
});
const got: unknown[] = [];
let pending:
| {
resolve: (value: unknown) => void;
reject: (err: Error) => void;
}
| undefined;
let closed = false;

rq.on('message', (message: unknown) => got.push(message));
await rq.start();

// the broker side of the race: the reply is already written to
// the reader's socket, and is parsed on a later turn of the event
// loop unless the socket is destroyed first
mock.method(
rq.reader,
'brpop',
() =>
new Promise((resolve, reject) => {
pending = { resolve, reject };
}),
);
mock.method(rq.reader, 'disconnect', () => {
closed = true;
pending?.reject(new Error('Connection is closed.'));

return true;
});
// the reader's first, real blocking read ends within 100 ms and
// the loop then blocks on the one above
await new Promise(resolve => setTimeout(resolve, 150));
assert.ok(pending, 'the reader is not blocked on its read');

const handed = pending;

setImmediate(() => {
if (!closed) {
handed.resolve([
rq.key,
rq.pack({
id: 'in-flight',
message: { reply: 'in the socket' },
from: rq.name,
}),
]);
}
});

await rq.stop();

assert.deepEqual(got, [{ reply: 'in the socket' }]);
assert.ok(!rq.reader);
await rq.destroy();
});

it('reads again when started after a stop', async () => {
const rq: any = new RedisQueue(`StopStart${Date.now()}`, {
logger,
});
const got: unknown[] = [];

rq.on('message', (message: unknown) => got.push(message));
await rq.start();
await new Promise(resolve => setTimeout(resolve, 20));
await rq.stop();

assert.equal(rq.draining, false);

await rq.start();
await new Promise(resolve => setTimeout(resolve, 20));
await rq.send(rq.name, { after: 'the restart' });
await new Promise(resolve => setTimeout(resolve, 250));

assert.deepEqual(got, [{ after: 'the restart' }]);
await rq.destroy();
});
});

describe('send()', () => {
Expand Down
Loading