@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,88 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { ListConsumer } = require('../lib/list-consumer.js');
|
|
4
|
+
const { replaceMeta, compact } = require('../lib/format.js');
|
|
5
|
+
const { requireConfig, classify } = require('../lib/node-helpers.js');
|
|
6
|
+
|
|
7
|
+
module.exports = function register(RED, palette) {
|
|
8
|
+
const { rk, kit, completion } = palette;
|
|
9
|
+
|
|
10
|
+
function RedisListInNode(config) {
|
|
11
|
+
RED.nodes.createNode(this, config);
|
|
12
|
+
const node = this;
|
|
13
|
+
const k = rk.bind(node);
|
|
14
|
+
const parsed = k.configure(config, {
|
|
15
|
+
server: { type: 'str', required: true },
|
|
16
|
+
key: { type: 'str', required: true },
|
|
17
|
+
direction: { type: 'enum', values: ['BLPOP', 'BRPOP'], default: 'BLPOP' },
|
|
18
|
+
timeout: { type: 'int', min: 0, max: 3600, default: 5 },
|
|
19
|
+
prefetch: { type: 'int', min: 0, max: 100000, default: 1 },
|
|
20
|
+
releaseTimeoutMs: { type: 'int', min: 1000, max: 86400000, default: 300000 }
|
|
21
|
+
});
|
|
22
|
+
const options = parsed.ok ? parsed.value : {};
|
|
23
|
+
let unregister;
|
|
24
|
+
let consumer;
|
|
25
|
+
|
|
26
|
+
function updateStatus(state) {
|
|
27
|
+
if (state.lastError) k.status('error', `retry ${state.lastError}`.toLowerCase());
|
|
28
|
+
else if (state.prefetch > 0 && state.inflight >= state.prefetch) k.status('warn', `waiting ${state.inflight}/${state.prefetch}`);
|
|
29
|
+
else k.status('ok', `received ${compact(state.received)}`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
let loop = null;
|
|
33
|
+
k.onStart(async (attempt) => {
|
|
34
|
+
const api = requireConfig(RED, config.server);
|
|
35
|
+
if (!unregister) {
|
|
36
|
+
unregister = api.register(node.id);
|
|
37
|
+
k.onClose(() => unregister());
|
|
38
|
+
}
|
|
39
|
+
const blockMs = options.timeout * 1000;
|
|
40
|
+
const blocking = api.createBlocking({
|
|
41
|
+
blockMs,
|
|
42
|
+
commandTimeout: options.timeout > 0 ? blockMs + 10000 : undefined
|
|
43
|
+
});
|
|
44
|
+
attempt.onClose(blocking.release, { force: blocking.release });
|
|
45
|
+
await blocking.connect();
|
|
46
|
+
let clientId = null;
|
|
47
|
+
try { clientId = await blocking.client.client('ID'); } catch { /* without the ID close waits for the pop instead */ }
|
|
48
|
+
// Runs before the release above (close stack is LIFO): end a BLPOP in
|
|
49
|
+
// progress so an element popped at that moment still reaches the
|
|
50
|
+
// pushback of the loop while the connection is open.
|
|
51
|
+
attempt.onClose(async () => {
|
|
52
|
+
if (!loop) return;
|
|
53
|
+
if (clientId !== null) {
|
|
54
|
+
try { await (await api.shared()).client('UNBLOCK', clientId); } catch { /* ACL without client|unblock */ }
|
|
55
|
+
}
|
|
56
|
+
await Promise.race([loop.catch(() => {}), kit.sleep(1500)]);
|
|
57
|
+
});
|
|
58
|
+
consumer = new ListConsumer({
|
|
59
|
+
client: blocking.client,
|
|
60
|
+
key: options.key,
|
|
61
|
+
direction: options.direction,
|
|
62
|
+
timeoutSec: options.timeout,
|
|
63
|
+
prefetch: options.prefetch,
|
|
64
|
+
releaseTimeoutMs: options.releaseTimeoutMs,
|
|
65
|
+
tracker: completion,
|
|
66
|
+
sleep: kit.sleep,
|
|
67
|
+
backoff: kit.backoff({ initial: 500, max: 30000, jitter: 'equal' }),
|
|
68
|
+
log: k.log,
|
|
69
|
+
onState: updateStatus,
|
|
70
|
+
newId: () => RED.util.generateId(),
|
|
71
|
+
// An unwired output never completes; do not hold a prefetch slot.
|
|
72
|
+
wired: () => Array.isArray(node.wires) && node.wires.some((port) => port.length > 0),
|
|
73
|
+
emit: (key, value, msgId) => {
|
|
74
|
+
const msg = { _msgid: msgId, topic: key, payload: value };
|
|
75
|
+
replaceMeta(msg, { list: key });
|
|
76
|
+
node.send(msg);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
}, { classify }).then(() => {
|
|
80
|
+
if (!consumer || k.signal.aborted) return;
|
|
81
|
+
updateStatus(consumer.snapshot());
|
|
82
|
+
loop = consumer.run(k.signal);
|
|
83
|
+
k.track(loop, { label: 'list-in loop' });
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
RED.nodes.registerType('redkern-redis-list-in', RedisListInNode);
|
|
88
|
+
};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { toTokens, checkCommand } = require('../lib/denylist.js');
|
|
4
|
+
const { codeError, setMeta } = require('../lib/format.js');
|
|
5
|
+
const { INPUT_SCHEMA, startShared, inputOptions, primary } = require('../lib/node-helpers.js');
|
|
6
|
+
|
|
7
|
+
const MAX_COMMANDS = 10000;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Accepts [["SET","k","v"],["INCR","c"]] from msg.commands or the node
|
|
11
|
+
* configuration (JSON). Each entry is normalised and checked against the
|
|
12
|
+
* denylist (RDS-CMD-4).
|
|
13
|
+
*/
|
|
14
|
+
function parseCommands(value, denylist, fromMsg = false) {
|
|
15
|
+
let commands = value;
|
|
16
|
+
if (typeof commands === 'string') {
|
|
17
|
+
if (commands.trim() === '') commands = [];
|
|
18
|
+
else {
|
|
19
|
+
try { commands = JSON.parse(commands); } catch {
|
|
20
|
+
throw codeError('COMMANDS_INVALID', 'Commands must be a JSON array of arrays');
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
if (!Array.isArray(commands) || commands.length === 0) {
|
|
25
|
+
throw codeError('COMMANDS_INVALID', 'msg.commands must be a non-empty array, e.g. [["set","k","v"],["incr","c"]]');
|
|
26
|
+
}
|
|
27
|
+
if (commands.length > MAX_COMMANDS) throw codeError('COMMANDS_TOO_MANY', `A transaction is limited to ${MAX_COMMANDS} commands`);
|
|
28
|
+
return commands.map((entry) => {
|
|
29
|
+
if (!Array.isArray(entry) || entry.length === 0) {
|
|
30
|
+
throw codeError('COMMANDS_INVALID', 'Each entry in msg.commands must be an array: [command, ...args]');
|
|
31
|
+
}
|
|
32
|
+
const tokens = toTokens([entry[0]], entry.slice(1));
|
|
33
|
+
checkCommand(tokens, { denylist, fromMsg });
|
|
34
|
+
return tokens;
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = function register(RED, palette) {
|
|
39
|
+
const { rk } = palette;
|
|
40
|
+
|
|
41
|
+
function RedisMultiNode(config) {
|
|
42
|
+
RED.nodes.createNode(this, config);
|
|
43
|
+
const node = this;
|
|
44
|
+
const k = rk.bind(node);
|
|
45
|
+
const parsed = k.configure(config, {
|
|
46
|
+
server: { type: 'str', required: true },
|
|
47
|
+
commands: { type: 'str', default: '' },
|
|
48
|
+
disableDenylist: { type: 'bool', default: false },
|
|
49
|
+
...INPUT_SCHEMA
|
|
50
|
+
});
|
|
51
|
+
const options = parsed.ok ? parsed.value : {};
|
|
52
|
+
const shared = startShared(RED, k, node, config.server);
|
|
53
|
+
let count = 0;
|
|
54
|
+
|
|
55
|
+
k.onInput(async (msg, send) => {
|
|
56
|
+
const fromMsg = msg.commands !== undefined;
|
|
57
|
+
const commands = parseCommands(fromMsg ? msg.commands : options.commands, !options.disableDenylist, fromMsg);
|
|
58
|
+
const results = await shared.client().multi(commands.map((tokens) => ['call', ...tokens])).exec();
|
|
59
|
+
if (!Array.isArray(results)) throw codeError('MULTI_ABORTED', 'Transaction was aborted');
|
|
60
|
+
const failed = results.filter(([error]) => error);
|
|
61
|
+
if (failed.length) {
|
|
62
|
+
throw codeError('MULTI_FAILED', `Transaction failed: ${failed.map(([error]) => error.message).join('; ')}`);
|
|
63
|
+
}
|
|
64
|
+
msg.payload = results.map(([, result]) => result);
|
|
65
|
+
setMeta(msg, { multi: { commands: commands.length } });
|
|
66
|
+
count += 1;
|
|
67
|
+
k.status('ok', `exec ${count}`);
|
|
68
|
+
primary(send, options.errorOutput, msg);
|
|
69
|
+
}, inputOptions(parsed, 1));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
RED.nodes.registerType('redkern-redis-multi', RedisMultiNode);
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
module.exports.parseCommands = parseCommands;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { codeError, setMeta } = require('../lib/format.js');
|
|
4
|
+
const { startShared } = require('../lib/node-helpers.js');
|
|
5
|
+
|
|
6
|
+
const TYPES = Object.freeze(['SCAN', 'HSCAN', 'SSCAN', 'ZSCAN']);
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Full cursor walk with a result limit and a deadline (RDS-CMD-5). In cluster
|
|
10
|
+
* mode SCAN visits every master; key scans are routed by the key's slot.
|
|
11
|
+
* @param {any} client
|
|
12
|
+
* @param {{ type: string, key?: string, match?: string, count: number, maxResults: number, timeoutMs: number, cluster: boolean, now?: () => number }} options
|
|
13
|
+
*/
|
|
14
|
+
async function scanAll(client, options) {
|
|
15
|
+
const now = options.now || (() => Date.now());
|
|
16
|
+
const deadline = now() + options.timeoutMs;
|
|
17
|
+
const method = options.type.toLowerCase();
|
|
18
|
+
const pairs = options.type === 'HSCAN' || options.type === 'ZSCAN';
|
|
19
|
+
const items = [];
|
|
20
|
+
let complete = true;
|
|
21
|
+
let timedOut = false;
|
|
22
|
+
const targets = options.type === 'SCAN' && options.cluster && typeof client.nodes === 'function'
|
|
23
|
+
? client.nodes('master')
|
|
24
|
+
: [client];
|
|
25
|
+
|
|
26
|
+
for (const target of targets) {
|
|
27
|
+
let cursor = '0';
|
|
28
|
+
do {
|
|
29
|
+
if (now() >= deadline) {
|
|
30
|
+
timedOut = true;
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
const args = options.type === 'SCAN' ? [cursor] : [options.key, cursor];
|
|
34
|
+
if (options.match) args.push('MATCH', options.match);
|
|
35
|
+
args.push('COUNT', options.count);
|
|
36
|
+
const [next, elements] = await target[method](...args);
|
|
37
|
+
cursor = String(next);
|
|
38
|
+
if (pairs) {
|
|
39
|
+
for (let index = 0; index + 1 < elements.length && items.length < options.maxResults; index += 2) {
|
|
40
|
+
items.push({ member: elements[index], value: elements[index + 1] });
|
|
41
|
+
}
|
|
42
|
+
} else {
|
|
43
|
+
items.push(...elements.slice(0, options.maxResults - items.length));
|
|
44
|
+
}
|
|
45
|
+
} while (cursor !== '0' && items.length < options.maxResults);
|
|
46
|
+
if (cursor !== '0') complete = false;
|
|
47
|
+
if (timedOut || items.length >= options.maxResults) {
|
|
48
|
+
if (targets.indexOf(target) < targets.length - 1) complete = false;
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return { items, complete: complete && !timedOut, timedOut };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
module.exports = function register(RED, palette) {
|
|
56
|
+
const { rk } = palette;
|
|
57
|
+
|
|
58
|
+
function RedisScanNode(config) {
|
|
59
|
+
RED.nodes.createNode(this, config);
|
|
60
|
+
const node = this;
|
|
61
|
+
const k = rk.bind(node);
|
|
62
|
+
const parsed = k.configure(config, {
|
|
63
|
+
server: { type: 'str', required: true },
|
|
64
|
+
scanType: { type: 'enum', values: [...TYPES], default: 'SCAN' },
|
|
65
|
+
match: { type: 'str', default: '' },
|
|
66
|
+
count: { type: 'int', min: 1, max: 100000, default: 100 },
|
|
67
|
+
maxResults: { type: 'int', min: 1, max: 1000000, default: 10000 },
|
|
68
|
+
timeoutMs: { type: 'int', min: 100, max: 600000, default: 10000 },
|
|
69
|
+
legacyMsgFields: { type: 'bool', default: false }
|
|
70
|
+
});
|
|
71
|
+
const options = parsed.ok ? parsed.value : {};
|
|
72
|
+
const shared = startShared(RED, k, node, config.server);
|
|
73
|
+
|
|
74
|
+
k.onInput(async (msg, send) => {
|
|
75
|
+
const type = String(msg.scanType || options.scanType).toUpperCase();
|
|
76
|
+
if (!TYPES.includes(type)) throw codeError('SCAN_TYPE_INVALID', `Unsupported scanType: ${type}`);
|
|
77
|
+
const key = type === 'SCAN' ? undefined : msg.key;
|
|
78
|
+
if (type !== 'SCAN' && (typeof key !== 'string' || key === '')) throw codeError('SCAN_KEY_REQUIRED', `${type} requires msg.key`);
|
|
79
|
+
const match = typeof msg.match === 'string' && msg.match !== '' ? msg.match : options.match;
|
|
80
|
+
const count = positive(msg.count, options.count, 100000);
|
|
81
|
+
const maxResults = positive(msg.maxResults, options.maxResults, 1000000);
|
|
82
|
+
const result = await scanAll(shared.client(), {
|
|
83
|
+
type, key, match, count, maxResults, timeoutMs: options.timeoutMs, cluster: shared.config().mode === 'cluster'
|
|
84
|
+
});
|
|
85
|
+
msg.payload = result.items;
|
|
86
|
+
setMeta(msg, { scan: { type, complete: result.complete, truncated: !result.complete, timedOut: result.timedOut, count: result.items.length } });
|
|
87
|
+
if (options.legacyMsgFields) {
|
|
88
|
+
msg.scanComplete = result.complete;
|
|
89
|
+
msg.scanTruncated = !result.complete;
|
|
90
|
+
}
|
|
91
|
+
if (result.complete) k.status('ok', `found ${result.items.length}`);
|
|
92
|
+
else k.status('warn', `${result.timedOut ? 'timeout' : 'limit'} ${result.items.length}`);
|
|
93
|
+
send(msg);
|
|
94
|
+
}, { concurrency: 4, maxQueue: 100, startQueueTimeoutMs: 30000 });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function positive(value, fallback, max) {
|
|
98
|
+
const number = Number.parseInt(value, 10);
|
|
99
|
+
return Number.isSafeInteger(number) && number >= 1 ? Math.min(number, max) : fallback;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
RED.nodes.registerType('redkern-redis-scan', RedisScanNode);
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
module.exports.scanAll = scanAll;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { codeError, setMeta } = require('../lib/format.js');
|
|
4
|
+
const { startShared } = require('../lib/node-helpers.js');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Reads the entry IDs and their stream/group from msg (RDS-STR-12): first
|
|
8
|
+
* msg.redkern.redis, then the legacy fields, then the node configuration.
|
|
9
|
+
*/
|
|
10
|
+
function resolveTarget(msg, options) {
|
|
11
|
+
const meta = msg?.redkern?.redis && typeof msg.redkern.redis === 'object' ? msg.redkern.redis : {};
|
|
12
|
+
const rawIds = meta.id !== undefined ? meta.id : msg.streamId;
|
|
13
|
+
const ids = (Array.isArray(rawIds) ? rawIds : [rawIds]).filter((id) => typeof id === 'string' && id !== '');
|
|
14
|
+
if (ids.length === 0) throw codeError('STREAM_ID_REQUIRED', 'msg.redkern.redis.id (or legacy msg.streamId) is required');
|
|
15
|
+
const stream = meta.stream || msg._streamKey || options.streamKey;
|
|
16
|
+
const group = meta.group || msg._streamGroup || options.group;
|
|
17
|
+
if (!stream || !group) throw codeError('STREAM_GROUP_REQUIRED', 'Stream key and group are required');
|
|
18
|
+
return { ids, stream: String(stream), group: String(group) };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
module.exports = function register(RED, palette) {
|
|
22
|
+
const { rk, registry, metrics } = palette;
|
|
23
|
+
|
|
24
|
+
function RedisStreamAckNode(config) {
|
|
25
|
+
RED.nodes.createNode(this, config);
|
|
26
|
+
const node = this;
|
|
27
|
+
const k = rk.bind(node);
|
|
28
|
+
const parsed = k.configure(config, {
|
|
29
|
+
server: { type: 'str', required: true },
|
|
30
|
+
streamKey: { type: 'str', default: '' },
|
|
31
|
+
group: { type: 'str', default: '' },
|
|
32
|
+
deleteAfterAck: { type: 'bool', default: false },
|
|
33
|
+
legacyMsgFields: { type: 'bool', default: false }
|
|
34
|
+
});
|
|
35
|
+
const options = parsed.ok ? parsed.value : {};
|
|
36
|
+
const shared = startShared(RED, k, node, config.server);
|
|
37
|
+
let total = 0;
|
|
38
|
+
|
|
39
|
+
k.onInput(async (msg, send) => {
|
|
40
|
+
const { ids, stream, group } = resolveTarget(msg, options);
|
|
41
|
+
// One XACK for the whole batch.
|
|
42
|
+
const acked = Number(await shared.client().xack(stream, group, ...ids)) || 0;
|
|
43
|
+
registry.remove(stream, group, ids);
|
|
44
|
+
if (acked) metrics.inc('redkern_redis_acked_total', { stream, group }, acked);
|
|
45
|
+
const deleteAfterAck = msg.deleteAfterAck === undefined ? options.deleteAfterAck : msg.deleteAfterAck === true;
|
|
46
|
+
let deleted;
|
|
47
|
+
if (deleteAfterAck && acked > 0) {
|
|
48
|
+
// XDEL after XACK: a failed delete leaves an auditable entry, never an
|
|
49
|
+
// unacknowledged loss.
|
|
50
|
+
deleted = Number(await shared.client().xdel(stream, ...ids)) || 0;
|
|
51
|
+
}
|
|
52
|
+
setMeta(msg, { ack: deleted === undefined ? { acked } : { acked, deleted } });
|
|
53
|
+
if (options.legacyMsgFields) {
|
|
54
|
+
msg.acked = acked;
|
|
55
|
+
if (deleted !== undefined) msg.deleted = deleted;
|
|
56
|
+
}
|
|
57
|
+
total += acked;
|
|
58
|
+
k.status('ok', `acked ${total}`);
|
|
59
|
+
if (Number(config.outputs) > 0) send(msg);
|
|
60
|
+
}, { concurrency: 64, maxQueue: 10000, startQueueTimeoutMs: 30000 });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
RED.nodes.registerType('redkern-redis-stream-ack', RedisStreamAckNode);
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
module.exports.resolveTarget = resolveTarget;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { codeError, setMeta, decodeFields } = require('../lib/format.js');
|
|
4
|
+
const { startShared } = require('../lib/node-helpers.js');
|
|
5
|
+
|
|
6
|
+
module.exports = function register(RED, palette) {
|
|
7
|
+
const { rk, kit } = palette;
|
|
8
|
+
|
|
9
|
+
function RedisStreamClaimNode(config) {
|
|
10
|
+
RED.nodes.createNode(this, config);
|
|
11
|
+
const node = this;
|
|
12
|
+
const k = rk.bind(node);
|
|
13
|
+
const parsed = k.configure(config, {
|
|
14
|
+
server: { type: 'str', required: true },
|
|
15
|
+
streamKey: { type: 'str', default: '' },
|
|
16
|
+
group: { type: 'str', default: '' },
|
|
17
|
+
consumer: { type: 'str', default: '' },
|
|
18
|
+
minIdleMs: { type: 'int', min: 0, max: 86400000, default: 60000 },
|
|
19
|
+
count: { type: 'int', min: 1, max: 100000, default: 100 },
|
|
20
|
+
maxMessages: { type: 'int', min: 1, max: 1000000, default: 1000 },
|
|
21
|
+
legacyMsgFields: { type: 'bool', default: false }
|
|
22
|
+
});
|
|
23
|
+
const options = parsed.ok ? parsed.value : {};
|
|
24
|
+
const shared = startShared(RED, k, node, config.server);
|
|
25
|
+
|
|
26
|
+
k.onInput(async (msg, send) => {
|
|
27
|
+
const meta = msg?.redkern?.redis || {};
|
|
28
|
+
const stream = (typeof msg.stream === 'string' && msg.stream) || meta.stream || options.streamKey;
|
|
29
|
+
const group = (typeof msg.group === 'string' && msg.group) || meta.group || options.group;
|
|
30
|
+
const consumer = (typeof msg.consumer === 'string' && msg.consumer) || options.consumer || `${kit.instanceId()}-${node.id}`;
|
|
31
|
+
const minIdleMs = Number.isSafeInteger(msg.minIdleMs) && msg.minIdleMs >= 0 ? msg.minIdleMs : options.minIdleMs;
|
|
32
|
+
if (!stream || !group) throw codeError('STREAM_GROUP_REQUIRED', 'Stream key and group are required');
|
|
33
|
+
const maxMessages = Math.max(options.count, options.maxMessages);
|
|
34
|
+
const claimed = [];
|
|
35
|
+
let cursor = '0-0';
|
|
36
|
+
do {
|
|
37
|
+
const remaining = maxMessages - claimed.length;
|
|
38
|
+
const [next, entries] = await shared.client().xautoclaim(stream, group, consumer, minIdleMs, cursor, 'COUNT', Math.min(options.count, remaining));
|
|
39
|
+
cursor = String(next);
|
|
40
|
+
for (const [id, flat] of entries || []) {
|
|
41
|
+
if (!Array.isArray(flat)) continue;
|
|
42
|
+
const item = { id, payload: decodeFields(flat) };
|
|
43
|
+
if (options.legacyMsgFields) item.streamId = id;
|
|
44
|
+
claimed.push(item);
|
|
45
|
+
}
|
|
46
|
+
} while (cursor !== '0-0' && claimed.length < maxMessages);
|
|
47
|
+
msg.payload = claimed;
|
|
48
|
+
setMeta(msg, { claim: { stream, group, consumer, complete: cursor === '0-0', count: claimed.length } });
|
|
49
|
+
if (options.legacyMsgFields) {
|
|
50
|
+
msg.stream = stream;
|
|
51
|
+
msg.group = group;
|
|
52
|
+
msg.consumer = consumer;
|
|
53
|
+
}
|
|
54
|
+
k.status(cursor === '0-0' ? 'ok' : 'warn', `claimed ${claimed.length}${cursor === '0-0' ? '' : '+'}`);
|
|
55
|
+
send(msg);
|
|
56
|
+
}, { concurrency: 1, maxQueue: 100, startQueueTimeoutMs: 30000 });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
RED.nodes.registerType('redkern-redis-stream-claim', RedisStreamClaimNode);
|
|
60
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { setMeta } = require('../lib/format.js');
|
|
4
|
+
|
|
5
|
+
module.exports = function register(RED, palette) {
|
|
6
|
+
const { rk } = palette;
|
|
7
|
+
|
|
8
|
+
function RedisStreamControlNode(config) {
|
|
9
|
+
RED.nodes.createNode(this, config);
|
|
10
|
+
const node = this;
|
|
11
|
+
const k = rk.bind(node);
|
|
12
|
+
k.configure(config, {
|
|
13
|
+
action: { type: 'enum', values: ['', 'pause', 'resume', 'drain', 'status'], default: '' }
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
k.onInput(async (msg, send) => {
|
|
17
|
+
const body = msg.payload && typeof msg.payload === 'object' && !Array.isArray(msg.payload) ? msg.payload : {};
|
|
18
|
+
const pick = (field) => (msg[field] !== undefined ? msg[field] : body[field]);
|
|
19
|
+
const result = await palette.executeControl({
|
|
20
|
+
action: pick('action') || config.action,
|
|
21
|
+
stream: pick('stream'),
|
|
22
|
+
group: pick('group'),
|
|
23
|
+
nodeId: pick('nodeId'),
|
|
24
|
+
drainTimeoutMs: pick('drainTimeoutMs')
|
|
25
|
+
});
|
|
26
|
+
msg.payload = result;
|
|
27
|
+
setMeta(msg, { control: { action: result.action, consumers: result.consumers.length } });
|
|
28
|
+
const state = result.action === 'drain' && !result.drained ? 'warn' : result.action === 'pause' ? 'paused' : 'ok';
|
|
29
|
+
k.status(state, `${result.action} ${result.consumers.length}`);
|
|
30
|
+
send(msg);
|
|
31
|
+
}, { concurrency: 4, maxQueue: 100 });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
RED.nodes.registerType('redkern-redis-stream-control', RedisStreamControlNode);
|
|
35
|
+
};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { codeError, setMeta, flatToObject, compact } = require('../lib/format.js');
|
|
4
|
+
const { startShared } = require('../lib/node-helpers.js');
|
|
5
|
+
|
|
6
|
+
const DELETE_IF_EMPTY = `
|
|
7
|
+
if #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[2]) > 0 then return -1 end
|
|
8
|
+
return redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[2])`;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Removes inactive consumers whose PEL is empty (RDS-STR-13). A consumer with
|
|
12
|
+
* pending entries is never deleted: XGROUP DELCONSUMER would drop its PEL.
|
|
13
|
+
*/
|
|
14
|
+
async function collectConsumers(client, stream, group, minIdleMs) {
|
|
15
|
+
const raw = await client.call('XINFO', 'CONSUMERS', stream, group);
|
|
16
|
+
const removed = [];
|
|
17
|
+
const kept = [];
|
|
18
|
+
for (const flat of raw || []) {
|
|
19
|
+
const info = flatToObject(flat);
|
|
20
|
+
const name = String(info.name);
|
|
21
|
+
const pending = Number(info.pending) || 0;
|
|
22
|
+
// Redis 7.2 reports "inactive" (time since the last successful read);
|
|
23
|
+
// older versions only have "idle".
|
|
24
|
+
const inactive = info.inactive !== undefined && Number(info.inactive) >= 0 ? Number(info.inactive) : Number(info.idle) || 0;
|
|
25
|
+
if (pending === 0 && inactive >= minIdleMs) {
|
|
26
|
+
// Check the PEL and delete in one script: DELCONSUMER drops the PEL of
|
|
27
|
+
// a consumer that read entries after XINFO was taken.
|
|
28
|
+
const deleted = Number(await client.eval(DELETE_IF_EMPTY, 1, stream, group, name));
|
|
29
|
+
if (deleted === 0) removed.push({ name, idleMs: inactive });
|
|
30
|
+
else kept.push({ name, pending: Math.max(0, deleted), idleMs: inactive, raced: true });
|
|
31
|
+
} else {
|
|
32
|
+
kept.push({ name, pending, idleMs: inactive });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return { removed, kept };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = function register(RED, palette) {
|
|
39
|
+
const { rk } = palette;
|
|
40
|
+
|
|
41
|
+
function RedisStreamGcNode(config) {
|
|
42
|
+
RED.nodes.createNode(this, config);
|
|
43
|
+
const node = this;
|
|
44
|
+
const k = rk.bind(node);
|
|
45
|
+
const parsed = k.configure(config, {
|
|
46
|
+
server: { type: 'str', required: true },
|
|
47
|
+
streamKey: { type: 'str', default: '' },
|
|
48
|
+
group: { type: 'str', default: '' },
|
|
49
|
+
minIdleMs: { type: 'int', min: 0, max: 31536000000, default: 600000 },
|
|
50
|
+
legacyMsgFields: { type: 'bool', default: false }
|
|
51
|
+
});
|
|
52
|
+
const options = parsed.ok ? parsed.value : {};
|
|
53
|
+
const shared = startShared(RED, k, node, config.server);
|
|
54
|
+
let total = 0;
|
|
55
|
+
|
|
56
|
+
k.onInput(async (msg, send) => {
|
|
57
|
+
const stream = (typeof msg.stream === 'string' && msg.stream) || options.streamKey;
|
|
58
|
+
const group = (typeof msg.group === 'string' && msg.group) || options.group;
|
|
59
|
+
const minIdleMs = Number.isSafeInteger(msg.minIdleMs) && msg.minIdleMs >= 0 ? msg.minIdleMs : options.minIdleMs;
|
|
60
|
+
if (!stream || !group) throw codeError('STREAM_GROUP_REQUIRED', 'Stream key and group are required');
|
|
61
|
+
const result = await collectConsumers(shared.client(), stream, group, minIdleMs);
|
|
62
|
+
msg.payload = result;
|
|
63
|
+
setMeta(msg, { gc: { stream, group, removed: result.removed.length, kept: result.kept.length } });
|
|
64
|
+
if (options.legacyMsgFields) {
|
|
65
|
+
msg.stream = stream;
|
|
66
|
+
msg.group = group;
|
|
67
|
+
}
|
|
68
|
+
total += result.removed.length;
|
|
69
|
+
k.status('ok', `removed ${compact(total)}`);
|
|
70
|
+
send(msg);
|
|
71
|
+
}, { concurrency: 1, maxQueue: 100, startQueueTimeoutMs: 30000 });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
RED.nodes.registerType('redkern-redis-stream-gc', RedisStreamGcNode);
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
module.exports.collectConsumers = collectConsumers;
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { StreamConsumer } = require('../lib/stream-consumer.js');
|
|
4
|
+
const { slotIssue } = require('../lib/dlq.js');
|
|
5
|
+
const { replaceMeta, compact } = require('../lib/format.js');
|
|
6
|
+
const { requireConfig, classify } = require('../lib/node-helpers.js');
|
|
7
|
+
|
|
8
|
+
const SCHEMA = Object.freeze({
|
|
9
|
+
server: { type: 'str', required: true },
|
|
10
|
+
streamKey: { type: 'str', required: true },
|
|
11
|
+
group: { type: 'str', required: true },
|
|
12
|
+
consumer: { type: 'str', default: '' },
|
|
13
|
+
ackMode: { type: 'enum', values: ['manual', 'auto'], default: 'manual' },
|
|
14
|
+
startId: { type: 'str', default: '$' },
|
|
15
|
+
maxPending: { type: 'int', min: 1, max: 1000000, default: 1000 },
|
|
16
|
+
backpressureScope: { type: 'enum', values: ['consumer', 'group'], default: 'consumer' },
|
|
17
|
+
maxDeliveries: { type: 'int', min: 0, max: 1000, default: 5 },
|
|
18
|
+
deadLetterStream: { type: 'str', default: '' },
|
|
19
|
+
autoClaim: { type: 'bool', default: true },
|
|
20
|
+
reclaimIdleMs: { type: 'int', min: 1000, max: 86400000, default: 60000 },
|
|
21
|
+
reclaimIntervalMs: { type: 'int', min: 1000, max: 86400000, default: 30000 },
|
|
22
|
+
reclaimCount: { type: 'int', min: 1, max: 100000, default: 100 },
|
|
23
|
+
drainTimeoutMs: { type: 'int', min: 0, max: 1800000, default: 30000 },
|
|
24
|
+
startPaused: { type: 'bool', default: false },
|
|
25
|
+
count: { type: 'int', min: 1, max: 100000, default: 100 },
|
|
26
|
+
blockMs: { type: 'int', min: 1, max: 600000, default: 5000 },
|
|
27
|
+
readIntervalMs: { type: 'int', min: 0, max: 3600000, default: 0 },
|
|
28
|
+
rateLimitPerSecond: { type: 'float', min: 0, max: 1000000, default: 0 },
|
|
29
|
+
batchWindowMs: { type: 'int', min: 0, max: 3600000, default: 0 },
|
|
30
|
+
batchIntervalMs: { type: 'int', min: 0, max: 3600000, default: 0 },
|
|
31
|
+
capacityCheckIntervalMs: { type: 'int', min: 50, max: 600000, default: 250 },
|
|
32
|
+
capacityPollMs: { type: 'int', min: 50, max: 600000, default: 500 },
|
|
33
|
+
initialBackoffMs: { type: 'int', min: 50, max: 600000, default: 500 },
|
|
34
|
+
maxBackoffMs: { type: 'int', min: 50, max: 3600000, default: 30000 },
|
|
35
|
+
backoffMultiplier: { type: 'float', min: 1, max: 10, default: 2 },
|
|
36
|
+
legacyMsgFields: { type: 'bool', default: false }
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
module.exports = function register(RED, palette) {
|
|
40
|
+
const { rk, kit, registry, metrics } = palette;
|
|
41
|
+
|
|
42
|
+
function RedisStreamInNode(config) {
|
|
43
|
+
RED.nodes.createNode(this, config);
|
|
44
|
+
const node = this;
|
|
45
|
+
const k = rk.bind(node);
|
|
46
|
+
const parsed = k.configure(config, SCHEMA);
|
|
47
|
+
const options = parsed.ok ? parsed.value : {};
|
|
48
|
+
const consumerName = options.consumer || `${kit.instanceId()}-${node.id}`;
|
|
49
|
+
const labels = { stream: options.streamKey, group: options.group };
|
|
50
|
+
let consumer;
|
|
51
|
+
let unregister;
|
|
52
|
+
let lastDelivered = 0;
|
|
53
|
+
let lastRateAt = Date.now();
|
|
54
|
+
let rate = 0;
|
|
55
|
+
|
|
56
|
+
function updateStatus() {
|
|
57
|
+
if (!consumer) return;
|
|
58
|
+
const state = consumer.snapshot();
|
|
59
|
+
metrics.set('redkern_redis_consumer_paused', { ...labels, node: node.id }, state.paused ? 1 : 0);
|
|
60
|
+
metrics.set('redkern_redis_consumer_inflight', { ...labels, node: node.id }, state.inflight);
|
|
61
|
+
if (state.lastError) k.status('error', `retry ${String(state.lastError).toLowerCase()}`);
|
|
62
|
+
else if (state.paused) k.status('paused', `paused ${compact(state.inflight + state.held)} pending`);
|
|
63
|
+
else if (state.backpressure) k.status('warn', `full ${compact(state.inflight)}/${compact(state.maxPending)}`);
|
|
64
|
+
else if (state.recovering) k.status('starting', 'recovering');
|
|
65
|
+
else if (rate > 0) k.status('ok', `consuming ${compact(rate)}/s`);
|
|
66
|
+
else k.status('ok', `reading ${compact(state.inflight)}/${compact(state.maxPending)}`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function emit({ entries, batched }) {
|
|
70
|
+
const ids = entries.map((entry) => entry.id);
|
|
71
|
+
const msg = {
|
|
72
|
+
_msgid: RED.util.generateId(),
|
|
73
|
+
payload: batched ? entries.map((entry) => entry.payload) : entries[0].payload
|
|
74
|
+
};
|
|
75
|
+
replaceMeta(msg, {
|
|
76
|
+
stream: options.streamKey,
|
|
77
|
+
group: options.group,
|
|
78
|
+
id: batched ? ids : ids[0],
|
|
79
|
+
consumer: consumerName,
|
|
80
|
+
deliveries: batched ? entries.map((entry) => entry.deliveries) : entries[0].deliveries
|
|
81
|
+
});
|
|
82
|
+
if (options.legacyMsgFields) {
|
|
83
|
+
msg.streamId = batched ? ids : ids[0];
|
|
84
|
+
msg.stream = options.streamKey;
|
|
85
|
+
msg.group = options.group;
|
|
86
|
+
msg._streamKey = options.streamKey;
|
|
87
|
+
msg._streamGroup = options.group;
|
|
88
|
+
msg.consumer = consumerName;
|
|
89
|
+
}
|
|
90
|
+
node.send(msg);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
k.onStart(async (attempt) => {
|
|
94
|
+
const api = requireConfig(RED, config.server);
|
|
95
|
+
const deadLetterStream = options.deadLetterStream || `${options.streamKey}:dlq`;
|
|
96
|
+
if (api.mode === 'cluster' && options.maxDeliveries > 0) {
|
|
97
|
+
const issue = slotIssue(options.streamKey, deadLetterStream);
|
|
98
|
+
if (issue) throw new kit.ConfigError([issue]);
|
|
99
|
+
}
|
|
100
|
+
if (!unregister) {
|
|
101
|
+
unregister = api.register(node.id);
|
|
102
|
+
k.onClose(() => unregister());
|
|
103
|
+
}
|
|
104
|
+
const shared = await api.shared();
|
|
105
|
+
const blocking = api.createBlocking({ blockMs: options.blockMs, commandTimeout: options.blockMs + 10000 });
|
|
106
|
+
attempt.onClose(blocking.release, { force: blocking.release });
|
|
107
|
+
await blocking.connect();
|
|
108
|
+
consumer = new StreamConsumer({
|
|
109
|
+
shared,
|
|
110
|
+
blocking: blocking.client,
|
|
111
|
+
stream: options.streamKey,
|
|
112
|
+
group: options.group,
|
|
113
|
+
consumer: consumerName,
|
|
114
|
+
registry,
|
|
115
|
+
metrics,
|
|
116
|
+
log: k.log,
|
|
117
|
+
emit,
|
|
118
|
+
onState: updateStatus,
|
|
119
|
+
clock: { now: Date.now, sleep: kit.sleep },
|
|
120
|
+
options: { ...options, deadLetterStream }
|
|
121
|
+
});
|
|
122
|
+
// RDS-STR-1: the group exists (MKSTREAM) before the node reports ready.
|
|
123
|
+
await consumer.ensureGroup();
|
|
124
|
+
}, { classify, startAlertMs: 60000 }).then(() => {
|
|
125
|
+
if (!consumer || k.signal.aborted) return;
|
|
126
|
+
const entry = { nodeId: node.id, consumer, drainTimeoutMs: options.drainTimeoutMs };
|
|
127
|
+
k.onClose(palette.addConsumer(entry));
|
|
128
|
+
if (rk.enabled && k.internalServer) {
|
|
129
|
+
const lease = k.internalServer.acquire(node.id, entry);
|
|
130
|
+
k.track(lease.ready, { label: 'internal server' });
|
|
131
|
+
}
|
|
132
|
+
const timer = setInterval(() => {
|
|
133
|
+
const now = Date.now();
|
|
134
|
+
rate = (consumer.delivered - lastDelivered) * 1000 / Math.max(1, now - lastRateAt);
|
|
135
|
+
lastDelivered = consumer.delivered;
|
|
136
|
+
lastRateAt = now;
|
|
137
|
+
updateStatus();
|
|
138
|
+
}, 1000);
|
|
139
|
+
timer.unref?.();
|
|
140
|
+
k.onClose(() => clearInterval(timer));
|
|
141
|
+
updateStatus();
|
|
142
|
+
k.track(consumer.run(k.signal), { label: 'stream-in loop' });
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
k.onClose(({ removed }) => {
|
|
146
|
+
metrics.delete('redkern_redis_consumer_paused', { ...labels, node: node.id });
|
|
147
|
+
metrics.delete('redkern_redis_consumer_inflight', { ...labels, node: node.id });
|
|
148
|
+
// On a redeploy the registry survives so the new instance does not
|
|
149
|
+
// resend entries the flow is still processing; a removed node clears it.
|
|
150
|
+
if (removed && parsed.ok) registry.clearConsumer(options.streamKey, options.group, consumerName);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
RED.nodes.registerType('redkern-redis-stream-in', RedisStreamInNode);
|
|
155
|
+
};
|