@rosepetal/node-red-contrib-image-tools 1.1.3 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +1 -13
  2. package/node-red-contrib-image-tools/lib/node-utils.js +218 -17
  3. package/node-red-contrib-image-tools/nodes/blend/add-bbs.js +64 -9
  4. package/node-red-contrib-image-tools/nodes/blend/add-mask.js +81 -9
  5. package/node-red-contrib-image-tools/nodes/blend/add-masks.js +64 -8
  6. package/node-red-contrib-image-tools/nodes/blend/blend.js +64 -10
  7. package/node-red-contrib-image-tools/nodes/io/folder-in.js +12 -1
  8. package/node-red-contrib-image-tools/nodes/io/image-in.js +10 -2
  9. package/node-red-contrib-image-tools/nodes/io/image-out.js +25 -3
  10. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.js +52 -26
  11. package/node-red-contrib-image-tools/nodes/mix/concat.js +46 -9
  12. package/node-red-contrib-image-tools/nodes/mix/mosaic.js +52 -15
  13. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +53 -5
  14. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +54 -7
  15. package/node-red-contrib-image-tools/nodes/transform/crop.js +38 -17
  16. package/node-red-contrib-image-tools/nodes/transform/draw.js +28 -7
  17. package/node-red-contrib-image-tools/nodes/transform/filter.js +34 -15
  18. package/node-red-contrib-image-tools/nodes/transform/padding.js +30 -9
  19. package/node-red-contrib-image-tools/nodes/transform/resize.js +58 -33
  20. package/node-red-contrib-image-tools/nodes/transform/rotate.js +40 -20
  21. package/node-red-contrib-image-tools/package.json +1 -8
  22. package/package.json +1 -1
  23. package/rosepetal-image-engine/binding.gyp +5 -23
  24. package/rosepetal-image-engine/src/add-mask.cpp +2 -2
  25. package/rosepetal-image-engine/src/add-masks.cpp +2 -2
  26. package/rosepetal-image-engine/src/advanced-mosaic.cpp +3 -4
  27. package/rosepetal-image-engine/src/blend.cpp +2 -2
  28. package/rosepetal-image-engine/src/concat.cpp +2 -2
  29. package/rosepetal-image-engine/src/crop.cpp +3 -3
  30. package/rosepetal-image-engine/src/draw.cpp +1 -1
  31. package/rosepetal-image-engine/src/filter.cpp +3 -3
  32. package/rosepetal-image-engine/src/mosaic.cpp +4 -5
  33. package/rosepetal-image-engine/src/padding.cpp +4 -3
  34. package/rosepetal-image-engine/src/resize.cpp +101 -23
  35. package/rosepetal-image-engine/src/rotate.cpp +3 -6
  36. package/rosepetal-image-engine/src/utils.h +46 -8
  37. package/docs/nodes/io/array-in.md +0 -119
  38. package/docs/nodes/io/array-out.md +0 -150
  39. package/docs/nodes/io/array-select.md +0 -157
  40. package/docs/nodes/io/queue.md +0 -57
  41. package/docs/nodes/io/save-file.md +0 -30
  42. package/docs/nodes/util/block-detect.md +0 -46
  43. package/node-red-contrib-image-tools/nodes/io/array-in.html +0 -110
  44. package/node-red-contrib-image-tools/nodes/io/array-in.js +0 -113
  45. package/node-red-contrib-image-tools/nodes/io/array-out.html +0 -125
  46. package/node-red-contrib-image-tools/nodes/io/array-out.js +0 -213
  47. package/node-red-contrib-image-tools/nodes/io/array-select.html +0 -156
  48. package/node-red-contrib-image-tools/nodes/io/array-select.js +0 -187
  49. package/node-red-contrib-image-tools/nodes/io/queue.html +0 -119
  50. package/node-red-contrib-image-tools/nodes/io/queue.js +0 -191
  51. package/node-red-contrib-image-tools/nodes/io/save-file.html +0 -243
  52. package/node-red-contrib-image-tools/nodes/io/save-file.js +0 -440
  53. package/node-red-contrib-image-tools/nodes/util/block-detect.html +0 -85
  54. package/node-red-contrib-image-tools/nodes/util/block-detect.js +0 -136
  55. package/node-red-contrib-image-tools/nodes/util/clean-debug.html +0 -201
  56. package/node-red-contrib-image-tools/nodes/util/clean-debug.js +0 -393
