ioredis-streams 2.0.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.
@@ -0,0 +1,339 @@
1
+ # Examples
2
+
3
+ ## Table of Contents
4
+
5
+ - [Basic Produce & Consume](#basic-produce--consume)
6
+ - [Typed Events with `.with()`](#typed-events-with-with)
7
+ - [Handling All Events with `*`](#handling-all-events-with-)
8
+ - [Serial Processing Mode](#serial-processing-mode)
9
+ - [Batch Producing with `produceMany`](#batch-producing-with-producemany)
10
+ - [Request/Reply Pattern](#requestreply-pattern)
11
+ - [Multiple Streams in One Group](#multiple-streams-in-one-group)
12
+ - [Redis Cluster](#redis-cluster)
13
+ - [Graceful Shutdown](#graceful-shutdown)
14
+
15
+ ---
16
+
17
+ ## Basic Produce & Consume
18
+
19
+ The simplest end-to-end example: one producer, one consumer.
20
+
21
+ ```ts
22
+ import { RedisStreams } from 'ioredis-streams';
23
+
24
+ const streams = new RedisStreams('my-service', {
25
+ redis: { host: 'localhost', port: 6379 },
26
+ });
27
+
28
+ const stream = streams.group('notifications').stream('alerts');
29
+
30
+ // Register handlers before consuming
31
+ stream.handle('alert.sent', async (id, event) => {
32
+ console.log(`[${id}] Alert sent to`, event.data.recipient);
33
+ });
34
+
35
+ // Start consuming
36
+ await stream.consume();
37
+
38
+ // Produce an event (can happen in any order relative to consume)
39
+ await stream.produce({
40
+ name: 'alert.sent',
41
+ v: '1.0.0',
42
+ time: Date.now(),
43
+ data: { recipient: 'ops-team', message: 'Disk usage at 90%' },
44
+ });
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Typed Events with `.with()`
50
+
51
+ Use `event()` factories and `.with()` to get TypeScript inference on both producing and handling.
52
+
53
+ ```ts
54
+ import { RedisStreams, event } from 'ioredis-streams';
55
+
56
+ // Define event schemas once
57
+ const OrderEvents = {
58
+ ...event('order.placed').of<{ orderId: string; total: number; currency: string }>(),
59
+ ...event('order.shipped').of<{ orderId: string; trackingCode: string }>(),
60
+ ...event('order.cancelled').of<{ orderId: string; reason: string }>(),
61
+ };
62
+
63
+ const streams = new RedisStreams('order-service');
64
+
65
+ const stream = streams
66
+ .group('order-processors')
67
+ .stream('orders')
68
+ .with(OrderEvents);
69
+
70
+ // Typed produce — data shape is enforced at compile time
71
+ await stream['order.placed']({ orderId: 'ORD-1', total: 49.99, currency: 'USD' });
72
+ await stream['order.shipped']({ orderId: 'ORD-1', trackingCode: 'TRK-XYZ' });
73
+
74
+ // Typed handle — event.data is fully inferred
75
+ stream
76
+ .handle('order.placed', async (id, event) => {
77
+ // event.data: { orderId: string; total: number; currency: string }
78
+ await db.orders.create(event.data);
79
+ })
80
+ .handle('order.shipped', async (id, event) => {
81
+ // event.data: { orderId: string; trackingCode: string }
82
+ await notifications.send(`Order ${event.data.orderId} shipped`);
83
+ });
84
+
85
+ await stream.consume();
86
+ ```
87
+
88
+ ---
89
+
90
+ ## Handling All Events with `*`
91
+
92
+ Use `'*'` as a catch-all handler for events that have no specific handler registered. Runs after named handlers are checked.
93
+
94
+ ```ts
95
+ stream
96
+ .handle('order.placed', async (id, event) => {
97
+ await db.orders.create(event.data);
98
+ })
99
+ .handle('*', async (id, event) => {
100
+ // Catches order.shipped, order.cancelled, and anything else
101
+ console.log('Unhandled event type:', event.name, event.data);
102
+ });
103
+
104
+ await stream.consume();
105
+ ```
106
+
107
+ > The `'*'` handler only fires if no named handler matched. If you register both `'order.placed'` and `'*'`, an `order.placed` event will only call the named handler.
108
+
109
+ ---
110
+
111
+ ## Serial Processing Mode
112
+
113
+ By default, messages in each batch are processed in **parallel**. Switch to `serial` mode to guarantee ordering — each message waits for the previous one to finish before processing begins.
114
+
115
+ ```ts
116
+ const stream = streams
117
+ .group('inventory')
118
+ .stream('stock-updates', {
119
+ mode: 'serial', // one at a time, in order
120
+ batchSize: 1, // read one message per poll for strict FIFO
121
+ });
122
+
123
+ stream.handle('stock.adjusted', async (id, event) => {
124
+ // Guaranteed not to run concurrently with another stock.adjusted handler
125
+ await db.inventory.adjust(event.data);
126
+ });
127
+
128
+ await stream.consume();
129
+ ```
130
+
131
+ > **When to use serial mode:** Database writes with ordering guarantees, state machines, or any workflow where two concurrent messages would produce incorrect results.
132
+
133
+ ---
134
+
135
+ ## Batch Producing with `produceMany`
136
+
137
+ Use `produceMany` to buffer multiple events into a single Redis pipeline and flush them atomically.
138
+
139
+ ```ts
140
+ import { RedisStreams, event } from 'ioredis-streams';
141
+
142
+ const MetricEvents = {
143
+ ...event('metric.recorded').of<{ name: string; value: number; tags: Record<string, string> }>(),
144
+ };
145
+
146
+ const streams = new RedisStreams('metrics-service');
147
+ const stream = streams.group('metrics').stream('metrics').with(MetricEvents);
148
+
149
+ // Queue events — nothing is written to Redis yet
150
+ const batch = stream
151
+ .produceMany(MetricEvents['metric.recorded']({ name: 'cpu', value: 72, tags: { host: 'web-1' } }))
152
+ .produceMany(MetricEvents['metric.recorded']({ name: 'mem', value: 55, tags: { host: 'web-1' } }))
153
+ .produceMany(MetricEvents['metric.recorded']({ name: 'disk', value: 90, tags: { host: 'web-1' } }));
154
+
155
+ // Write all three in one round-trip
156
+ await batch.flush();
157
+ ```
158
+
159
+ > **Why use `produceMany`?** It reduces round-trips to Redis when you need to publish several events at once, e.g. at the end of a request lifecycle or a batch job.
160
+
161
+ ---
162
+
163
+ ## Request/Reply Pattern
164
+
165
+ Use `eventWithReply` when you need a synchronous-feeling response from a consumer. The producer publishes an event and awaits a reply over a Redis Pub/Sub channel. The consumer's handler return value becomes the reply.
166
+
167
+ ### Producer service
168
+
169
+ ```ts
170
+ import { RedisStreams, eventWithReply } from 'ioredis-streams';
171
+
172
+ const PricingEvents = {
173
+ ...eventWithReply('pricing.calculate', 'order-service').of<
174
+ { items: Array<{ sku: string; qty: number }> },
175
+ { total: number; breakdown: Record<string, number> }
176
+ >(),
177
+ };
178
+
179
+ const streams = new RedisStreams('order-service');
180
+ const stream = streams
181
+ .group('pricing')
182
+ .stream('pricing-requests')
183
+ .with(PricingEvents);
184
+
185
+ // Produce the event and wait up to 5 seconds for the reply
186
+ const reply = await stream['pricing.calculate']({
187
+ items: [{ sku: 'SKU-A', qty: 2 }, { sku: 'SKU-B', qty: 1 }],
188
+ }).wait(5000);
189
+
190
+ console.log('Total:', reply.total);
191
+ // → Total: 149.97
192
+ ```
193
+
194
+ ### Consumer service
195
+
196
+ ```ts
197
+ import { RedisStreams } from 'ioredis-streams';
198
+
199
+ const streams = new RedisStreams('pricing-service');
200
+ const stream = streams.group('pricing').stream('pricing-requests');
201
+
202
+ stream.handle('pricing.calculate', async (id, event) => {
203
+ const { items } = event.data;
204
+ const breakdown: Record<string, number> = {};
205
+ let total = 0;
206
+
207
+ for (const item of items) {
208
+ const price = await pricingDb.getPrice(item.sku) * item.qty;
209
+ breakdown[item.sku] = price;
210
+ total += price;
211
+ }
212
+
213
+ // Whatever you return here is sent back to the producer's .wait() call
214
+ return { total, breakdown };
215
+ });
216
+
217
+ await stream.consume();
218
+ ```
219
+
220
+ > **Timeouts:** If the consumer does not reply within the timeout passed to `.wait(ms)`, a `Timeout` error is thrown. Always wrap `.wait()` in try/catch for production use.
221
+
222
+ ```ts
223
+ try {
224
+ const reply = await stream['pricing.calculate']({ items }).wait(5000);
225
+ } catch (err) {
226
+ if (err.message === 'Timeout') {
227
+ // handle timeout
228
+ }
229
+ throw err;
230
+ }
231
+ ```
232
+
233
+ ---
234
+
235
+ ## Multiple Streams in One Group
236
+
237
+ A single consumer group can consume from multiple streams. Each stream gets its own handlers.
238
+
239
+ ```ts
240
+ import { RedisStreams, event } from 'ioredis-streams';
241
+
242
+ const streams = new RedisStreams('warehouse-service');
243
+ const group = streams.group('warehouse-processors');
244
+
245
+ // Stream 1: orders
246
+ const ordersStream = group.stream('orders').with({
247
+ ...event('order.placed').of<{ orderId: string }>(),
248
+ });
249
+
250
+ ordersStream
251
+ .handle('order.placed', async (id, event) => {
252
+ await warehouse.reserveStock(event.data.orderId);
253
+ });
254
+
255
+ await ordersStream.consume();
256
+
257
+ // Stream 2: returns
258
+ const returnsStream = group.stream('returns').with({
259
+ ...event('return.initiated').of<{ orderId: string; reason: string }>(),
260
+ });
261
+
262
+ returnsStream
263
+ .handle('return.initiated', async (id, event) => {
264
+ await warehouse.processReturn(event.data.orderId);
265
+ });
266
+
267
+ await returnsStream.consume();
268
+ ```
269
+
270
+ ---
271
+
272
+ ## Redis Cluster
273
+
274
+ ```ts
275
+ import { RedisStreams, event } from 'ioredis-streams';
276
+
277
+ const streams = new RedisStreams('my-service', {
278
+ redis: {
279
+ cluster: 'redis-node-1:6379,redis-node-2:6379,redis-node-3:6379',
280
+ },
281
+ clusterOptions: {
282
+ redisOptions: {
283
+ password: process.env.REDIS_PASSWORD,
284
+ tls: {},
285
+ },
286
+ scaleReads: 'slave',
287
+ },
288
+ });
289
+
290
+ const stream = streams
291
+ .group('my-group')
292
+ .stream('my-stream')
293
+ .with({
294
+ ...event('job.queued').of<{ jobId: string }>(),
295
+ });
296
+
297
+ await stream['job.queued']({ jobId: 'job-123' });
298
+ ```
299
+
300
+ ---
301
+
302
+ ## Graceful Shutdown
303
+
304
+ Stop the consumer cleanly on process exit to avoid mid-flight message loss.
305
+
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).
317
+
318
+ ```ts
319
+ import { RedisStreams, event } from 'ioredis-streams';
320
+
321
+ const streams = new RedisStreams('my-service');
322
+ const stream = streams.group('workers').stream('tasks');
323
+
324
+ stream.handle('task.run', async (id, event) => {
325
+ await runTask(event.data);
326
+ });
327
+
328
+ const { stop } = await stream.consume();
329
+
330
+ // Graceful shutdown on SIGTERM / SIGINT (e.g. Kubernetes pod termination)
331
+ const shutdown = async () => {
332
+ console.log('Shutting down...');
333
+ await stop(); // finishes in-flight work; pending (failed) messages stay retryable
334
+ process.exit(0);
335
+ };
336
+
337
+ process.on('SIGTERM', shutdown);
338
+ process.on('SIGINT', shutdown);
339
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ioredis-streams",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "author": "Zaid Al-Omari",
@@ -57,7 +57,7 @@
57
57
  "chai-as-promised": "^8.0.2",
58
58
  "eslint": "^7.0.0",
59
59
  "mocha": "^11.7.5",
60
- "nyc": "^15.0.1",
60
+ "nyc": "^18.0.0",
61
61
  "sinon": "^9.0.2",
62
62
  "sinon-chai": "^3.5.0",
63
63
  "source-map-support": "^0.5.19",
@@ -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>;
@@ -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;
@@ -18,6 +32,7 @@ export class StreamConsumer {
18
32
  protected checkBacklog = true;
19
33
 
20
34
  protected readonly buffer: ConsumerBuffer;
35
+ protected readingLoop: Promise<void> = Promise.resolve();
21
36
 
22
37
  constructor(
23
38
  protected readonly redis: IRedisClient,
@@ -67,11 +82,13 @@ export class StreamConsumer {
67
82
 
68
83
  async start(): Promise<void> {
69
84
  this.logger.trace('Started...');
70
- await this.tryReading();
85
+ this.readingLoop = this.tryReading();
86
+ await this.readingLoop;
71
87
  }
72
88
 
73
89
  protected async tryReading(): Promise<void> {
74
90
  while (!this.disposing) {
91
+ await this.cleanupDeadConsumers();
75
92
  try {
76
93
  const claimedAnything = await this.doClaim();
77
94
  if (claimedAnything && !this.disposing) continue;
@@ -193,8 +210,75 @@ export class StreamConsumer {
193
210
  return result;
194
211
  }
195
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
+ */
196
221
  async dispose(): Promise<void> {
197
222
  this.disposing = true;
223
+ await this.readingLoop;
224
+ await this.cleanupDeadConsumers(true);
225
+ }
226
+
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));
250
+ try {
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
+ }
261
+ } catch (err) {
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?`,
279
+ );
280
+ }
281
+ return true;
198
282
  }
199
283
 
200
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 & {
@@ -60,7 +73,7 @@ export type NamedEventHandler<E = IEvent<any>> = (id: string, event: E) => Promi
60
73
 
61
74
  export type ConsumeFunctions = {
62
75
  consume: () => Promise<{
63
- stop: () => void;
76
+ stop: () => Promise<void>;
64
77
  continue: () => void;
65
78
  }>;
66
79
  };
@@ -6,7 +6,7 @@ import { StreamGroupConsumer, IEvent } from '../src/types';
6
6
 
7
7
  function makeStream(produce: sinon.SinonStub = sinon.stub().resolves()): StreamGroupConsumer {
8
8
  const s: StreamGroupConsumer = {
9
- consume: async () => ({ stop: () => {}, continue: () => {} }),
9
+ consume: async () => ({ stop: async () => {}, continue: () => {} }),
10
10
  handle: (() => ({ handle: s.handle, consume: s.consume })) as any,
11
11
  produce,
12
12
  produceMany: () => ({ produceMany: s.produceMany, flush: async () => {} }),
@@ -85,6 +85,14 @@ describe('RedisStreams - buildConfig', () => {
85
85
  expect((rs as any).config.deadLetters.maxRetries).to.equal(3);
86
86
  });
87
87
 
88
+ it('stores clusterOptions when provided', () => {
89
+ const rs = new TestRedisStreams(createFakeRedis(), [], {
90
+ redis: { cluster: 'n1:7001' },
91
+ clusterOptions: { scaleReads: 'slave' },
92
+ });
93
+ expect((rs as any).config.clusterOptions).to.deep.equal({ scaleReads: 'slave' });
94
+ });
95
+
88
96
  it('uses the provided logger instead of creating a default one', () => {
89
97
  const myLogger = { trace: () => {}, info: () => {}, error: () => {}, warn: () => {} };
90
98
  const rs = new TestRedisStreams(createFakeRedis(), [], {
@@ -367,8 +375,16 @@ describe('RedisStreams - consume() and continue()', () => {
367
375
  expect(stop).to.be.a('function');
368
376
  expect(cont).to.be.a('function');
369
377
 
370
- await stop();
378
+ // let the (fire-and-forget) start() reach the blocked xreadgroup call and assign `unblock`
379
+ await new Promise(r => setTimeout(r, 0));
380
+
381
+ // stop() now waits for the in-flight (blocked) read to finish before resolving
382
+ const stopping = stop();
371
383
  unblock();
384
+ await stopping;
385
+
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;
372
388
  });
373
389
 
374
390
  it('continue() calls start() again on the consumer', async () => {
@@ -384,11 +400,15 @@ describe('RedisStreams - consume() and continue()', () => {
384
400
  });
385
401
 
386
402
  const { stop, continue: cont } = await stream.consume();
387
- await stop();
403
+ // let the (fire-and-forget) start() reach the blocked xreadgroup call and assign `unblock`
404
+ await new Promise(r => setTimeout(r, 0));
405
+ const stopping = stop();
388
406
  unblock();
407
+ await stopping;
389
408
  // after stop, calling continue re-invokes start (exits immediately since disposing=true)
390
409
  cont();
391
- expect(fakeConsumer.xgroup.calledOnce).to.be.true; // only one init
410
+ const createCalls = fakeConsumer.xgroup.getCalls().filter((c: any) => c.args[0] === 'CREATE');
411
+ expect(createCalls.length).to.equal(1); // only one init
392
412
  });
393
413
  });
394
414