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.
Files changed (46) hide show
  1. package/.claude/settings.local.json +8 -0
  2. package/README.md +75 -3
  3. package/coverage.js +11 -0
  4. package/dist/consumer-buffer.d.ts +16 -0
  5. package/dist/consumer-buffer.js +53 -0
  6. package/dist/consumer-buffer.js.map +1 -0
  7. package/dist/events.d.ts +15 -0
  8. package/dist/events.js +30 -0
  9. package/dist/events.js.map +1 -0
  10. package/dist/index.d.ts +5 -134
  11. package/dist/index.js +9 -452
  12. package/dist/index.js.map +1 -1
  13. package/dist/redis-client.d.ts +32 -0
  14. package/dist/redis-client.js +46 -0
  15. package/dist/redis-client.js.map +1 -0
  16. package/dist/redis-streams.d.ts +19 -0
  17. package/dist/redis-streams.js +198 -0
  18. package/dist/redis-streams.js.map +1 -0
  19. package/dist/stream-consumer.d.ts +28 -0
  20. package/dist/stream-consumer.js +177 -0
  21. package/dist/stream-consumer.js.map +1 -0
  22. package/dist/types.d.ts +112 -0
  23. package/dist/types.js +3 -0
  24. package/dist/types.js.map +1 -0
  25. package/docs/api.md +393 -0
  26. package/docs/configuration.md +129 -0
  27. package/docs/dead-letters.md +132 -0
  28. package/docs/examples.md +334 -0
  29. package/docs/superpowers/specs/2026-04-04-refactor-design.md +60 -0
  30. package/package.json +27 -5
  31. package/src/consumer-buffer.ts +60 -0
  32. package/src/events.ts +35 -0
  33. package/src/index.ts +18 -609
  34. package/src/redis-client.ts +64 -0
  35. package/src/redis-streams.ts +249 -0
  36. package/src/stream-consumer.ts +241 -0
  37. package/src/types.ts +115 -0
  38. package/test/consumer-buffer.spec.ts +154 -0
  39. package/test/events.spec.ts +104 -0
  40. package/test/helpers/fake-redis.ts +60 -0
  41. package/test/mocha.opts +2 -1
  42. package/test/redis-client.spec.ts +122 -0
  43. package/test/redis-streams.spec.ts +494 -0
  44. package/test/setup.ts +3 -0
  45. package/test/stream-consumer.spec.ts +493 -0
  46. package/.nycrc +0 -20
