@nestjs-redisx/streams 1.0.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/LICENSE +21 -0
- package/README.md +56 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +596 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +563 -0
- package/dist/index.mjs.map +1 -0
- package/dist/shared/constants/index.d.ts +5 -0
- package/dist/shared/constants/index.d.ts.map +1 -0
- package/dist/shared/errors/index.d.ts +15 -0
- package/dist/shared/errors/index.d.ts.map +1 -0
- package/dist/shared/types/index.d.ts +107 -0
- package/dist/shared/types/index.d.ts.map +1 -0
- package/dist/streams/api/decorators/stream-consumer.decorator.d.ts +4 -0
- package/dist/streams/api/decorators/stream-consumer.decorator.d.ts.map +1 -0
- package/dist/streams/api/discovery/stream-consumer.discovery.d.ts +15 -0
- package/dist/streams/api/discovery/stream-consumer.discovery.d.ts.map +1 -0
- package/dist/streams/application/ports/dead-letter.port.d.ts +8 -0
- package/dist/streams/application/ports/dead-letter.port.d.ts.map +1 -0
- package/dist/streams/application/ports/stream-consumer.port.d.ts +9 -0
- package/dist/streams/application/ports/stream-consumer.port.d.ts.map +1 -0
- package/dist/streams/application/ports/stream-producer.port.d.ts +8 -0
- package/dist/streams/application/ports/stream-producer.port.d.ts.map +1 -0
- package/dist/streams/application/services/consumer-instance.d.ts +41 -0
- package/dist/streams/application/services/consumer-instance.d.ts.map +1 -0
- package/dist/streams/application/services/dead-letter.service.d.ts +13 -0
- package/dist/streams/application/services/dead-letter.service.d.ts.map +1 -0
- package/dist/streams/application/services/stream-consumer.service.d.ts +26 -0
- package/dist/streams/application/services/stream-consumer.service.d.ts.map +1 -0
- package/dist/streams/application/services/stream-producer.service.d.ts +20 -0
- package/dist/streams/application/services/stream-producer.service.d.ts.map +1 -0
- package/dist/streams/domain/entities/stream-message.entity.d.ts +14 -0
- package/dist/streams/domain/entities/stream-message.entity.d.ts.map +1 -0
- package/dist/streams.plugin.d.ts +45 -0
- package/dist/streams.plugin.d.ts.map +1 -0
- package/package.json +78 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 NestJS RedisX Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/nestjs-redisx/nestjs-redisx/main/website/public/images/logo.png" alt="NestJS RedisX" />
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
# @nestjs-redisx/streams
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/@nestjs-redisx/streams)
|
|
8
|
+
[](https://www.npmjs.com/package/@nestjs-redisx/streams)
|
|
9
|
+
[](https://opensource.org/licenses/MIT)
|
|
10
|
+
|
|
11
|
+
Redis Streams plugin for NestJS RedisX. Provides `StreamProducerService` for publishing and `@StreamConsumer` decorator for declarative consumer groups with dead-letter queues and backpressure.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @nestjs-redisx/core @nestjs-redisx/streams ioredis
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quick Example
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
import { RedisModule } from '@nestjs-redisx/core';
|
|
23
|
+
import { StreamsPlugin, StreamConsumer, STREAM_PRODUCER, IStreamProducer } from '@nestjs-redisx/streams';
|
|
24
|
+
|
|
25
|
+
@Module({
|
|
26
|
+
imports: [
|
|
27
|
+
RedisModule.forRoot({
|
|
28
|
+
clients: { host: 'localhost', port: 6379 },
|
|
29
|
+
plugins: [new StreamsPlugin({ consumer: { batchSize: 10 }, dlq: { enabled: true } })],
|
|
30
|
+
}),
|
|
31
|
+
],
|
|
32
|
+
})
|
|
33
|
+
export class AppModule {}
|
|
34
|
+
|
|
35
|
+
@Injectable()
|
|
36
|
+
export class OrderService {
|
|
37
|
+
constructor(@Inject(STREAM_PRODUCER) private producer: IStreamProducer) {}
|
|
38
|
+
async create(order: Order) {
|
|
39
|
+
await this.producer.publish('orders', { orderId: order.id });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
@Injectable()
|
|
44
|
+
export class OrderProcessor {
|
|
45
|
+
@StreamConsumer({ stream: 'orders', group: 'processors' })
|
|
46
|
+
async handle(msg: { orderId: string }) { /* process */ }
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Documentation
|
|
51
|
+
|
|
52
|
+
Full documentation: [nestjs-redisx.dev/en/reference/streams/](https://nestjs-redisx.dev/en/reference/streams/)
|
|
53
|
+
|
|
54
|
+
## License
|
|
55
|
+
|
|
56
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { StreamsPlugin } from './streams.plugin';
|
|
2
|
+
export { StreamProducerService } from './streams/application/services/stream-producer.service';
|
|
3
|
+
export { StreamConsumerService } from './streams/application/services/stream-consumer.service';
|
|
4
|
+
export { DeadLetterService } from './streams/application/services/dead-letter.service';
|
|
5
|
+
export type { IStreamProducer } from './streams/application/ports/stream-producer.port';
|
|
6
|
+
export type { IStreamConsumer } from './streams/application/ports/stream-consumer.port';
|
|
7
|
+
export type { IDeadLetterService } from './streams/application/ports/dead-letter.port';
|
|
8
|
+
export { StreamMessage } from './streams/domain/entities/stream-message.entity';
|
|
9
|
+
export { StreamConsumer, STREAM_CONSUMER_METADATA } from './streams/api/decorators/stream-consumer.decorator';
|
|
10
|
+
export type { IStreamsPluginOptions, IStreamsPluginOptions as StreamsPluginOptions, IStreamMessage, PublishOptions, StreamInfo, ConsumeOptions, ConsumerHandle, PendingInfo, MessageHandler, DlqMessage, StreamConsumerOptions } from './shared/types';
|
|
11
|
+
export { StreamError, StreamPublishError, StreamConsumeError, StreamGroupError } from './shared/errors';
|
|
12
|
+
export { STREAM_PRODUCER, STREAM_CONSUMER, DEAD_LETTER_SERVICE, STREAMS_PLUGIN_OPTIONS } from './shared/constants';
|
|
13
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAGjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wDAAwD,CAAC;AAC/F,OAAO,EAAE,qBAAqB,EAAE,MAAM,wDAAwD,CAAC;AAC/F,OAAO,EAAE,iBAAiB,EAAE,MAAM,oDAAoD,CAAC;AAGvF,YAAY,EAAE,eAAe,EAAE,MAAM,kDAAkD,CAAC;AACxF,YAAY,EAAE,eAAe,EAAE,MAAM,kDAAkD,CAAC;AACxF,YAAY,EAAE,kBAAkB,EAAE,MAAM,8CAA8C,CAAC;AAGvF,OAAO,EAAE,aAAa,EAAE,MAAM,iDAAiD,CAAC;AAGhF,OAAO,EAAE,cAAc,EAAE,wBAAwB,EAAE,MAAM,oDAAoD,CAAC;AAG9G,YAAY,EAAE,qBAAqB,EAAE,qBAAqB,IAAI,oBAAoB,EAAE,cAAc,EAAE,cAAc,EAAE,UAAU,EAAE,cAAc,EAAE,cAAc,EAAE,WAAW,EAAE,cAAc,EAAE,UAAU,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAGvP,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAGxG,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var os = require('os');
|
|
4
|
+
var common = require('@nestjs/common');
|
|
5
|
+
var core = require('@nestjs-redisx/core');
|
|
6
|
+
|
|
7
|
+
function _interopNamespace(e) {
|
|
8
|
+
if (e && e.__esModule) return e;
|
|
9
|
+
var n = Object.create(null);
|
|
10
|
+
if (e) {
|
|
11
|
+
Object.keys(e).forEach(function (k) {
|
|
12
|
+
if (k !== 'default') {
|
|
13
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
14
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
15
|
+
enumerable: true,
|
|
16
|
+
get: function () { return e[k]; }
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
n.default = e;
|
|
22
|
+
return Object.freeze(n);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
var os__namespace = /*#__PURE__*/_interopNamespace(os);
|
|
26
|
+
|
|
27
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
28
|
+
var __decorateClass = (decorators, target, key, kind) => {
|
|
29
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
30
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
31
|
+
if (decorator = decorators[i])
|
|
32
|
+
result = (decorator(result)) || result;
|
|
33
|
+
return result;
|
|
34
|
+
};
|
|
35
|
+
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
36
|
+
|
|
37
|
+
// src/shared/constants/index.ts
|
|
38
|
+
var STREAMS_PLUGIN_OPTIONS = /* @__PURE__ */ Symbol.for("STREAMS_PLUGIN_OPTIONS");
|
|
39
|
+
var STREAM_PRODUCER = /* @__PURE__ */ Symbol.for("STREAM_PRODUCER");
|
|
40
|
+
var STREAM_CONSUMER = /* @__PURE__ */ Symbol.for("STREAM_CONSUMER");
|
|
41
|
+
var DEAD_LETTER_SERVICE = /* @__PURE__ */ Symbol.for("DEAD_LETTER_SERVICE");
|
|
42
|
+
var STREAM_CONSUMER_METADATA = /* @__PURE__ */ Symbol.for("STREAM_CONSUMER_METADATA");
|
|
43
|
+
function StreamConsumer(options) {
|
|
44
|
+
return (target, propertyKey, descriptor) => {
|
|
45
|
+
common.SetMetadata(STREAM_CONSUMER_METADATA, {
|
|
46
|
+
...options,
|
|
47
|
+
methodName: propertyKey
|
|
48
|
+
})(target, propertyKey, descriptor);
|
|
49
|
+
return descriptor;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/streams/api/discovery/stream-consumer.discovery.ts
|
|
54
|
+
var StreamConsumerDiscovery = class {
|
|
55
|
+
constructor(discoveryService, consumerService, reflector, moduleRef) {
|
|
56
|
+
this.discoveryService = discoveryService;
|
|
57
|
+
this.consumerService = consumerService;
|
|
58
|
+
this.reflector = reflector;
|
|
59
|
+
this.moduleRef = moduleRef;
|
|
60
|
+
}
|
|
61
|
+
logger = new common.Logger(StreamConsumerDiscovery.name);
|
|
62
|
+
handles = [];
|
|
63
|
+
async onModuleInit() {
|
|
64
|
+
if (!this.discoveryService) {
|
|
65
|
+
this.logger.warn("DiscoveryService not available. Import DiscoveryModule from @nestjs/core to enable @StreamConsumer decorator.");
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const providers = this.discoveryService.getProviders();
|
|
69
|
+
for (const wrapper of providers) {
|
|
70
|
+
const { instance } = wrapper;
|
|
71
|
+
if (!instance) {
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const prototype = Object.getPrototypeOf(instance);
|
|
75
|
+
for (const methodName of Object.getOwnPropertyNames(prototype)) {
|
|
76
|
+
const method = prototype[methodName];
|
|
77
|
+
if (typeof method !== "function") {
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const options = this.reflector.get(STREAM_CONSUMER_METADATA, method);
|
|
81
|
+
if (options) {
|
|
82
|
+
await this.registerConsumer(instance, methodName, options);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async registerConsumer(instance, methodName, options) {
|
|
88
|
+
const method = instance[methodName];
|
|
89
|
+
if (!method || typeof method !== "function") {
|
|
90
|
+
throw new Error(`Method ${methodName} is not a function on instance`);
|
|
91
|
+
}
|
|
92
|
+
const handler = method.bind(instance);
|
|
93
|
+
const consumer = options.consumer ?? `${os__namespace.hostname()}-${process.pid}`;
|
|
94
|
+
await this.consumerService.createGroup(options.stream, options.group);
|
|
95
|
+
const handle = this.consumerService.consume(options.stream, options.group, consumer, handler, options);
|
|
96
|
+
this.handles.push(handle);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
StreamConsumerDiscovery = __decorateClass([
|
|
100
|
+
common.Injectable(),
|
|
101
|
+
__decorateParam(0, common.Optional()),
|
|
102
|
+
__decorateParam(1, common.Inject(STREAM_CONSUMER))
|
|
103
|
+
], StreamConsumerDiscovery);
|
|
104
|
+
var DEFAULT_DLQ_FETCH_COUNT = 100;
|
|
105
|
+
exports.DeadLetterService = class DeadLetterService {
|
|
106
|
+
constructor(driver, config) {
|
|
107
|
+
this.driver = driver;
|
|
108
|
+
this.config = config;
|
|
109
|
+
}
|
|
110
|
+
async add(stream, originalId, data, error) {
|
|
111
|
+
if (!this.config.dlq?.enabled) {
|
|
112
|
+
return "";
|
|
113
|
+
}
|
|
114
|
+
const dlqStream = `${stream}${this.config.dlq.streamSuffix ?? ":dlq"}`;
|
|
115
|
+
const maxLen = this.config.dlq.maxLen ?? 1e4;
|
|
116
|
+
return await this.driver.xadd(
|
|
117
|
+
dlqStream,
|
|
118
|
+
"*",
|
|
119
|
+
{
|
|
120
|
+
data: JSON.stringify(data),
|
|
121
|
+
originalId,
|
|
122
|
+
originalStream: stream,
|
|
123
|
+
error: error?.message ?? "Unknown error",
|
|
124
|
+
failedAt: Date.now().toString()
|
|
125
|
+
},
|
|
126
|
+
{ maxLen, approximate: true }
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
async getMessages(stream, count = DEFAULT_DLQ_FETCH_COUNT) {
|
|
130
|
+
const dlqSuffix = this.config.dlq?.streamSuffix ?? ":dlq";
|
|
131
|
+
const dlqStream = `${stream}${dlqSuffix}`;
|
|
132
|
+
const entries = await this.driver.xrange(dlqStream, "-", "+", { count });
|
|
133
|
+
return entries.map((entry) => ({
|
|
134
|
+
id: entry.id,
|
|
135
|
+
data: JSON.parse(entry.fields.data),
|
|
136
|
+
originalId: entry.fields.originalId,
|
|
137
|
+
originalStream: entry.fields.originalStream,
|
|
138
|
+
error: entry.fields.error,
|
|
139
|
+
failedAt: new Date(parseInt(entry.fields.failedAt, 10))
|
|
140
|
+
}));
|
|
141
|
+
}
|
|
142
|
+
async requeue(dlqMessageId, stream) {
|
|
143
|
+
const dlqSuffix = this.config.dlq?.streamSuffix ?? ":dlq";
|
|
144
|
+
const dlqStream = `${stream}${dlqSuffix}`;
|
|
145
|
+
const entries = await this.driver.xrange(dlqStream, dlqMessageId, dlqMessageId);
|
|
146
|
+
if (!entries.length) {
|
|
147
|
+
throw new Error(`DLQ message ${dlqMessageId} not found`);
|
|
148
|
+
}
|
|
149
|
+
const entry = entries[0];
|
|
150
|
+
const newId = await this.driver.xadd(stream, "*", {
|
|
151
|
+
data: entry.fields.data,
|
|
152
|
+
_attempt: "1"
|
|
153
|
+
});
|
|
154
|
+
await this.driver.xdel(dlqStream, dlqMessageId);
|
|
155
|
+
return newId;
|
|
156
|
+
}
|
|
157
|
+
async purge(stream) {
|
|
158
|
+
const dlqSuffix = this.config.dlq?.streamSuffix ?? ":dlq";
|
|
159
|
+
const dlqStream = `${stream}${dlqSuffix}`;
|
|
160
|
+
return await this.driver.del(dlqStream);
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
exports.DeadLetterService = __decorateClass([
|
|
164
|
+
common.Injectable(),
|
|
165
|
+
__decorateParam(0, common.Inject(core.REDIS_DRIVER)),
|
|
166
|
+
__decorateParam(1, common.Inject(STREAMS_PLUGIN_OPTIONS))
|
|
167
|
+
], exports.DeadLetterService);
|
|
168
|
+
|
|
169
|
+
// src/streams/domain/entities/stream-message.entity.ts
|
|
170
|
+
var StreamMessage = class {
|
|
171
|
+
constructor(id, stream, data, attempt, timestamp, ackFn, rejectFn) {
|
|
172
|
+
this.id = id;
|
|
173
|
+
this.stream = stream;
|
|
174
|
+
this.data = data;
|
|
175
|
+
this.attempt = attempt;
|
|
176
|
+
this.timestamp = timestamp;
|
|
177
|
+
this.ackFn = ackFn;
|
|
178
|
+
this.rejectFn = rejectFn;
|
|
179
|
+
}
|
|
180
|
+
async ack() {
|
|
181
|
+
await this.ackFn();
|
|
182
|
+
}
|
|
183
|
+
async reject(error) {
|
|
184
|
+
await this.rejectFn(error);
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
// src/streams/application/services/consumer-instance.ts
|
|
189
|
+
var STOP_POLL_INTERVAL_MS = 100;
|
|
190
|
+
var BACKPRESSURE_WAIT_MS = 10;
|
|
191
|
+
var ERROR_RETRY_DELAY_MS = 1e3;
|
|
192
|
+
var ConsumerInstance = class _ConsumerInstance {
|
|
193
|
+
constructor(driver, dlqService, config, metrics) {
|
|
194
|
+
this.driver = driver;
|
|
195
|
+
this.dlqService = dlqService;
|
|
196
|
+
this.config = config;
|
|
197
|
+
this.metrics = metrics;
|
|
198
|
+
}
|
|
199
|
+
logger = new common.Logger(_ConsumerInstance.name);
|
|
200
|
+
running = false;
|
|
201
|
+
processing = 0;
|
|
202
|
+
async start() {
|
|
203
|
+
this.running = true;
|
|
204
|
+
await this.ensureGroup();
|
|
205
|
+
void this.poll();
|
|
206
|
+
}
|
|
207
|
+
async stop() {
|
|
208
|
+
this.running = false;
|
|
209
|
+
while (this.processing > 0) {
|
|
210
|
+
await new Promise((r) => setTimeout(r, STOP_POLL_INTERVAL_MS));
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
async ensureGroup() {
|
|
214
|
+
try {
|
|
215
|
+
await this.driver.xgroupCreate(this.config.stream, this.config.group, this.config.startId === ">" ? "$" : "0", true);
|
|
216
|
+
} catch (error) {
|
|
217
|
+
if (!error.message.includes("BUSYGROUP")) {
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
async poll() {
|
|
223
|
+
while (this.running) {
|
|
224
|
+
try {
|
|
225
|
+
while (this.processing >= this.config.concurrency) {
|
|
226
|
+
await new Promise((r) => setTimeout(r, BACKPRESSURE_WAIT_MS));
|
|
227
|
+
}
|
|
228
|
+
const result = await this.driver.xreadgroup(this.config.group, this.config.consumer, [{ key: this.config.stream, id: ">" }], {
|
|
229
|
+
count: this.config.batchSize,
|
|
230
|
+
block: this.config.blockTimeout
|
|
231
|
+
});
|
|
232
|
+
if (!result?.length) {
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
for (const streamResult of result) {
|
|
236
|
+
for (const entry of streamResult.entries) {
|
|
237
|
+
void this.processMessage(entry.id, entry.fields);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
} catch (error) {
|
|
241
|
+
this.logger.error("Stream consumer error:", error);
|
|
242
|
+
await new Promise((r) => setTimeout(r, ERROR_RETRY_DELAY_MS));
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
async processMessage(id, fields) {
|
|
247
|
+
this.processing++;
|
|
248
|
+
const startTime = Date.now();
|
|
249
|
+
const labels = { stream: this.config.stream, group: this.config.group };
|
|
250
|
+
try {
|
|
251
|
+
const data = JSON.parse(fields.data);
|
|
252
|
+
const attempt = parseInt(fields._attempt ?? "1", 10);
|
|
253
|
+
const timestamp = new Date(parseInt(id.split("-")[0], 10));
|
|
254
|
+
const message = new StreamMessage(
|
|
255
|
+
id,
|
|
256
|
+
this.config.stream,
|
|
257
|
+
data,
|
|
258
|
+
attempt,
|
|
259
|
+
timestamp,
|
|
260
|
+
() => this.ack(id),
|
|
261
|
+
(error) => this.handleFailure(id, data, attempt, error)
|
|
262
|
+
);
|
|
263
|
+
await this.config.handler(message);
|
|
264
|
+
await this.ack(id);
|
|
265
|
+
this.metrics?.incrementCounter("redisx_stream_messages_consumed_total", { ...labels, status: "success" });
|
|
266
|
+
this.metrics?.observeHistogram("redisx_stream_processing_duration_seconds", (Date.now() - startTime) / 1e3, labels);
|
|
267
|
+
} catch (error) {
|
|
268
|
+
const attempt = parseInt(fields._attempt ?? "1", 10);
|
|
269
|
+
await this.handleFailure(id, JSON.parse(fields.data), attempt, error);
|
|
270
|
+
this.metrics?.incrementCounter("redisx_stream_messages_consumed_total", { ...labels, status: "error" });
|
|
271
|
+
this.metrics?.observeHistogram("redisx_stream_processing_duration_seconds", (Date.now() - startTime) / 1e3, labels);
|
|
272
|
+
} finally {
|
|
273
|
+
this.processing--;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
async ack(id) {
|
|
277
|
+
await this.driver.xack(this.config.stream, this.config.group, id);
|
|
278
|
+
}
|
|
279
|
+
async handleFailure(id, data, attempt, error) {
|
|
280
|
+
if (attempt >= this.config.maxRetries) {
|
|
281
|
+
await this.dlqService.add(this.config.stream, id, data, error);
|
|
282
|
+
await this.ack(id);
|
|
283
|
+
this.metrics?.incrementCounter("redisx_stream_messages_consumed_total", {
|
|
284
|
+
stream: this.config.stream,
|
|
285
|
+
group: this.config.group,
|
|
286
|
+
status: "dead_letter"
|
|
287
|
+
});
|
|
288
|
+
} else {
|
|
289
|
+
const delay = Math.min(this.config.retryInitialDelay * Math.pow(this.config.retryMultiplier, attempt - 1), this.config.retryMaxDelay);
|
|
290
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
291
|
+
await this.driver.xadd(this.config.stream, "*", {
|
|
292
|
+
data: JSON.stringify(data),
|
|
293
|
+
_attempt: String(attempt + 1)
|
|
294
|
+
});
|
|
295
|
+
await this.ack(id);
|
|
296
|
+
this.metrics?.incrementCounter("redisx_stream_messages_consumed_total", {
|
|
297
|
+
stream: this.config.stream,
|
|
298
|
+
group: this.config.group,
|
|
299
|
+
status: "retry"
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
// src/streams/application/services/stream-consumer.service.ts
|
|
306
|
+
var METRICS_SERVICE = /* @__PURE__ */ Symbol.for("METRICS_SERVICE");
|
|
307
|
+
exports.StreamConsumerService = class StreamConsumerService {
|
|
308
|
+
constructor(driver, config, dlqService, metrics) {
|
|
309
|
+
this.driver = driver;
|
|
310
|
+
this.config = config;
|
|
311
|
+
this.dlqService = dlqService;
|
|
312
|
+
this.metrics = metrics;
|
|
313
|
+
}
|
|
314
|
+
consumers = /* @__PURE__ */ new Map();
|
|
315
|
+
async onModuleDestroy() {
|
|
316
|
+
await Promise.all(Array.from(this.consumers.values()).map((c) => c.stop()));
|
|
317
|
+
}
|
|
318
|
+
consume(stream, group, consumer, handler, options = {}) {
|
|
319
|
+
const id = `${stream}:${group}:${consumer}`;
|
|
320
|
+
if (this.consumers.has(id)) {
|
|
321
|
+
throw new Error(`Consumer ${id} already exists`);
|
|
322
|
+
}
|
|
323
|
+
const instance = new ConsumerInstance(
|
|
324
|
+
this.driver,
|
|
325
|
+
this.dlqService,
|
|
326
|
+
{
|
|
327
|
+
stream,
|
|
328
|
+
group,
|
|
329
|
+
consumer,
|
|
330
|
+
handler,
|
|
331
|
+
batchSize: options.batchSize ?? this.config.consumer?.batchSize ?? 10,
|
|
332
|
+
blockTimeout: options.blockTimeout ?? this.config.consumer?.blockTimeout ?? 5e3,
|
|
333
|
+
maxRetries: options.maxRetries ?? this.config.consumer?.maxRetries ?? 3,
|
|
334
|
+
concurrency: options.concurrency ?? this.config.consumer?.concurrency ?? 1,
|
|
335
|
+
startId: options.startId ?? ">",
|
|
336
|
+
retryInitialDelay: this.config.retry?.initialDelay ?? 1e3,
|
|
337
|
+
retryMaxDelay: this.config.retry?.maxDelay ?? 3e4,
|
|
338
|
+
retryMultiplier: this.config.retry?.multiplier ?? 2
|
|
339
|
+
},
|
|
340
|
+
this.metrics
|
|
341
|
+
);
|
|
342
|
+
this.consumers.set(id, instance);
|
|
343
|
+
void instance.start();
|
|
344
|
+
return { id, isRunning: true };
|
|
345
|
+
}
|
|
346
|
+
async stop(handle) {
|
|
347
|
+
const instance = this.consumers.get(handle.id);
|
|
348
|
+
if (instance) {
|
|
349
|
+
await instance.stop();
|
|
350
|
+
this.consumers.delete(handle.id);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
async createGroup(stream, group, startId = "0") {
|
|
354
|
+
try {
|
|
355
|
+
await this.driver.xgroupCreate(stream, group, startId, true);
|
|
356
|
+
} catch (error) {
|
|
357
|
+
if (!error.message.includes("BUSYGROUP")) {
|
|
358
|
+
throw error;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
async getPending(stream, group) {
|
|
363
|
+
const result = await this.driver.xpending(stream, group);
|
|
364
|
+
return {
|
|
365
|
+
count: result.count,
|
|
366
|
+
minId: result.minId ?? "",
|
|
367
|
+
maxId: result.maxId ?? "",
|
|
368
|
+
consumers: result.consumers.map((c) => ({
|
|
369
|
+
name: c.name,
|
|
370
|
+
pending: c.count
|
|
371
|
+
}))
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
async claimIdle(stream, group, consumer, minIdleTime) {
|
|
375
|
+
const pending = await this.driver.xpendingRange(stream, group, "-", "+", 100);
|
|
376
|
+
const idlePending = pending.filter((entry) => entry.idleTime >= minIdleTime);
|
|
377
|
+
if (idlePending.length === 0) {
|
|
378
|
+
return [];
|
|
379
|
+
}
|
|
380
|
+
const ids = idlePending.map((entry) => entry.id);
|
|
381
|
+
const claimed = await this.driver.xclaim(stream, group, consumer, minIdleTime, ...ids);
|
|
382
|
+
const maxRetries = this.config.consumer?.maxRetries ?? 3;
|
|
383
|
+
return claimed.map((entry) => {
|
|
384
|
+
const data = JSON.parse(entry.fields.data ?? "{}");
|
|
385
|
+
const attempt = parseInt(entry.fields._attempt ?? "1", 10);
|
|
386
|
+
const timestamp = new Date(parseInt(entry.id.split("-")[0], 10));
|
|
387
|
+
return {
|
|
388
|
+
id: entry.id,
|
|
389
|
+
stream,
|
|
390
|
+
data,
|
|
391
|
+
attempt,
|
|
392
|
+
timestamp,
|
|
393
|
+
ack: () => this.driver.xack(stream, group, entry.id).then(() => {
|
|
394
|
+
}),
|
|
395
|
+
reject: async (error) => {
|
|
396
|
+
if (attempt >= maxRetries) {
|
|
397
|
+
await this.dlqService.add(stream, entry.id, data, error);
|
|
398
|
+
} else {
|
|
399
|
+
await this.driver.xadd(stream, "*", {
|
|
400
|
+
data: JSON.stringify(data),
|
|
401
|
+
_attempt: String(attempt + 1)
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
await this.driver.xack(stream, group, entry.id);
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
exports.StreamConsumerService = __decorateClass([
|
|
411
|
+
common.Injectable(),
|
|
412
|
+
__decorateParam(0, common.Inject(core.REDIS_DRIVER)),
|
|
413
|
+
__decorateParam(1, common.Inject(STREAMS_PLUGIN_OPTIONS)),
|
|
414
|
+
__decorateParam(2, common.Inject(DEAD_LETTER_SERVICE)),
|
|
415
|
+
__decorateParam(3, common.Optional()),
|
|
416
|
+
__decorateParam(3, common.Inject(METRICS_SERVICE))
|
|
417
|
+
], exports.StreamConsumerService);
|
|
418
|
+
var StreamError = class extends core.RedisXError {
|
|
419
|
+
constructor(message, code, stream, cause) {
|
|
420
|
+
super(message, code, cause, { stream });
|
|
421
|
+
this.stream = stream;
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
var StreamPublishError = class extends StreamError {
|
|
425
|
+
constructor(stream, cause) {
|
|
426
|
+
super(`Failed to publish to stream "${stream}"`, core.ErrorCode.OP_FAILED, stream, cause);
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
var StreamConsumeError = class extends StreamError {
|
|
430
|
+
constructor(stream, cause) {
|
|
431
|
+
super(`Failed to consume from stream "${stream}"`, core.ErrorCode.STREAM_READ_FAILED, stream, cause);
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
var StreamGroupError = class extends StreamError {
|
|
435
|
+
constructor(stream, group, cause) {
|
|
436
|
+
super(`Failed to access group "${group}" on stream "${stream}"`, core.ErrorCode.STREAM_CONSUMER_GROUP_ERROR, stream, cause);
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
// src/streams/application/services/stream-producer.service.ts
|
|
441
|
+
var METRICS_SERVICE2 = /* @__PURE__ */ Symbol.for("METRICS_SERVICE");
|
|
442
|
+
exports.StreamProducerService = class StreamProducerService {
|
|
443
|
+
constructor(driver, config, metrics) {
|
|
444
|
+
this.driver = driver;
|
|
445
|
+
this.config = config;
|
|
446
|
+
this.metrics = metrics;
|
|
447
|
+
}
|
|
448
|
+
async publish(stream, data, options = {}) {
|
|
449
|
+
const startTime = Date.now();
|
|
450
|
+
try {
|
|
451
|
+
const maxLen = options.maxLen ?? this.config.producer?.maxLen ?? 1e5;
|
|
452
|
+
const id = options.id ?? "*";
|
|
453
|
+
const result = await this.driver.xadd(stream, id, { data: JSON.stringify(data) }, { maxLen, approximate: true });
|
|
454
|
+
this.metrics?.incrementCounter("redisx_stream_messages_published_total", { stream });
|
|
455
|
+
this.metrics?.observeHistogram("redisx_stream_publish_duration_seconds", (Date.now() - startTime) / 1e3, { stream });
|
|
456
|
+
return result;
|
|
457
|
+
} catch (error) {
|
|
458
|
+
this.metrics?.incrementCounter("redisx_stream_publish_errors_total", { stream });
|
|
459
|
+
throw new StreamPublishError(stream, error);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
async publishBatch(stream, messages, options = {}) {
|
|
463
|
+
const startTime = Date.now();
|
|
464
|
+
try {
|
|
465
|
+
const maxLen = options.maxLen ?? this.config.producer?.maxLen ?? 1e5;
|
|
466
|
+
const results = [];
|
|
467
|
+
for (const data of messages) {
|
|
468
|
+
const id = await this.driver.xadd(stream, "*", { data: JSON.stringify(data) }, { maxLen, approximate: true });
|
|
469
|
+
results.push(id);
|
|
470
|
+
}
|
|
471
|
+
this.metrics?.incrementCounter("redisx_stream_messages_published_total", { stream }, messages.length);
|
|
472
|
+
this.metrics?.observeHistogram("redisx_stream_publish_duration_seconds", (Date.now() - startTime) / 1e3, { stream });
|
|
473
|
+
return results;
|
|
474
|
+
} catch (error) {
|
|
475
|
+
this.metrics?.incrementCounter("redisx_stream_publish_errors_total", { stream });
|
|
476
|
+
throw new StreamPublishError(stream, error);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
async getStreamInfo(stream) {
|
|
480
|
+
try {
|
|
481
|
+
const info = await this.driver.xinfo(stream);
|
|
482
|
+
return {
|
|
483
|
+
length: info.length,
|
|
484
|
+
firstEntry: info.firstEntry ? {
|
|
485
|
+
id: info.firstEntry.id,
|
|
486
|
+
timestamp: new Date(parseInt(info.firstEntry.id.split("-")[0] ?? "0", 10))
|
|
487
|
+
} : void 0,
|
|
488
|
+
lastEntry: info.lastEntry ? {
|
|
489
|
+
id: info.lastEntry.id,
|
|
490
|
+
timestamp: new Date(parseInt(info.lastEntry.id.split("-")[0] ?? "0", 10))
|
|
491
|
+
} : void 0,
|
|
492
|
+
groups: info.groups
|
|
493
|
+
};
|
|
494
|
+
} catch {
|
|
495
|
+
return {
|
|
496
|
+
length: 0,
|
|
497
|
+
groups: 0
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
async trim(stream, maxLen) {
|
|
502
|
+
return await this.driver.xtrim(stream, maxLen, true);
|
|
503
|
+
}
|
|
504
|
+
};
|
|
505
|
+
exports.StreamProducerService = __decorateClass([
|
|
506
|
+
common.Injectable(),
|
|
507
|
+
__decorateParam(0, common.Inject(core.REDIS_DRIVER)),
|
|
508
|
+
__decorateParam(1, common.Inject(STREAMS_PLUGIN_OPTIONS)),
|
|
509
|
+
__decorateParam(2, common.Optional()),
|
|
510
|
+
__decorateParam(2, common.Inject(METRICS_SERVICE2))
|
|
511
|
+
], exports.StreamProducerService);
|
|
512
|
+
|
|
513
|
+
// src/streams.plugin.ts
|
|
514
|
+
var DEFAULT_STREAMS_CONFIG = {
|
|
515
|
+
keyPrefix: "stream:",
|
|
516
|
+
consumer: {
|
|
517
|
+
batchSize: 10,
|
|
518
|
+
blockTimeout: 5e3,
|
|
519
|
+
concurrency: 1,
|
|
520
|
+
maxRetries: 3,
|
|
521
|
+
claimIdleTimeout: 3e4
|
|
522
|
+
},
|
|
523
|
+
producer: {
|
|
524
|
+
maxLen: 1e5,
|
|
525
|
+
autoCreate: true
|
|
526
|
+
},
|
|
527
|
+
dlq: {
|
|
528
|
+
enabled: true,
|
|
529
|
+
streamSuffix: ":dlq",
|
|
530
|
+
maxLen: 1e4
|
|
531
|
+
},
|
|
532
|
+
retry: {
|
|
533
|
+
maxRetries: 3,
|
|
534
|
+
initialDelay: 1e3,
|
|
535
|
+
maxDelay: 3e4,
|
|
536
|
+
multiplier: 2
|
|
537
|
+
},
|
|
538
|
+
trim: {
|
|
539
|
+
enabled: true,
|
|
540
|
+
maxLen: 1e5,
|
|
541
|
+
strategy: "MAXLEN",
|
|
542
|
+
approximate: true
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
var StreamsPlugin = class {
|
|
546
|
+
constructor(options = {}) {
|
|
547
|
+
this.options = options;
|
|
548
|
+
}
|
|
549
|
+
name = "streams";
|
|
550
|
+
version = "0.1.0";
|
|
551
|
+
description = "Redis Streams support with consumer groups and DLQ";
|
|
552
|
+
getProviders() {
|
|
553
|
+
const config = {
|
|
554
|
+
keyPrefix: this.options.keyPrefix ?? DEFAULT_STREAMS_CONFIG.keyPrefix,
|
|
555
|
+
consumer: {
|
|
556
|
+
...DEFAULT_STREAMS_CONFIG.consumer,
|
|
557
|
+
...this.options.consumer
|
|
558
|
+
},
|
|
559
|
+
producer: {
|
|
560
|
+
...DEFAULT_STREAMS_CONFIG.producer,
|
|
561
|
+
...this.options.producer
|
|
562
|
+
},
|
|
563
|
+
dlq: {
|
|
564
|
+
...DEFAULT_STREAMS_CONFIG.dlq,
|
|
565
|
+
...this.options.dlq
|
|
566
|
+
},
|
|
567
|
+
retry: {
|
|
568
|
+
...DEFAULT_STREAMS_CONFIG.retry,
|
|
569
|
+
...this.options.retry
|
|
570
|
+
},
|
|
571
|
+
trim: {
|
|
572
|
+
...DEFAULT_STREAMS_CONFIG.trim,
|
|
573
|
+
...this.options.trim
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
return [{ provide: STREAMS_PLUGIN_OPTIONS, useValue: config }, { provide: DEAD_LETTER_SERVICE, useClass: exports.DeadLetterService }, { provide: STREAM_PRODUCER, useClass: exports.StreamProducerService }, { provide: STREAM_CONSUMER, useClass: exports.StreamConsumerService }, StreamConsumerDiscovery];
|
|
577
|
+
}
|
|
578
|
+
getExports() {
|
|
579
|
+
return [STREAM_PRODUCER, STREAM_CONSUMER, DEAD_LETTER_SERVICE];
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
|
|
583
|
+
exports.DEAD_LETTER_SERVICE = DEAD_LETTER_SERVICE;
|
|
584
|
+
exports.STREAMS_PLUGIN_OPTIONS = STREAMS_PLUGIN_OPTIONS;
|
|
585
|
+
exports.STREAM_CONSUMER = STREAM_CONSUMER;
|
|
586
|
+
exports.STREAM_CONSUMER_METADATA = STREAM_CONSUMER_METADATA;
|
|
587
|
+
exports.STREAM_PRODUCER = STREAM_PRODUCER;
|
|
588
|
+
exports.StreamConsumeError = StreamConsumeError;
|
|
589
|
+
exports.StreamConsumer = StreamConsumer;
|
|
590
|
+
exports.StreamError = StreamError;
|
|
591
|
+
exports.StreamGroupError = StreamGroupError;
|
|
592
|
+
exports.StreamMessage = StreamMessage;
|
|
593
|
+
exports.StreamPublishError = StreamPublishError;
|
|
594
|
+
exports.StreamsPlugin = StreamsPlugin;
|
|
595
|
+
//# sourceMappingURL=index.js.map
|
|
596
|
+
//# sourceMappingURL=index.js.map
|