@redkern/node-red-redis 0.0.0-stage → 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/CHANGELOG.md +24 -0
- package/LICENSE +188 -0
- package/README.md +283 -2
- package/SECURITY.md +11 -0
- package/examples/commands-and-pubsub.json +15 -0
- package/examples/streams-at-least-once.json +23 -0
- package/lib/completion.js +79 -0
- package/lib/control.js +59 -0
- package/lib/denylist.js +118 -0
- package/lib/dlq.js +49 -0
- package/lib/format.js +122 -0
- package/lib/inflight.js +131 -0
- package/lib/list-consumer.js +125 -0
- package/lib/metrics.js +85 -0
- package/lib/node-helpers.js +77 -0
- package/lib/palette.js +168 -0
- package/lib/slot.js +33 -0
- package/lib/stream-consumer.js +669 -0
- package/nodes/icons/redkern-redis-command.svg +4 -0
- package/nodes/icons/redkern-redis-list-in.svg +4 -0
- package/nodes/icons/redkern-redis-multi.svg +4 -0
- package/nodes/icons/redkern-redis-scan.svg +4 -0
- package/nodes/icons/redkern-redis-stream-ack.svg +4 -0
- package/nodes/icons/redkern-redis-stream-claim.svg +4 -0
- package/nodes/icons/redkern-redis-stream-control.svg +4 -0
- package/nodes/icons/redkern-redis-stream-gc.svg +4 -0
- package/nodes/icons/redkern-redis-stream-in.svg +4 -0
- package/nodes/icons/redkern-redis-stream-metrics.svg +4 -0
- package/nodes/icons/redkern-redis-stream-out.svg +4 -0
- package/nodes/icons/redkern-redis-subscribe.svg +4 -0
- package/nodes/icons/redkern-redis.svg +4 -0
- package/nodes/locales/en-US/redkern-redis.html +299 -0
- package/nodes/locales/en-US/redkern-redis.json +308 -0
- package/nodes/redkern-redis-command.js +49 -0
- package/nodes/redkern-redis-config.js +273 -0
- package/nodes/redkern-redis-list-in.js +88 -0
- package/nodes/redkern-redis-multi.js +75 -0
- package/nodes/redkern-redis-scan.js +105 -0
- package/nodes/redkern-redis-stream-ack.js +66 -0
- package/nodes/redkern-redis-stream-claim.js +60 -0
- package/nodes/redkern-redis-stream-control.js +35 -0
- package/nodes/redkern-redis-stream-gc.js +77 -0
- package/nodes/redkern-redis-stream-in.js +155 -0
- package/nodes/redkern-redis-stream-metrics.js +85 -0
- package/nodes/redkern-redis-stream-out.js +55 -0
- package/nodes/redkern-redis-subscribe.js +51 -0
- package/nodes/redkern-redis.html +1126 -0
- package/nodes/redkern-redis.js +31 -0
- package/package.json +76 -4
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { decodeFields, codeError } = require('./format.js');
|
|
4
|
+
const { moveToDlq } = require('./dlq.js');
|
|
5
|
+
const { compareIds } = require('./inflight.js');
|
|
6
|
+
|
|
7
|
+
const DEFAULTS = Object.freeze({
|
|
8
|
+
count: 100,
|
|
9
|
+
blockMs: 5000,
|
|
10
|
+
startId: '$',
|
|
11
|
+
ackMode: 'manual',
|
|
12
|
+
maxPending: 1000,
|
|
13
|
+
backpressureScope: 'consumer',
|
|
14
|
+
capacityCheckIntervalMs: 250,
|
|
15
|
+
capacityPollMs: 500,
|
|
16
|
+
maxDeliveries: 5,
|
|
17
|
+
deadLetterStream: '',
|
|
18
|
+
autoClaim: true,
|
|
19
|
+
reclaimIdleMs: 60000,
|
|
20
|
+
reclaimIntervalMs: 30000,
|
|
21
|
+
reclaimCount: 100,
|
|
22
|
+
readIntervalMs: 0,
|
|
23
|
+
rateLimitPerSecond: 0,
|
|
24
|
+
batchWindowMs: 0,
|
|
25
|
+
batchIntervalMs: 0,
|
|
26
|
+
startPaused: false,
|
|
27
|
+
drainCheckIntervalMs: 250,
|
|
28
|
+
pausePollMs: 1000,
|
|
29
|
+
initialBackoffMs: 500,
|
|
30
|
+
maxBackoffMs: 30000,
|
|
31
|
+
backoffMultiplier: 2
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
function isNoGroup(error) {
|
|
35
|
+
return /NOGROUP/.test(String(error?.message || error));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function abortError() {
|
|
39
|
+
return Object.assign(new Error('The operation was aborted'), { name: 'AbortError', code: 'ABORT_ERR' });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Default abortable sleep. */
|
|
43
|
+
function defaultSleep(ms, signal) {
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
if (signal?.aborted) return reject(abortError());
|
|
46
|
+
const timer = setTimeout(() => {
|
|
47
|
+
signal?.removeEventListener('abort', onAbort);
|
|
48
|
+
resolve();
|
|
49
|
+
}, ms);
|
|
50
|
+
function onAbort() {
|
|
51
|
+
clearTimeout(timer);
|
|
52
|
+
reject(abortError());
|
|
53
|
+
}
|
|
54
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Parses an XREADGROUP / XAUTOCLAIM entry list into { id, fields } where
|
|
60
|
+
* fields is null for entries deleted while still pending.
|
|
61
|
+
* @param {unknown} list
|
|
62
|
+
*/
|
|
63
|
+
function parseEntries(list) {
|
|
64
|
+
if (!Array.isArray(list)) return [];
|
|
65
|
+
// Redis 6.2 XAUTOCLAIM answers a bare nil for an entry deleted while
|
|
66
|
+
// pending; it stays in the PEL and recovery acknowledges it later.
|
|
67
|
+
return list.filter(Array.isArray).map(([id, flat]) => ({ id: String(id), fields: Array.isArray(flat) ? flat : null }));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Redis Streams consumer loop (RDS-STR-1..11). The class has no Node-RED
|
|
72
|
+
* dependency: clients, the clock and the output are injected so the loop is
|
|
73
|
+
* unit-testable.
|
|
74
|
+
*
|
|
75
|
+
* Delivery order of work in one iteration:
|
|
76
|
+
* 1. entries held back by pause are delivered first after resume;
|
|
77
|
+
* 2. own PEL recovery through a cursor over XPENDING of this consumer;
|
|
78
|
+
* only entries that are not local are claimed back with XCLAIM, so the
|
|
79
|
+
* delivery count grows only for entries really sent again (RDS-STR-3);
|
|
80
|
+
* 3. XAUTOCLAIM of abandoned entries with a cursor kept between calls
|
|
81
|
+
* (RDS-STR-9), only after own recovery finished;
|
|
82
|
+
* 4. XREADGROUP ">" sized to the free backpressure capacity (RDS-STR-8).
|
|
83
|
+
*/
|
|
84
|
+
class StreamConsumer {
|
|
85
|
+
/**
|
|
86
|
+
* @param {{
|
|
87
|
+
* shared: any, blocking: any, stream: string, group: string, consumer: string,
|
|
88
|
+
* registry: import('./inflight.js').InflightRegistry,
|
|
89
|
+
* emit: (delivery: { entries: Array<{ id: string, payload: Record<string, unknown>, deliveries: number }>, batched: boolean }) => void,
|
|
90
|
+
* options?: Partial<typeof DEFAULTS>,
|
|
91
|
+
* metrics?: { inc: Function, set: Function },
|
|
92
|
+
* log?: { warn: Function, error: Function },
|
|
93
|
+
* onState?: (state: object) => void,
|
|
94
|
+
* clock?: { now: () => number, sleep: (ms: number, signal?: AbortSignal) => Promise<void>, setTimeout?: Function, clearTimeout?: Function },
|
|
95
|
+
* backoff?: { next: () => number, reset: () => void }
|
|
96
|
+
* }} params
|
|
97
|
+
*/
|
|
98
|
+
constructor(params) {
|
|
99
|
+
this.shared = params.shared;
|
|
100
|
+
this.blocking = params.blocking;
|
|
101
|
+
this.stream = params.stream;
|
|
102
|
+
this.group = params.group;
|
|
103
|
+
this.consumer = params.consumer;
|
|
104
|
+
this.registry = params.registry;
|
|
105
|
+
this.emit = params.emit;
|
|
106
|
+
this.options = { ...DEFAULTS, ...(params.options || {}) };
|
|
107
|
+
if (!this.options.deadLetterStream) this.options.deadLetterStream = `${this.stream}:dlq`;
|
|
108
|
+
this.batching = this.options.batchWindowMs > 0 || this.options.batchIntervalMs > 0;
|
|
109
|
+
if (this.batching && !this.options.batchWindowMs) this.options.batchWindowMs = this.options.batchIntervalMs;
|
|
110
|
+
this.metrics = params.metrics || { inc() {}, set() {} };
|
|
111
|
+
this.log = params.log || { warn() {}, error() {} };
|
|
112
|
+
this.onState = params.onState || (() => {});
|
|
113
|
+
const clock = params.clock || {};
|
|
114
|
+
this.clock = {
|
|
115
|
+
now: clock.now || (() => Date.now()),
|
|
116
|
+
sleep: clock.sleep || defaultSleep,
|
|
117
|
+
setTimeout: clock.setTimeout || setTimeout,
|
|
118
|
+
clearTimeout: clock.clearTimeout || clearTimeout
|
|
119
|
+
};
|
|
120
|
+
this.backoff = params.backoff || createBackoff(this.options);
|
|
121
|
+
this.labels = { stream: this.stream, group: this.group };
|
|
122
|
+
|
|
123
|
+
this.paused = Boolean(this.options.startPaused);
|
|
124
|
+
/** Number of drain() calls running; while above 0, reserved entries are sent even though paused. */
|
|
125
|
+
this.draining = 0;
|
|
126
|
+
this.recoveryGeneration = 0;
|
|
127
|
+
this.readInFlight = null;
|
|
128
|
+
this.running = false;
|
|
129
|
+
this.pausedAt = this.paused ? this.clock.now() : 0;
|
|
130
|
+
this.recovering = true;
|
|
131
|
+
this.cursor = '0';
|
|
132
|
+
this.claimCursor = '0-0';
|
|
133
|
+
this.lastReclaimAt = 0;
|
|
134
|
+
this.lastReadAt = 0;
|
|
135
|
+
this.lastCapacityCheckAt = -Infinity;
|
|
136
|
+
this.groupPending = 0;
|
|
137
|
+
this.rateTokens = this.options.rateLimitPerSecond;
|
|
138
|
+
this.rateRefillAt = this.clock.now();
|
|
139
|
+
/** Entries read from Redis but not yet sent (pause or batch window). */
|
|
140
|
+
this.held = [];
|
|
141
|
+
this.buffer = [];
|
|
142
|
+
this.batchTimer = null;
|
|
143
|
+
this.lastBatchAt = 0;
|
|
144
|
+
this.delivered = 0;
|
|
145
|
+
this.lastError = null;
|
|
146
|
+
this.backpressure = false;
|
|
147
|
+
this.wakeResolve = null;
|
|
148
|
+
this.signal = undefined;
|
|
149
|
+
this.unsubscribe = () => {};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** True when entries must not be sent now: paused (and not draining) or closing. */
|
|
153
|
+
get stopped() {
|
|
154
|
+
return (this.paused && !this.draining) || Boolean(this.signal?.aborted);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** IDs read but not sent yet, or in flight in the flow. */
|
|
158
|
+
isLocal(id) {
|
|
159
|
+
if (this.held.some((entry) => entry.id === id) || this.buffer.some((entry) => entry.id === id)) return true;
|
|
160
|
+
return this.registry.has(this.stream, this.group, id);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
get manualAck() {
|
|
164
|
+
return this.options.ackMode !== 'auto';
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
snapshot() {
|
|
168
|
+
return {
|
|
169
|
+
stream: this.stream,
|
|
170
|
+
group: this.group,
|
|
171
|
+
consumer: this.consumer,
|
|
172
|
+
paused: this.paused,
|
|
173
|
+
recovering: this.recovering,
|
|
174
|
+
backpressure: this.backpressure,
|
|
175
|
+
inflight: this.manualAck ? this.registry.count(this.stream, this.group, this.consumer) : 0,
|
|
176
|
+
held: this.held.length + this.buffer.length,
|
|
177
|
+
maxPending: this.options.maxPending,
|
|
178
|
+
delivered: this.delivered,
|
|
179
|
+
lastError: this.lastError
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
state(extra = {}) {
|
|
184
|
+
this.onState({ ...this.snapshot(), ...extra });
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
wake() {
|
|
188
|
+
const resolve = this.wakeResolve;
|
|
189
|
+
this.wakeResolve = null;
|
|
190
|
+
if (resolve) resolve();
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async waitWake(ms) {
|
|
194
|
+
const woken = new Promise((resolve) => { this.wakeResolve = resolve; });
|
|
195
|
+
try {
|
|
196
|
+
await Promise.race([this.clock.sleep(ms, this.signal), woken]);
|
|
197
|
+
} finally {
|
|
198
|
+
this.wakeResolve = null;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async ensureGroup() {
|
|
203
|
+
try {
|
|
204
|
+
await this.shared.xgroup('CREATE', this.stream, this.group, this.options.startId, 'MKSTREAM');
|
|
205
|
+
} catch (error) {
|
|
206
|
+
if (!/BUSYGROUP/.test(String(error?.message))) throw error;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Runs until the signal aborts. Never rejects for Redis errors: they are
|
|
212
|
+
* logged, reported through onState and retried with backoff.
|
|
213
|
+
* @param {AbortSignal} signal
|
|
214
|
+
*/
|
|
215
|
+
async run(signal) {
|
|
216
|
+
this.signal = signal;
|
|
217
|
+
// Subscribed here, not in the constructor, so a consumer that never runs
|
|
218
|
+
// (failed start) leaves no listener behind.
|
|
219
|
+
this.unsubscribe = this.registry.onRemove(() => this.wake());
|
|
220
|
+
this.running = true;
|
|
221
|
+
const onAbort = () => this.wake();
|
|
222
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
223
|
+
try {
|
|
224
|
+
while (!signal.aborted) {
|
|
225
|
+
try {
|
|
226
|
+
await this.iteration();
|
|
227
|
+
} catch (error) {
|
|
228
|
+
if (signal.aborted || error?.name === 'AbortError') break;
|
|
229
|
+
await this.handleError(error);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
} finally {
|
|
233
|
+
this.running = false;
|
|
234
|
+
signal.removeEventListener('abort', onAbort);
|
|
235
|
+
if (this.batchTimer) this.clock.clearTimeout(this.batchTimer);
|
|
236
|
+
this.batchTimer = null;
|
|
237
|
+
this.unsubscribe();
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async handleError(error) {
|
|
242
|
+
if (isNoGroup(error)) {
|
|
243
|
+
try {
|
|
244
|
+
await this.ensureGroup();
|
|
245
|
+
this.log.warn(`Consumer group restored: ${this.group}@${this.stream}`, { key: 'NOGROUP_RESTORED' });
|
|
246
|
+
this.startRecovery();
|
|
247
|
+
return;
|
|
248
|
+
} catch (restoreError) {
|
|
249
|
+
error = restoreError;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
// A lost XREADGROUP reply leaves its entries in this consumer's PEL, so
|
|
253
|
+
// every failure is followed by a recovery pass.
|
|
254
|
+
this.startRecovery();
|
|
255
|
+
this.lastError = error?.code || error?.name || 'ERROR';
|
|
256
|
+
this.state({ error: this.lastError });
|
|
257
|
+
this.log.error(error, { key: error?.code || 'STREAM_LOOP_ERROR' });
|
|
258
|
+
await this.clock.sleep(this.backoff.next(), this.signal).catch(() => {});
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
startRecovery() {
|
|
262
|
+
this.recoveryGeneration += 1;
|
|
263
|
+
this.recovering = true;
|
|
264
|
+
this.cursor = '0';
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async iteration() {
|
|
268
|
+
if (this.paused && !this.draining) {
|
|
269
|
+
this.state();
|
|
270
|
+
await this.waitWake(this.options.pausePollMs);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (this.held.length) {
|
|
274
|
+
const entries = this.held.splice(0);
|
|
275
|
+
await this.deliver(entries);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
if (this.recovering) {
|
|
279
|
+
await this.recoverStep();
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
if (this.draining) {
|
|
283
|
+
// No new reads while draining; reserved entries were sent above.
|
|
284
|
+
await this.waitWake(this.options.drainCheckIntervalMs);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
await this.maybeAutoclaim();
|
|
288
|
+
if (this.paused || this.recovering) return;
|
|
289
|
+
|
|
290
|
+
const room = await this.capacity();
|
|
291
|
+
if (room <= 0) {
|
|
292
|
+
if (!this.backpressure) {
|
|
293
|
+
this.backpressure = true;
|
|
294
|
+
this.state();
|
|
295
|
+
}
|
|
296
|
+
await this.waitWake(this.options.capacityPollMs);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
if (this.backpressure) {
|
|
300
|
+
this.backpressure = false;
|
|
301
|
+
this.state();
|
|
302
|
+
}
|
|
303
|
+
await this.waitReadInterval();
|
|
304
|
+
if (this.paused || this.signal.aborted) return;
|
|
305
|
+
|
|
306
|
+
this.lastReadAt = this.clock.now();
|
|
307
|
+
// Drain waits for this read: entries it returns are reserved by this pod.
|
|
308
|
+
this.readInFlight = this.blocking.xreadgroup(
|
|
309
|
+
'GROUP', this.group, this.consumer,
|
|
310
|
+
'COUNT', Math.max(1, Math.min(this.options.count, room)),
|
|
311
|
+
'BLOCK', this.options.blockMs,
|
|
312
|
+
'STREAMS', this.stream, '>'
|
|
313
|
+
);
|
|
314
|
+
let reply;
|
|
315
|
+
try {
|
|
316
|
+
reply = await this.readInFlight;
|
|
317
|
+
} finally {
|
|
318
|
+
this.readInFlight = null;
|
|
319
|
+
}
|
|
320
|
+
this.backoff.reset();
|
|
321
|
+
if (this.lastError) {
|
|
322
|
+
this.lastError = null;
|
|
323
|
+
this.state();
|
|
324
|
+
}
|
|
325
|
+
if (!reply) return;
|
|
326
|
+
const entries = parseEntries(reply[0]?.[1]).filter((entry) => entry.fields !== null)
|
|
327
|
+
.map((entry) => ({ id: entry.id, payload: decodeFields(entry.fields), deliveries: 1 }));
|
|
328
|
+
await this.deliver(entries);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* One page of own PEL recovery (RDS-STR-3). XPENDING of this consumer does
|
|
333
|
+
* not touch delivery counts, so entries still in flight are only skipped.
|
|
334
|
+
* The rest are claimed back with XCLAIM, which returns their fields, adds
|
|
335
|
+
* one delivery and skips entries acknowledged since the XPENDING call.
|
|
336
|
+
*/
|
|
337
|
+
async recoverStep() {
|
|
338
|
+
const generation = this.recoveryGeneration;
|
|
339
|
+
const start = this.cursor === '0' ? '-' : `(${this.cursor}`;
|
|
340
|
+
const rows = await this.shared.xpending(this.stream, this.group, start, '+', this.options.count, this.consumer);
|
|
341
|
+
this.backoff.reset();
|
|
342
|
+
// A new pass was requested meanwhile (drain, an error): it starts over.
|
|
343
|
+
if (generation !== this.recoveryGeneration) return;
|
|
344
|
+
if (!Array.isArray(rows) || rows.length === 0) {
|
|
345
|
+
this.recovering = false;
|
|
346
|
+
this.cursor = '0';
|
|
347
|
+
if (this.lastError) this.lastError = null;
|
|
348
|
+
this.state();
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
this.cursor = String(rows[rows.length - 1][0]);
|
|
352
|
+
const counts = new Map();
|
|
353
|
+
let minIdle = Infinity;
|
|
354
|
+
for (const row of rows) {
|
|
355
|
+
const id = String(row[0]);
|
|
356
|
+
if (this.isLocal(id)) continue;
|
|
357
|
+
counts.set(id, Number(row[3]) || 1);
|
|
358
|
+
minIdle = Math.min(minIdle, Number(row[2]) || 0);
|
|
359
|
+
}
|
|
360
|
+
if (counts.size === 0) return;
|
|
361
|
+
// min-idle = the smallest idle time XPENDING just reported: an entry that
|
|
362
|
+
// another consumer claims after that call has its idle time reset and is
|
|
363
|
+
// not taken back, while every own candidate is at least that idle.
|
|
364
|
+
const reply = await this.shared.xclaim(this.stream, this.group, this.consumer, Number.isFinite(minIdle) ? minIdle : 0, ...counts.keys());
|
|
365
|
+
const list = Array.isArray(reply) ? reply : [];
|
|
366
|
+
const claimed = parseEntries(list.filter(Boolean));
|
|
367
|
+
// Redis 6.2 answers nil for entries deleted from the stream while pending
|
|
368
|
+
// and keeps them in the PEL; Redis 7 and Valkey drop them from the PEL
|
|
369
|
+
// themselves. XACK of an ID acknowledged meanwhile is a no-op.
|
|
370
|
+
if (list.some((item) => item === null || (Array.isArray(item) && item[1] === null))) {
|
|
371
|
+
// The nils carry no ID: check which unreturned IDs are really gone from
|
|
372
|
+
// the stream (others were acknowledged or claimed meanwhile).
|
|
373
|
+
const returned = new Set(claimed.filter((entry) => entry.fields !== null).map((entry) => entry.id));
|
|
374
|
+
const gone = [];
|
|
375
|
+
for (const id of counts.keys()) {
|
|
376
|
+
if (returned.has(id)) continue;
|
|
377
|
+
const range = await this.shared.xrange(this.stream, id, id);
|
|
378
|
+
if (!Array.isArray(range) || range.length === 0) gone.push(id);
|
|
379
|
+
}
|
|
380
|
+
if (gone.length) await this.ackMissing(gone);
|
|
381
|
+
}
|
|
382
|
+
const entries = claimed.filter((entry) => entry.fields !== null && counts.has(entry.id) && !this.isLocal(entry.id))
|
|
383
|
+
.map((entry) => ({ ...entry, deliveries: counts.get(entry.id) + 1 }));
|
|
384
|
+
const live = await this.applyDeliveries(entries, true);
|
|
385
|
+
await this.deliver(live);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async ackMissing(ids) {
|
|
389
|
+
await this.shared.xack(this.stream, this.group, ...ids);
|
|
390
|
+
this.log.warn(`Acknowledged ${ids.length} pending entries deleted from ${this.stream}; do not trim streams below the PEL horizon`, { key: 'ENTRY_DELETED' });
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** XAUTOCLAIM of abandoned entries (RDS-STR-9). */
|
|
394
|
+
async maybeAutoclaim() {
|
|
395
|
+
if (!this.options.autoClaim || !this.manualAck) return;
|
|
396
|
+
const now = this.clock.now();
|
|
397
|
+
if (now - this.lastReclaimAt < this.options.reclaimIntervalMs) return;
|
|
398
|
+
this.lastReclaimAt = now;
|
|
399
|
+
const reply = await this.shared.xautoclaim(
|
|
400
|
+
this.stream, this.group, this.consumer, this.options.reclaimIdleMs,
|
|
401
|
+
this.claimCursor, 'COUNT', this.options.reclaimCount
|
|
402
|
+
);
|
|
403
|
+
this.claimCursor = reply?.[0] ? String(reply[0]) : '0-0';
|
|
404
|
+
const candidates = parseEntries(reply?.[1]).filter((entry) => entry.fields !== null && !this.isLocal(entry.id));
|
|
405
|
+
if (candidates.length === 0) return;
|
|
406
|
+
const live = await this.applyDeliveries(candidates);
|
|
407
|
+
await this.deliver(live);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Reads delivery counts with one range XPENDING per batch (RDS-STR-6) and
|
|
412
|
+
* moves entries over maxDeliveries to the DLQ atomically (RDS-STR-7).
|
|
413
|
+
* @param {Array<{ id: string, fields: unknown[] }>} entries
|
|
414
|
+
*/
|
|
415
|
+
async applyDeliveries(entries, known = false) {
|
|
416
|
+
if (entries.length === 0) return [];
|
|
417
|
+
const decoded = entries.map((entry) => ({ id: entry.id, payload: decodeFields(entry.fields), deliveries: entry.deliveries || 1 }));
|
|
418
|
+
let counts = null;
|
|
419
|
+
if (!known) {
|
|
420
|
+
const first = entries[0].id;
|
|
421
|
+
const last = entries[entries.length - 1].id;
|
|
422
|
+
const bound = Math.min(50000, entries.length + this.registry.count(this.stream, this.group, this.consumer) + this.options.count);
|
|
423
|
+
const rows = await this.shared.xpending(this.stream, this.group, first, last, bound, this.consumer);
|
|
424
|
+
counts = new Map((rows || []).map((row) => [String(row[0]), Number(row[3]) || 1]));
|
|
425
|
+
}
|
|
426
|
+
const dead = [];
|
|
427
|
+
const live = [];
|
|
428
|
+
for (const entry of decoded) {
|
|
429
|
+
if (counts) entry.deliveries = counts.get(entry.id) || 1;
|
|
430
|
+
if (this.options.maxDeliveries > 0 && entry.deliveries > this.options.maxDeliveries) dead.push(entry);
|
|
431
|
+
else live.push(entry);
|
|
432
|
+
}
|
|
433
|
+
if (dead.length) {
|
|
434
|
+
await moveToDlq(this.shared, {
|
|
435
|
+
stream: this.stream,
|
|
436
|
+
group: this.group,
|
|
437
|
+
dlq: this.options.deadLetterStream,
|
|
438
|
+
consumer: this.consumer
|
|
439
|
+
}, dead);
|
|
440
|
+
this.registry.remove(this.stream, this.group, dead.map((entry) => entry.id));
|
|
441
|
+
this.metrics.inc('redkern_redis_dead_letter_total', this.labels, dead.length);
|
|
442
|
+
this.log.warn(`Moved ${dead.length} entries from ${this.stream} to ${this.options.deadLetterStream} after more than ${this.options.maxDeliveries} deliveries`, { key: 'DLQ_MOVED' });
|
|
443
|
+
}
|
|
444
|
+
return live;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Free backpressure capacity (RDS-STR-8). */
|
|
448
|
+
async capacity() {
|
|
449
|
+
if (!this.manualAck) return this.options.count;
|
|
450
|
+
const now = this.clock.now();
|
|
451
|
+
if (this.options.backpressureScope === 'group') {
|
|
452
|
+
if (now - this.lastCapacityCheckAt >= this.options.capacityCheckIntervalMs) {
|
|
453
|
+
const summary = await this.shared.xpending(this.stream, this.group);
|
|
454
|
+
this.groupPending = Number(summary?.[0]) || 0;
|
|
455
|
+
this.lastCapacityCheckAt = now;
|
|
456
|
+
}
|
|
457
|
+
return this.options.maxPending - this.groupPending;
|
|
458
|
+
}
|
|
459
|
+
let pending = this.registry.count(this.stream, this.group, this.consumer);
|
|
460
|
+
if (pending >= this.options.maxPending && now - this.lastCapacityCheckAt >= this.options.capacityCheckIntervalMs) {
|
|
461
|
+
// Entries acknowledged outside stream-ack still occupy the registry;
|
|
462
|
+
// reconcile with the real PEL before waiting for their TTL.
|
|
463
|
+
this.lastCapacityCheckAt = now;
|
|
464
|
+
const limit = this.options.maxPending;
|
|
465
|
+
const rows = (await this.shared.xpending(this.stream, this.group, '-', '+', limit, this.consumer)) || [];
|
|
466
|
+
// A full page may hide newer in-flight IDs behind older stale ones:
|
|
467
|
+
// reconcile only up to the last ID the page covers.
|
|
468
|
+
const upTo = rows.length >= limit ? String(rows[rows.length - 1][0]) : undefined;
|
|
469
|
+
this.registry.retain(this.stream, this.group, this.consumer, rows.map((row) => String(row[0])), upTo);
|
|
470
|
+
pending = this.registry.count(this.stream, this.group, this.consumer);
|
|
471
|
+
}
|
|
472
|
+
return this.options.maxPending - pending;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
async waitReadInterval() {
|
|
476
|
+
if (!this.options.readIntervalMs || !this.lastReadAt) return;
|
|
477
|
+
const wait = this.options.readIntervalMs - (this.clock.now() - this.lastReadAt);
|
|
478
|
+
if (wait > 0) await this.clock.sleep(wait, this.signal);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** Token bucket per entry. Returns false when paused or closing. */
|
|
482
|
+
async rateSlot() {
|
|
483
|
+
const limit = this.options.rateLimitPerSecond;
|
|
484
|
+
if (!limit || this.draining) return !this.stopped;
|
|
485
|
+
while (!this.stopped) {
|
|
486
|
+
const now = this.clock.now();
|
|
487
|
+
this.rateTokens = Math.min(limit, this.rateTokens + ((now - this.rateRefillAt) * limit / 1000));
|
|
488
|
+
this.rateRefillAt = now;
|
|
489
|
+
if (this.rateTokens >= 1) {
|
|
490
|
+
this.rateTokens -= 1;
|
|
491
|
+
return true;
|
|
492
|
+
}
|
|
493
|
+
await this.clock.sleep(Math.max(1, Math.ceil((1 - this.rateTokens) * 1000 / limit)), this.signal);
|
|
494
|
+
}
|
|
495
|
+
return false;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** @param {Array<{ id: string, payload: Record<string, unknown>, deliveries: number }>} entries */
|
|
499
|
+
async deliver(entries) {
|
|
500
|
+
for (let index = 0; index < entries.length; index += 1) {
|
|
501
|
+
const entry = entries[index];
|
|
502
|
+
if (!(await this.rateSlot())) {
|
|
503
|
+
if (!this.signal.aborted) this.held.push(...entries.slice(index));
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
if (this.batching) {
|
|
507
|
+
this.buffer.push(entry);
|
|
508
|
+
if (this.buffer.length >= this.options.count) await this.flushBatch(false);
|
|
509
|
+
else this.scheduleBatch();
|
|
510
|
+
} else {
|
|
511
|
+
await this.send([entry]);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
scheduleBatch() {
|
|
517
|
+
if (this.batchTimer || this.buffer.length === 0) return;
|
|
518
|
+
this.batchTimer = this.clock.setTimeout(() => {
|
|
519
|
+
this.batchTimer = null;
|
|
520
|
+
this.flushBatch(false).catch((error) => {
|
|
521
|
+
if (!this.signal?.aborted) this.log.error(error, { key: error?.code || 'BATCH_FLUSH_FAILED' });
|
|
522
|
+
});
|
|
523
|
+
}, this.options.batchWindowMs);
|
|
524
|
+
this.batchTimer?.unref?.();
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
async flushBatch(force) {
|
|
528
|
+
if (this.buffer.length === 0) return;
|
|
529
|
+
if (!force && this.stopped) return;
|
|
530
|
+
if (!force && this.options.batchIntervalMs && this.lastBatchAt) {
|
|
531
|
+
const wait = this.options.batchIntervalMs - (this.clock.now() - this.lastBatchAt);
|
|
532
|
+
if (wait > 0) {
|
|
533
|
+
await this.clock.sleep(wait, this.signal).catch(() => {});
|
|
534
|
+
if (this.stopped || this.buffer.length === 0) return;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (this.batchTimer) {
|
|
538
|
+
this.clock.clearTimeout(this.batchTimer);
|
|
539
|
+
this.batchTimer = null;
|
|
540
|
+
}
|
|
541
|
+
const entries = this.buffer.splice(0, this.buffer.length);
|
|
542
|
+
this.lastBatchAt = this.clock.now();
|
|
543
|
+
await this.send(entries);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
async send(entries) {
|
|
547
|
+
if (entries.length === 0) return;
|
|
548
|
+
if (this.manualAck) {
|
|
549
|
+
for (const entry of entries) this.registry.add(this.stream, this.group, entry.id, this.consumer, this.options.reclaimIdleMs);
|
|
550
|
+
}
|
|
551
|
+
const redelivered = entries.filter((entry) => entry.deliveries > 1).length;
|
|
552
|
+
if (redelivered) this.metrics.inc('redkern_redis_redeliveries_total', this.labels, redelivered);
|
|
553
|
+
this.metrics.inc('redkern_redis_delivered_total', this.labels, entries.length);
|
|
554
|
+
this.delivered += entries.length;
|
|
555
|
+
this.emit({ entries, batched: this.batching });
|
|
556
|
+
if (!this.manualAck) {
|
|
557
|
+
await this.shared.xack(this.stream, this.group, ...entries.map((entry) => entry.id));
|
|
558
|
+
this.metrics.inc('redkern_redis_acked_total', this.labels, entries.length);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
pause() {
|
|
563
|
+
if (!this.paused) {
|
|
564
|
+
this.paused = true;
|
|
565
|
+
this.pausedAt = this.clock.now();
|
|
566
|
+
if (this.buffer.length) {
|
|
567
|
+
this.held.push(...this.buffer.splice(0));
|
|
568
|
+
if (this.batchTimer) this.clock.clearTimeout(this.batchTimer);
|
|
569
|
+
this.batchTimer = null;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
this.state();
|
|
573
|
+
return this.status();
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
resume() {
|
|
577
|
+
if (this.paused) {
|
|
578
|
+
// Held entries may have been claimed by another consumer during a long
|
|
579
|
+
// pause; re-read the own PEL instead of sending them blindly.
|
|
580
|
+
if (this.held.length && this.clock.now() - this.pausedAt >= this.options.reclaimIdleMs / 2) {
|
|
581
|
+
this.held = [];
|
|
582
|
+
this.startRecovery();
|
|
583
|
+
}
|
|
584
|
+
this.paused = false;
|
|
585
|
+
this.wake();
|
|
586
|
+
}
|
|
587
|
+
this.state();
|
|
588
|
+
return this.status();
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* Stops reading new entries, sends entries already reserved and waits for
|
|
593
|
+
* an empty own PEL (RDS-CTL-4).
|
|
594
|
+
* @param {number} timeoutMs
|
|
595
|
+
*/
|
|
596
|
+
async drain(timeoutMs) {
|
|
597
|
+
// Held back during a long pause, these entries may have been reclaimed by
|
|
598
|
+
// another consumer: drop them, recovery claims back what is still own.
|
|
599
|
+
if (this.paused && this.held.length && this.clock.now() - this.pausedAt >= this.options.reclaimIdleMs / 2) this.held = [];
|
|
600
|
+
if (!this.paused) this.pausedAt = this.clock.now();
|
|
601
|
+
this.paused = true;
|
|
602
|
+
this.draining += 1;
|
|
603
|
+
// Own PEL entries that are not in flight here (a lost reply, a dropped
|
|
604
|
+
// flow) would keep the PEL non-empty forever: send them again now.
|
|
605
|
+
this.startRecovery();
|
|
606
|
+
this.wake();
|
|
607
|
+
try {
|
|
608
|
+
this.state();
|
|
609
|
+
const deadline = this.clock.now() + Math.max(0, timeoutMs);
|
|
610
|
+
await this.flushReserved();
|
|
611
|
+
let pending = await this.ownPending();
|
|
612
|
+
const busy = () => this.running && (this.readInFlight || this.recovering);
|
|
613
|
+
while ((pending > 0 || busy()) && this.clock.now() < deadline && !this.signal?.aborted) {
|
|
614
|
+
await this.clock.sleep(Math.min(this.options.drainCheckIntervalMs, Math.max(1, deadline - this.clock.now())), this.signal).catch(() => {});
|
|
615
|
+
// A read that was blocked when drain started can still return entries.
|
|
616
|
+
await this.flushReserved();
|
|
617
|
+
pending = await this.ownPending();
|
|
618
|
+
}
|
|
619
|
+
return { ...this.status(), drained: pending === 0, pending };
|
|
620
|
+
} finally {
|
|
621
|
+
this.draining -= 1;
|
|
622
|
+
this.state();
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/** Sends entries held back by pause or waiting in a batch. */
|
|
627
|
+
async flushReserved() {
|
|
628
|
+
if (this.batchTimer) this.clock.clearTimeout(this.batchTimer);
|
|
629
|
+
this.batchTimer = null;
|
|
630
|
+
const reserved = [...this.held.splice(0), ...this.buffer.splice(0)];
|
|
631
|
+
const size = this.batching ? this.options.count : 1;
|
|
632
|
+
for (let index = 0; index < reserved.length; index += size) await this.send(reserved.slice(index, index + size));
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
async ownPending() {
|
|
636
|
+
const summary = await this.shared.xpending(this.stream, this.group);
|
|
637
|
+
const consumers = Array.isArray(summary?.[3]) ? summary[3] : [];
|
|
638
|
+
const own = consumers.find(([name]) => name === this.consumer);
|
|
639
|
+
return own ? Number(own[1]) || 0 : 0;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
status() {
|
|
643
|
+
const snapshot = this.snapshot();
|
|
644
|
+
return {
|
|
645
|
+
stream: snapshot.stream,
|
|
646
|
+
group: snapshot.group,
|
|
647
|
+
consumer: snapshot.consumer,
|
|
648
|
+
paused: snapshot.paused,
|
|
649
|
+
inflight: snapshot.inflight,
|
|
650
|
+
held: snapshot.held
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
function createBackoff({ initialBackoffMs, maxBackoffMs, backoffMultiplier }) {
|
|
656
|
+
let attempt = 0;
|
|
657
|
+
return {
|
|
658
|
+
next() {
|
|
659
|
+
const ceiling = Math.min(maxBackoffMs, initialBackoffMs * backoffMultiplier ** attempt);
|
|
660
|
+
attempt += 1;
|
|
661
|
+
// Equal jitter: at least half of the ceiling, so the whole HPA pool does
|
|
662
|
+
// not reconnect in lockstep after a Redis failover.
|
|
663
|
+
return Math.floor(ceiling / 2 + Math.random() * ceiling / 2);
|
|
664
|
+
},
|
|
665
|
+
reset() { attempt = 0; }
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
module.exports = { StreamConsumer, DEFAULTS, parseEntries, isNoGroup, codeError };
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="60" viewBox="0 0 40 60">
|
|
2
|
+
<title>Command</title>
|
|
3
|
+
<path fill="none" stroke="#ffffff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" d="M8 13a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M8 21a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M8 29a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M12 42l5 4l-5 4 M20 51h9"/>
|
|
4
|
+
</svg>
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="60" viewBox="0 0 40 60">
|
|
2
|
+
<title>List in</title>
|
|
3
|
+
<path fill="none" stroke="#ffffff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" d="M8 13a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M8 21a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M8 29a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M20 41v14 M15 50l5 5l5 -5"/>
|
|
4
|
+
</svg>
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="60" viewBox="0 0 40 60">
|
|
2
|
+
<title>Transaction</title>
|
|
3
|
+
<path fill="none" stroke="#ffffff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" d="M8 13a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M8 21a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M8 29a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M12 41h16v13h-16z M15 47l3 3l6 -6"/>
|
|
4
|
+
</svg>
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="60" viewBox="0 0 40 60">
|
|
2
|
+
<title>Scan</title>
|
|
3
|
+
<path fill="none" stroke="#ffffff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" d="M8 13a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M8 21a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M8 29a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M14 47a5 5 0 1 0 10 0a5 5 0 1 0 -10 0 M23 51l5 5"/>
|
|
4
|
+
</svg>
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="60" viewBox="0 0 40 60">
|
|
2
|
+
<title>Stream ack</title>
|
|
3
|
+
<path fill="none" stroke="#ffffff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" d="M8 13a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M8 21a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M8 29a12 4 0 1 0 24 0a12 4 0 1 0 -24 0 M12 48l5 5l11 -11"/>
|
|
4
|
+
</svg>
|