@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,79 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const HOOK_ID = 'redkern-redis-completion';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Tracks when a message sent by a source node has been fully handled by the
|
|
7
|
+
* flow, using the public Node-RED runtime hooks: every preDeliver of the
|
|
8
|
+
* message's _msgid adds one pending delivery and every onComplete removes one.
|
|
9
|
+
* When the count returns to zero, the message is done. A timeout releases the
|
|
10
|
+
* slot for flows whose nodes never complete (RDS-CMD-7, list-in prefetch).
|
|
11
|
+
*
|
|
12
|
+
* Hooks are installed only while at least one message is tracked, so a
|
|
13
|
+
* runtime without list-in pays nothing.
|
|
14
|
+
*/
|
|
15
|
+
function createCompletionTracker(RED, { setTimer = setTimeout, clearTimer = clearTimeout } = {}) {
|
|
16
|
+
/** @type {Map<string, { count: number, seen: boolean, done: () => void, timer: any }>} */
|
|
17
|
+
const tracked = new Map();
|
|
18
|
+
let installed = false;
|
|
19
|
+
|
|
20
|
+
function install() {
|
|
21
|
+
if (installed || !RED.hooks || typeof RED.hooks.add !== 'function') return;
|
|
22
|
+
installed = true;
|
|
23
|
+
RED.hooks.add(`preDeliver.${HOOK_ID}`, (event) => {
|
|
24
|
+
const entry = tracked.get(event?.msg?._msgid);
|
|
25
|
+
if (entry) {
|
|
26
|
+
entry.count += 1;
|
|
27
|
+
entry.seen = true;
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
RED.hooks.add(`onComplete.${HOOK_ID}`, (event) => {
|
|
31
|
+
const id = event?.msg?._msgid;
|
|
32
|
+
const entry = tracked.get(id);
|
|
33
|
+
if (!entry) return;
|
|
34
|
+
entry.count -= 1;
|
|
35
|
+
if (entry.seen && entry.count <= 0) finish(id);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function uninstall() {
|
|
40
|
+
if (!installed || tracked.size > 0) return;
|
|
41
|
+
installed = false;
|
|
42
|
+
RED.hooks.remove(`*.${HOOK_ID}`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function finish(id) {
|
|
46
|
+
const entry = tracked.get(id);
|
|
47
|
+
if (!entry) return;
|
|
48
|
+
tracked.delete(id);
|
|
49
|
+
clearTimer(entry.timer);
|
|
50
|
+
uninstall();
|
|
51
|
+
entry.done();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
/**
|
|
56
|
+
* @param {string} msgId
|
|
57
|
+
* @param {() => void} done called once
|
|
58
|
+
* @param {number} timeoutMs
|
|
59
|
+
* @returns {() => void} cancel
|
|
60
|
+
*/
|
|
61
|
+
track(msgId, done, timeoutMs) {
|
|
62
|
+
install();
|
|
63
|
+
const timer = setTimer(() => finish(msgId), timeoutMs);
|
|
64
|
+
timer?.unref?.();
|
|
65
|
+
tracked.set(msgId, { count: 0, seen: false, done, timer });
|
|
66
|
+
return () => {
|
|
67
|
+
const entry = tracked.get(msgId);
|
|
68
|
+
if (!entry) return;
|
|
69
|
+
tracked.delete(msgId);
|
|
70
|
+
clearTimer(entry.timer);
|
|
71
|
+
uninstall();
|
|
72
|
+
};
|
|
73
|
+
},
|
|
74
|
+
get size() { return tracked.size; },
|
|
75
|
+
get installed() { return installed; }
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
module.exports = { createCompletionTracker, HOOK_ID };
|
package/lib/control.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { codeError } = require('./format.js');
|
|
4
|
+
|
|
5
|
+
const ACTIONS = Object.freeze(['pause', 'resume', 'drain', 'status']);
|
|
6
|
+
const MAX_DRAIN_TIMEOUT_MS = 30 * 60 * 1000;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Validates a control command from a node message, an admin route or the
|
|
10
|
+
* internal drain route (RDS-CTL-1). Unknown fields are ignored.
|
|
11
|
+
* @param {unknown} input
|
|
12
|
+
*/
|
|
13
|
+
function parseCommand(input) {
|
|
14
|
+
const source = input && typeof input === 'object' && !Array.isArray(input) ? input : {};
|
|
15
|
+
const action = typeof source.action === 'string' ? source.action.trim().toLowerCase() : '';
|
|
16
|
+
if (!ACTIONS.includes(action)) throw codeError('CONTROL_ACTION_INVALID', 'action must be pause, resume, drain or status');
|
|
17
|
+
const command = { action };
|
|
18
|
+
for (const field of ['stream', 'group', 'nodeId']) {
|
|
19
|
+
if (source[field] === undefined || source[field] === null || source[field] === '') continue;
|
|
20
|
+
if (typeof source[field] !== 'string' || source[field].length > 1024) throw codeError('CONTROL_FILTER_INVALID', `${field} must be a string`);
|
|
21
|
+
command[field] = source[field];
|
|
22
|
+
}
|
|
23
|
+
if (source.drainTimeoutMs !== undefined && source.drainTimeoutMs !== null && source.drainTimeoutMs !== '') {
|
|
24
|
+
const timeout = Number(source.drainTimeoutMs);
|
|
25
|
+
if (!Number.isSafeInteger(timeout) || timeout < 0 || timeout > MAX_DRAIN_TIMEOUT_MS) {
|
|
26
|
+
throw codeError('CONTROL_TIMEOUT_INVALID', 'drainTimeoutMs must be an integer between 0 and 1800000');
|
|
27
|
+
}
|
|
28
|
+
command.drainTimeoutMs = timeout;
|
|
29
|
+
}
|
|
30
|
+
return command;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Runs a control command over the stream-in consumers of this runtime.
|
|
35
|
+
* @param {Iterable<{ nodeId: string, consumer: import('./stream-consumer.js').StreamConsumer, drainTimeoutMs: number }>} entries
|
|
36
|
+
* @param {{ action: string, stream?: string, group?: string, nodeId?: string, drainTimeoutMs?: number }} command
|
|
37
|
+
*/
|
|
38
|
+
async function executeControl(entries, command) {
|
|
39
|
+
const targets = [...entries].filter((entry) => (!command.stream || entry.consumer.stream === command.stream)
|
|
40
|
+
&& (!command.group || entry.consumer.group === command.group)
|
|
41
|
+
&& (!command.nodeId || entry.nodeId === command.nodeId));
|
|
42
|
+
const results = await Promise.all(targets.map(async (entry) => {
|
|
43
|
+
const base = { nodeId: entry.nodeId };
|
|
44
|
+
switch (command.action) {
|
|
45
|
+
case 'pause': return { ...base, ...entry.consumer.pause() };
|
|
46
|
+
case 'resume': return { ...base, ...entry.consumer.resume() };
|
|
47
|
+
case 'drain': return { ...base, ...(await entry.consumer.drain(command.drainTimeoutMs ?? entry.drainTimeoutMs)) };
|
|
48
|
+
default: return { ...base, ...entry.consumer.status() };
|
|
49
|
+
}
|
|
50
|
+
}));
|
|
51
|
+
return {
|
|
52
|
+
action: command.action,
|
|
53
|
+
target: { stream: command.stream || null, group: command.group || null, nodeId: command.nodeId || null },
|
|
54
|
+
consumers: results,
|
|
55
|
+
drained: command.action === 'drain' ? results.every((result) => result.drained) : undefined
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
module.exports = { parseCommand, executeControl, ACTIONS };
|
package/lib/denylist.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { codeError } = require('./format.js');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Commands rejected by default (RDS-CMD-3). Two-word entries match the first
|
|
7
|
+
* two tokens. The spec list plus commands with the same blast radius: data
|
|
8
|
+
* loss (SWAPDB, FUNCTION FLUSH), topology changes (FAILOVER, CLUSTER admin
|
|
9
|
+
* subcommands), server stalls (SAVE, CLIENT PAUSE) and killing other clients.
|
|
10
|
+
*/
|
|
11
|
+
const DEFAULT_DENYLIST = Object.freeze([
|
|
12
|
+
'FLUSHALL', 'FLUSHDB', 'CONFIG', 'SHUTDOWN', 'DEBUG', 'MODULE', 'ACL',
|
|
13
|
+
'REPLICAOF', 'SLAVEOF', 'MIGRATE', 'SCRIPT FLUSH',
|
|
14
|
+
'SWAPDB', 'FAILOVER', 'SAVE', 'BGSAVE', 'BGREWRITEAOF', 'LASTSAVE',
|
|
15
|
+
'FUNCTION FLUSH', 'FUNCTION DELETE', 'FUNCTION RESTORE', 'SCRIPT KILL', 'FUNCTION KILL',
|
|
16
|
+
'CLIENT KILL', 'CLIENT PAUSE', 'CLIENT UNPAUSE', 'CLIENT UNBLOCK',
|
|
17
|
+
'CLUSTER RESET', 'CLUSTER FAILOVER', 'CLUSTER FORGET', 'CLUSTER MEET', 'CLUSTER REPLICATE',
|
|
18
|
+
'CLUSTER ADDSLOTS', 'CLUSTER ADDSLOTSRANGE', 'CLUSTER DELSLOTS', 'CLUSTER DELSLOTSRANGE',
|
|
19
|
+
'CLUSTER FLUSHSLOTS', 'CLUSTER SETSLOT', 'CLUSTER SAVECONFIG', 'CLUSTER BUMPEPOCH', 'CLUSTER SET-CONFIG-EPOCH'
|
|
20
|
+
]);
|
|
21
|
+
const DEFAULT_DENIED_BY_COMMAND = new Map();
|
|
22
|
+
for (const entry of DEFAULT_DENYLIST) {
|
|
23
|
+
const [first, second] = entry.split(/\s+/);
|
|
24
|
+
const commands = DEFAULT_DENIED_BY_COMMAND.get(first) || [];
|
|
25
|
+
commands.push({ entry, second });
|
|
26
|
+
DEFAULT_DENIED_BY_COMMAND.set(first, commands);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Commands that run code chosen by the message. With the command or the
|
|
31
|
+
* transaction taken from msg they would bypass the denylist entirely
|
|
32
|
+
* (EVAL "return redis.call('FLUSHALL')" 0), so they are rejected for
|
|
33
|
+
* msg.command and msg.commands unless the denylist is disabled. A script set
|
|
34
|
+
* in the node configuration stays allowed.
|
|
35
|
+
*/
|
|
36
|
+
const SCRIPT_COMMANDS = Object.freeze(new Set([
|
|
37
|
+
'EVAL', 'EVALSHA', 'EVAL_RO', 'EVALSHA_RO', 'FCALL', 'FCALL_RO', 'FUNCTION', 'SCRIPT'
|
|
38
|
+
]));
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Commands that block or switch the connection mode. They would stall the
|
|
42
|
+
* shared auto-pipelined connection, so they are always rejected on command and
|
|
43
|
+
* multi; list-in, subscribe and stream-in own dedicated connections for them.
|
|
44
|
+
*/
|
|
45
|
+
const CONNECTION_COMMANDS = Object.freeze(new Set([
|
|
46
|
+
'BLPOP', 'BRPOP', 'BLMOVE', 'BRPOPLPUSH', 'BLMPOP', 'BZPOPMIN', 'BZPOPMAX', 'BZMPOP',
|
|
47
|
+
'WAIT', 'WAITAOF', 'SUBSCRIBE', 'PSUBSCRIBE', 'SSUBSCRIBE', 'UNSUBSCRIBE', 'PUNSUBSCRIBE',
|
|
48
|
+
'SUNSUBSCRIBE', 'MONITOR', 'SYNC', 'PSYNC', 'QUIT', 'RESET', 'SELECT', 'MULTI', 'EXEC', 'DISCARD', 'WATCH', 'UNWATCH',
|
|
49
|
+
// Change the state of the shared connection for every node using it.
|
|
50
|
+
'HELLO', 'AUTH', 'READONLY', 'READWRITE', 'ASKING'
|
|
51
|
+
]));
|
|
52
|
+
|
|
53
|
+
/** CLIENT subcommands that change the shared connection (reply mode, tracking, name). */
|
|
54
|
+
const CONNECTION_CLIENT_SUBCOMMANDS = Object.freeze(new Set([
|
|
55
|
+
'REPLY', 'TRACKING', 'CACHING', 'SETNAME', 'SETINFO', 'NO-EVICT', 'NO-TOUCH'
|
|
56
|
+
]));
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Normalises a command into tokens. Accepts "HGET", "XINFO STREAM" or
|
|
60
|
+
* ["XINFO", "STREAM"]; args must be an array.
|
|
61
|
+
* @param {unknown} command
|
|
62
|
+
* @param {unknown} [args]
|
|
63
|
+
* @returns {Array<string|number|Buffer>}
|
|
64
|
+
*/
|
|
65
|
+
function toTokens(command, args) {
|
|
66
|
+
let head;
|
|
67
|
+
if (Array.isArray(command)) {
|
|
68
|
+
head = command.map((token) => (Buffer.isBuffer(token) || typeof token === 'number' ? token : String(token)));
|
|
69
|
+
} else if (typeof command === 'string') {
|
|
70
|
+
head = command.trim().split(/\s+/).filter(Boolean);
|
|
71
|
+
} else {
|
|
72
|
+
throw codeError('COMMAND_MISSING', 'Redis command is not set (node config or msg.command)');
|
|
73
|
+
}
|
|
74
|
+
if (head.length === 0 || typeof head[0] !== 'string' || head[0].length === 0) {
|
|
75
|
+
throw codeError('COMMAND_MISSING', 'Redis command is not set (node config or msg.command)');
|
|
76
|
+
}
|
|
77
|
+
if (args !== undefined && args !== null && !Array.isArray(args)) {
|
|
78
|
+
throw codeError('ARGS_INVALID', 'msg.args must be an array of arguments, e.g. ["mykey", "myvalue"]');
|
|
79
|
+
}
|
|
80
|
+
return [...head, ...(args || [])];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Throws when a command is denied (RDS-CMD-3, RDS-CMD-4) or would block the
|
|
85
|
+
* shared connection.
|
|
86
|
+
* @param {Array<string|number|Buffer>} tokens
|
|
87
|
+
* @param {{ denylist?: boolean, extraDenied?: string[] }} [options]
|
|
88
|
+
*/
|
|
89
|
+
function checkCommand(tokens, { denylist = true, extraDenied = [], fromMsg = false } = {}) {
|
|
90
|
+
const first = String(tokens[0]).toUpperCase();
|
|
91
|
+
const second = tokens.length > 1 ? String(tokens[1]).toUpperCase() : '';
|
|
92
|
+
if (CONNECTION_COMMANDS.has(first) || (first === 'CLIENT' && CONNECTION_CLIENT_SUBCOMMANDS.has(second))) {
|
|
93
|
+
const name = first === 'CLIENT' ? `CLIENT ${second}` : first;
|
|
94
|
+
throw codeError('COMMAND_BLOCKING', `${name} is not allowed on the shared connection; use the dedicated list-in, subscribe or stream-in nodes`);
|
|
95
|
+
}
|
|
96
|
+
if ((first === 'XREAD' || first === 'XREADGROUP') && tokens.some((token) => String(token).toUpperCase() === 'BLOCK')) {
|
|
97
|
+
throw codeError('COMMAND_BLOCKING', `${first} with BLOCK is not allowed on the shared connection; use stream-in`);
|
|
98
|
+
}
|
|
99
|
+
if (!denylist) return;
|
|
100
|
+
if (fromMsg && SCRIPT_COMMANDS.has(first)) {
|
|
101
|
+
throw codeError('COMMAND_DENIED', `${first} from msg is denied: a script from the message bypasses the denylist; set the script in the node configuration`);
|
|
102
|
+
}
|
|
103
|
+
const extra = extraDenied.map((entry) => entry.toUpperCase());
|
|
104
|
+
for (const { entry, second: deniedSubcommand } of DEFAULT_DENIED_BY_COMMAND.get(first) || []) {
|
|
105
|
+
if (deniedSubcommand === undefined || deniedSubcommand === second) {
|
|
106
|
+
throw codeError('COMMAND_DENIED', `${entry} is in the command denylist`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
for (const entry of extra) {
|
|
110
|
+
const parts = entry.split(/\s+/);
|
|
111
|
+
if (parts[0] !== first) continue;
|
|
112
|
+
if (parts.length === 1 || parts[1] === second) {
|
|
113
|
+
throw codeError('COMMAND_DENIED', `${entry} is in the command denylist`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
module.exports = { DEFAULT_DENYLIST, CONNECTION_COMMANDS, SCRIPT_COMMANDS, toTokens, checkCommand };
|
package/lib/dlq.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { keySlot } = require('./slot.js');
|
|
4
|
+
const { codeError } = require('./format.js');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Moves entries to the dead-letter stream atomically (RDS-STR-7): XADD to the
|
|
8
|
+
* DLQ and XACK on the source run in one MULTI/EXEC. DLQ record fields are the
|
|
9
|
+
* same as in the legacy palette.
|
|
10
|
+
* @param {any} client shared ioredis client
|
|
11
|
+
* @param {{ stream: string, group: string, dlq: string, consumer: string }} target
|
|
12
|
+
* @param {Array<{ id: string, payload: unknown, deliveries: number }>} entries
|
|
13
|
+
*/
|
|
14
|
+
async function moveToDlq(client, { stream, group, dlq, consumer }, entries) {
|
|
15
|
+
if (entries.length === 0) return 0;
|
|
16
|
+
const transaction = client.multi();
|
|
17
|
+
for (const entry of entries) {
|
|
18
|
+
transaction.xadd(dlq, '*',
|
|
19
|
+
'sourceStream', stream,
|
|
20
|
+
'sourceGroup', group,
|
|
21
|
+
'sourceId', entry.id,
|
|
22
|
+
'consumer', consumer,
|
|
23
|
+
'deliveries', String(entry.deliveries),
|
|
24
|
+
'payload', JSON.stringify(entry.payload === undefined ? null : entry.payload));
|
|
25
|
+
}
|
|
26
|
+
transaction.xack(stream, group, ...entries.map((entry) => entry.id));
|
|
27
|
+
const results = await transaction.exec();
|
|
28
|
+
if (!Array.isArray(results)) throw codeError('DLQ_ABORTED', 'DLQ transaction was aborted');
|
|
29
|
+
const failed = results.find(([error]) => error);
|
|
30
|
+
if (failed) throw codeError('DLQ_FAILED', `DLQ transaction failed: ${failed[0].message}`);
|
|
31
|
+
return entries.length;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* In Redis Cluster MULTI works only inside one hash slot. Returns an issue for
|
|
36
|
+
* kit.ConfigError when the source stream and DLQ land in different slots.
|
|
37
|
+
* @param {string} stream
|
|
38
|
+
* @param {string} dlq
|
|
39
|
+
*/
|
|
40
|
+
function slotIssue(stream, dlq) {
|
|
41
|
+
if (keySlot(stream) === keySlot(dlq)) return null;
|
|
42
|
+
return {
|
|
43
|
+
field: 'deadLetterStream',
|
|
44
|
+
code: 'DLQ_CROSS_SLOT',
|
|
45
|
+
message: `Stream and DLQ are in different cluster slots; use a hash tag such as orders:{eu} and orders:{eu}:dlq`
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
module.exports = { moveToDlq, slotIssue };
|
package/lib/format.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Compact number for status texts: 950 -> "950", 1234 -> "1.2k", 3400000 -> "3.4M".
|
|
5
|
+
* @param {number} value
|
|
6
|
+
* @returns {string}
|
|
7
|
+
*/
|
|
8
|
+
function compact(value) {
|
|
9
|
+
const number = Number(value) || 0;
|
|
10
|
+
const abs = Math.abs(number);
|
|
11
|
+
if (abs < 1000) return String(Math.round(number * 10) / 10);
|
|
12
|
+
const units = [['G', 1e9], ['M', 1e6], ['k', 1e3]];
|
|
13
|
+
for (const [unit, size] of units) {
|
|
14
|
+
if (abs >= size) {
|
|
15
|
+
const scaled = number / size;
|
|
16
|
+
const text = Math.abs(scaled) >= 100 ? String(Math.round(scaled)) : String(Math.round(scaled * 10) / 10);
|
|
17
|
+
return `${text}${unit}`;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return String(number);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Converts a flat Redis reply ([k1, v1, k2, v2]) to an object.
|
|
25
|
+
* @param {unknown[]} flat
|
|
26
|
+
* @returns {Record<string, unknown>}
|
|
27
|
+
*/
|
|
28
|
+
function flatToObject(flat) {
|
|
29
|
+
const result = {};
|
|
30
|
+
if (!Array.isArray(flat)) return result;
|
|
31
|
+
for (let index = 0; index + 1 < flat.length; index += 2) {
|
|
32
|
+
result[String(flat[index])] = flat[index + 1];
|
|
33
|
+
}
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Decodes stream entry fields written by stream-out. Compound values (objects
|
|
39
|
+
* and arrays) were serialised to JSON and are restored; scalar strings such as
|
|
40
|
+
* "true", "42" or "null" stay strings to preserve Redis field semantics.
|
|
41
|
+
* @param {unknown[]} flat
|
|
42
|
+
* @returns {Record<string, unknown>}
|
|
43
|
+
*/
|
|
44
|
+
function decodeFields(flat) {
|
|
45
|
+
const result = flatToObject(flat);
|
|
46
|
+
for (const [field, value] of Object.entries(result)) {
|
|
47
|
+
if (typeof value !== 'string' || !/^\s*[[{]/.test(value)) continue;
|
|
48
|
+
try {
|
|
49
|
+
result[field] = JSON.parse(value);
|
|
50
|
+
} catch {
|
|
51
|
+
// A value that only looks like JSON is still a valid Redis string.
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Encodes a flat object to XADD field arguments. Format is unchanged from the
|
|
59
|
+
* legacy palette: objects and arrays as JSON, everything else via String().
|
|
60
|
+
* @param {unknown} payload
|
|
61
|
+
* @returns {string[]}
|
|
62
|
+
*/
|
|
63
|
+
function encodeFields(payload) {
|
|
64
|
+
if (typeof payload !== 'object' || payload === null || Array.isArray(payload) || Buffer.isBuffer(payload)) {
|
|
65
|
+
throw codeError('PAYLOAD_INVALID', 'msg.payload must be a flat object (field -> value) for XADD');
|
|
66
|
+
}
|
|
67
|
+
const fields = [];
|
|
68
|
+
for (const [field, value] of Object.entries(payload)) {
|
|
69
|
+
if (value === undefined) continue;
|
|
70
|
+
fields.push(field, value !== null && typeof value === 'object' && !Buffer.isBuffer(value) ? JSON.stringify(value) : String(value));
|
|
71
|
+
}
|
|
72
|
+
if (fields.length === 0) throw codeError('PAYLOAD_EMPTY', 'msg.payload must contain at least one field for XADD');
|
|
73
|
+
return fields;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Splits "a,b , c" into ["a","b","c"].
|
|
78
|
+
* @param {unknown} value
|
|
79
|
+
* @returns {string[]}
|
|
80
|
+
*/
|
|
81
|
+
function splitList(value) {
|
|
82
|
+
if (Array.isArray(value)) return value.map((item) => String(item).trim()).filter(Boolean);
|
|
83
|
+
if (typeof value !== 'string') return [];
|
|
84
|
+
return value.split(',').map((item) => item.trim()).filter(Boolean);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Error with a stable code. Messages never include values from msg.
|
|
89
|
+
* @param {string} code
|
|
90
|
+
* @param {string} message
|
|
91
|
+
* @returns {Error & { code: string }}
|
|
92
|
+
*/
|
|
93
|
+
function codeError(code, message) {
|
|
94
|
+
return Object.assign(new Error(message), { code });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Merges metadata into msg.redkern.redis without touching other palettes' keys.
|
|
99
|
+
* @param {Record<string, any>} msg
|
|
100
|
+
* @param {Record<string, unknown>} values
|
|
101
|
+
*/
|
|
102
|
+
function setMeta(msg, values) {
|
|
103
|
+
if (!msg.redkern || typeof msg.redkern !== 'object' || Array.isArray(msg.redkern)) msg.redkern = {};
|
|
104
|
+
const current = msg.redkern.redis && typeof msg.redkern.redis === 'object' && !Array.isArray(msg.redkern.redis)
|
|
105
|
+
? msg.redkern.redis
|
|
106
|
+
: {};
|
|
107
|
+
msg.redkern.redis = { ...current, ...values };
|
|
108
|
+
return msg.redkern.redis;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Replaces msg.redkern.redis (used by source nodes that start a new message).
|
|
113
|
+
* @param {Record<string, any>} msg
|
|
114
|
+
* @param {Record<string, unknown>} values
|
|
115
|
+
*/
|
|
116
|
+
function replaceMeta(msg, values) {
|
|
117
|
+
if (!msg.redkern || typeof msg.redkern !== 'object' || Array.isArray(msg.redkern)) msg.redkern = {};
|
|
118
|
+
msg.redkern.redis = { ...values };
|
|
119
|
+
return msg.redkern.redis;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
module.exports = { compact, flatToObject, decodeFields, encodeFields, splitList, codeError, setMeta, replaceMeta };
|
package/lib/inflight.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* In-flight registry (RDS-STR-4, RDS-STR-5). Holds stream entry IDs that a
|
|
5
|
+
* stream-in node has sent into the flow and nobody has acknowledged yet.
|
|
6
|
+
*
|
|
7
|
+
* The registry lives in the palette closure, not in a node, so it survives a
|
|
8
|
+
* redeploy of stream-in: the new instance has the same consumer name and
|
|
9
|
+
* recovers the same PEL, and the registry stops it from sending entries the
|
|
10
|
+
* old flow is still processing. stream-ack removes entries through the same
|
|
11
|
+
* registry. An entry also leaves the registry when it moves to the DLQ or when
|
|
12
|
+
* it is older than its TTL (reclaimIdleMs), after which it may be redelivered.
|
|
13
|
+
*/
|
|
14
|
+
class InflightRegistry {
|
|
15
|
+
/** @param {{ now?: () => number }} [options] */
|
|
16
|
+
constructor({ now = () => Date.now() } = {}) {
|
|
17
|
+
this.now = now;
|
|
18
|
+
/** @type {Map<string, Map<string, { consumer: string, expiresAt: number }>>} */
|
|
19
|
+
this.groups = new Map();
|
|
20
|
+
/** @type {Set<(key: string) => void>} */
|
|
21
|
+
this.listeners = new Set();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
static key(stream, group) {
|
|
25
|
+
return `${stream}\u0000${group}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
entries(stream, group, create = false) {
|
|
29
|
+
const key = InflightRegistry.key(stream, group);
|
|
30
|
+
let entries = this.groups.get(key);
|
|
31
|
+
if (!entries && create) {
|
|
32
|
+
entries = new Map();
|
|
33
|
+
this.groups.set(key, entries);
|
|
34
|
+
}
|
|
35
|
+
return entries;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
add(stream, group, id, consumer, ttlMs) {
|
|
39
|
+
this.entries(stream, group, true).set(id, { consumer, expiresAt: this.now() + ttlMs });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** True when the ID is in flight and has not expired. */
|
|
43
|
+
has(stream, group, id) {
|
|
44
|
+
const entries = this.entries(stream, group);
|
|
45
|
+
const entry = entries?.get(id);
|
|
46
|
+
if (!entry) return false;
|
|
47
|
+
if (entry.expiresAt <= this.now()) {
|
|
48
|
+
entries.delete(id);
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @returns {number} number of removed IDs */
|
|
55
|
+
remove(stream, group, ids) {
|
|
56
|
+
const entries = this.entries(stream, group);
|
|
57
|
+
if (!entries) return 0;
|
|
58
|
+
let removed = 0;
|
|
59
|
+
for (const id of ids) if (entries.delete(String(id))) removed += 1;
|
|
60
|
+
if (entries.size === 0) this.groups.delete(InflightRegistry.key(stream, group));
|
|
61
|
+
if (removed) this.notify(InflightRegistry.key(stream, group));
|
|
62
|
+
return removed;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Keeps only IDs present in `ids` for the consumer (reconcile with XPENDING).
|
|
67
|
+
* With `upTo`, IDs above it are kept: a truncated XPENDING page says nothing
|
|
68
|
+
* about them.
|
|
69
|
+
*/
|
|
70
|
+
retain(stream, group, consumer, ids, upTo) {
|
|
71
|
+
const entries = this.entries(stream, group);
|
|
72
|
+
if (!entries) return 0;
|
|
73
|
+
const keep = new Set(ids.map(String));
|
|
74
|
+
let removed = 0;
|
|
75
|
+
for (const [id, entry] of entries) {
|
|
76
|
+
if (upTo !== undefined && compareIds(id, upTo) > 0) continue;
|
|
77
|
+
if (entry.consumer === consumer && !keep.has(id)) {
|
|
78
|
+
entries.delete(id);
|
|
79
|
+
removed += 1;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (removed) this.notify(InflightRegistry.key(stream, group));
|
|
83
|
+
return removed;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
count(stream, group, consumer) {
|
|
87
|
+
const entries = this.entries(stream, group);
|
|
88
|
+
if (!entries) return 0;
|
|
89
|
+
const now = this.now();
|
|
90
|
+
let count = 0;
|
|
91
|
+
for (const [id, entry] of entries) {
|
|
92
|
+
if (entry.expiresAt <= now) {
|
|
93
|
+
entries.delete(id);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (consumer === undefined || entry.consumer === consumer) count += 1;
|
|
97
|
+
}
|
|
98
|
+
return count;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Clears a consumer's entries (used when a node is removed, not redeployed). */
|
|
102
|
+
clearConsumer(stream, group, consumer) {
|
|
103
|
+
const entries = this.entries(stream, group);
|
|
104
|
+
if (!entries) return;
|
|
105
|
+
for (const [id, entry] of entries) if (entry.consumer === consumer) entries.delete(id);
|
|
106
|
+
if (entries.size === 0) this.groups.delete(InflightRegistry.key(stream, group));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
onRemove(listener) {
|
|
110
|
+
this.listeners.add(listener);
|
|
111
|
+
return () => this.listeners.delete(listener);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
notify(key) {
|
|
115
|
+
for (const listener of this.listeners) {
|
|
116
|
+
try { listener(key); } catch { /* listeners are internal and must not throw */ }
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Compares two stream IDs "ms-seq" numerically. */
|
|
122
|
+
function compareIds(a, b) {
|
|
123
|
+
const [am, as = '0'] = String(a).split('-');
|
|
124
|
+
const [bm, bs = '0'] = String(b).split('-');
|
|
125
|
+
const ms = BigInt(am) - BigInt(bm);
|
|
126
|
+
if (ms !== 0n) return ms > 0n ? 1 : -1;
|
|
127
|
+
const seq = BigInt(as) - BigInt(bs);
|
|
128
|
+
return seq === 0n ? 0 : seq > 0n ? 1 : -1;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
module.exports = { compareIds, InflightRegistry };
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* BLPOP/BRPOP intake for list queues (RDS-CMD-7). Popping removes the element
|
|
5
|
+
* from the list, exactly like the legacy subscribe node in list mode; there is
|
|
6
|
+
* no reliable BLMOVE mode, delivery guarantees come from Streams.
|
|
7
|
+
*
|
|
8
|
+
* prefetch limits how many popped elements may be in the flow at once:
|
|
9
|
+
* 1 (default for new nodes) pops the next element only after the previous
|
|
10
|
+
* message completed; 0 means unlimited, which is the legacy behaviour.
|
|
11
|
+
*/
|
|
12
|
+
class ListConsumer {
|
|
13
|
+
/**
|
|
14
|
+
* @param {{
|
|
15
|
+
* client: any, key: string, direction: 'BLPOP'|'BRPOP', timeoutSec: number, prefetch: number,
|
|
16
|
+
* releaseTimeoutMs: number,
|
|
17
|
+
* emit: (key: string, value: string, msgId: string) => void,
|
|
18
|
+
* newId: () => string,
|
|
19
|
+
* wired: () => boolean,
|
|
20
|
+
* tracker?: { track: (id: string, done: () => void, timeoutMs: number) => () => void },
|
|
21
|
+
* sleep: (ms: number, signal?: AbortSignal) => Promise<void>,
|
|
22
|
+
* backoff: { next: () => number, reset: () => void },
|
|
23
|
+
* log?: { error: Function },
|
|
24
|
+
* onState?: (state: object) => void
|
|
25
|
+
* }} params
|
|
26
|
+
*/
|
|
27
|
+
constructor(params) {
|
|
28
|
+
Object.assign(this, params);
|
|
29
|
+
this.inflight = 0;
|
|
30
|
+
this.received = 0;
|
|
31
|
+
this.lastError = null;
|
|
32
|
+
this.wakeResolve = null;
|
|
33
|
+
this.cancels = new Set();
|
|
34
|
+
this.log = params.log || { error() {} };
|
|
35
|
+
this.onState = params.onState || (() => {});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
wake() {
|
|
39
|
+
const resolve = this.wakeResolve;
|
|
40
|
+
this.wakeResolve = null;
|
|
41
|
+
resolve?.();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async waitSlot(signal) {
|
|
45
|
+
while (!signal.aborted && this.prefetch > 0 && this.inflight >= this.prefetch) {
|
|
46
|
+
const woken = new Promise((resolve) => { this.wakeResolve = resolve; });
|
|
47
|
+
await Promise.race([this.sleep(1000, signal).catch(() => {}), woken]);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
release() {
|
|
52
|
+
this.inflight = Math.max(0, this.inflight - 1);
|
|
53
|
+
this.onState(this.snapshot());
|
|
54
|
+
this.wake();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
snapshot() {
|
|
58
|
+
return { inflight: this.inflight, prefetch: this.prefetch, received: this.received, lastError: this.lastError };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async pushBack(key, value) {
|
|
62
|
+
try {
|
|
63
|
+
if (this.direction === 'BRPOP') await this.client.rpush(key, value);
|
|
64
|
+
else await this.client.lpush(key, value);
|
|
65
|
+
} catch (error) {
|
|
66
|
+
this.log.error(Object.assign(new Error(`Element popped from ${key} during close could not be returned to the list`), { code: 'LIST_PUSHBACK_FAILED', cause: error }), { key: 'LIST_PUSHBACK_FAILED' });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** @param {AbortSignal} signal */
|
|
71
|
+
async run(signal) {
|
|
72
|
+
const onAbort = () => this.wake();
|
|
73
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
74
|
+
try {
|
|
75
|
+
while (!signal.aborted) {
|
|
76
|
+
await this.waitSlot(signal);
|
|
77
|
+
if (signal.aborted) break;
|
|
78
|
+
try {
|
|
79
|
+
const method = this.direction === 'BRPOP' ? 'brpop' : 'blpop';
|
|
80
|
+
const reply = await this.client[method](this.key, this.timeoutSec);
|
|
81
|
+
this.backoff.reset();
|
|
82
|
+
if (this.lastError) {
|
|
83
|
+
this.lastError = null;
|
|
84
|
+
this.onState(this.snapshot());
|
|
85
|
+
}
|
|
86
|
+
if (!reply) continue;
|
|
87
|
+
const [key, value] = reply;
|
|
88
|
+
if (signal.aborted) {
|
|
89
|
+
// Popped while the node was closing: put it back where it came from.
|
|
90
|
+
await this.pushBack(String(key), value);
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
this.received += 1;
|
|
94
|
+
const msgId = this.newId();
|
|
95
|
+
// Track before sending: runtime hooks may fire during send().
|
|
96
|
+
if (this.prefetch > 0 && this.tracker && this.wired()) {
|
|
97
|
+
this.inflight += 1;
|
|
98
|
+
let released = false;
|
|
99
|
+
const cancel = this.tracker.track(msgId, () => {
|
|
100
|
+
if (released) return;
|
|
101
|
+
released = true;
|
|
102
|
+
this.cancels.delete(cancel);
|
|
103
|
+
this.release();
|
|
104
|
+
}, this.releaseTimeoutMs);
|
|
105
|
+
this.cancels.add(cancel);
|
|
106
|
+
}
|
|
107
|
+
this.emit(String(key), value, msgId);
|
|
108
|
+
this.onState(this.snapshot());
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (signal.aborted) break;
|
|
111
|
+
this.lastError = error?.code || error?.name || 'ERROR';
|
|
112
|
+
this.onState(this.snapshot());
|
|
113
|
+
this.log.error(error, { key: error?.code || 'LIST_POP_FAILED' });
|
|
114
|
+
await this.sleep(this.backoff.next(), signal).catch(() => {});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
} finally {
|
|
118
|
+
signal.removeEventListener('abort', onAbort);
|
|
119
|
+
for (const cancel of this.cancels) cancel();
|
|
120
|
+
this.cancels.clear();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
module.exports = { ListConsumer };
|