node-red-contrib-ccu 4.7.2 → 4.8.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 CHANGED
@@ -5,6 +5,45 @@ Notable changes to node-red-contrib-ccu. Format follows
5
5
  user-visible symptom and the cause, not the commit list (the release notes
6
6
  append commits automatically).
7
7
 
8
+ ## 4.8.0 (2026-10-29)
9
+
10
+ Less memory: the connection's own bookkeeping no longer grows with the
11
+ number of datapoints, and the paramset descriptions in memory are those of
12
+ the device types the system has. On a large system (a few thousand
13
+ datapoints, a few hundred subscriptions from value nodes, RedMatic-HomeKit
14
+ and RedMatic-Matter) that is on the order of 100 MB of live heap less, and
15
+ a deploy no longer adds to it. It is a reduction, not the whole of a large
16
+ Node-RED's memory: flows and the other nodes keep what they keep.
17
+
18
+ ### Changed
19
+
20
+ - **Datapoint subscriptions are dispatched through an index.** Until now the
21
+ connection remembered, for every datapoint, which subscriptions had matched
22
+ it and which had not - two sets of ids per datapoint name, so the memory
23
+ grew with datapoints × subscriptions (3,500 datapoints × 536 subscriptions
24
+ were about 70 MB of live heap on a CCU3), a subscription with `cache` on
25
+ walked every cached value at deploy time to fill them all, and - because
26
+ the replay and the event path stored the id in two different forms - a
27
+ redeploy left the old entries behind and grew the sets again. Now a
28
+ subscription is indexed by the most exact attribute of its filter (the
29
+ datapoint name, the channel, the device, ...), an event is tested only
30
+ against the subscriptions that can match it, and unsubscribe removes
31
+ exactly one entry. What a subscription receives, and in which order, is
32
+ unchanged (a randomised equivalence test against the old dispatch guards
33
+ it). In the benchmark (`test/bench/subscriptions.js`, 12,000 datapoints,
34
+ 1,000 subscriptions) the heap goes from 481 MB to 3 MB, a deploy from
35
+ 6.5 s to 40 ms, an event from 28 µs to 8 µs.
36
+ - **Paramset descriptions in memory only for the device types present.**
37
+ `paramsets.json` - the shipped 14 MB plus what a system fetched - was held
38
+ in memory whole: some 2,800 type/version keys, 16-20 MB of heap, where a
39
+ system uses the few dozen types it has (40 types are 3 MB). The file on
40
+ disk keeps every description in its format; the memory holds the ones the
41
+ device table needs, loaded at start and, for a device that arrives later,
42
+ from the file before the interface is asked. A fetched description is
43
+ merged into the file. The editor's device data is correspondingly smaller.
44
+ - An obsolete `ccu_paramsets_v2.json` (the format of 2019) still lying in a
45
+ userDir is removed at start, once, with a log line.
46
+
8
47
  ## 4.7.2 (2026-10-29)
9
48
 
10
49
  ### Fixed
@@ -20,6 +20,7 @@ const metaProvider = require('./lib/metaprovider.js');
20
20
  const {InitRetry, retryDelay, RETRY_INTERVAL} = require('./lib/initretry.js');
21
21
  const lite = require('./lib/lite.js');
22
22
  const {writeJsonAtomic, DebouncedSave} = require('./lib/cachefile.js');
23
+ const {SubscriptionIndex, matches: filterMatches} = require('./lib/subscriptions.js');
23
24
  const xmlrpc = require('homematic-xmlrpc');
24
25
  const binrpc = require('binrpc');
25
26
 