@@ -1,440 +0,0 @@
1
- /**
2
- * @file Generic filesystem sink that can write JSON, images, text, or binary data.
3
- * Designed to accept raw image objects, encoded buffers, or plain JS values.
4
- */
5
- const fs = require('fs').promises;
6
- const path = require('path');
7
- const sharp = require('sharp');
8
- const JSON_WARN_BYTES = 5 * 1024 * 1024; // warn when JSON output is larger than 5MB
9
-
10
- module.exports = function (RED) {
11
- const NodeUtils = require('../../lib/node-utils.js')(RED);
12
-
13
- function SaveFileNode(config) {
14
- RED.nodes.createNode(this, config);
15
- const node = this;
16
- const diskWarnState = { logged: false };
17
-
18
- node.on('input', async (msg, send, done) => {
19
- const started = Date.now();
20
- node.status({ fill: 'blue', shape: 'dot', text: 'saving...' });
21
-
22
- try {
23
- const evaluateProperty = (value, type, fallback = 'str') =>
24
- new Promise((resolve, reject) => {
25
- const actualType = type || fallback;
26
- try {
27
- RED.util.evaluateNodeProperty(value, actualType, node, msg, (err, res) => {
28
- if (err) reject(err);
29
- else resolve(res);
30
- });
31
- } catch (err) {
32
- reject(err);
33
- }
34
- });
35
-
36
- // Resolve paths and inputs
37
- const folderPathType = config.folderPathType || 'str';
38
- const folderPathValue = await evaluateProperty(config.folderPath, folderPathType);
39
- const folderPath = String(folderPathValue ?? '').trim();
40
- if (!folderPath) {
41
- throw new Error('Folder path is not configured or resolved.');
42
- }
43
- await fs.mkdir(folderPath, { recursive: true });
44
-
45
- const inputPath = config.inputPath || 'payload';
46
- const inputPathType = config.inputPathType || 'msg';
47
- let incoming;
48
- if (inputPathType === 'msg') {
49
- incoming = RED.util.getMessageProperty(msg, inputPath);
50
- } else if (inputPathType === 'flow') {
51
- incoming = node.context().flow.get(inputPath);
52
- } else if (inputPathType === 'global') {
53
- incoming = node.context().global.get(inputPath);
54
- }
55
- if (incoming === undefined) {
56
- throw new Error('No data found at configured input path.');
57
- }
58
-
59
- // Resolve file name
60
- const filenameType = config.filenameType || 'str';
61
- const filenameValue = await evaluateProperty(config.filename, filenameType);
62
- const filenameRaw = filenameValue !== undefined && filenameValue !== null
63
- ? String(filenameValue).trim()
64
- : '';
65
- if (/[\\/]/.test(filenameRaw)) {
66
- throw new Error('Filename must not contain path separators.');
67
- }
68
- const parsedName = path.parse(filenameRaw);
69
- let baseName = parsedName.name || '';
70
- let extFromName = parsedName.ext ? parsedName.ext.replace(/^\./, '') : '';
71
-
72
- // Determine file type and format
73
- const configType = String(config.fileType || 'auto').toLowerCase();
74
- let imageFormat = String(config.imageFormat || 'jpg').toLowerCase();
75
- const extInfo = mapExtension(extFromName);
76
-
77
- let fileType = configType;
78
- if (fileType === 'auto' && extInfo?.type) {
79
- fileType = extInfo.type;
80
- if (extInfo.format) {
81
- imageFormat = extInfo.format;
82
- }
83
- }
84
-
85
- const inferred = fileType === 'auto'
86
- ? await inferFileType(incoming, extInfo)
87
- : { type: fileType, format: imageFormat };
88
-
89
- fileType = inferred.type;
90
- if (fileType === 'image' && inferred.format) {
91
- imageFormat = inferred.format;
92
- }
93
- if (fileType === 'image' && extInfo?.format) {
94
- imageFormat = extInfo.format;
95
- }
96
-
97
- if (!['image', 'json', 'text', 'binary'].includes(fileType)) {
98
- throw new Error(`Unsupported file type: ${fileType}`);
99
- }
100
-
101
- // Finalize extension and name
102
- let extension = extFromName || defaultExtension(fileType, imageFormat);
103
- if (!extension) {
104
- throw new Error('Unable to determine file extension.');
105
- }
106
- if (!baseName) {
107
- baseName = defaultBaseName(fileType);
108
- }
109
- let filename = `${baseName}.${extension}`;
110
- const originalFilename = filename;
111
- let filePath = path.join(folderPath, filename);
112
-
113
- const overwriteEnabled = String(config.overwriteProtection) !== 'false';
114
- if (overwriteEnabled) {
115
- let counter = 2;
116
- while (await fileExists(filePath)) {
117
- filename = `${baseName}_${counter}.${extension}`;
118
- filePath = path.join(folderPath, filename);
119
- counter += 1;
120
- if (counter > 1000) {
121
- throw new Error('Too many file variations exist in target folder.');
122
- }
123
- }
124
- }
125
-
126
- // Check disk space (skip if 90%+ used)
127
- const diskInfo = await getDiskUsageInfo(folderPath, node, diskWarnState);
128
- if (diskInfo && diskInfo.usedRatio >= 0.9) {
129
- const usedPercent = (diskInfo.usedRatio * 100).toFixed(1);
130
- node.warn(`Storage at "${folderPath}" is ${usedPercent}% full. Skipping save to avoid exhausting disk space.`);
131
- node.status({ fill: 'yellow', shape: 'ring', text: `disk ${usedPercent}% full` });
132
- done && done();
133
- return;
134
- }
135
-
136
- // Prepare data to write
137
- const quality = parseInt(config.imageQuality, 10) || 90;
138
- const pngOptimize = config.pngOptimize === true || config.pngOptimize === 'true';
139
- const jsonIndent = Number.isInteger(parseInt(config.jsonIndent, 10))
140
- ? parseInt(config.jsonIndent, 10)
141
- : 2;
142
-
143
- let payloadToWrite;
144
- let isText = false;
145
-
146
- if (fileType === 'image') {
147
- payloadToWrite = await toImageBuffer(incoming, imageFormat, quality, pngOptimize, NodeUtils, node);
148
- } else if (fileType === 'json') {
149
- if (typeof incoming === 'string') {
150
- try {
151
- // Keep valid JSON strings as-is
152
- JSON.parse(incoming);
153
- payloadToWrite = incoming;
154
- } catch {
155
- payloadToWrite = JSON.stringify(incoming, null, jsonIndent);
156
- }
157
- } else {
158
- payloadToWrite = JSON.stringify(incoming, null, jsonIndent);
159
- }
160
- isText = true;
161
- } else if (fileType === 'text') {
162
- payloadToWrite = incoming === undefined || incoming === null ? '' : String(incoming);
163
- isText = true;
164
- } else {
165
- payloadToWrite = await toBinary(incoming);
166
- }
167
-
168
- if (isText) {
169
- await fs.writeFile(filePath, payloadToWrite, 'utf8');
170
- } else {
171
- await fs.writeFile(filePath, payloadToWrite);
172
- }
173
-
174
- const sizeBytes = isText
175
- ? Buffer.byteLength(payloadToWrite, 'utf8')
176
- : payloadToWrite.length;
177
-
178
- if (fileType === 'json' && sizeBytes >= JSON_WARN_BYTES) {
179
- const sizeMB = (sizeBytes / (1024 * 1024)).toFixed(1);
180
- node.warn(`JSON output is large (${sizeMB} MB); this may impact the event loop and memory usage.`);
181
- }
182
-
183
- const resultInfo = {
184
- path: filePath,
185
- filename,
186
- type: fileType,
187
- extension,
188
- sizeBytes
189
- };
190
- if (fileType === 'image') {
191
- resultInfo.format = imageFormat;
192
- }
193
-
194
- // Optionally attach result info for downstream nodes
195
- const outputPath = config.outputPath || 'savedFile';
196
- const outputPathType = config.outputPathType || 'msg';
197
- try {
198
- if (outputPathType === 'msg') {
199
- RED.util.setMessageProperty(msg, outputPath, resultInfo, true);
200
- } else if (outputPathType === 'flow') {
201
- node.context().flow.set(outputPath, resultInfo);
202
- } else if (outputPathType === 'global') {
203
- node.context().global.set(outputPath, resultInfo);
204
- }
205
- } catch (setErr) {
206
- node.warn(`Unable to store output metadata: ${setErr.message}`);
207
- }
208
-
209
- const elapsed = Date.now() - started;
210
- const renameOccurred = overwriteEnabled && filename !== originalFilename;
211
- const statusSuffix = renameOccurred ? ' (avoided overwrite)' : '';
212
- node.status({
213
- fill: 'green',
214
- shape: 'dot',
215
- text: `saved ${filename}${statusSuffix} (${elapsed}ms)`
216
- });
217
-
218
- // Record basic performance metric for consistency across nodes
219
- NodeUtils.recordPerformanceMetrics(node, msg, { taskMs: elapsed }, elapsed);
220
-
221
- send(msg);
222
- done && done();
223
- } catch (err) {
224
- node.status({ fill: 'red', shape: 'ring', text: 'Error' });
225
- node.error(err.message, msg);
226
- done && done(err);
227
- }
228
- });
229
- }
230
-
231
- RED.nodes.registerType('save-file', SaveFileNode);
232
- };
233
-
234
- // Helpers
235
- function mapExtension(ext) {
236
- if (!ext) return null;
237
- const lower = ext.toLowerCase();
238
- if (lower === 'jpg' || lower === 'jpeg') return { type: 'image', format: 'jpg' };
239
- if (lower === 'png') return { type: 'image', format: 'png' };
240
- if (lower === 'webp') return { type: 'image', format: 'webp' };
241
- if (lower === 'json') return { type: 'json' };
242
- if (lower === 'txt') return { type: 'text' };
243
- if (lower === 'bin' || lower === 'dat') return { type: 'binary' };
244
- return null;
245
- }
246
-
247
- function defaultExtension(type, imageFormat) {
248
- if (type === 'image') return imageFormat || 'jpg';
249
- if (type === 'json') return 'json';
250
- if (type === 'text') return 'txt';
251
- if (type === 'binary') return 'bin';
252
- return '';
253
- }
254
-
255
- function defaultBaseName(type) {
256
- const timestamp = new Date()
257
- .toISOString()
258
- .replace(/[-:]/g, '')
259
- .replace(/\.\d{3}Z$/, 'Z')
260
- .replace('T', '_');
261
- switch (type) {
262
- case 'image': return `image_${timestamp}`;
263
- case 'json': return `data_${timestamp}`;
264
- case 'text': return `text_${timestamp}`;
265
- default: return `file_${timestamp}`;
266
- }
267
- }
268
-
269
- async function fileExists(p) {
270
- try {
271
- await fs.access(p);
272
- return true;
273
- } catch {
274
- return false;
275
- }
276
- }
277
-
278
- async function inferFileType(value, extInfo) {
279
- if (extInfo?.type) {
280
- return { type: extInfo.type, format: extInfo.format };
281
- }
282
-
283
- if (value && typeof value === 'object') {
284
- if (Buffer.isBuffer(value)) {
285
- try {
286
- const meta = await sharp(value).metadata();
287
- if (meta?.format) {
288
- const fmt = normalizeSharpFormat(meta.format);
289
- if (fmt) return { type: 'image', format: fmt };
290
- }
291
- } catch {
292
- // Not an image buffer
293
- }
294
- return { type: 'binary' };
295
- }
296
-
297
- if (isRawImageLike(value)) {
298
- return { type: 'image' };
299
- }
300
-
301
- return { type: 'json' };
302
- }
303
-
304
- if (typeof value === 'string') {
305
- const trimmed = value.trim();
306
- if ((trimmed.startsWith('{') && trimmed.endsWith('}')) ||
307
- (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
308
- return { type: 'json' };
309
- }
310
- return { type: 'text' };
311
- }
312
-
313
- return { type: 'binary' };
314
- }
315
-
316
- function normalizeSharpFormat(fmt) {
317
- if (!fmt) return null;
318
- if (fmt === 'jpeg' || fmt === 'jpg') return 'jpg';
319
- if (fmt === 'png') return 'png';
320
- if (fmt === 'webp') return 'webp';
321
- return null;
322
- }
323
-
324
- function isRawImageLike(obj) {
325
- return obj &&
326
- typeof obj === 'object' &&
327
- !Buffer.isBuffer(obj) &&
328
- Object.prototype.hasOwnProperty.call(obj, 'data') &&
329
- Object.prototype.hasOwnProperty.call(obj, 'width') &&
330
- Object.prototype.hasOwnProperty.call(obj, 'height');
331
- }
332
-
333
- async function toBinary(value) {
334
- if (Buffer.isBuffer(value)) return value;
335
- if (value && typeof value === 'object' && Buffer.isBuffer(value.data)) {
336
- return Buffer.from(value.data);
337
- }
338
- if (typeof value === 'string') {
339
- return Buffer.from(value, 'utf8');
340
- }
341
- return Buffer.from(JSON.stringify(value ?? ''), 'utf8');
342
- }
343
-
344
- async function toImageBuffer(imageValue, format, quality, pngOptimize, NodeUtils, node) {
345
- // Encoded buffer path
346
- if (Buffer.isBuffer(imageValue) && !(imageValue.width && imageValue.height)) {
347
- let inputFormat;
348
- try {
349
- const metadata = await sharp(imageValue).metadata();
350
- inputFormat = metadata.format;
351
- } catch {
352
- inputFormat = null;
353
- }
354
-
355
- if (inputFormat && (normalizeSharpFormat(inputFormat) === format)) {
356
- return imageValue;
357
- }
358
-
359
- const sharpInstance = sharp(imageValue);
360
- return encodeSharp(sharpInstance, format, quality, pngOptimize);
361
- }
362
-
363
- // Raw image path (uses validator for clear errors)
364
- const validated = NodeUtils.validateImageStructure(imageValue, node);
365
- if (!validated) {
366
- throw new Error('Invalid image structure.');
367
- }
368
-
369
- const colorSpace = validated.colorSpace;
370
- const channels = validated.channels;
371
- let data = validated.data;
372
-
373
- if (colorSpace === 'BGR' || colorSpace === 'BGRA') {
374
- data = Buffer.from(data);
375
- for (let i = 0; i < data.length; i += channels) {
376
- const t = data[i];
377
- data[i] = data[i + 2];
378
- data[i + 2] = t;
379
- }
380
- }
381
-
382
- let sharpInstance = sharp(data, {
383
- raw: {
384
- width: validated.width,
385
- height: validated.height,
386
- channels: channels
387
- }
388
- });
389
-
390
- if (colorSpace === 'GRAY') {
391
- sharpInstance = sharpInstance.toColourspace('b-w');
392
- }
393
-
394
- return encodeSharp(sharpInstance, format, quality, pngOptimize);
395
- }
396
-
397
- function encodeSharp(sharpInstance, format, quality, pngOptimize) {
398
- if (format === 'png') {
399
- const pngOptions = pngOptimize
400
- ? { compressionLevel: 9, palette: true }
401
- : { compressionLevel: 6 };
402
- return sharpInstance.png(pngOptions).toBuffer();
403
- }
404
- if (format === 'webp') {
405
- return sharpInstance.webp({ quality }).toBuffer();
406
- }
407
- return sharpInstance.jpeg({ quality }).toBuffer();
408
- }
409
-
410
- async function getDiskUsageInfo(targetPath, node, warnState) {
411
- try {
412
- const stats = await fs.statfs(targetPath);
413
- const blockSize = Number(stats.bsize) || 0;
414
- const totalBlocks = Number(stats.blocks) || 0;
415
- const availableBlocks = Number(
416
- stats.bavail !== undefined ? stats.bavail :
417
- stats.bfree !== undefined ? stats.bfree : 0
418
- );
419
-
420
- const totalBytes = totalBlocks * blockSize;
421
- const availableBytes = availableBlocks * blockSize;
422
-
423
- if (totalBytes <= 0) {
424
- return null;
425
- }
426
-
427
- const usedRatio = 1 - (availableBytes / totalBytes);
428
- return {
429
- totalBytes,
430
- availableBytes,
431
- usedRatio
432
- };
433
- } catch (err) {
434
- if (!warnState.logged) {
435
- node.warn(`Disk usage check failed for "${targetPath}": ${err.message}`);
436
- warnState.logged = true;
437
- }
438
- return null;
439
- }
440
- }
@@ -1,85 +0,0 @@
1
- <script type="text/javascript">
2
- (function() {
3
- RED.nodes.registerType('block-detect', {
4
- category: 'RP Image',
5
- color: '#F4C95D',
6
- defaults: {
7
- name: { value: "" },
8
- intervalMs: { value: 1000, required: true, validate: RED.validators.number() },
9
- thresholdMs: { value: 120, required: true, validate: RED.validators.number() },
10
- consecutive: { value: 1, required: true, validate: RED.validators.number() },
11
- cooldown: { value: 30000, required: true, validate: RED.validators.number() },
12
- showStats: { value: true }
13
- },
14
- inputs: 0,
15
- outputs: 0,
16
- icon: "font-awesome/fa-shield",
17
- label: function() {
18
- return this.name || "block detect";
19
- },
20
- oneditprepare: function() {
21
- $("#node-input-showStats").prop("checked", this.showStats !== false);
22
- },
23
- oneditsave: function() {
24
- this.showStats = $("#node-input-showStats").is(":checked");
25
- }
26
- });
27
- })();
28
- </script>
29
-
30
- <script type="text/x-red" data-template-name="block-detect">
31
- <div class="form-row">
32
- <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
33
- <input type="text" id="node-input-name" placeholder="Event loop watchdog">
34
- </div>
35
-
36
- <div class="form-row">
37
- <label for="node-input-thresholdMs"><i class="fa fa-bolt"></i> Threshold (ms)</label>
38
- <input type="number" id="node-input-thresholdMs" min="1" step="10">
39
- </div>
40
-
41
- <div class="form-row">
42
- <label for="node-input-intervalMs"><i class="fa fa-clock-o"></i> Sample interval (ms)</label>
43
- <input type="number" id="node-input-intervalMs" min="100" step="100">
44
- </div>
45
-
46
- <div class="form-row">
47
- <label for="node-input-consecutive"><i class="fa fa-repeat"></i> Consecutive hits</label>
48
- <input type="number" id="node-input-consecutive" min="1" step="1">
49
- </div>
50
-
51
- <div class="form-row">
52
- <label for="node-input-cooldown"><i class="fa fa-hourglass-half"></i> Cooldown (ms)</label>
53
- <input type="number" id="node-input-cooldown" min="1000" step="1000">
54
- </div>
55
-
56
- <div class="form-row">
57
- <label></label>
58
- <input type="checkbox" id="node-input-showStats" checked>
59
- <label for="node-input-showStats" style="width: auto;">Show live delay metrics</label>
60
- </div>
61
- </script>
62
-
63
- <script type="text/x-red" data-help-name="block-detect">
64
- <p>Continuously monitors Node-RED's event loop for blocking work that would slow down flows.</p>
65
-
66
- <h3>How it works</h3>
67
- <p>The node samples <code>monitorEventLoopDelay</code> (or falls back to timer drift) and raises an alert when the measured delay exceeds the configured threshold for a number of consecutive samples.</p>
68
-
69
- <h3>Properties</h3>
70
- <dl class="message-properties">
71
- <dt>Threshold (ms)<span class="property-type">number</span></dt>
72
- <dd>Maximum allowed event loop delay before the node treats a sample as blocking.</dd>
73
- <dt>Sample interval (ms)<span class="property-type">number</span></dt>
74
- <dd>How often to collect a measurement. Lower values catch spikes sooner but cost a little more CPU.</dd>
75
- <dt>Consecutive hits<span class="property-type">number</span></dt>
76
- <dd>Number of back-to-back samples that must exceed the threshold before an alert is emitted.</dd>
77
- <dt>Cooldown (ms)<span class="property-type">number</span></dt>
78
- <dd>Minimum time between alerts so your logs do not flood when something stays blocked.</dd>
79
- <dt>Show live delay metrics<span class="property-type">boolean</span></dt>
80
- <dd>Toggle live status text that displays the current average and max delay.</dd>
81
- </dl>
82
-
83
- <h3>Usage</h3>
84
- <p>Drop the node anywhere in a flow (it has no wires) to keep a lightweight background watchdog running. Use multiple instances with different thresholds if you want per-flow granularity.</p>
85
- </script>
@@ -1,136 +0,0 @@
1
- /**
2
- * @file Node-RED logic for the block-detect node.
3
- * Monitors the Node.js event loop delay to detect blocking work.
4
- */
5
- const { performance, monitorEventLoopDelay } = require('perf_hooks');
6
-
7
- module.exports = function(RED) {
8
- function BlockDetectNode(config) {
9
- RED.nodes.createNode(this, config);
10
- const node = this;
11
-
12
- const intervalMs = sanitizeNumber(config.intervalMs, 1000, 100);
13
- const thresholdMs = sanitizeNumber(config.thresholdMs, 120, 1);
14
- const resolutionMs = 20; // Medium resolution for event-loop histogram (ms)
15
- const consecutive = Math.max(1, Math.round(sanitizeNumber(config.consecutive, 1, 1)));
16
- const cooldownMs = sanitizeNumber(config.cooldown, 30000, 1000);
17
- const showStats = config.showStats !== false;
18
-
19
- let overThresholdCount = 0;
20
- let lastAlertAt = 0;
21
- let timer = null;
22
- let histogram = null;
23
- let fallbackPrev = performance.now();
24
- let monitorAvailable = typeof monitorEventLoopDelay === 'function';
25
-
26
- if (monitorAvailable) {
27
- histogram = monitorEventLoopDelay({ resolution: resolutionMs });
28
- histogram.enable();
29
- } else {
30
- node.warn('monitorEventLoopDelay not available; falling back to coarse timer drift detection.');
31
- }
32
-
33
- node.status({ fill: 'grey', shape: 'ring', text: 'monitoring…' });
34
-
35
- timer = setInterval(() => {
36
- const stats = monitorAvailable
37
- ? readHistogramStats(histogram)
38
- : readFallbackStats();
39
-
40
- if (showStats) {
41
- const color = stats.max >= thresholdMs ? (stats.alert ? 'red' : 'yellow') : 'green';
42
- const shape = stats.max >= thresholdMs ? 'ring' : 'dot';
43
- node.status({
44
- fill: color,
45
- shape,
46
- text: `avg ${stats.mean.toFixed(1)}ms | max ${stats.max.toFixed(1)}ms`
47
- });
48
- } else {
49
- if (stats.alert) {
50
- node.status({ fill: 'red', shape: 'dot', text: 'blocking detected' });
51
- } else if (stats.max >= thresholdMs) {
52
- node.status({ fill: 'yellow', shape: 'ring', text: 'high loop delay' });
53
- } else {
54
- node.status({ fill: 'green', shape: 'dot', text: 'ok' });
55
- }
56
- }
57
-
58
- if (stats.max >= thresholdMs) {
59
- overThresholdCount += 1;
60
- } else {
61
- overThresholdCount = 0;
62
- }
63
-
64
- if (overThresholdCount >= consecutive) {
65
- const now = Date.now();
66
- if (now - lastAlertAt >= cooldownMs) {
67
- emitAlert(stats);
68
- lastAlertAt = now;
69
- }
70
- overThresholdCount = 0;
71
- }
72
- }, intervalMs);
73
-
74
- node.on('close', function() {
75
- if (timer) {
76
- clearInterval(timer);
77
- }
78
- if (histogram) {
79
- histogram.disable();
80
- }
81
- });
82
-
83
- function emitAlert(stats) {
84
- const message =
85
- `Detected potential blocking: max ${stats.max.toFixed(1)} ms ` +
86
- `(avg ${stats.mean.toFixed(1)} ms, min ${stats.min.toFixed(1)} ms, threshold ${thresholdMs} ms).`;
87
-
88
- node.warn(message);
89
- }
90
-
91
- function readHistogramStats(hist) {
92
- const mean = Number.isFinite(hist.mean) ? hist.mean / 1e6 : 0;
93
- const max = Number.isFinite(hist.max) ? hist.max / 1e6 : 0;
94
- const min = Number.isFinite(hist.min) ? hist.min / 1e6 : 0;
95
- hist.reset();
96
- return {
97
- mean,
98
- max,
99
- min,
100
- alert: max >= thresholdMs
101
- };
102
- }
103
-
104
- function readFallbackStats() {
105
- const now = performance.now();
106
- const delta = now - fallbackPrev;
107
- fallbackPrev = now;
108
- const delay = Math.max(0, delta - intervalMs);
109
- return {
110
- mean: delay,
111
- max: delay,
112
- min: delay,
113
- alert: delay >= thresholdMs
114
- };
115
- }
116
- }
117
-
118
- RED.nodes.registerType('block-detect', BlockDetectNode, {
119
- defaults: {
120
- name: { value: '' },
121
- intervalMs: { value: 1000 },
122
- thresholdMs: { value: 120 },
123
- consecutive: { value: 1 },
124
- cooldown: { value: 30000 },
125
- showStats: { value: true }
126
- }
127
- });
128
- };
129
-
130
- function sanitizeNumber(value, fallback, min) {
131
- const num = Number(value);
132
- if (Number.isFinite(num)) {
133
- return Math.max(min, num);
134
- }
135
- return fallback;
136
- }