ioredis-streams 2.1.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/redis-client.d.ts +1 -0
- package/dist/redis-client.js.map +1 -1
- package/dist/stream-consumer.d.ts +25 -1
- package/dist/stream-consumer.js +76 -8
- package/dist/stream-consumer.js.map +1 -1
- package/dist/types.d.ts +13 -0
- package/docs/api.md +3 -1
- package/docs/configuration.md +2 -0
- package/docs/examples.md +12 -7
- package/package.json +1 -1
- package/src/redis-client.ts +3 -0
- package/src/stream-consumer.ts +75 -14
- package/src/types.ts +13 -0
- package/test/redis-streams.spec.ts +2 -1
- package/test/stream-consumer.integration.spec.ts +149 -0
- package/test/stream-consumer.spec.ts +178 -14
package/dist/redis-client.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ export interface IRedisClient {
|
|
|
4
4
|
xreadgroup(...args: any[]): Promise<any>;
|
|
5
5
|
xpending(...args: any[]): Promise<any>;
|
|
6
6
|
xclaim(...args: any[]): Promise<any>;
|
|
7
|
+
xinfo?(...args: any[]): Promise<any>;
|
|
7
8
|
xadd(...args: any[]): Promise<any>;
|
|
8
9
|
xack(stream: string, group: string, ...ids: string[]): Promise<number>;
|
|
9
10
|
publish(channel: string, message: string): Promise<number>;
|
package/dist/redis-client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redis-client.js","sourceRoot":"","sources":["../src/redis-client.ts"],"names":[],"mappings":";;;;;;AAAA,sDAAgD;
|
|
1
|
+
{"version":3,"file":"redis-client.js","sourceRoot":"","sources":["../src/redis-client.ts"],"names":[],"mappings":";;;;;;AAAA,sDAAgD;AAyBzC,MAAM,kBAAkB,GAAG,CAAC,UAAkB,EAAoC,EAAE,CACzF,UAAU;KACP,KAAK,CAAC,GAAG,CAAC;KACV,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;KACtB,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C,CAAC;IACtC,OAAO,CAAC,SAAsB,IAAA,8BAAsB,GAAE,EAAE,iBAAiC,EAAE,EAAgB,EAAE;QAC3G,IAAI,CAAC,OAAO;YAAE,OAAO,GAAG,IAAA,yBAAiB,EAAC,MAAM,EAAE,cAAc,CAAC,CAAC;QAClE,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC,CAAC,EAAE,CAAC"}
|
|
@@ -3,6 +3,8 @@ import { IRedisClient } from './redis-client';
|
|
|
3
3
|
import { ConsumerBuffer } from './consumer-buffer';
|
|
4
4
|
import { ConsumerConfigs, IEvent, IWaitEvent } from './types';
|
|
5
5
|
export declare type EventProcessor = <T>(id: string, event: string, eventObj: IEvent<T> | IWaitEvent<T>) => Promise<any>;
|
|
6
|
+
export declare const DEFAULT_DEAD_CONSUMER_IDLE_TIME: number;
|
|
7
|
+
export declare const DEFAULT_DEAD_CONSUMER_CHECK_INTERVAL: number;
|
|
6
8
|
export declare class StreamConsumer {
|
|
7
9
|
protected readonly redis: IRedisClient;
|
|
8
10
|
protected readonly processEvent: EventProcessor;
|
|
@@ -22,7 +24,29 @@ export declare class StreamConsumer {
|
|
|
22
24
|
protected doClaim(): Promise<boolean>;
|
|
23
25
|
protected doRead(): Promise<boolean>;
|
|
24
26
|
protected processMessage<T>(id: string, message: string[]): Promise<any>;
|
|
27
|
+
/**
|
|
28
|
+
* Stops reading and waits for the in-flight read/claim iteration (and everything it buffered) to finish.
|
|
29
|
+
*
|
|
30
|
+
* This consumer is deliberately NOT removed from the group: XGROUP DELCONSUMER would discard its pending
|
|
31
|
+
* entries (messages whose handler failed and that are waiting for a retry). They stay pending, so the
|
|
32
|
+
* live consumers' `doClaim()` retries them, exactly as for a crashed consumer. Instead, the dead-consumer
|
|
33
|
+
* cleanup runs once here, and its name is removed by a later cleanup once it is idle and owns nothing.
|
|
34
|
+
*/
|
|
25
35
|
dispose(): Promise<void>;
|
|
26
|
-
protected
|
|
36
|
+
protected lastTimeConsumersCleanup: number;
|
|
37
|
+
/**
|
|
38
|
+
* Removes consumers that have been idle (XINFO CONSUMERS `idle`) longer than `deadConsumerIdleTime` and
|
|
39
|
+
* own no pending messages, e.g. names left behind by stopped or killed pods.
|
|
40
|
+
*
|
|
41
|
+
* Runs from the reading loop every `deadConsumerCheckInterval`, and on `dispose()` (`force`).
|
|
42
|
+
* Live consumers poll (XREADGROUP BLOCK) every `readBlockTime`, so their idle time stays far below the
|
|
43
|
+
* threshold. Uses plain sequential Redis 5.0 commands; never throws.
|
|
44
|
+
*/
|
|
45
|
+
protected cleanupDeadConsumers(force?: boolean): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Re-checks that `consumer` owns no pending messages, then runs XGROUP DELCONSUMER
|
|
48
|
+
* (which would otherwise discard them). Returns false when the consumer was kept.
|
|
49
|
+
*/
|
|
50
|
+
protected removeConsumerIfNoPending(consumer: string): Promise<boolean>;
|
|
27
51
|
publishDeadLetters(...messages: [string, string[]][]): Promise<void>;
|
|
28
52
|
}
|
package/dist/stream-consumer.js
CHANGED
|
@@ -3,9 +3,22 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.StreamConsumer = void 0;
|
|
6
|
+
exports.StreamConsumer = exports.DEFAULT_DEAD_CONSUMER_CHECK_INTERVAL = exports.DEFAULT_DEAD_CONSUMER_IDLE_TIME = void 0;
|
|
7
7
|
const log4js_api_1 = __importDefault(require("@log4js-node/log4js-api"));
|
|
8
8
|
const consumer_buffer_1 = require("./consumer-buffer");
|
|
9
|
+
exports.DEFAULT_DEAD_CONSUMER_IDLE_TIME = 24 * 60 * 60 * 1000;
|
|
10
|
+
exports.DEFAULT_DEAD_CONSUMER_CHECK_INTERVAL = 6 * 60 * 60 * 1000;
|
|
11
|
+
// XINFO CONSUMERS returns each consumer as a flat [key, value, key, value, ...] array (RESP2)
|
|
12
|
+
// or as an object (RESP3 / some clients).
|
|
13
|
+
function parseInfoEntry(raw) {
|
|
14
|
+
if (Array.isArray(raw)) {
|
|
15
|
+
const out = {};
|
|
16
|
+
for (let i = 0; i + 1 < raw.length; i += 2)
|
|
17
|
+
out[String(raw[i])] = raw[i + 1];
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
return (raw && typeof raw === 'object') ? raw : {};
|
|
21
|
+
}
|
|
9
22
|
class StreamConsumer {
|
|
10
23
|
redis;
|
|
11
24
|
processEvent;
|
|
@@ -55,6 +68,7 @@ class StreamConsumer {
|
|
|
55
68
|
}
|
|
56
69
|
async tryReading() {
|
|
57
70
|
while (!this.disposing) {
|
|
71
|
+
await this.cleanupDeadConsumers();
|
|
58
72
|
try {
|
|
59
73
|
const claimedAnything = await this.doClaim();
|
|
60
74
|
if (claimedAnything && !this.disposing)
|
|
@@ -139,21 +153,75 @@ class StreamConsumer {
|
|
|
139
153
|
}
|
|
140
154
|
return result;
|
|
141
155
|
}
|
|
156
|
+
/**
|
|
157
|
+
* Stops reading and waits for the in-flight read/claim iteration (and everything it buffered) to finish.
|
|
158
|
+
*
|
|
159
|
+
* This consumer is deliberately NOT removed from the group: XGROUP DELCONSUMER would discard its pending
|
|
160
|
+
* entries (messages whose handler failed and that are waiting for a retry). They stay pending, so the
|
|
161
|
+
* live consumers' `doClaim()` retries them, exactly as for a crashed consumer. Instead, the dead-consumer
|
|
162
|
+
* cleanup runs once here, and its name is removed by a later cleanup once it is idle and owns nothing.
|
|
163
|
+
*/
|
|
142
164
|
async dispose() {
|
|
143
165
|
this.disposing = true;
|
|
144
|
-
// Wait for the in-flight read/claim iteration (and everything it buffered) to finish
|
|
145
|
-
// before deregistering, so we don't delete the consumer out from under active work.
|
|
146
166
|
await this.readingLoop;
|
|
147
|
-
await this.
|
|
167
|
+
await this.cleanupDeadConsumers(true);
|
|
148
168
|
}
|
|
149
|
-
|
|
169
|
+
lastTimeConsumersCleanup = 0;
|
|
170
|
+
/**
|
|
171
|
+
* Removes consumers that have been idle (XINFO CONSUMERS `idle`) longer than `deadConsumerIdleTime` and
|
|
172
|
+
* own no pending messages, e.g. names left behind by stopped or killed pods.
|
|
173
|
+
*
|
|
174
|
+
* Runs from the reading loop every `deadConsumerCheckInterval`, and on `dispose()` (`force`).
|
|
175
|
+
* Live consumers poll (XREADGROUP BLOCK) every `readBlockTime`, so their idle time stays far below the
|
|
176
|
+
* threshold. Uses plain sequential Redis 5.0 commands; never throws.
|
|
177
|
+
*/
|
|
178
|
+
async cleanupDeadConsumers(force = false) {
|
|
179
|
+
const { streamName, groupName, peerName, readBlockTime, claimIdleTime } = this.config;
|
|
180
|
+
const idleTime = this.config.deadConsumerIdleTime ?? exports.DEFAULT_DEAD_CONSUMER_IDLE_TIME;
|
|
181
|
+
if (!(idleTime > 0) || !this.redis.xinfo)
|
|
182
|
+
return;
|
|
183
|
+
if (!force) {
|
|
184
|
+
const interval = this.config.deadConsumerCheckInterval ?? exports.DEFAULT_DEAD_CONSUMER_CHECK_INTERVAL;
|
|
185
|
+
if (!(interval > 0))
|
|
186
|
+
return;
|
|
187
|
+
if (this.lastTimeConsumersCleanup + interval > Date.now())
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
this.lastTimeConsumersCleanup = Date.now();
|
|
191
|
+
const threshold = Math.max(idleTime, 2 * (readBlockTime + claimIdleTime));
|
|
150
192
|
try {
|
|
151
|
-
await this.redis.
|
|
152
|
-
|
|
193
|
+
const consumers = await this.redis.xinfo('CONSUMERS', streamName, groupName);
|
|
194
|
+
for (const raw of consumers ?? []) {
|
|
195
|
+
const info = parseInfoEntry(raw);
|
|
196
|
+
const name = info.name !== undefined ? String(info.name) : undefined;
|
|
197
|
+
if (!name || name === peerName)
|
|
198
|
+
continue;
|
|
199
|
+
if (Number(info.pending) !== 0 || !(Number(info.idle) > threshold))
|
|
200
|
+
continue;
|
|
201
|
+
if (await this.removeConsumerIfNoPending(name)) {
|
|
202
|
+
this.logger.info(`Removed dead consumer '${name}' (idle ${info.idle}ms) from group '${groupName}'`);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
153
205
|
}
|
|
154
206
|
catch (err) {
|
|
155
|
-
this.logger.
|
|
207
|
+
this.logger.warn(`Error while cleaning up dead consumers of group '${groupName}'`, err);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Re-checks that `consumer` owns no pending messages, then runs XGROUP DELCONSUMER
|
|
212
|
+
* (which would otherwise discard them). Returns false when the consumer was kept.
|
|
213
|
+
*/
|
|
214
|
+
async removeConsumerIfNoPending(consumer) {
|
|
215
|
+
const { streamName, groupName } = this.config;
|
|
216
|
+
const pending = await this.redis.xpending(streamName, groupName, '-', '+', 1, consumer);
|
|
217
|
+
if (pending && pending.length)
|
|
218
|
+
return false;
|
|
219
|
+
const discarded = Number(await this.redis.xgroup('DELCONSUMER', streamName, groupName, consumer));
|
|
220
|
+
if (discarded > 0) {
|
|
221
|
+
this.logger.warn(`Removing consumer '${consumer}' from group '${groupName}' discarded ${discarded} pending message(s) ` +
|
|
222
|
+
`on stream '${streamName}'. Is the consumer name (peerName) used by more than one process?`);
|
|
156
223
|
}
|
|
224
|
+
return true;
|
|
157
225
|
}
|
|
158
226
|
async publishDeadLetters(...messages) {
|
|
159
227
|
if (!this.config.deadLetters)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream-consumer.js","sourceRoot":"","sources":["../src/stream-consumer.ts"],"names":[],"mappings":";;;;;;AAAA,yEAAoD;AAEpD,uDAAmD;
|
|
1
|
+
{"version":3,"file":"stream-consumer.js","sourceRoot":"","sources":["../src/stream-consumer.ts"],"names":[],"mappings":";;;;;;AAAA,yEAAoD;AAEpD,uDAAmD;AAStC,QAAA,+BAA+B,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACtD,QAAA,oCAAoC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,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parallel' | 'serial';
|
|
50
50
|
maxLen: number;
|
|
51
|
+
/**
|
|
52
|
+
* Consumers in the group that have been idle (XINFO CONSUMERS `idle`) longer than this and own no
|
|
53
|
+
* pending messages are removed from the group (e.g. names left behind by stopped or killed pods).
|
|
54
|
+
* `0` disables the cleanup. Default: 86400000 (24 hours). Values lower than
|
|
55
|
+
* `2 × (readBlockTime + claimIdleTime)` are raised to that floor.
|
|
56
|
+
*/
|
|
57
|
+
deadConsumerIdleTime?: number;
|
|
58
|
+
/**
|
|
59
|
+
* How often each consumer runs the dead-consumer cleanup. It also runs once on startup and once when
|
|
60
|
+
* the consumer is stopped. `0` disables the periodic run (it still runs on stop).
|
|
61
|
+
* Default: 21600000 (6 hours).
|
|
62
|
+
*/
|
|
63
|
+
deadConsumerCheckInterval?: number;
|
|
51
64
|
};
|
|
52
65
|
export declare type ConsumerConfigs = StreamConfigs & {
|
|
53
66
|
peerName: string;
|
package/docs/api.md
CHANGED
|
@@ -172,7 +172,7 @@ Starts the consumer loop. Must be called after all `.handle()` registrations.
|
|
|
172
172
|
|
|
173
173
|
| Method | Description |
|
|
174
174
|
|---|---|
|
|
175
|
-
| `stop()` | Gracefully stops reading new messages
|
|
175
|
+
| `stop()` | Gracefully stops reading new messages and waits for in-flight/buffered messages to finish processing. The consumer is **not** deleted from the group: messages whose handler failed stay pending and are retried by the other consumers, exactly as for a crashed consumer. `stop()` then runs the dead-consumer cleanup once (see `deadConsumerIdleTime`), and this consumer's own name is removed by a later cleanup once it is idle and owns no pending messages. Always `await` it before your process exits (e.g. on `SIGTERM`). |
|
|
176
176
|
| `continue()` | Resumes a stopped consumer without re-initializing. |
|
|
177
177
|
|
|
178
178
|
```ts
|
|
@@ -370,6 +370,8 @@ type StreamConfigs = {
|
|
|
370
370
|
readBlockTime: number;
|
|
371
371
|
claimIdleTime: number;
|
|
372
372
|
maxLen: number;
|
|
373
|
+
deadConsumerIdleTime?: number; // default 86400000 (24h), 0 disables dead-consumer cleanup
|
|
374
|
+
deadConsumerCheckInterval?: number; // default 21600000 (6h), 0 = only on startup/stop
|
|
373
375
|
}
|
|
374
376
|
```
|
|
375
377
|
|
package/docs/configuration.md
CHANGED
|
@@ -80,6 +80,8 @@ These can be set per-stream when calling `.stream(name, options)`:
|
|
|
80
80
|
| `readBlockTime` | `number` (ms) | `5000` | How long to block waiting for new messages |
|
|
81
81
|
| `claimIdleTime` | `number` (ms) | `15000` | How long a message must be idle before another consumer can claim it |
|
|
82
82
|
| `maxLen` | `number` | `100000` | Maximum number of entries the stream will hold (trimmed with `MAXLEN ~`) |
|
|
83
|
+
| `deadConsumerIdleTime` | `number` (ms) | `86400000` (24h) | Consumers in the group idle longer than this **and** with no pending messages are removed (e.g. names left by stopped or killed pods). `0` disables the cleanup. Values below `2 × (readBlockTime + claimIdleTime)` are raised to that floor |
|
|
84
|
+
| `deadConsumerCheckInterval` | `number` (ms) | `21600000` (6h) | How often each consumer runs that cleanup. It also runs on startup and when the consumer is stopped. `0` disables the periodic run (it still runs on stop) |
|
|
83
85
|
|
|
84
86
|
```ts
|
|
85
87
|
const stream = streams
|
package/docs/examples.md
CHANGED
|
@@ -303,12 +303,17 @@ await stream['job.queued']({ jobId: 'job-123' });
|
|
|
303
303
|
|
|
304
304
|
Stop the consumer cleanly on process exit to avoid mid-flight message loss.
|
|
305
305
|
|
|
306
|
-
`stop()` stops reading
|
|
307
|
-
and be acked
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
the
|
|
306
|
+
`stop()` stops reading and waits for in-flight/buffered messages to finish processing
|
|
307
|
+
and be acked. It does **not** delete the consumer from the group: `XGROUP DELCONSUMER`
|
|
308
|
+
would discard messages whose handler failed and that are waiting to be retried. Those
|
|
309
|
+
stay pending and the other consumers retry them, exactly as when a pod crashes.
|
|
310
|
+
|
|
311
|
+
Names of stopped or killed consumers are cleaned up by the live consumers: every
|
|
312
|
+
`deadConsumerCheckInterval` (default 6 hours), on startup and on `stop()`, consumers
|
|
313
|
+
idle for more than `deadConsumerIdleTime` (default 24 hours) that own no pending
|
|
314
|
+
messages are removed. The consumer name (`peerName`) must be unique per running
|
|
315
|
+
process (stable StatefulSet pod names are fine). **Always `await` `stop()`** before
|
|
316
|
+
the process exits (e.g. on pod termination).
|
|
312
317
|
|
|
313
318
|
```ts
|
|
314
319
|
import { RedisStreams, event } from 'ioredis-streams';
|
|
@@ -325,7 +330,7 @@ const { stop } = await stream.consume();
|
|
|
325
330
|
// Graceful shutdown on SIGTERM / SIGINT (e.g. Kubernetes pod termination)
|
|
326
331
|
const shutdown = async () => {
|
|
327
332
|
console.log('Shutting down...');
|
|
328
|
-
await stop(); // finishes in-flight work
|
|
333
|
+
await stop(); // finishes in-flight work; pending (failed) messages stay retryable
|
|
329
334
|
process.exit(0);
|
|
330
335
|
};
|
|
331
336
|
|
package/package.json
CHANGED
package/src/redis-client.ts
CHANGED
|
@@ -5,6 +5,9 @@ export interface IRedisClient {
|
|
|
5
5
|
xreadgroup(...args: any[]): Promise<any>;
|
|
6
6
|
xpending(...args: any[]): Promise<any>;
|
|
7
7
|
xclaim(...args: any[]): Promise<any>;
|
|
8
|
+
// Optional so custom IRedisClient implementations keep compiling (ioredis provides it).
|
|
9
|
+
// Used by StreamConsumer.cleanupDeadConsumers(); skipped when absent.
|
|
10
|
+
xinfo?(...args: any[]): Promise<any>;
|
|
8
11
|
xadd(...args: any[]): Promise<any>;
|
|
9
12
|
xack(stream: string, group: string, ...ids: string[]): Promise<number>;
|
|
10
13
|
publish(channel: string, message: string): Promise<number>;
|
package/src/stream-consumer.ts
CHANGED
|
@@ -9,6 +9,20 @@ export type EventProcessor = <T>(
|
|
|
9
9
|
eventObj: IEvent<T> | IWaitEvent<T>
|
|
10
10
|
) => Promise<any>;
|
|
11
11
|
|
|
12
|
+
export const DEFAULT_DEAD_CONSUMER_IDLE_TIME = 24 * 60 * 60 * 1000;
|
|
13
|
+
export const DEFAULT_DEAD_CONSUMER_CHECK_INTERVAL = 6 * 60 * 60 * 1000;
|
|
14
|
+
|
|
15
|
+
// XINFO CONSUMERS returns each consumer as a flat [key, value, key, value, ...] array (RESP2)
|
|
16
|
+
// or as an object (RESP3 / some clients).
|
|
17
|
+
function parseInfoEntry(raw: unknown): Record<string, unknown> {
|
|
18
|
+
if (Array.isArray(raw)) {
|
|
19
|
+
const out: Record<string, unknown> = {};
|
|
20
|
+
for (let i = 0; i + 1 < raw.length; i += 2) out[String(raw[i])] = raw[i + 1];
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
return (raw && typeof raw === 'object') ? raw as Record<string, unknown> : {};
|
|
24
|
+
}
|
|
25
|
+
|
|
12
26
|
export class StreamConsumer {
|
|
13
27
|
|
|
14
28
|
protected logger: loggerFactory.Logger;
|
|
@@ -74,6 +88,7 @@ export class StreamConsumer {
|
|
|
74
88
|
|
|
75
89
|
protected async tryReading(): Promise<void> {
|
|
76
90
|
while (!this.disposing) {
|
|
91
|
+
await this.cleanupDeadConsumers();
|
|
77
92
|
try {
|
|
78
93
|
const claimedAnything = await this.doClaim();
|
|
79
94
|
if (claimedAnything && !this.disposing) continue;
|
|
@@ -195,29 +210,75 @@ export class StreamConsumer {
|
|
|
195
210
|
return result;
|
|
196
211
|
}
|
|
197
212
|
|
|
213
|
+
/**
|
|
214
|
+
* Stops reading and waits for the in-flight read/claim iteration (and everything it buffered) to finish.
|
|
215
|
+
*
|
|
216
|
+
* This consumer is deliberately NOT removed from the group: XGROUP DELCONSUMER would discard its pending
|
|
217
|
+
* entries (messages whose handler failed and that are waiting for a retry). They stay pending, so the
|
|
218
|
+
* live consumers' `doClaim()` retries them, exactly as for a crashed consumer. Instead, the dead-consumer
|
|
219
|
+
* cleanup runs once here, and its name is removed by a later cleanup once it is idle and owns nothing.
|
|
220
|
+
*/
|
|
198
221
|
async dispose(): Promise<void> {
|
|
199
222
|
this.disposing = true;
|
|
200
|
-
// Wait for the in-flight read/claim iteration (and everything it buffered) to finish
|
|
201
|
-
// before deregistering, so we don't delete the consumer out from under active work.
|
|
202
223
|
await this.readingLoop;
|
|
203
|
-
await this.
|
|
224
|
+
await this.cleanupDeadConsumers(true);
|
|
204
225
|
}
|
|
205
226
|
|
|
206
|
-
protected
|
|
227
|
+
protected lastTimeConsumersCleanup = 0;
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Removes consumers that have been idle (XINFO CONSUMERS `idle`) longer than `deadConsumerIdleTime` and
|
|
231
|
+
* own no pending messages, e.g. names left behind by stopped or killed pods.
|
|
232
|
+
*
|
|
233
|
+
* Runs from the reading loop every `deadConsumerCheckInterval`, and on `dispose()` (`force`).
|
|
234
|
+
* Live consumers poll (XREADGROUP BLOCK) every `readBlockTime`, so their idle time stays far below the
|
|
235
|
+
* threshold. Uses plain sequential Redis 5.0 commands; never throws.
|
|
236
|
+
*/
|
|
237
|
+
protected async cleanupDeadConsumers(force = false): Promise<void> {
|
|
238
|
+
const { streamName, groupName, peerName, readBlockTime, claimIdleTime } = this.config;
|
|
239
|
+
const idleTime = this.config.deadConsumerIdleTime ?? DEFAULT_DEAD_CONSUMER_IDLE_TIME;
|
|
240
|
+
if (!(idleTime > 0) || !this.redis.xinfo) return;
|
|
241
|
+
|
|
242
|
+
if (!force) {
|
|
243
|
+
const interval = this.config.deadConsumerCheckInterval ?? DEFAULT_DEAD_CONSUMER_CHECK_INTERVAL;
|
|
244
|
+
if (!(interval > 0)) return;
|
|
245
|
+
if (this.lastTimeConsumersCleanup + interval > Date.now()) return;
|
|
246
|
+
}
|
|
247
|
+
this.lastTimeConsumersCleanup = Date.now();
|
|
248
|
+
|
|
249
|
+
const threshold = Math.max(idleTime, 2 * (readBlockTime + claimIdleTime));
|
|
207
250
|
try {
|
|
208
|
-
await this.redis.
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
251
|
+
const consumers: unknown[] = await this.redis.xinfo('CONSUMERS', streamName, groupName);
|
|
252
|
+
for (const raw of consumers ?? []) {
|
|
253
|
+
const info = parseInfoEntry(raw);
|
|
254
|
+
const name = info.name !== undefined ? String(info.name) : undefined;
|
|
255
|
+
if (!name || name === peerName) continue;
|
|
256
|
+
if (Number(info.pending) !== 0 || !(Number(info.idle) > threshold)) continue;
|
|
257
|
+
if (await this.removeConsumerIfNoPending(name)) {
|
|
258
|
+
this.logger.info(`Removed dead consumer '${name}' (idle ${info.idle}ms) from group '${groupName}'`);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
215
261
|
} catch (err) {
|
|
216
|
-
this.logger.
|
|
217
|
-
|
|
218
|
-
|
|
262
|
+
this.logger.warn(`Error while cleaning up dead consumers of group '${groupName}'`, err);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Re-checks that `consumer` owns no pending messages, then runs XGROUP DELCONSUMER
|
|
268
|
+
* (which would otherwise discard them). Returns false when the consumer was kept.
|
|
269
|
+
*/
|
|
270
|
+
protected async removeConsumerIfNoPending(consumer: string): Promise<boolean> {
|
|
271
|
+
const { streamName, groupName } = this.config;
|
|
272
|
+
const pending: unknown[] = await this.redis.xpending(streamName, groupName, '-', '+', 1, consumer);
|
|
273
|
+
if (pending && pending.length) return false;
|
|
274
|
+
const discarded = Number(await this.redis.xgroup('DELCONSUMER', streamName, groupName, consumer));
|
|
275
|
+
if (discarded > 0) {
|
|
276
|
+
this.logger.warn(
|
|
277
|
+
`Removing consumer '${consumer}' from group '${groupName}' discarded ${discarded} pending message(s) ` +
|
|
278
|
+
`on stream '${streamName}'. Is the consumer name (peerName) used by more than one process?`,
|
|
219
279
|
);
|
|
220
280
|
}
|
|
281
|
+
return true;
|
|
221
282
|
}
|
|
222
283
|
|
|
223
284
|
async publishDeadLetters(...messages: [string, string[]][]): Promise<void> {
|
package/src/types.ts
CHANGED
|
@@ -43,6 +43,19 @@ export type StreamConfigs = {
|
|
|
43
43
|
batchSize: number;
|
|
44
44
|
mode: 'parallel' | 'serial';
|
|
45
45
|
maxLen: number;
|
|
46
|
+
/**
|
|
47
|
+
* Consumers in the group that have been idle (XINFO CONSUMERS `idle`) longer than this and own no
|
|
48
|
+
* pending messages are removed from the group (e.g. names left behind by stopped or killed pods).
|
|
49
|
+
* `0` disables the cleanup. Default: 86400000 (24 hours). Values lower than
|
|
50
|
+
* `2 × (readBlockTime + claimIdleTime)` are raised to that floor.
|
|
51
|
+
*/
|
|
52
|
+
deadConsumerIdleTime?: number;
|
|
53
|
+
/**
|
|
54
|
+
* How often each consumer runs the dead-consumer cleanup. It also runs once on startup and once when
|
|
55
|
+
* the consumer is stopped. `0` disables the periodic run (it still runs on stop).
|
|
56
|
+
* Default: 21600000 (6 hours).
|
|
57
|
+
*/
|
|
58
|
+
deadConsumerCheckInterval?: number;
|
|
46
59
|
};
|
|
47
60
|
|
|
48
61
|
export type ConsumerConfigs = StreamConfigs & {
|
|
@@ -383,7 +383,8 @@ describe('RedisStreams - consume() and continue()', () => {
|
|
|
383
383
|
unblock();
|
|
384
384
|
await stopping;
|
|
385
385
|
|
|
386
|
-
|
|
386
|
+
// the consumer is not deleted on stop: DELCONSUMER would discard its pending (to be retried) messages
|
|
387
|
+
expect(fakeConsumer.xgroup.calledWith('DELCONSUMER')).to.be.false;
|
|
387
388
|
});
|
|
388
389
|
|
|
389
390
|
it('continue() calls start() again on the consumer', async () => {
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import 'mocha';
|
|
2
|
+
import { expect } from 'chai';
|
|
3
|
+
import Redis from 'ioredis';
|
|
4
|
+
import { StreamConsumer } from '../src/stream-consumer';
|
|
5
|
+
import { ConsumerConfigs } from '../src/types';
|
|
6
|
+
import { IRedisClient } from '../src/redis-client';
|
|
7
|
+
|
|
8
|
+
// Runs against a real Redis only when REDIS_IT_HOST is set, e.g.
|
|
9
|
+
// docker run --rm -d -p 6390:6379 redis:7 && REDIS_IT_HOST=localhost REDIS_IT_PORT=6390 npm test
|
|
10
|
+
const host = process.env.REDIS_IT_HOST;
|
|
11
|
+
const port = parseInt(process.env.REDIS_IT_PORT || '6379');
|
|
12
|
+
const describeIt = host ? describe : describe.skip;
|
|
13
|
+
|
|
14
|
+
const silent: any = { trace: () => {}, info: () => {}, warn: () => {}, error: () => {} };
|
|
15
|
+
const wait = (ms: number) => new Promise(r => setTimeout(r, ms));
|
|
16
|
+
|
|
17
|
+
async function until(cond: () => boolean | Promise<boolean>, timeout = 10000): Promise<void> {
|
|
18
|
+
const start = Date.now();
|
|
19
|
+
while (!(await cond())) {
|
|
20
|
+
if (Date.now() - start > timeout) throw new Error('Timed out waiting for condition');
|
|
21
|
+
await wait(50);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describeIt('StreamConsumer (integration, real Redis)', function () {
|
|
26
|
+
this.timeout(30000);
|
|
27
|
+
|
|
28
|
+
let admin: Redis.Redis;
|
|
29
|
+
const clients: Redis.Redis[] = [];
|
|
30
|
+
let stream: string;
|
|
31
|
+
const group = 'it-group';
|
|
32
|
+
|
|
33
|
+
const newClient = () => {
|
|
34
|
+
const c = new Redis({ host, port });
|
|
35
|
+
clients.push(c);
|
|
36
|
+
return c;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const makeConsumer = (
|
|
40
|
+
peerName: string,
|
|
41
|
+
handler: (id: string) => Promise<any>,
|
|
42
|
+
overrides: Partial<ConsumerConfigs> = {},
|
|
43
|
+
) => new StreamConsumer(newClient() as unknown as IRedisClient, async (id) => handler(id), {
|
|
44
|
+
streamName: stream,
|
|
45
|
+
groupName: group,
|
|
46
|
+
peerName,
|
|
47
|
+
batchSize: 5,
|
|
48
|
+
claimIdleTime: 300,
|
|
49
|
+
readBlockTime: 100,
|
|
50
|
+
mode: 'parallel',
|
|
51
|
+
maxLen: 1000,
|
|
52
|
+
logger: silent,
|
|
53
|
+
...overrides,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const consumerNames = async () =>
|
|
57
|
+
((await admin.xinfo('CONSUMERS', stream, group)) as any[]).map(c => c[1] as string);
|
|
58
|
+
|
|
59
|
+
beforeEach(async () => {
|
|
60
|
+
admin = newClient();
|
|
61
|
+
stream = `it-stream-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
afterEach(async () => {
|
|
65
|
+
await admin.del(stream);
|
|
66
|
+
clients.splice(0).forEach(c => c.disconnect());
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
const pendingOf = async (consumer: string) =>
|
|
70
|
+
(await admin.xpending(stream, group, '-', '+', 100, consumer)) as [string, string, number, number][];
|
|
71
|
+
const payload = JSON.stringify({ name: 'evt', v: '1', time: 1, data: {} });
|
|
72
|
+
|
|
73
|
+
it('does not lose a failed message on stop: the consumer is kept and another consumer retries it', async () => {
|
|
74
|
+
const processedByB: string[] = [];
|
|
75
|
+
|
|
76
|
+
const a = makeConsumer('pod-a', async () => { throw new Error('handler failed'); });
|
|
77
|
+
await a.init();
|
|
78
|
+
a.start();
|
|
79
|
+
const id = await admin.xadd(stream, '*', 'evt', payload);
|
|
80
|
+
|
|
81
|
+
// pod-a read the message, its handler failed, so it stays pending on pod-a
|
|
82
|
+
await until(async () => (await pendingOf('pod-a')).length === 1);
|
|
83
|
+
await a.dispose();
|
|
84
|
+
|
|
85
|
+
// pod-a is kept, together with its pending message
|
|
86
|
+
expect(await consumerNames()).to.include('pod-a');
|
|
87
|
+
expect((await pendingOf('pod-a')).map(p => p[0])).to.deep.equal([id]);
|
|
88
|
+
|
|
89
|
+
const b = makeConsumer('pod-b', async (msgId) => { processedByB.push(msgId); });
|
|
90
|
+
await b.init();
|
|
91
|
+
b.start();
|
|
92
|
+
await until(() => processedByB.length > 0);
|
|
93
|
+
await b.dispose();
|
|
94
|
+
|
|
95
|
+
expect(processedByB).to.deep.equal([id]);
|
|
96
|
+
expect(((await admin.xpending(stream, group)) as any[])[0]).to.equal(0);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('periodic cleanup removes idle consumers with nothing pending and keeps those with pending messages', async () => {
|
|
100
|
+
const reader = newClient();
|
|
101
|
+
await admin.xgroup('CREATE', stream, group, '$', 'MKSTREAM');
|
|
102
|
+
const id1 = await admin.xadd(stream, '*', 'evt', payload);
|
|
103
|
+
await admin.xadd(stream, '*', 'evt', payload);
|
|
104
|
+
// two "killed" consumers: one holding a pending message, one with nothing pending
|
|
105
|
+
await reader.xreadgroup('GROUP', group, 'killed-with-pending', 'COUNT', 1, 'STREAMS', stream, '>');
|
|
106
|
+
const read = await reader.xreadgroup('GROUP', group, 'killed-empty', 'COUNT', 1, 'STREAMS', stream, '>') as any;
|
|
107
|
+
await reader.xack(stream, group, read[0][1][0][0]);
|
|
108
|
+
|
|
109
|
+
// idle floor = 2 * (readBlockTime + claimIdleTime) = 2 * (100 + 300) = 800ms
|
|
110
|
+
await wait(1000);
|
|
111
|
+
const b = makeConsumer('pod-b', async () => undefined, {
|
|
112
|
+
deadConsumerIdleTime: 1,
|
|
113
|
+
deadConsumerCheckInterval: 100000,
|
|
114
|
+
});
|
|
115
|
+
b.lastTimePendingCheck = Date.now() + 60000; // keep pod-b from claiming, to observe the cleanup alone
|
|
116
|
+
await b.init();
|
|
117
|
+
b.start();
|
|
118
|
+
await until(async () => !(await consumerNames()).includes('killed-empty'), 5000);
|
|
119
|
+
await b.dispose();
|
|
120
|
+
|
|
121
|
+
const names = await consumerNames();
|
|
122
|
+
expect(names).to.not.include('killed-empty');
|
|
123
|
+
expect(names).to.include('killed-with-pending');
|
|
124
|
+
expect((await pendingOf('killed-with-pending')).map(p => p[0])).to.deep.equal([id1]);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it('cleanup runs on stop and removes consumers that became idle and empty', async () => {
|
|
128
|
+
const processed: string[] = [];
|
|
129
|
+
const a = makeConsumer('pod-a', async (msgId) => { processed.push(msgId); });
|
|
130
|
+
await a.init();
|
|
131
|
+
a.start();
|
|
132
|
+
await admin.xadd(stream, '*', 'evt', payload);
|
|
133
|
+
await until(() => processed.length === 1);
|
|
134
|
+
await a.dispose();
|
|
135
|
+
expect(await consumerNames()).to.include('pod-a');
|
|
136
|
+
|
|
137
|
+
// pod-b only checks on startup and on stop (huge interval); idle floor = 2 * (100 + 300) = 800ms
|
|
138
|
+
const b = makeConsumer('pod-b', async () => undefined, {
|
|
139
|
+
deadConsumerIdleTime: 1,
|
|
140
|
+
deadConsumerCheckInterval: 100000000,
|
|
141
|
+
});
|
|
142
|
+
await b.init();
|
|
143
|
+
b.start();
|
|
144
|
+
await wait(1000);
|
|
145
|
+
expect(await consumerNames()).to.include('pod-a');
|
|
146
|
+
await b.dispose();
|
|
147
|
+
expect(await consumerNames()).to.not.include('pod-a');
|
|
148
|
+
});
|
|
149
|
+
});
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import 'mocha';
|
|
2
2
|
import { expect } from 'chai';
|
|
3
|
-
import
|
|
3
|
+
import sinon from 'sinon';
|
|
4
|
+
import {
|
|
5
|
+
StreamConsumer, EventProcessor, DEFAULT_DEAD_CONSUMER_IDLE_TIME, DEFAULT_DEAD_CONSUMER_CHECK_INTERVAL,
|
|
6
|
+
} from '../src/stream-consumer';
|
|
4
7
|
import { ConsumerConfigs, IEvent, IWaitEvent } from '../src/types';
|
|
5
8
|
import { createFakeRedis, FakeRedis } from './helpers/fake-redis';
|
|
6
9
|
|
|
@@ -17,6 +20,16 @@ class T extends StreamConsumer {
|
|
|
17
20
|
async testDoRead() { return this.doRead(); }
|
|
18
21
|
async testProcessMessage(id: string, message: string[]) { return this.processMessage(id, message); }
|
|
19
22
|
async testTryReading() { return this.tryReading(); }
|
|
23
|
+
async testCleanupDeadConsumers() { return this.cleanupDeadConsumers(); }
|
|
24
|
+
get testLastTimeConsumersCleanup() { return this.lastTimeConsumersCleanup; }
|
|
25
|
+
set testLastTimeConsumersCleanup(v: number) { this.lastTimeConsumersCleanup = v; }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function makeLogger() {
|
|
29
|
+
const calls: Record<string, any[][]> = { trace: [], info: [], warn: [], error: [] };
|
|
30
|
+
const logger: any = {};
|
|
31
|
+
for (const level of Object.keys(calls)) logger[level] = (...args: any[]) => { calls[level].push(args); };
|
|
32
|
+
return { logger, calls };
|
|
20
33
|
}
|
|
21
34
|
|
|
22
35
|
function makeConfig(overrides: Partial<ConsumerConfigs> = {}): ConsumerConfigs {
|
|
@@ -416,6 +429,9 @@ describe('StreamConsumer', () => {
|
|
|
416
429
|
});
|
|
417
430
|
|
|
418
431
|
describe('dispose()', () => {
|
|
432
|
+
const HOUR = 60 * 60 * 1000;
|
|
433
|
+
const flat = (name: string, pending: number, idle: number) => ['name', name, 'pending', pending, 'idle', idle];
|
|
434
|
+
|
|
419
435
|
it('sets the disposing flag to stop the reading loop', async () => {
|
|
420
436
|
const fake = createFakeRedis();
|
|
421
437
|
const consumer = new T(fake, async () => undefined, makeConfig());
|
|
@@ -424,16 +440,35 @@ describe('StreamConsumer', () => {
|
|
|
424
440
|
expect(consumer.testDisposing).to.be.true;
|
|
425
441
|
});
|
|
426
442
|
|
|
427
|
-
it('
|
|
428
|
-
const fake = createFakeRedis();
|
|
443
|
+
it('does not remove itself from the group, so its pending messages stay retryable', async () => {
|
|
444
|
+
const fake: any = createFakeRedis();
|
|
445
|
+
fake.xinfo = sinon.stub().resolves([flat('peer-1', 2, 25 * HOUR)]);
|
|
429
446
|
const consumer = new T(fake, async () => undefined, makeConfig());
|
|
430
447
|
await consumer.dispose();
|
|
431
|
-
expect(fake.xgroup.calledWith('DELCONSUMER', 'my-stream', 'my-group', 'peer-1')).to.be.
|
|
448
|
+
expect(fake.xgroup.calledWith('DELCONSUMER', 'my-stream', 'my-group', 'peer-1')).to.be.false;
|
|
432
449
|
});
|
|
433
450
|
|
|
434
|
-
it('
|
|
435
|
-
const fake = createFakeRedis();
|
|
436
|
-
fake.
|
|
451
|
+
it('runs the dead-consumer cleanup on stop, even right after a periodic run', async () => {
|
|
452
|
+
const fake: any = createFakeRedis();
|
|
453
|
+
fake.xinfo = sinon.stub().resolves([flat('dead', 0, 25 * HOUR)]);
|
|
454
|
+
const consumer = new T(fake, async () => undefined, makeConfig());
|
|
455
|
+
consumer.testLastTimeConsumersCleanup = Date.now();
|
|
456
|
+
await consumer.dispose();
|
|
457
|
+
expect(fake.xinfo.calledOnce).to.be.true;
|
|
458
|
+
expect(fake.xgroup.calledWith('DELCONSUMER', 'my-stream', 'my-group', 'dead')).to.be.true;
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
it('runs the cleanup on stop even when the periodic run is disabled', async () => {
|
|
462
|
+
const fake: any = createFakeRedis();
|
|
463
|
+
fake.xinfo = sinon.stub().resolves([]);
|
|
464
|
+
const consumer = new T(fake, async () => undefined, makeConfig({ deadConsumerCheckInterval: 0 }));
|
|
465
|
+
await consumer.dispose();
|
|
466
|
+
expect(fake.xinfo.calledOnce).to.be.true;
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
it('waits for the in-flight reading loop to finish before running the cleanup', async () => {
|
|
470
|
+
const fake: any = createFakeRedis();
|
|
471
|
+
fake.xinfo = sinon.stub().resolves([]);
|
|
437
472
|
let unblock!: () => void;
|
|
438
473
|
fake.xreadgroup.callsFake(async () => {
|
|
439
474
|
await new Promise<void>(r => { unblock = r; });
|
|
@@ -442,27 +477,156 @@ describe('StreamConsumer', () => {
|
|
|
442
477
|
|
|
443
478
|
const consumer = new T(fake, async () => undefined, makeConfig());
|
|
444
479
|
consumer.lastTimePendingCheck = Date.now(); // skip claim
|
|
480
|
+
consumer.testLastTimeConsumersCleanup = Date.now(); // skip periodic cleanup
|
|
445
481
|
|
|
446
482
|
const started = consumer.start();
|
|
447
|
-
// give start() a tick to enter tryReading() and register the in-flight xreadgroup call
|
|
448
483
|
await new Promise(r => setTimeout(r, 0));
|
|
449
484
|
|
|
450
485
|
const disposing = consumer.dispose();
|
|
451
|
-
|
|
452
|
-
expect(fake.
|
|
486
|
+
await new Promise(r => setTimeout(r, 0));
|
|
487
|
+
expect(fake.xinfo.called).to.be.false;
|
|
453
488
|
|
|
454
489
|
unblock();
|
|
455
490
|
await started;
|
|
456
491
|
await disposing;
|
|
492
|
+
expect(fake.xinfo.calledOnce).to.be.true;
|
|
493
|
+
});
|
|
494
|
+
|
|
495
|
+
it('never throws when the cleanup fails', async () => {
|
|
496
|
+
const fake: any = createFakeRedis();
|
|
497
|
+
fake.xinfo = sinon.stub().rejects(new Error('connection closed'));
|
|
498
|
+
const consumer = new T(fake, async () => undefined, makeConfig());
|
|
499
|
+
await expect(consumer.dispose()).to.eventually.not.be.rejected;
|
|
500
|
+
});
|
|
501
|
+
});
|
|
502
|
+
|
|
503
|
+
describe('cleanupDeadConsumers()', () => {
|
|
504
|
+
const HOUR = 60 * 60 * 1000;
|
|
505
|
+
const flat = (name: string, pending: number, idle: number) => ['name', name, 'pending', pending, 'idle', idle];
|
|
506
|
+
|
|
507
|
+
function setup(consumers: any[], overrides: Partial<ConsumerConfigs> = {}) {
|
|
508
|
+
const fake: any = createFakeRedis();
|
|
509
|
+
fake.xinfo = sinon.stub().resolves(consumers);
|
|
510
|
+
const { logger, calls } = makeLogger();
|
|
511
|
+
const consumer = new T(fake, async () => undefined, makeConfig({ logger, ...overrides }));
|
|
512
|
+
return { fake, consumer, calls };
|
|
513
|
+
}
|
|
514
|
+
const deleted = (fake: any) => fake.xgroup.getCalls()
|
|
515
|
+
.filter((c: any) => c.args[0] === 'DELCONSUMER').map((c: any) => c.args[3]);
|
|
516
|
+
|
|
517
|
+
it('defaults to removing consumers idle for 24h, checked every 6h', () => {
|
|
518
|
+
expect(DEFAULT_DEAD_CONSUMER_IDLE_TIME).to.equal(24 * HOUR);
|
|
519
|
+
expect(DEFAULT_DEAD_CONSUMER_CHECK_INTERVAL).to.equal(6 * HOUR);
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
it('removes only consumers idle beyond 24h with no pending messages, never itself', async () => {
|
|
523
|
+
const { fake, consumer } = setup([
|
|
524
|
+
flat('dead', 0, 25 * HOUR),
|
|
525
|
+
flat('dead-with-pending', 3, 25 * HOUR),
|
|
526
|
+
flat('recent', 0, 2 * HOUR),
|
|
527
|
+
flat('alive', 0, 1000),
|
|
528
|
+
flat('peer-1', 0, 25 * HOUR),
|
|
529
|
+
]);
|
|
530
|
+
await consumer.testCleanupDeadConsumers();
|
|
531
|
+
expect(fake.xinfo.calledWith('CONSUMERS', 'my-stream', 'my-group')).to.be.true;
|
|
532
|
+
expect(deleted(fake)).to.deep.equal(['dead']);
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
it('re-checks the pending entries of the consumer right before DELCONSUMER', async () => {
|
|
536
|
+
const { fake, consumer } = setup([flat('dead', 0, 25 * HOUR)]);
|
|
537
|
+
await consumer.testCleanupDeadConsumers();
|
|
538
|
+
expect(fake.xpending.calledWith('my-stream', 'my-group', '-', '+', 1, 'dead')).to.be.true;
|
|
539
|
+
expect(fake.xpending.calledBefore(fake.xgroup)).to.be.true;
|
|
540
|
+
});
|
|
457
541
|
|
|
458
|
-
|
|
542
|
+
it('keeps the consumer when the re-check finds pending messages', async () => {
|
|
543
|
+
const { fake, consumer, calls } = setup([flat('dead', 0, 25 * HOUR)]);
|
|
544
|
+
fake.xpending.withArgs('my-stream', 'my-group', '-', '+', 1, 'dead').resolves([['1-0', 'dead', 10, 1]]);
|
|
545
|
+
await consumer.testCleanupDeadConsumers();
|
|
546
|
+
expect(deleted(fake)).to.deep.equal([]);
|
|
547
|
+
expect(calls.info).to.have.length(0);
|
|
459
548
|
});
|
|
460
549
|
|
|
461
|
-
it('
|
|
550
|
+
it('warns with the count when DELCONSUMER reports discarded pending messages', async () => {
|
|
551
|
+
const { fake, consumer, calls } = setup([flat('dead', 0, 25 * HOUR)]);
|
|
552
|
+
fake.xgroup.withArgs('DELCONSUMER').resolves(2);
|
|
553
|
+
await consumer.testCleanupDeadConsumers();
|
|
554
|
+
expect(calls.warn.some(args => /discarded 2 pending/.test(args[0]))).to.be.true;
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
it('accepts object-shaped XINFO entries', async () => {
|
|
558
|
+
const { fake, consumer } = setup([{ name: 'dead', pending: 0, idle: 25 * HOUR }]);
|
|
559
|
+
await consumer.testCleanupDeadConsumers();
|
|
560
|
+
expect(deleted(fake)).to.deep.equal(['dead']);
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
it('honours a custom deadConsumerIdleTime', async () => {
|
|
564
|
+
const { fake, consumer } = setup([flat('a', 0, 3 * HOUR), flat('b', 0, HOUR)], { deadConsumerIdleTime: 2 * HOUR });
|
|
565
|
+
await consumer.testCleanupDeadConsumers();
|
|
566
|
+
expect(deleted(fake)).to.deep.equal(['a']);
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
it('raises a too-low idle threshold to 2 x (readBlockTime + claimIdleTime)', async () => {
|
|
570
|
+
// floor = 2 * (5000 + 15000) = 40000
|
|
571
|
+
const { fake, consumer } = setup([flat('a', 0, 30000), flat('b', 0, 50000)], { deadConsumerIdleTime: 1 });
|
|
572
|
+
await consumer.testCleanupDeadConsumers();
|
|
573
|
+
expect(deleted(fake)).to.deep.equal(['b']);
|
|
574
|
+
});
|
|
575
|
+
|
|
576
|
+
it('is disabled entirely when deadConsumerIdleTime is 0', async () => {
|
|
577
|
+
const { fake, consumer } = setup([flat('a', 0, 25 * HOUR)], { deadConsumerIdleTime: 0 });
|
|
578
|
+
await consumer.testCleanupDeadConsumers();
|
|
579
|
+
await consumer.dispose();
|
|
580
|
+
expect(fake.xinfo.called).to.be.false;
|
|
581
|
+
});
|
|
582
|
+
|
|
583
|
+
it('is skipped when the client has no xinfo', async () => {
|
|
462
584
|
const fake = createFakeRedis();
|
|
463
|
-
fake.xgroup.rejects(new Error('connection closed'));
|
|
464
585
|
const consumer = new T(fake, async () => undefined, makeConfig());
|
|
465
|
-
await expect(consumer.
|
|
586
|
+
await expect(consumer.testCleanupDeadConsumers()).to.eventually.not.be.rejected;
|
|
587
|
+
expect(fake.xgroup.called).to.be.false;
|
|
588
|
+
});
|
|
589
|
+
|
|
590
|
+
it('runs at most once every 6 hours by default', async () => {
|
|
591
|
+
const { fake, consumer } = setup([]);
|
|
592
|
+
await consumer.testCleanupDeadConsumers();
|
|
593
|
+
await consumer.testCleanupDeadConsumers();
|
|
594
|
+
expect(fake.xinfo.calledOnce).to.be.true;
|
|
595
|
+
consumer.testLastTimeConsumersCleanup = Date.now() - 5 * HOUR;
|
|
596
|
+
await consumer.testCleanupDeadConsumers();
|
|
597
|
+
expect(fake.xinfo.calledOnce).to.be.true;
|
|
598
|
+
consumer.testLastTimeConsumersCleanup = Date.now() - 6 * HOUR - 1;
|
|
599
|
+
await consumer.testCleanupDeadConsumers();
|
|
600
|
+
expect(fake.xinfo.calledTwice).to.be.true;
|
|
601
|
+
});
|
|
602
|
+
|
|
603
|
+
it('honours a custom deadConsumerCheckInterval', async () => {
|
|
604
|
+
const { fake, consumer } = setup([], { deadConsumerCheckInterval: 60 * 1000 });
|
|
605
|
+
await consumer.testCleanupDeadConsumers();
|
|
606
|
+
consumer.testLastTimeConsumersCleanup = Date.now() - 61 * 1000;
|
|
607
|
+
await consumer.testCleanupDeadConsumers();
|
|
608
|
+
expect(fake.xinfo.calledTwice).to.be.true;
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
it('does not run periodically when deadConsumerCheckInterval is 0', async () => {
|
|
612
|
+
const { fake, consumer } = setup([], { deadConsumerCheckInterval: 0 });
|
|
613
|
+
await consumer.testCleanupDeadConsumers();
|
|
614
|
+
expect(fake.xinfo.called).to.be.false;
|
|
615
|
+
});
|
|
616
|
+
|
|
617
|
+
it('logs and swallows errors', async () => {
|
|
618
|
+
const { fake, consumer, calls } = setup([]);
|
|
619
|
+
fake.xinfo.rejects(new Error('NOGROUP'));
|
|
620
|
+
await expect(consumer.testCleanupDeadConsumers()).to.eventually.not.be.rejected;
|
|
621
|
+
expect(calls.warn).to.have.length(1);
|
|
622
|
+
});
|
|
623
|
+
|
|
624
|
+
it('runs from the reading loop on startup', async () => {
|
|
625
|
+
const { fake, consumer } = setup([]);
|
|
626
|
+
consumer.lastTimePendingCheck = Date.now();
|
|
627
|
+
fake.xreadgroup.callsFake(async () => { consumer.testDisposing = true; return null; });
|
|
628
|
+
await consumer.testTryReading();
|
|
629
|
+
expect(fake.xinfo.calledOnce).to.be.true;
|
|
466
630
|
});
|
|
467
631
|
});
|
|
468
632
|
|