@@ -719,13 +720,19 @@ module.exports = function (RED) {
719
720
  this.paramsQueue = [];
720
721
 
721
722
  this.paramsetFile = path.join(RED.settings.userDir || path.join(__dirname, '..'), 'paramsets.json');
722
-
723
- this.loadParamsets();
724
-
725
- this.callbacks = {};
726
- this.idCallback = 0;
727
- this.callbackBlacklists = {};
728
- this.callbackWhitelists = {};
723
+ // task 28: the descriptions in memory are those of the device types present (and
724
+ // whatever was fetched); the file on disk keeps them all. Fetched since the last
725
+ // save, merged into the file by saveParamsets():
726
+ this.paramsetNew = {};
727
+ // names the file does not have, so a miss does not parse it again
728
+ this.paramsetFileMissing = new Set();
729
+ this.paramsetFilePass = null;
730
+ this.paramsetDescriptions = {};
731
+
732
+ // task 27: the datapoint subscriptions, indexed by their exact key - memory grows with
733
+ // the subscriptions, not with datapoints x subscriptions as the per-datapoint
734
+ // whitelists/blacklists did
735
+ this.subscriptions = new SubscriptionIndex();
729
736
 
730
737
  this.sysvarCallbacks = {};
731
738
  this.idSysvarCallback = 0;
@@ -787,6 +794,8 @@ module.exports = function (RED) {
787
794
  this.metadataSave = new DebouncedSave(() => this.writeMetadata(), 1000);
788
795
 
789
796
  this.loadMetadata();
797
+ // after the metadata: the descriptions of the device table's types are what is loaded
798
+ this.loadParamsets();
790
799
  this.loadRegadata();
791
800
  this.loadValues();
792
801
  this.pruneCaches();
@@ -987,7 +996,7 @@ module.exports = function (RED) {
987
996
  this.logger.debug(
988
997
  'stats rpc rx: ' + JSON.stringify(this.rxCounters) + ' tx: ' + JSON.stringify(this.txCounters),
989
998
  );
990
- this.logger.debug('stats rpc subscribers ' + Object.keys(this.callbacks).length);
999
+ this.logger.debug('stats rpc subscribers ' + this.subscriptions.size);
991
1000
  this.logger.debug(
992
1001
  'stats rega subscribers ' +
993
1002
  (Object.keys(this.programCallbacks).length + Object.keys(this.sysvarCallbacks).length),
@@ -1291,44 +1300,180 @@ module.exports = function (RED) {
1291
1300
  }
1292
1301
 
1293
1302
  /**
1294
- *
1303
+ * Merges the descriptions fetched since the last save into the file on disk. The file
1304
+ * holds every description ever known (the vendored ones and the fetched ones, in the
1305
+ * format other consumers and the editor read); the memory holds only the present types,
1306
+ * so the file is read, merged and written back atomically (task 28).
1295
1307
  * @returns {Promise<any>}
1296
1308
  */
1297
1309
  saveParamsets() {
1298
1310
  return new Promise((resolve) => {
1299
- fs.writeFileSync(this.paramsetFile, JSON.stringify(this.paramsetDescriptions, null, ' '));
1300
- this.logger.info(
1301
- 'paramsets saved to',
1302
- this.paramsetFile,
1303
- this.paramsetDescriptions ? Object.keys(this.paramsetDescriptions).length : 0,
1304
- );
1311
+ const names = Object.keys(this.paramsetNew);
1312
+ if (names.length === 0) {
1313
+ resolve();
1314
+ return;
1315
+ }
1316
+
1317
+ try {
1318
+ const all = this.readParamsetFile() || {};
1319
+ for (const name of names) {
1320
+ all[name] = this.paramsetNew[name];
1321
+ }
1322
+
1323
+ writeJsonAtomic(this.paramsetFile, all, ' ');
1324
+ this.paramsetNew = {};
1325
+ this.logger.info(
1326
+ 'paramsets saved to',
1327
+ this.paramsetFile,
1328
+ names.length,
1329
+ 'new,',
1330
+ Object.keys(all).length,
1331
+ 'total',
1332
+ );
1333
+ } catch (error) {
1334
+ this.logger.error('error saving paramsets ' + error.message);
1335
+ }
1336
+
1305
1337
  resolve();
1306
1338
  });
1307
1339
  }
1308
1340
 
1309
1341
  /**
1310
- *
1342
+ * Parses the paramsets file - the userDir's, or the vendored one when the userDir has none
1343
+ * yet (then it is copied there, as before, so the format on disk stays the same).
1344
+ * @returns {object|null} every description the file holds, or null when there is none
1345
+ */
1346
+ readParamsetFile() {
1347
+ if (!fs.existsSync(this.paramsetFile)) {
1348
+ const vendored = path.join(__dirname, '..', 'paramsets.json');
1349
+ try {
1350
+ fs.copyFileSync(vendored, this.paramsetFile);
1351
+ this.logger.info('paramsets copied from', vendored, 'to', this.paramsetFile);
1352
+ } catch (error) {
1353
+ this.logger.error('error copying paramsets ' + error.message);
1354
+ }
1355
+ }
1356
+
1357
+ try {
1358
+ return JSON.parse(fs.readFileSync(this.paramsetFile));
1359
+ } catch (error) {
1360
+ if (error.code === 'ENOENT') {
1361
+ this.logger.info('paramsets new empty');
1362
+ } else {
1363
+ this.logger.error('error loading paramsets ' + error.message);
1364
+ }
1365
+
1366
+ return null;
1367
+ }
1368
+ }
1369
+
1370
+ /**
1371
+ * The paramset names the device table needs: every PARAMSETS entry of every device and
1372
+ * channel of every interface.
1373
+ * @returns {Set<string>}
1374
+ */
1375
+ neededParamsetNames() {
1376
+ const names = new Set();
1377
+ const tables = (this.metadata && this.metadata.devices) || {};
1378
+ for (const iface of Object.keys(tables)) {
1379
+ for (const address of Object.keys(tables[iface])) {
1380
+ const device = tables[iface][address];
1381
+ if (device && Array.isArray(device.PARAMSETS)) {
1382
+ for (const paramset of device.PARAMSETS) {
1383
+ const name = this.paramsetName(iface, device, paramset);
1384
+ if (name) {
1385
+ names.add(name);
1386
+ }
1387
+ }
1388
+ }
1389
+ }
1390
+ }
1391
+
1392
+ return names;
1393
+ }
1394
+
1395
+ /**
1396
+ * Takes the descriptions the device table needs (and `extra`) from the file into memory;
1397
+ * one parse of the file per call. A name the file does not have is remembered, so the
1398
+ * queue asks the interface for it without another parse.
1399
+ * @param {Iterable<string>} [extra] further names
1400
+ * @returns {number} how many descriptions came in
1401
+ */
1402
+ paramsetsFromFile(extra) {
1403
+ const needed = this.neededParamsetNames();
1404
+ for (const name of extra || []) {
1405
+ needed.add(name);
1406
+ }
1407
+
1408
+ const all = this.readParamsetFile();
1409
+ let loaded = 0;
1410
+ for (const name of needed) {
1411
+ if (this.paramsetDescriptions[name]) {
1412
+ continue;
1413
+ }
1414
+
1415
+ if (all && all[name]) {
1416
+ this.paramsetDescriptions[name] = all[name];
1417
+ this.paramsetFileMissing.delete(name);
1418
+ loaded += 1;
1419
+ } else {
1420
+ this.paramsetFileMissing.add(name);
1421
+ }
1422
+ }
1423
+
1424
+ this.logger.info(
1425
+ 'paramsets loaded from',
1426
+ this.paramsetFile,
1427
+ loaded,
1428
+ 'of',
1429
+ all ? Object.keys(all).length : 0,
1430
+ '(' + Object.keys(this.paramsetDescriptions).length + ' in memory for the device types present)',
1431
+ );
1432
+ return loaded;
1433
+ }
1434
+
1435
+ /**
1436
+ * One file pass on the next turn of the event loop, however often it is asked for until then.
1437
+ */
1438
+ paramsetFilePassSoon() {
1439
+ if (this.paramsetFilePass) {
1440
+ return;
1441
+ }
1442
+
1443
+ this.paramsetFilePass = setImmediate(() => {
1444
+ this.paramsetFilePass = null;
1445
+ try {
1446
+ this.paramsetsFromFile();
1447
+ } catch (error) {
1448
+ this.logger.error('error loading paramsets ' + error.message);
1449
+ }
1450
+ });
1451
+ }
1452
+
1453
+ /**
1454
+ * At start: the descriptions of the cached device table's types from the file. An obsolete
1455
+ * `ccu_paramsets_v2.json` (the format of 2019) still lying in the userDir is removed.
1311
1456
  * @returns {Promise<any>}
1312
1457
  */
1313
1458
  loadParamsets() {
1314
1459
  return new Promise((resolve) => {
1315
- const load = (file) => {
1316
- try {
1317
- this.paramsetDescriptions = JSON.parse(fs.readFileSync(file));
1318
- this.logger.info('paramsets loaded from', file);
1319
- } catch {
1320
- this.logger.info('paramsets new empty');
1321
- this.paramsetDescriptions = {};
1460
+ const obsolete = path.join(path.dirname(this.paramsetFile), 'ccu_paramsets_v2.json');
1461
+ try {
1462
+ if (fs.existsSync(obsolete)) {
1463
+ fs.unlinkSync(obsolete);
1464
+ this.logger.info('removed the obsolete', obsolete);
1322
1465
  }
1323
- };
1466
+ } catch (error) {
1467
+ this.logger.warn('could not remove ' + obsolete + ': ' + error.message);
1468
+ }
1324
1469
 
1325
- if (fs.existsSync(this.paramsetFile)) {
1326
- load(this.paramsetFile);
1327
- resolve();
1328
- } else {
1329
- load(path.join(__dirname, '..', 'paramsets.json'));
1330
- this.saveParamsets().then(resolve);
1470
+ try {
1471
+ this.paramsetsFromFile();
1472
+ } catch (error) {
1473
+ this.logger.error('error loading paramsets ' + error.message);
1331
1474
  }
1475
+
1476
+ resolve();
1332
1477
  });
1333
1478
  }
1334
1479
 
@@ -1361,6 +1506,9 @@ module.exports = function (RED) {
1361
1506
  });
1362
1507
  Object.keys(this.liveness).forEach((iface) => this.stopLiveness(iface));
1363
1508
  clearTimeout(this.valuesPruneTimer);
1509
+ clearTimeout(this.getParamsetTimeout);
1510
+ clearImmediate(this.paramsetFilePass);
1511
+ this.paramsetFilePass = null;
1364
1512
 
1365
1513
  this.metadataSave.flush();
1366
1514
  this.saveRegadata();
@@ -3349,6 +3497,12 @@ module.exports = function (RED) {
3349
3497
  if (device && device.PARAMSETS) {
3350
3498
  device.PARAMSETS.forEach((paramset) => {
3351
3499
  const name = this.paramsetName(iface, device, paramset);
3500
+ if (name && !this.paramsetDescriptions[name] && !this.paramsetFileMissing.has(name)) {
3501
+ // task 28: the file may have it - one pass after this burst of pushes (a
3502
+ // device list arrives as one callback), not one parse per device
3503
+ this.paramsetFilePassSoon();
3504
+ }
3505
+
3352
3506
  if (
3353
3507
  !this.paramsetDescriptions[name] &&
3354
3508
  // B-36: once per description key in the queue, and never again
@@ -3385,6 +3539,17 @@ module.exports = function (RED) {
3385
3539
  if (item) {
3386
3540
  const {iface, name, address, paramset} = item;
3387
3541
 
3542
+ if (!this.paramsetDescriptions[name] && name && !this.paramsetFileMissing.has(name)) {
3543
+ // task 28: the file first - one parse takes every name the device table
3544
+ // needs by now, the rest is asked of the interface
3545
+ try {
3546
+ this.paramsetsFromFile([name]);
3547
+ } catch (error) {
3548
+ this.logger.error('error loading paramsets ' + error.message);
3549
+ this.paramsetFileMissing.add(name);
3550
+ }
3551
+ }
3552
+
3388
3553
  if (this.paramsetDescriptions[name]) {
3389
3554
  //this.logger.trace('paramset', name, 'already known');
3390
3555
  this.paramsetPending = false;
@@ -3397,6 +3562,8 @@ module.exports = function (RED) {
3397
3562
  this.newParamsetDescriptionCount += 1;
3398
3563
  this.newParamsetDescription = true;
3399
3564
  this.paramsetDescriptions[name] = res;
3565
+ this.paramsetNew[name] = res;
3566
+ this.paramsetFileMissing.delete(name);
3400
3567
  if (this.newParamsetDescriptionCount >= 30) {
3401
3568
  this.newParamsetDescription = false;
3402
3569
  this.newParamsetDescriptionCount = 0;
@@ -4182,27 +4349,18 @@ module.exports = function (RED) {
4182
4349
  }
4183
4350
  }
4184
4351
 
4185
- const id = this.idCallback;
4186
- this.idCallback += 1;
4187
-
4188
- //this.logger.trace('subscribe', id, JSON.stringify(filter));
4189
- this.callbacks[id] = {filter, callback};
4352
+ const id = this.subscriptions.add(filter, callback);
4190
4353
 
4191
4354
  if (filter.cache && this.cachedValuesReceived) {
4192
- Object.keys(this.values).forEach((dp) => {
4193
- const message = {...this.values[dp]};
4355
+ // the replay goes through the index: one lookup for a filter that names its
4356
+ // datapoint, a walk over the cached values for the others (as before, but
4357
+ // nothing is remembered per datapoint any more)
4358
+ for (const cached of SubscriptionIndex.replayCandidates(filter, this.values)) {
4359
+ const message = {...cached};
4194
4360
  message.cache = true;
4195
4361
  message.change = false;
4196
- if (!this.callbackBlacklists[message.datapointName]) {
4197
- this.callbackBlacklists[message.datapointName] = new Set();
4198
- }
4199
-
4200
- if (!this.callbackWhitelists[message.datapointName]) {
4201
- this.callbackWhitelists[message.datapointName] = new Set();
4202
- }
4203
-
4204
4362
  this.callCallback(message, id);
4205
- });
4363
+ }
4206
4364
  }
4207
4365
 
4208
4366
  return id;
@@ -4214,18 +4372,8 @@ module.exports = function (RED) {
4214
4372
  * @returns {boolean}
4215
4373
  */
4216
4374
  unsubscribe(id) {
4217
- if (this.callbacks[id]) {
4375
+ if (this.subscriptions.remove(id)) {
4218
4376
  this.logger.trace('unsubscribe', id);
4219
- delete this.callbacks[id];
4220
-
4221
- Object.keys(this.callbackBlacklists).forEach((dp) => {
4222
- this.callbackBlacklists[dp].delete(id);
4223
- });
4224
-
4225
- Object.keys(this.callbackWhitelists).forEach((dp) => {
4226
- this.callbackWhitelists[dp].delete(id);
4227
- });
4228
-
4229
4377
  return true;
4230
4378
  }
4231
4379
 
@@ -4361,145 +4509,30 @@ module.exports = function (RED) {
4361
4509
  * @returns {boolean}
4362
4510
  */
4363
4511
  callCallback(message, id) {
4364
- const {filter, callback} = this.callbacks[id];
4365
- //this.logger.trace('filter', JSON.stringify(filter));
4366
-
4367
- let match = true;
4368
- let matchCache;
4369
- let matchChange;
4370
- let matchStable;
4371
-
4372
- // Checked before the attribute loop below: that loop may break
4373
- // early for a whitelisted datapoint, and this decision has to be
4374
- // made for every message regardless of key order. Only present in
4375
- // the filter when a node opted in, so existing subscriptions keep
4376
- // receiving values the ReGa could not timestamp (#96).
4377
- if (filter && filter.uncertain === false && message.uncertain) {
4512
+ const subscription = this.subscriptions.get(id);
4513
+ if (!subscription) {
4378
4514
  return false;
4379
4515
  }
4380
4516
 
4381
- if (filter) {
4382
- const arrayAttr = Object.keys(filter);
4383
-
4384
- for (let i = 0, {length} = arrayAttr; match && i < length; i++) {
4385
- const attr = arrayAttr[i];
4386
-
4387
- if (attr === 'cache') {
4388
- // if filter.cache==false - Drop messages with msg.cache==true
4389
- if (!filter.cache && message.cache) {
4390
- //this.logger.trace('cb mismatch cache ' + id + ' ' + filter.cache + ' ' + msg.cache);
4391
- return false;
4392
- }
4393
-
4394
- matchCache = true;
4395
- continue;
4396
- }
4397
-
4398
- if (attr === 'change') {
4399
- // if filter.change==true - Drop messages with msg.change==false - except msg.cache==true && filter.cache==true
4400
- if (filter.change && !message.change && !(filter.cache && message.cache)) {
4401
- //this.logger.trace('cb mismatch change ' + id + ' ' + filter.change + ' ' + msg.change + ' ' + msg.cache);
4402
- return false;
4403
- }
4404
-
4405
- matchChange = true;
4406
- continue;
4407
- }
4408
-
4409
- if (attr === 'stable') {
4410
- // if filter.stable==true - Drop messages with msg.stable==false
4411
- if (filter.stable && !message.stable) {
4412
- //this.logger.trace('cb mismatch stable ' + id + ' ' + filter.stable + ' ' + msg.stable);
4413
- return false;
4414
- }
4415
-
4416
- matchStable = true;
4417
- continue;
4418
- }
4419
-
4420
- if (attr === 'uncertain') {
4421
- // already decided above, and not a value to compare
4422
- continue;
4423
- }
4424
-
4425
- if (this.callbackWhitelists[message.datapointName].has(id)) {
4426
- if (matchCache && matchChange && matchStable) {
4427
- break;
4428
- }
4429
-
4430
- continue;
4431
- }
4432
-
4433
- if (filter[attr] === '') {
4434
- // TODO rethink
4435
- continue;
4436
- }
4437
-
4438
- if (attr === 'channelIndex' && typeof filter[attr] !== 'undefined') {
4439
- filter[attr] = Number.parseInt(filter[attr], 10);
4440
- }
4441
-
4442
- if (Array.isArray(message[attr])) {
4443
- if (filter[attr] instanceof RegExp) {
4444
- match = false;
4445
- this.logger.trace('cb test regex array', id, attr, filter[attr], message[attr]);
4446
- message[attr].forEach((item) => {
4447
- if (filter[attr].test(item)) {
4448
- match = true;
4449
- }
4450
- });
4451
- } else if (!message[attr].includes(filter[attr])) {
4452
- this.logger.trace('cb mismatch array', id, attr, filter[attr], message[attr]);
4453
- match = false;
4454
- }
4455
- } else if (filter[attr] instanceof RegExp) {
4456
- if (!filter[attr].test(message[attr])) {
4457
- this.logger.trace('cb mismatch regex', id, attr, filter[attr], message[attr]);
4458
- match = false;
4459
- }
4460
- } else if (filter[attr] !== message[attr]) {
4461
- this.logger.trace(
4462
- 'cb mismatch misc ' + id + ' ' + attr + ' ' + filter[attr] + ' ' + message[attr],
4463
- );
4464
- match = false;
4465
- }
4466
- }
4467
- }
4468
-
4469
- if (match) {
4470
- //this.logger.trace('callCallback ' + id + ' ' + msg.datapointName + ' ' + msg.value);
4471
- callback(RED.util.cloneMessage(message));
4472
- this.callbackWhitelists[message.datapointName].add(id);
4473
- } else {
4474
- //this.logger.trace('add to blacklist ' + id + ' ' + msg.datapointName);
4475
- this.callbackBlacklists[message.datapointName].add(id);
4517
+ const {filter, callback} = subscription;
4518
+ if (!filterMatches(filter, message, id, this.logger)) {
4519
+ return false;
4476
4520
  }
4477
4521
 
4478
- return match;
4522
+ callback(RED.util.cloneMessage(message));
4523
+ return true;
4479
4524
  }
4480
4525
 
4481
4526
  /**
4482
- * Apply msg to callCallback() for all (not blacklisted) callbacks
4527
+ * Apply msg to callCallback() for every subscription the index names as a candidate
4528
+ * for it (task 27: those keyed by one of the message's own attribute values, plus the
4529
+ * generic ones), in subscription order
4483
4530
  * @param msg
4484
4531
  */
4485
4532
  callCallbacks(message) {
4486
- //this.logger.trace('callCallbacks', this.callbacks.length, JSON.stringify({datapointName: msg.datapointName, value: msg.value, cache: msg.cache, change: msg.change, stable: msg.stable}));
4487
- if (!this.callbackBlacklists[message.datapointName]) {
4488
- this.callbackBlacklists[message.datapointName] = new Set();
4533
+ for (const id of this.subscriptions.candidates(message)) {
4534
+ this.callCallback(message, id);
4489
4535
  }
4490
-
4491
- if (!this.callbackWhitelists[message.datapointName]) {
4492
- this.callbackWhitelists[message.datapointName] = new Set();
4493
- }
4494
-
4495
- Object.keys(this.callbacks).forEach((key) => {
4496
- if (this.callbackBlacklists[message.datapointName].has(key)) {
4497
- //this.logger.trace('blacklistet ' + key + ' ' + msg.datapointName);
4498
- return;
4499
- }
4500
-
4501
- this.callCallback(message, key);
4502
- });
4503
4536
  }
4504
4537
 
4505
4538
  /**
@@ -0,0 +1,333 @@
1
+ /*
2
+ * The datapoint subscriptions of a connection and their dispatch.
3
+ *
4
+ * Until 4.7.2 every subscription was tested against every event, and the outcome was remembered
5
+ * per datapoint in two Sets of subscription ids (a whitelist and a blacklist per datapoint name):
6
+ * a subscription that did not match a datapoint landed in that datapoint's blacklist, so the
7
+ * memory grew with datapoints x subscriptions (12,000 datapoints x 1,000 subscriptions was some
8
+ * 300 MB of live heap on a CCU3), and a `cache: true` subscription walked every cached value at
9
+ * subscribe time to fill them all at once. Worse, the replay added the id as a number while the
10
+ * event path added it as a string, so an unsubscribe (by number) left the string entries behind:
11
+ * every deploy grew the sets again.
12
+ *
13
+ * Now the subscriptions are indexed by one exact key: the most selective filter attribute given
14
+ * as a plain non-empty string (`datapointName`, then `channel`, `device`, ...). An event looks up
15
+ * the buckets of its own attribute values plus the small list of subscriptions without an exact
16
+ * key (rooms, functions, regular expressions, ...) and tests only those candidates - with the
17
+ * filter logic as it was. Memory is O(subscriptions): one entry per subscription, and unsubscribe
18
+ * removes exactly that entry.
19
+ */
20
+
21
+ /**
22
+ * The filter attributes an event can be looked up by, most selective first. A subscription is
23
+ * indexed by the first of these its filter names with a plain, non-empty string; the others
24
+ * (and anything that is a RegExp, a number, an array or empty) go into the generic list.
25
+ */
26
+ const INDEXED_ATTRIBUTES = [
27
+ 'datapointName',
28
+ 'channel',
29
+ 'device',
30
+ 'channelName',
31
+ 'deviceName',
32
+ 'datapoint',
33
+ 'channelType',
34
+ 'deviceType',
35
+ 'iface',
36
+ ];
37
+
38
+ /**
39
+ * The exact key a filter is indexed by.
40
+ * @param {object} filter
41
+ * @returns {{attr: string, value: string}|null} null for a subscription that goes into the generic list
42
+ */
43
+ function keyOf(filter) {
44
+ for (const attr of INDEXED_ATTRIBUTES) {
45
+ const value = filter[attr];
46
+ if (typeof value === 'string' && value !== '') {
47
+ return {attr, value};
48
+ }
49
+ }
50
+
51
+ return null;
52
+ }
53
+
54
+ /**
55
+ * Whether a message passes a subscription's filter. This is the attribute loop of the old
56
+ * callCallback(), unchanged in what it compares; only the per-datapoint whitelist shortcut is
57
+ * gone (it skipped the comparison for a datapoint that had matched once).
58
+ * @param {object} filter
59
+ * @param {object} message
60
+ * @param {number|string} [id] for the trace lines
61
+ * @param {{trace: Function}} [logger]
62
+ * @returns {boolean}
63
+ */
64
+ function matches(filter, message, id, logger) {
65
+ if (!filter) {
66
+ return true;
67
+ }
68
+
69
+ // Checked before the attribute loop: only present in the filter when a node opted in, so
70
+ // existing subscriptions keep receiving values the ReGa could not timestamp (#96)
71
+ if (filter.uncertain === false && message.uncertain) {
72
+ return false;
73
+ }
74
+
75
+ const attributes = Object.keys(filter);
76
+
77
+ for (let i = 0, {length} = attributes; i < length; i++) {
78
+ const attr = attributes[i];
79
+
80
+ if (attr === 'cache') {
81
+ // if filter.cache==false - Drop messages with msg.cache==true
82
+ if (!filter.cache && message.cache) {
83
+ return false;
84
+ }
85
+
86
+ continue;
87
+ }
88
+
89
+ if (attr === 'change') {
90
+ // if filter.change==true - Drop messages with msg.change==false - except msg.cache==true && filter.cache==true
91
+ if (filter.change && !message.change && !(filter.cache && message.cache)) {
92
+ return false;
93
+ }
94
+
95
+ continue;
96
+ }
97
+
98
+ if (attr === 'stable') {
99
+ // if filter.stable==true - Drop messages with msg.stable==false
100
+ if (filter.stable && !message.stable) {
101
+ return false;
102
+ }
103
+
104
+ continue;
105
+ }
106
+
107
+ if (attr === 'uncertain') {
108
+ // already decided above, and not a value to compare
109
+ continue;
110
+ }
111
+
112
+ if (filter[attr] === '') {
113
+ // an empty value filters nothing
114
+ continue;
115
+ }
116
+
117
+ if (attr === 'channelIndex' && typeof filter[attr] !== 'undefined') {
118
+ filter[attr] = Number.parseInt(filter[attr], 10);
119
+ }
120
+
121
+ if (Array.isArray(message[attr])) {
122
+ if (filter[attr] instanceof RegExp) {
123
+ if (logger) {
124
+ logger.trace('cb test regex array', id, attr, filter[attr], message[attr]);
125
+ }
126
+
127
+ if (!message[attr].some((item) => filter[attr].test(item))) {
128
+ return false;
129
+ }
130
+ } else if (!message[attr].includes(filter[attr])) {
131
+ if (logger) {
132
+ logger.trace('cb mismatch array', id, attr, filter[attr], message[attr]);
133
+ }
134
+
135
+ return false;
136
+ }
137
+ } else if (filter[attr] instanceof RegExp) {
138
+ if (!filter[attr].test(message[attr])) {
139
+ if (logger) {
140
+ logger.trace('cb mismatch regex', id, attr, filter[attr], message[attr]);
141
+ }
142
+
143
+ return false;
144
+ }
145
+ } else if (filter[attr] !== message[attr]) {
146
+ if (logger) {
147
+ logger.trace('cb mismatch misc ' + id + ' ' + attr + ' ' + filter[attr] + ' ' + message[attr]);
148
+ }
149
+
150
+ return false;
151
+ }
152
+ }
153
+
154
+ return true;
155
+ }
156
+
157
+ class SubscriptionIndex {
158
+ constructor() {
159
+ /** @type {Map<number, {filter: object, callback: Function, key: {attr: string, value: string}|null}>} */
160
+ this.subscriptions = new Map();
161
+ /** @type {Map<string, Map<string, Set<number>>>} attribute -> value -> ids */
162
+ this.buckets = new Map();
163
+ /** @type {Set<number>} the subscriptions without an exact key */
164
+ this.generic = new Set();
165
+ this.nextId = 0;
166
+ }
167
+
168
+ get size() {
169
+ return this.subscriptions.size;
170
+ }
171
+
172
+ /**
173
+ * @param {object} filter
174
+ * @param {Function} callback
175
+ * @returns {number} the subscription id
176
+ */
177
+ add(filter, callback) {
178
+ const id = this.nextId;
179
+ this.nextId += 1;
180
+ const key = keyOf(filter);
181
+ this.subscriptions.set(id, {filter, callback, key});
182
+
183
+ if (key) {
184
+ let byValue = this.buckets.get(key.attr);
185
+ if (!byValue) {
186
+ byValue = new Map();
187
+ this.buckets.set(key.attr, byValue);
188
+ }
189
+
190
+ let ids = byValue.get(key.value);
191
+ if (!ids) {
192
+ ids = new Set();
193
+ byValue.set(key.value, ids);
194
+ }
195
+
196
+ ids.add(id);
197
+ } else {
198
+ this.generic.add(id);
199
+ }
200
+
201
+ return id;
202
+ }
203
+
204
+ /**
205
+ * @param {number|string} id
206
+ * @returns {boolean} whether the subscription existed
207
+ */
208
+ remove(id) {
209
+ const subscription = this.subscriptions.get(Number(id));
210
+ if (!subscription) {
211
+ return false;
212
+ }
213
+
214
+ id = Number(id);
215
+ this.subscriptions.delete(id);
216
+ const {key} = subscription;
217
+ if (key) {
218
+ const byValue = this.buckets.get(key.attr);
219
+ const ids = byValue && byValue.get(key.value);
220
+ if (ids) {
221
+ ids.delete(id);
222
+ if (ids.size === 0) {
223
+ byValue.delete(key.value);
224
+ if (byValue.size === 0) {
225
+ this.buckets.delete(key.attr);
226
+ }
227
+ }
228
+ }
229
+ } else {
230
+ this.generic.delete(id);
231
+ }
232
+
233
+ return true;
234
+ }
235
+
236
+ /**
237
+ * @param {number|string} id
238
+ * @returns {{filter: object, callback: Function, key: object|null}|undefined}
239
+ */
240
+ get(id) {
241
+ return this.subscriptions.get(Number(id));
242
+ }
243
+
244
+ /**
245
+ * The ids whose filter can match the message - those indexed by one of the message's own
246
+ * attribute values, and the generic ones - in subscription order, as every subscription was
247
+ * called in before.
248
+ * @param {object} message
249
+ * @returns {number[]}
250
+ */
251
+ candidates(message) {
252
+ const ids = [];
253
+ for (const [attr, byValue] of this.buckets) {
254
+ const value = message[attr];
255
+ if (typeof value === 'string') {
256
+ const bucket = byValue.get(value);
257
+ if (bucket) {
258
+ for (const id of bucket) {
259
+ ids.push(id);
260
+ }
261
+ }
262
+ }
263
+ }
264
+
265
+ for (const id of this.generic) {
266
+ ids.push(id);
267
+ }
268
+
269
+ if (ids.length > 1) {
270
+ ids.sort((a, b) => a - b);
271
+ }
272
+
273
+ return ids;
274
+ }
275
+
276
+ /**
277
+ * The number of index entries - what the memory grows with. Equals size: one entry per
278
+ * subscription, in a bucket or in the generic list.
279
+ * @returns {number}
280
+ */
281
+ entries() {
282
+ let count = this.generic.size;
283
+ for (const byValue of this.buckets.values()) {
284
+ for (const ids of byValue.values()) {
285
+ count += ids.size;
286
+ }
287
+ }
288
+
289
+ return count;
290
+ }
291
+
292
+ /**
293
+ * For a `cache: true` subscription: the cached values it has to be replayed with. A filter that
294
+ * names the datapoint exactly (`datapointName`, or `iface` + `channel` + `datapoint`) is one
295
+ * lookup; any other walks the values, testing the exact key before the full filter.
296
+ * @param {object} filter
297
+ * @param {object} values datapointName -> cached message
298
+ * @returns {object[]} the cached messages that can match, in the values' order
299
+ */
300
+ static replayCandidates(filter, values) {
301
+ const key = keyOf(filter);
302
+ let datapointName;
303
+ if (key && key.attr === 'datapointName') {
304
+ datapointName = key.value;
305
+ } else if (
306
+ typeof filter.iface === 'string' &&
307
+ filter.iface !== '' &&
308
+ typeof filter.channel === 'string' &&
309
+ filter.channel !== '' &&
310
+ typeof filter.datapoint === 'string' &&
311
+ filter.datapoint !== ''
312
+ ) {
313
+ datapointName = filter.iface + '.' + filter.channel + '.' + filter.datapoint;
314
+ }
315
+
316
+ if (datapointName !== undefined) {
317
+ const value = values[datapointName];
318
+ return value ? [value] : [];
319
+ }
320
+
321
+ const result = [];
322
+ for (const name of Object.keys(values)) {
323
+ const value = values[name];
324
+ if (!key || value[key.attr] === key.value) {
325
+ result.push(value);
326
+ }
327
+ }
328
+
329
+ return result;
330
+ }
331
+ }
332
+
333
+ module.exports = {SubscriptionIndex, keyOf, matches, INDEXED_ATTRIBUTES};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-ccu",
3
- "version": "4.7.2",
3
+ "version": "4.8.0",
4
4
  "license": "MIT",
5
5
  "main": "none",
6
6
  "keywords": [