@@ -0,0 +1,154 @@
1
+ import 'mocha';
2
+ import { expect } from 'chai';
3
+ import { ConsumerBuffer, ConsumerBufferConfigs } from '../src/consumer-buffer';
4
+
5
+ function makeConfigs(overrides: Partial<ConsumerBufferConfigs> = {}): ConsumerBufferConfigs {
6
+ return {
7
+ ack: async () => {},
8
+ process: async () => {},
9
+ error: async () => {},
10
+ mode: 'parallel',
11
+ size: 10,
12
+ ...overrides,
13
+ };
14
+ }
15
+
16
+ describe('ConsumerBuffer', () => {
17
+
18
+ describe('size getter', () => {
19
+ it('returns the configured size', () => {
20
+ const buf = new ConsumerBuffer(makeConfigs({ size: 7 }));
21
+ expect(buf.size).to.equal(7);
22
+ });
23
+ });
24
+
25
+ describe('parallel mode', () => {
26
+ it('processes all messages and ACKs successful ones', async () => {
27
+ const processed: string[] = [];
28
+ const acked: string[] = [];
29
+ const buf = new ConsumerBuffer(makeConfigs({
30
+ mode: 'parallel',
31
+ process: async (id) => { processed.push(id); },
32
+ ack: async (...ids) => { acked.push(...ids); },
33
+ }));
34
+ await buf.add(['1', ['e', '{}']], ['2', ['e', '{}']]);
35
+ expect(processed).to.have.members(['1', '2']);
36
+ expect(acked).to.have.members(['1', '2']);
37
+ });
38
+
39
+ it('does not ACK messages whose processing throws', async () => {
40
+ const acked: string[] = [];
41
+ const buf = new ConsumerBuffer(makeConfigs({
42
+ mode: 'parallel',
43
+ process: async (id) => { if (id === '2') throw new Error('fail'); },
44
+ ack: async (...ids) => { acked.push(...ids); },
45
+ }));
46
+ await buf.add(['1', ['e', '{}']], ['2', ['e', '{}']]);
47
+ expect(acked).to.deep.equal(['1']);
48
+ });
49
+
50
+ it('calls the error handler when processing throws', async () => {
51
+ const errorIds: string[] = [];
52
+ const buf = new ConsumerBuffer(makeConfigs({
53
+ mode: 'parallel',
54
+ process: async () => { throw new Error('oops'); },
55
+ error: async (id) => { errorIds.push(id); },
56
+ }));
57
+ await buf.add(['1', ['e', '{}']]);
58
+ expect(errorIds).to.deep.equal(['1']);
59
+ });
60
+
61
+ it('swallows errors thrown by the error handler itself', async () => {
62
+ const buf = new ConsumerBuffer(makeConfigs({
63
+ mode: 'parallel',
64
+ process: async () => { throw new Error('process error'); },
65
+ error: async () => { throw new Error('error handler error'); },
66
+ }));
67
+ await expect(buf.add(['1', ['e', '{}']])).to.eventually.not.be.rejected;
68
+ });
69
+
70
+ it('does nothing when the buffer is empty', async () => {
71
+ const acked: string[] = [];
72
+ const buf = new ConsumerBuffer(makeConfigs({ ack: async (...ids) => { acked.push(...ids); } }));
73
+ await buf.add();
74
+ expect(acked).to.be.empty;
75
+ });
76
+ });
77
+
78
+ describe('serial mode', () => {
79
+ it('processes messages in insertion order', async () => {
80
+ const order: string[] = [];
81
+ const buf = new ConsumerBuffer(makeConfigs({
82
+ mode: 'serial',
83
+ process: async (id) => { order.push(id); },
84
+ }));
85
+ await buf.add(['1', ['e', '{}']], ['2', ['e', '{}']], ['3', ['e', '{}']]);
86
+ expect(order).to.deep.equal(['1', '2', '3']);
87
+ });
88
+
89
+ it('ACKs each message immediately after processing succeeds', async () => {
90
+ const log: string[] = [];
91
+ const buf = new ConsumerBuffer(makeConfigs({
92
+ mode: 'serial',
93
+ process: async (id) => { log.push(`proc:${id}`); },
94
+ ack: async (id) => { log.push(`ack:${id}`); },
95
+ }));
96
+ await buf.add(['1', ['e', '{}']], ['2', ['e', '{}']]);
97
+ expect(log).to.deep.equal(['proc:1', 'ack:1', 'proc:2', 'ack:2']);
98
+ });
99
+
100
+ it('does not ACK when processing throws', async () => {
101
+ const acked: string[] = [];
102
+ const buf = new ConsumerBuffer(makeConfigs({
103
+ mode: 'serial',
104
+ process: async () => { throw new Error('fail'); },
105
+ ack: async (id) => { acked.push(id); },
106
+ }));
107
+ await buf.add(['1', ['e', '{}']]);
108
+ expect(acked).to.be.empty;
109
+ });
110
+
111
+ it('continues processing remaining messages after one fails', async () => {
112
+ const processed: string[] = [];
113
+ const acked: string[] = [];
114
+ const buf = new ConsumerBuffer(makeConfigs({
115
+ mode: 'serial',
116
+ process: async (id) => {
117
+ processed.push(id);
118
+ if (id === '1') throw new Error('fail');
119
+ },
120
+ ack: async (id) => { acked.push(id); },
121
+ }));
122
+ await buf.add(['1', ['e', '{}']], ['2', ['e', '{}']]);
123
+ expect(processed).to.deep.equal(['1', '2']);
124
+ expect(acked).to.deep.equal(['2']);
125
+ });
126
+
127
+ it('swallows errors thrown by the error handler itself', async () => {
128
+ const buf = new ConsumerBuffer(makeConfigs({
129
+ mode: 'serial',
130
+ process: async () => { throw new Error('process error'); },
131
+ error: async () => { throw new Error('error handler error'); },
132
+ }));
133
+ await expect(buf.add(['1', ['e', '{}']])).to.eventually.not.be.rejected;
134
+ });
135
+
136
+ it('processes messages added to the buffer while a do() loop is already running', async () => {
137
+ const processed: string[] = [];
138
+ let bufRef!: ConsumerBuffer;
139
+ bufRef = new ConsumerBuffer(makeConfigs({
140
+ mode: 'serial',
141
+ process: async (id) => {
142
+ processed.push(id);
143
+ if (id === '1') {
144
+ // add msg2 while msg1 is being awaited — isDoing is true so do() returns immediately
145
+ // but msg2 is still pushed to the buffer and picked up by the running while loop
146
+ bufRef.add(['2', ['e', '{}']]);
147
+ }
148
+ },
149
+ }));
150
+ await bufRef.add(['1', ['e', '{}']]);
151
+ expect(processed).to.deep.equal(['1', '2']);
152
+ });
153
+ });
154
+ });
@@ -0,0 +1,104 @@
1
+ import 'mocha';
2
+ import { expect } from 'chai';
3
+ import sinon from 'sinon';
4
+ import { event, eventWithReply, augmentEvents } from '../src/events';
5
+ import { StreamGroupConsumer, IEvent } from '../src/types';
6
+
7
+ function makeStream(produce: sinon.SinonStub = sinon.stub().resolves()): StreamGroupConsumer {
8
+ const s: StreamGroupConsumer = {
9
+ consume: async () => ({ stop: async () => {}, continue: () => {} }),
10
+ handle: (() => ({ handle: s.handle, consume: s.consume })) as any,
11
+ produce,
12
+ produceMany: () => ({ produceMany: s.produceMany, flush: async () => {} }),
13
+ with: (events) => augmentEvents(events, s),
14
+ };
15
+ return s;
16
+ }
17
+
18
+ describe('event()', () => {
19
+ it('returns a factory keyed by the event name', () => {
20
+ const factories = event('userSignedUp').of<{ email: string }>();
21
+ expect(factories).to.have.property('userSignedUp');
22
+ expect(factories.userSignedUp).to.be.a('function');
23
+ });
24
+
25
+ it('creates an event with the correct name, version, and data', () => {
26
+ const factories = event('clicked', '2.0.0').of<{ x: number }>();
27
+ const ev = factories.clicked({ x: 5 });
28
+ expect(ev.name).to.equal('clicked');
29
+ expect(ev.v).to.equal('2.0.0');
30
+ expect(ev.data).to.deep.equal({ x: 5 });
31
+ });
32
+
33
+ it('uses the current timestamp when time is not supplied', () => {
34
+ const before = Date.now();
35
+ const factories = event('ping').of<void>();
36
+ const ev = factories.ping(undefined as any);
37
+ const after = Date.now();
38
+ expect(ev.time).to.be.within(before, after);
39
+ });
40
+
41
+ it('uses the provided timestamp when supplied', () => {
42
+ const factories = event('ping').of<void>();
43
+ const ev = factories.ping(undefined as any, 12345);
44
+ expect(ev.time).to.equal(12345);
45
+ });
46
+
47
+ it('defaults the version to "1.0.0" when not specified', () => {
48
+ const factories = event('ping').of<void>();
49
+ const ev = factories.ping(undefined as any);
50
+ expect(ev.v).to.equal('1.0.0');
51
+ });
52
+ });
53
+
54
+ describe('eventWithReply()', () => {
55
+ it('returns a factory that creates a wait event with the correct source', () => {
56
+ const factories = eventWithReply('fetchUser', 'api-gateway').of<{ id: string }, { name: string }>();
57
+ const ev = factories.fetchUser({ id: '1' });
58
+ expect(ev.name).to.equal('fetchUser');
59
+ expect((ev as any).wait).to.deep.equal({ source: 'api-gateway' });
60
+ });
61
+
62
+ it('creates the wait event with correct name, version, data, and time', () => {
63
+ const factories = eventWithReply('doThing', 'svc', '3.0.0').of<{ n: number }>();
64
+ const ev = factories.doThing({ n: 7 }, 999);
65
+ expect(ev.name).to.equal('doThing');
66
+ expect(ev.v).to.equal('3.0.0');
67
+ expect(ev.data).to.deep.equal({ n: 7 });
68
+ expect(ev.time).to.equal(999);
69
+ expect(ev.wait.source).to.equal('svc');
70
+ });
71
+
72
+ it('defaults version to "1.0.0"', () => {
73
+ const factories = eventWithReply('ping', 'src').of<void>();
74
+ const ev = factories.ping(undefined as any);
75
+ expect(ev.v).to.equal('1.0.0');
76
+ });
77
+ });
78
+
79
+ describe('augmentEvents()', () => {
80
+ it('wraps each factory so calling it produces via the stream', () => {
81
+ const produce = sinon.stub().resolves();
82
+ const stream = makeStream(produce);
83
+ const factories = {
84
+ login: (userId: string) => ({ name: 'login', v: '1', data: { userId }, time: 1 }),
85
+ };
86
+ const augmented = augmentEvents(factories, stream);
87
+ augmented.login('u1');
88
+ expect(produce.calledOnce).to.be.true;
89
+ const producedEvent = produce.firstCall.args[0] as IEvent<any>;
90
+ expect(producedEvent.name).to.equal('login');
91
+ expect(producedEvent.data.userId).to.equal('u1');
92
+ });
93
+
94
+ it('merges the original stream methods into the returned object', () => {
95
+ const stream = makeStream();
96
+ const factories = {
97
+ ping: () => ({ name: 'ping', v: '1', data: {}, time: 0 }),
98
+ };
99
+ const augmented = augmentEvents(factories, stream);
100
+ expect(augmented.consume).to.equal(stream.consume);
101
+ expect(augmented.produce).to.equal(stream.produce);
102
+ expect(augmented.handle).to.equal(stream.handle);
103
+ });
104
+ });
@@ -0,0 +1,60 @@
1
+ import sinon from 'sinon';
2
+ import { IRedisClient } from '../../src/redis-client';
3
+
4
+ export type FakeRedis = IRedisClient & {
5
+ xgroup: sinon.SinonStub;
6
+ xreadgroup: sinon.SinonStub;
7
+ xpending: sinon.SinonStub;
8
+ xclaim: sinon.SinonStub;
9
+ xadd: sinon.SinonStub;
10
+ xack: sinon.SinonStub;
11
+ publish: sinon.SinonStub;
12
+ subscribe: sinon.SinonStub;
13
+ unsubscribe: sinon.SinonStub;
14
+ on: sinon.SinonStub;
15
+ off: sinon.SinonStub;
16
+ disconnect: sinon.SinonStub;
17
+ pipeline: sinon.SinonStub;
18
+ multi: sinon.SinonStub;
19
+ exec: sinon.SinonStub;
20
+ };
21
+
22
+ export function createFakeRedis(): FakeRedis {
23
+ const createPipeline = (): any => {
24
+ const pipe: any = {};
25
+ pipe.xadd = sinon.stub().callsFake(() => pipe);
26
+ pipe.exec = sinon.stub().resolves([]);
27
+ pipe.xgroup = sinon.stub().resolves('OK');
28
+ pipe.xpending = sinon.stub().resolves([]);
29
+ pipe.xclaim = sinon.stub().resolves([]);
30
+ pipe.xack = sinon.stub().resolves(1);
31
+ pipe.publish = sinon.stub().resolves(1);
32
+ pipe.subscribe = sinon.stub().resolves();
33
+ pipe.unsubscribe = sinon.stub().resolves();
34
+ pipe.xreadgroup = sinon.stub().resolves(null);
35
+ pipe.on = sinon.stub().returnsThis();
36
+ pipe.off = sinon.stub().returnsThis();
37
+ pipe.disconnect = sinon.stub();
38
+ pipe.pipeline = sinon.stub().callsFake(createPipeline);
39
+ pipe.multi = sinon.stub().callsFake(createPipeline);
40
+ return pipe;
41
+ };
42
+
43
+ const client: any = {};
44
+ client.xgroup = sinon.stub().resolves('OK');
45
+ client.xreadgroup = sinon.stub().resolves(null);
46
+ client.xpending = sinon.stub().resolves([]);
47
+ client.xclaim = sinon.stub().resolves([]);
48
+ client.xadd = sinon.stub().callsFake(() => client);
49
+ client.xack = sinon.stub().resolves(1);
50
+ client.publish = sinon.stub().resolves(1);
51
+ client.subscribe = sinon.stub().resolves();
52
+ client.unsubscribe = sinon.stub().resolves();
53
+ client.on = sinon.stub().returnsThis();
54
+ client.off = sinon.stub().returnsThis();
55
+ client.disconnect = sinon.stub();
56
+ client.pipeline = sinon.stub().callsFake(createPipeline);
57
+ client.multi = sinon.stub().callsFake(createPipeline);
58
+ client.exec = sinon.stub().resolves([]);
59
+ return client as FakeRedis;
60
+ }
package/test/mocha.opts CHANGED
@@ -1,3 +1,4 @@
1
1
  --require source-map-support/register
