ioredis-streams 1.3.0 → 2.1.0
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/.claude/settings.local.json +8 -0
- package/README.md +75 -3
- package/coverage.js +11 -0
- package/dist/consumer-buffer.d.ts +16 -0
- package/dist/consumer-buffer.js +53 -0
- package/dist/consumer-buffer.js.map +1 -0
- package/dist/events.d.ts +15 -0
- package/dist/events.js +30 -0
- package/dist/events.js.map +1 -0
- package/dist/index.d.ts +5 -134
- package/dist/index.js +9 -452
- package/dist/index.js.map +1 -1
- package/dist/redis-client.d.ts +32 -0
- package/dist/redis-client.js +46 -0
- package/dist/redis-client.js.map +1 -0
- package/dist/redis-streams.d.ts +19 -0
- package/dist/redis-streams.js +198 -0
- package/dist/redis-streams.js.map +1 -0
- package/dist/stream-consumer.d.ts +28 -0
- package/dist/stream-consumer.js +177 -0
- package/dist/stream-consumer.js.map +1 -0
- package/dist/types.d.ts +112 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/docs/api.md +393 -0
- package/docs/configuration.md +129 -0
- package/docs/dead-letters.md +132 -0
- package/docs/examples.md +334 -0
- package/docs/superpowers/specs/2026-04-04-refactor-design.md +60 -0
- package/package.json +27 -5
- package/src/consumer-buffer.ts +60 -0
- package/src/events.ts +35 -0
- package/src/index.ts +18 -609
- package/src/redis-client.ts +64 -0
- package/src/redis-streams.ts +249 -0
- package/src/stream-consumer.ts +241 -0
- package/src/types.ts +115 -0
- package/test/consumer-buffer.spec.ts +154 -0
- package/test/events.spec.ts +104 -0
- package/test/helpers/fake-redis.ts +60 -0
- package/test/mocha.opts +2 -1
- package/test/redis-client.spec.ts +122 -0
- package/test/redis-streams.spec.ts +494 -0
- package/test/setup.ts +3 -0
- package/test/stream-consumer.spec.ts +493 -0
- package/.nycrc +0 -20
package/docs/examples.md
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
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, waits for in-flight/buffered messages to finish processing
|
|
307
|
+
and be acked, and then removes the consumer from the Redis consumer group (via
|
|
308
|
+
`XGROUP DELCONSUMER`) so it stops showing up in `XINFO CONSUMERS` and no longer
|
|
309
|
+
holds a name that a replacement pod would need. **Always `await` it** before the
|
|
310
|
+
process exits (e.g. on pod termination) — otherwise the process may exit before
|
|
311
|
+
the consumer is removed.
|
|
312
|
+
|
|
313
|
+
```ts
|
|
314
|
+
import { RedisStreams, event } from 'ioredis-streams';
|
|
315
|
+
|
|
316
|
+
const streams = new RedisStreams('my-service');
|
|
317
|
+
const stream = streams.group('workers').stream('tasks');
|
|
318
|
+
|
|
319
|
+
stream.handle('task.run', async (id, event) => {
|
|
320
|
+
await runTask(event.data);
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
const { stop } = await stream.consume();
|
|
324
|
+
|
|
325
|
+
// Graceful shutdown on SIGTERM / SIGINT (e.g. Kubernetes pod termination)
|
|
326
|
+
const shutdown = async () => {
|
|
327
|
+
console.log('Shutting down...');
|
|
328
|
+
await stop(); // finishes in-flight work, then deregisters the consumer
|
|
329
|
+
process.exit(0);
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
process.on('SIGTERM', shutdown);
|
|
333
|
+
process.on('SIGINT', shutdown);
|
|
334
|
+
```
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# ioredis-streams Refactor Design
|
|
2
|
+
|
|
3
|
+
## Goal
|
|
4
|
+
|
|
5
|
+
Split the single `src/index.ts` into focused modules with clean boundaries, introduce a narrow `IRedisClient` interface for testability, and preserve the exact existing public API surface.
|
|
6
|
+
|
|
7
|
+
## File Structure
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
src/
|
|
11
|
+
types.ts — all exported types and interfaces
|
|
12
|
+
redis-client.ts — IRedisClient interface + connection factories
|
|
13
|
+
consumer-buffer.ts — ConsumerBuffer class
|
|
14
|
+
stream-consumer.ts — StreamConsumer class
|
|
15
|
+
redis-streams.ts — RedisStreams class (main entry point)
|
|
16
|
+
events.ts — event(), eventWithReply(), augmentEvents() helpers
|
|
17
|
+
index.ts — re-exports only, no logic
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## IRedisClient Interface
|
|
21
|
+
|
|
22
|
+
Narrow interface covering only the ~12 methods actually used internally. Real ioredis instances satisfy it structurally. Tests pass plain fake objects.
|
|
23
|
+
|
|
24
|
+
Methods: `xgroup`, `xreadgroup`, `xpending`, `xclaim`, `xadd`, `xack`, `publish`, `subscribe`, `unsubscribe`, `on`, `off`, `disconnect`, `pipeline`, `multi`, `exec`.
|
|
25
|
+
|
|
26
|
+
`pipeline()` and `multi()` return `IRedisClient` so pipeline chaining works without importing ioredis types.
|
|
27
|
+
|
|
28
|
+
## Dependencies Between Modules
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
index.ts
|
|
32
|
+
└── redis-streams.ts
|
|
33
|
+
├── redis-client.ts (IRedisClient, getNewRedisClient)
|
|
34
|
+
├── stream-consumer.ts
|
|
35
|
+
│ ├── consumer-buffer.ts
|
|
36
|
+
│ └── types.ts
|
|
37
|
+
└── types.ts
|
|
38
|
+
└── events.ts
|
|
39
|
+
└── types.ts
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Public API — No Changes
|
|
43
|
+
|
|
44
|
+
All exports from the current `src/index.ts` are re-exported from the new `src/index.ts` unchanged:
|
|
45
|
+
- `RedisStreams`, `IEvent`, `IWaitEvent`, `DeadLetterEvent`
|
|
46
|
+
- `RedisStreamsConfig`, `RedisStreamsInputConfig`, `StreamConfigs`
|
|
47
|
+
- `StreamGroupConsumer`, `ConsumerGroup`, `ConsumeFunctions`, `HandleFunction`
|
|
48
|
+
- `ProduceFunc`, `NamedEventHandler`
|
|
49
|
+
- `event`, `eventWithReply`
|
|
50
|
+
- `getNewRedisClient`, `getExistingRedisClient`
|
|
51
|
+
|
|
52
|
+
## Bug Fixes Preserved
|
|
53
|
+
|
|
54
|
+
All 6 fixes from prior session are carried over as-is into the new structure:
|
|
55
|
+
1. Serial mode only ACKs on success
|
|
56
|
+
2. Per-instance producer client (not module-level singleton)
|
|
57
|
+
3. Per-stream pipeline (not shared across streams on same instance)
|
|
58
|
+
4. XPENDING idle filter done in userland (Redis 6 compatible)
|
|
59
|
+
5. NOGROUP recovery resets checkBacklog and lastReadId
|
|
60
|
+
6. RedisStreamsConfig type reflects array form for cluster
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ioredis-streams",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"author": "Zaid Al-Omari",
|
|
@@ -9,12 +9,32 @@
|
|
|
9
9
|
"type": "git",
|
|
10
10
|
"url": "https://github.com/Zaid-AlOmari/ioredis-streams"
|
|
11
11
|
},
|
|
12
|
+
"overrides": {
|
|
13
|
+
"diff": "^8.0.4",
|
|
14
|
+
"serialize-javascript": "^7.0.5"
|
|
15
|
+
},
|
|
12
16
|
"publishConfig": {
|
|
13
17
|
"registry": "https://registry.npmjs.org"
|
|
14
18
|
},
|
|
19
|
+
"nyc": {
|
|
20
|
+
"include": [
|
|
21
|
+
"dist-test/src/**/*.js",
|
|
22
|
+
"src/**/*.ts"
|
|
23
|
+
],
|
|
24
|
+
"exclude": [
|
|
25
|
+
"dist-test/src/example.js",
|
|
26
|
+
"dist-test/src/index.js",
|
|
27
|
+
"src/index.ts",
|
|
28
|
+
"src/example.ts"
|
|
29
|
+
],
|
|
30
|
+
"reporter": [
|
|
31
|
+
"text",
|
|
32
|
+
"html"
|
|
33
|
+
]
|
|
34
|
+
},
|
|
15
35
|
"scripts": {
|
|
16
36
|
"build": "./node_modules/.bin/tsc --p tsconfig.json",
|
|
17
|
-
"test": "cd test
|
|
37
|
+
"test": "cd test && ../node_modules/.bin/tsc -p . && cd .. && NODE_ENV=test node_modules/.bin/nyc --use-spawn-wrap --silent node_modules/.bin/mocha --require source-map-support/register --require ./dist-test/test/setup.js --timeout 60000 './dist-test/**/*.spec.js' && node coverage.js",
|
|
18
38
|
"type-check": "tsc --noEmit",
|
|
19
39
|
"lint": "./node_modules/.bin/eslint src/*/*.ts --format codeframe",
|
|
20
40
|
"fix-lint": "./node_modules/.bin/eslint src/*/*.ts --fix"
|
|
@@ -25,17 +45,19 @@
|
|
|
25
45
|
},
|
|
26
46
|
"devDependencies": {
|
|
27
47
|
"@types/chai": "^4.2.3",
|
|
48
|
+
"@types/chai-as-promised": "^8.0.2",
|
|
28
49
|
"@types/ioredis": "^4.28.5",
|
|
29
|
-
"@types/mocha": "^
|
|
50
|
+
"@types/mocha": "^10.0.0",
|
|
30
51
|
"@types/node": "^10.12.2",
|
|
31
52
|
"@types/sinon": "^7.5.0",
|
|
32
53
|
"@typescript-eslint/eslint-plugin": "^4.22.0",
|
|
33
54
|
"@typescript-eslint/experimental-utils": "^4.22.0",
|
|
34
55
|
"@typescript-eslint/parser": "^4.22.0",
|
|
35
56
|
"chai": "^4.2.0",
|
|
57
|
+
"chai-as-promised": "^8.0.2",
|
|
36
58
|
"eslint": "^7.0.0",
|
|
37
|
-
"mocha": "^11.7.
|
|
38
|
-
"nyc": "^
|
|
59
|
+
"mocha": "^11.7.5",
|
|
60
|
+
"nyc": "^18.0.0",
|
|
39
61
|
"sinon": "^9.0.2",
|
|
40
62
|
"sinon-chai": "^3.5.0",
|
|
41
63
|
"source-map-support": "^0.5.19",
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export type ConsumerBufferConfigs = {
|
|
2
|
+
ack: (...ids: string[]) => Promise<void>;
|
|
3
|
+
process: (id: string, message: string[]) => Promise<any>;
|
|
4
|
+
error: (id: string, message: string[], error: Error) => Promise<void>;
|
|
5
|
+
mode: 'parallel' | 'serial';
|
|
6
|
+
size: number;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
export class ConsumerBuffer {
|
|
10
|
+
|
|
11
|
+
private buffer: [string, string[]][] = [];
|
|
12
|
+
private isDoing = false;
|
|
13
|
+
|
|
14
|
+
constructor(private readonly configs: ConsumerBufferConfigs) {}
|
|
15
|
+
|
|
16
|
+
get size(): number {
|
|
17
|
+
return this.configs.size;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async add(...rawMessages: [string, string[]][]): Promise<void> {
|
|
21
|
+
this.buffer.push(...rawMessages);
|
|
22
|
+
return this.do();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
private async do(): Promise<void> {
|
|
26
|
+
if (this.isDoing) return;
|
|
27
|
+
this.isDoing = true;
|
|
28
|
+
|
|
29
|
+
const toBeAck: string[] = [];
|
|
30
|
+
const operations: Promise<void>[] = [];
|
|
31
|
+
|
|
32
|
+
while (this.buffer.length) {
|
|
33
|
+
const [id, message] = this.buffer.shift()!;
|
|
34
|
+
|
|
35
|
+
if (this.configs.mode === 'serial') {
|
|
36
|
+
const succeeded = await this.configs.process(id, message)
|
|
37
|
+
.then(() => true)
|
|
38
|
+
.catch(async err => {
|
|
39
|
+
await this.configs.error(id, message, err).catch(() => {});
|
|
40
|
+
return false;
|
|
41
|
+
});
|
|
42
|
+
if (succeeded) await this.configs.ack(id);
|
|
43
|
+
} else {
|
|
44
|
+
const operation = this.configs.process(id, message)
|
|
45
|
+
.then(() => { toBeAck.push(id); })
|
|
46
|
+
.catch(err => this.configs.error(id, message, err).catch(() => {}));
|
|
47
|
+
operations.push(operation);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
this.isDoing = false;
|
|
52
|
+
|
|
53
|
+
if (this.configs.mode === 'parallel') {
|
|
54
|
+
await Promise.all(operations);
|
|
55
|
+
if (toBeAck.length) {
|
|
56
|
+
await this.configs.ack(...toBeAck);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { AllowedFactories, IEvent, IWaitEvent, StreamGroupConsumer } from './types';
|
|
2
|
+
|
|
3
|
+
type NamedEvent<T, N extends string> = IEvent<T> & { name: N };
|
|
4
|
+
type NamedWaitEvent<T, N extends string, ReplyType = any> = IWaitEvent<T> & { name: N };
|
|
5
|
+
|
|
6
|
+
export const event = <N extends string>(name: N, v = '1.0.0') => {
|
|
7
|
+
type Result<T, K extends string> = { [P in K]: (data: T, time?: number) => NamedEvent<T, K> };
|
|
8
|
+
return {
|
|
9
|
+
of: <T>() => ({
|
|
10
|
+
[name]: (data: T, time = Date.now()) => ({ name, v, data, time }),
|
|
11
|
+
} as Result<T, N>),
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export const eventWithReply = <N extends string>(name: N, source: string, v = '1.0.0') => {
|
|
16
|
+
type Result<T, K extends string, R> = { [P in K]: (data: T, time?: number) => NamedWaitEvent<T, K, R> };
|
|
17
|
+
return {
|
|
18
|
+
of: <T, ReplyType = any>() => ({
|
|
19
|
+
[name]: (data: T, time = Date.now()): IWaitEvent<T> => ({
|
|
20
|
+
name, v, data, time, wait: { source },
|
|
21
|
+
}),
|
|
22
|
+
} as Result<T, N, ReplyType>),
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export const augmentEvents = <T extends AllowedFactories<R>, R>(
|
|
27
|
+
events: T,
|
|
28
|
+
stream: StreamGroupConsumer,
|
|
29
|
+
) => {
|
|
30
|
+
return Object.keys(events).reduce((acc, key) => {
|
|
31
|
+
const factory = events[key as keyof T];
|
|
32
|
+
acc[key] = (...args: any[]) => stream.produce(factory(...args));
|
|
33
|
+
return acc;
|
|
34
|
+
}, { ...events, ...stream } as any);
|
|
35
|
+
};
|