2
+ --require ../dist-test/test/setup.js
2
3
  --ui bdd
3
- --timeout 60000
4
+ --timeout 60000
@@ -0,0 +1,122 @@
1
+ import 'mocha';
2
+ import { expect } from 'chai';
3
+ import { parseClusterString, getDefaultRedisConfigs, getNewRedisClient, getExistingRedisClient } from '../src/redis-client';
4
+
5
+ describe('parseClusterString()', () => {
6
+ it('parses a single host:port entry', () => {
7
+ const result = parseClusterString('redis1:6379');
8
+ expect(result).to.deep.equal([{ host: 'redis1', port: 6379 }]);
9
+ });
10
+
11
+ it('parses multiple comma-separated host:port entries', () => {
12
+ const result = parseClusterString('h1:6379,h2:6380,h3:6381');
13
+ expect(result).to.deep.equal([
14
+ { host: 'h1', port: 6379 },
15
+ { host: 'h2', port: 6380 },
16
+ { host: 'h3', port: 6381 },
17
+ ]);
18
+ });
19
+ });
20
+
21
+ describe('getDefaultRedisConfigs()', () => {
22
+ let originalHost: string | undefined;
23
+ let originalPort: string | undefined;
24
+ let originalCluster: string | undefined;
25
+
26
+ beforeEach(() => {
27
+ originalHost = process.env.REDIS_HOST;
28
+ originalPort = process.env.REDIS_PORT;
29
+ originalCluster = process.env.REDIS_CLUSTER;
30
+ delete process.env.REDIS_HOST;
31
+ delete process.env.REDIS_PORT;
32
+ delete process.env.REDIS_CLUSTER;
33
+ });
34
+
35
+ afterEach(() => {
36
+ if (originalHost !== undefined) process.env.REDIS_HOST = originalHost;
37
+ else delete process.env.REDIS_HOST;
38
+ if (originalPort !== undefined) process.env.REDIS_PORT = originalPort;
39
+ else delete process.env.REDIS_PORT;
40
+ if (originalCluster !== undefined) process.env.REDIS_CLUSTER = originalCluster;
41
+ else delete process.env.REDIS_CLUSTER;
42
+ });
43
+
44
+ it('returns parsed cluster nodes when REDIS_CLUSTER is set', () => {
45
+ process.env.REDIS_CLUSTER = 'node1:7001,node2:7002';
46
+ const result = getDefaultRedisConfigs();
47
+ expect(result).to.deep.equal([
48
+ { host: 'node1', port: 7001 },
49
+ { host: 'node2', port: 7002 },
50
+ ]);
51
+ });
52
+
53
+ it('throws when REDIS_HOST is not set', () => {
54
+ expect(() => getDefaultRedisConfigs()).to.throw('REDIS_HOST');
55
+ });
56
+
57
+ it('throws when REDIS_HOST is an empty string', () => {
58
+ process.env.REDIS_HOST = '';
59
+ expect(() => getDefaultRedisConfigs()).to.throw('REDIS_HOST');
60
+ });
61
+
62
+ it('throws when REDIS_PORT is 0 or missing', () => {
63
+ process.env.REDIS_HOST = 'localhost';
64
+ expect(() => getDefaultRedisConfigs()).to.throw('REDIS_PORT');
65
+ });
66
+
67
+ it('returns a single host/port config when both env vars are set', () => {
68
+ process.env.REDIS_HOST = 'my-redis';
69
+ process.env.REDIS_PORT = '6379';
70
+ const result = getDefaultRedisConfigs() as { host: string; port: number };
71
+ expect(result.host).to.equal('my-redis');
72
+ expect(result.port).to.equal(6379);
73
+ });
74
+ });
75
+
76
+ describe('getNewRedisClient()', () => {
77
+ it('returns a client-like object for a single-node config', () => {
78
+ const client = getNewRedisClient({ host: 'localhost', port: 6399 });
79
+ expect(client).to.exist;
80
+ (client as any).disconnect();
81
+ });
82
+
83
+ it('returns a cluster client for an array config', () => {
84
+ const client = getNewRedisClient([{ host: 'localhost', port: 7001 }]);
85
+ expect(client).to.exist;
86
+ (client as any).disconnect();
87
+ });
88
+
89
+ it('uses env-var default config when called without arguments', () => {
90
+ process.env.REDIS_HOST = 'localhost';
91
+ process.env.REDIS_PORT = '6399';
92
+ try {
93
+ const client = getNewRedisClient();
94
+ expect(client).to.exist;
95
+ (client as any).disconnect();
96
+ } finally {
97
+ delete process.env.REDIS_HOST;
98
+ delete process.env.REDIS_PORT;
99
+ }
100
+ });
101
+ });
102
+
103
+ describe('getExistingRedisClient()', () => {
104
+ it('uses env-var default config when called without arguments (first call)', () => {
105
+ process.env.REDIS_HOST = 'localhost';
106
+ process.env.REDIS_PORT = '6399';
107
+ try {
108
+ const client = getExistingRedisClient();
109
+ expect(client).to.exist;
110
+ } finally {
111
+ delete process.env.REDIS_HOST;
112
+ delete process.env.REDIS_PORT;
113
+ }
114
+ });
115
+
116
+ it('returns the same cached instance on repeated calls', () => {
117
+ const c1 = getExistingRedisClient({ host: 'localhost', port: 6400 });
118
+ const c2 = getExistingRedisClient({ host: 'different-host', port: 9999 });
119
+ expect(c1).to.equal(c2);
120
+ (c1 as any).disconnect();
121
+ });
122
+ });