-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1704 lines (1499 loc) · 58.4 KB
/
index.js
File metadata and controls
1704 lines (1499 loc) · 58.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// #region F I L E
// <copyright file="mcode-cache/index.js" company="MicroCODE Incorporated">Copyright © 2022-2024 MicroCODE Incorporated Troy, MI</copyright><author>Timothy J. McGuire</author>
// #region M O D U L E
// #region D O C U M E N T A T I O N
/**
* Project: MicroCODE MERN Applications
* Customer: Internal + MIT xPRO Course
* @module 'mcode-cache.js'
* @memberof mcode
* @created January 2022-2024
* @author Timothy McGuire, MicroCODE, Inc.
* @description >
* MicroCODE File and Data Caching Library
*
* LICENSE:
* --------
* MIT License: MicroCODE.mcode-cache
*
* Copyright (c) 2022-2024 Timothy McGuire, MicroCODE, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
* DESCRIPTION:
* ------------
* This module implements the MicroCODE's Common JavaScript functions for data caching.
*
* NOTE:
*
* o 'key' in this code refers to the Application Key or File Path.
*
* o 'cacheKey' in this code refers to a fully qualified cache Key.
*
* o 'cacheKeys' are made from 'key' values by the 'cacheMakeKey()' method,
* which formats the 'key' into a cache Key with a prefix
* based on the current Namespace.
*
* o '_cache*()' are private methods that are not exposed to the caller,
* these expect 'cacheKey' values, not 'key' values.
*
* <key> - application 'key' format
* <namespace>:<key> - 'cacheKey' format
*
* Examples:
*
* key: '/backend/components/app/tool/tool.template.htmx'
* cacheKey: 'GM-GPS-eMITS-UI:backend:components:app:tool:tool.template.htmx'
*
* key: 'myKey'
* cacheKey: 'MicroCODE:myKey'
*
*
* REFERENCES:
* -----------
* 1. MIT xPRO Course: Professional Certificate in Coding: Full Stack Development with MERN
*
* 2. MicroCODE JavaScript Style Guide
* Local File: MCX-S02 (Internal JS Style Guide).docx
* https://github.com/MicroCODEIncorporated/JavaScriptSG
*
*
*
*
* MODIFICATIONS:
* --------------
* Date: By-Group: Rev: Description:
*
* 30-Jan-2024 TJM-MCODE {0001} New module for common reusable JavaScript data caching functions.
* 01-Feb-2024 TJM-MCODE {0002} Changed to the Universal Module Definition (UMD) pattern to support AMD,
* CommonJS/Node.js, and browser global in our exported module.
* 15-Sep-2024 TJM-MCODE {0003} Extended to support *node-cache* package for caching local information
* to avoid network latency, this is now the default cache provider.
*
*
*
*
* NOTE: This module follow's MicroCODE's JavaScript Style Guide and Template JS file, see:
*
* o https://github.com/MicroCODEIncorporated/JavaScriptSG
* o https://github.com/MicroCODEIncorporated/TemplatesJS
*
* ...be sure to check out the CTRL-SHIFT+K, +L, +J keybaord shortcuts in Visual Studio Code
* for taking advance of the #regions in this file and our templates.
*
*/
// #endregion
// #endregion
// #endregion
// #region I N C L U D E S
const _log = require('mcode-log');
const _data = require('mcode-data');
const path = require('path');
const fs = require('fs').promises;
const Redis = require('redis');
const NodeCache = require('node-cache');
// #endregion
// #region C O N S T A N T S
// MicroCODE: define this module's name for our 'mcode-log' package
const MODULE_NAME = 'mcode-cache.js';
// #endregion
// #region C L A S S
/**
* @class cache Class to provide transparent data caching for MicroCODE applications.
*
*/
class cache
{
// #region C O N S T A N T S
static CACHE_TTL = 60 * 60 * 24; // 24 hours in seconds
static CLASS_TYPE = 'cache';
static REDIS_URL = 'redis://127.0.0.1:6379';
static REDIS_PORT = 6379;
static REDIS_USER = 'user';
static REDIS_PASSWORD = 'password';
// #endregion
// #region P R I V A T E F I E L D S
// node-cache instance
#cache = null;
#cacheTTL = cache.CACHE_TTL;
#cacheNamespace = '';
#cacheNamespaces = [];
// Redis instance
#redis = null;
#redisURL = cache.REDIS_URL;
#redisPort = cache.REDIS_PORT;
#redisUser = cache.REDIS_USER;
#redisPassword = cache.REDIS_PASSWORD;
#redisConnected = false;
#privateExample = 'PRIVATE PROPERTY';
// #endregion
// #region C O N S T R U C T O R
/**
* @constructor cache class constructor.
*/
constructor ()
{
// Create a Singleton instance
if (!cache.instance)
{
this.#cacheTTL = cache.CACHE_TTL;
this.#redisURL = `${cache.REDIS_URL}`;
this.#redisPort = `${cache.REDIS_PORT}`;
this.#redisUser = `${cache.REDIS_USER}`;
this.#redisPassword = `${cache.REDIS_PASSWORD}`;
this._cacheInit();
// add the default namespace as a node-cache namespace
this.addNamespace({name: 'MicroCODE', type: 'node'});
// make it current
this.#cacheNamespace = 'MicroCODE';
cache.instance = this;
}
_log.done(`mcode-cache initialized with namespace: ${this.#cacheNamespace}`, MODULE_NAME);
return cache.instance;
}
// #endregion
// #region E N U M E R A T I O N S
/**
* @enum namedEnum1 - a description of this enum, its use, and meaning. TEMPLATE.
*/
static namedEnum1 = Object.freeze
({
name1: 0,
name2: 1,
name3: 2,
name4: 3,
name5: 4,
name6: 5,
name7: 6
});
// #endregion
// #region P R O P E R T I E S
/**
* @property {number} cacheReady the cache instance and default namespace has=ve been established successfully.
*/
get cacheReady()
{
if (this.#redis)
{
return (this.#cache != null && this.#redisConnected);
}
else
{
return this.#cache != null;
}
}
/**
* @property {number} cacheTTL the cache Time-To-Live property, in seconds.
*/
get cacheTTL()
{
return this.#cacheTTL;
}
set cacheTTL(value)
{
this.#cacheTTL = value;
}
/**
* @property {array} cacheNamespaces returns an array containing all the namespaces defined in the cache server.
* The array contains objects with name, type (node or redis), enabled properties, and current statistics for each namespace.
*/
get cacheNamespaces()
{
// Update statistics for each namespace before returning
this._updateNamespaceStatistics();
return this.#cacheNamespaces;
}
/**
* @property {string} cacheNamespace the 'prefix' used to group our keys in the cache Server.
* This property switches to a new namespace, to be used for all subsequent cache operations as the default.
* The namespace must already exist in the cache servers 'namespace' list, see addNamespace().
*/
get cacheNamespace()
{
return this.#cacheNamespace;
}
set cacheNamespace(value)
{
this.#cacheNamespace = value;
_log.success(`Switched to namespace: '${this.#cacheNamespace}`, MODULE_NAME);
}
/**
* @property {string} redisURL the URL to the Redis Server.
*/
get redisURL()
{
return this.#redisURL;
}
set redisURL(value)
{
this.#redisURL = value;
}
/**
* @property {string} redisPort the PORT to the Redis Server.
*/
get redisPort()
{
return this.#redisPort;
}
set redisPort(value)
{
this.#redisPort = value;
}
/**
* @property {string} redisUser the User to the Redis Server.
*/
get redisUser()
{
return this.#redisUser;
}
set redisUser(value)
{
this.#redisUser = value;
}
/**
* @property {string} redisPassword the Password to the Redis Server.
*/
get redisPassword()
{
return this.#redisPassword;
}
set redisPassword(value)
{
this.#redisPassword = value;
}
/**
* @property {string} _privateExample an example of a private property.
*/
get _privateExample()
{
return this.#privateExample;
}
set _privateExample(value)
{
this.#privateExample = value;
}
// #endregion
// #region S Y M B O L S
/**
* iterator1 - a description of this iterator, its use, and meaning.
*/
[Symbol('iterator1')]()
{
// method with computed name (symbol here) TEMPLATE
}
// #endregion
// #region M E T H O D S – S T A T I C
/**
* static1() – description of public static method, called by prototype not object.
* This does not operate on a specific copy of a Class object.
* @api public
*
* @param {type} param1 description of param1.
* @returns {type} description of return value.
*
* @example
*
* cache.static1('param1');
*/
static static1(param1)
{
// ... TEMPLATE
return value;
}
// #endregion
// #region M E T H O D S – P U B L I C
/**
* @func addNamespace
* @memberof mcode.cache
* @desc Adds a new namespace to the cache server.
* @param {object} namespace the namespace and configuration to be added to the cache server.
* @api public
* @example
* const namespace = {name: 'MicroCODE', type: 'node', user: 'username', password: '...'};
*/
addNamespace(namespace)
{
// get the namespace name and type
if (!namespace || !namespace.name || !namespace.type)
{
_log.warn(`Invalid namespace: it must have a 'name' and 'type' defined.`, MODULE_NAME);
return;
}
// only allow 'node' or 'redis' cache types
if (namespace.type !== 'node' && namespace.type !== 'redis')
{
_log.warn(`Invalid cache type: ${namespace.type}, selected for namespace: ${namespace.name}, must be 'node' or 'redis'.`, MODULE_NAME);
return;
}
// When we add the 1st Redis namespace, initialize the Redis client
if (namespace.type === 'redis' && !this.#redis)
{
// if no Redis url is provided, use the default
if (!namespace.url)
{
namespace.url = this.#redisURL;
}
// if no port is provided, use the default
if (!namespace.port)
{
namespace.port = 6379;
}
// if no user is provided, use the default
if (!namespace.user)
{
namespace.user = null;
}
// if no password is provided, use the default
if (!namespace.password)
{
namespace.password = null;
}
this.#redisURL = `${namespace.url}`;
this.#redisPort = `${namespace.port}`;
this.#redisUser = `${namespace.user}`;
this.#redisPassword = `${namespace.password}`;
this._redisInit();
}
// add the namespace to the cache server
this.#cacheNamespaces.push({
name: namespace.name,
type: namespace.type,
enabled: true,
hits: 0, // Number of successful cache retrievals
misses: 0, // Number of failed cache retrievals (key not found/expired)
keys: 0, // Current number of keys in cache
ksize: 0, // Current key size in bytes
vsize: 0 // Current value size in bytes
});
_log.success(`Added namespace: '${namespace.name}`, MODULE_NAME);
}
/**
* @func cacheMakeKey
* @memberof mcode.cache
* @desc Converts a 'key source' into a cache Key by replacing slashes with colons and removing spaces.
* @param {string} keySource the path to the key to be converted.
* @returns {string} the cache Key.
* @api public
* @example
* const keyPath = 'components/app/tool/tool.template.htmx';
* returns 'GM-GPS-eMITS-UI:components:app:tool:tool.template.htmx';
*/
cacheMakeKey(keySource)
{
// convert the file path into a cache Key
let key = keySource.replace(/[\\/]/g, ':'); // Handle both forward and backward slashes
// remove spaces ' '
key = key.replace(/\s/g, ' ');
// remove double-dots '..'
key = key.replace(/\.\./g, '.');
// remove leading '.' and trailing '.'
key = key.replace(/^\.+|\.+$/g, '');
// remove leading and trailing colons
key = key.replace(/^:+|:+$/g, '');
// now, make it specific to the caller's namespace..
return `${this.cacheNamespace}:${key}`;
}
/**
* @function cacheGet
* @memberof mcode.cache
* @desc Caches the results of a callback function in cache under the current namespace and returns the key's value.
* @param {string} key the app key to get from the current namespace.
* @param {function} cb the callback function to get fresh value.
* @returns {Promise} the cached value.
*/
async cacheGet(key, cb = () => {return undefined;})
{
// make the auto-generated cache key for the 'key' - get from current namespace, add if not cached
const cacheKey = this.fileMakeKey(key);
// get the namespace info for the current namespace
const namespaceInfo = this._getNamespaceInfo(this.#cacheNamespace);
if (!namespaceInfo)
{
_log.warn(`Current namespace '${this.#cacheNamespace}' not found`, MODULE_NAME);
return cb();
}
// get the value from the cache associated with the current namespace
if (namespaceInfo.type === 'redis')
{
// use the Redis client
return await this.#redis.get(cacheKey);
}
return await this._cacheGet(cacheKey, cb);
}
/**
* @function cacheSet
* @memberof mcode.cache
* @desc Sets a key value in the cache.
* @param {string} key the app key to be set into current namespace.
* @param {string} value the value to be set in the cache.
* @returns {string} the value set in the cache.
*/
async cacheSet(key, value)
{
// make the auto-generated cache key for the 'key' - set into current namespace
const cacheKey = this.fileMakeKey(key);
// get the namespace info for the current namespace
const namespaceInfo = this._getNamespaceInfo(this.#cacheNamespace);
if (!namespaceInfo)
{
_log.warn(`Current namespace '${this.#cacheNamespace}' not found`, MODULE_NAME);
return;
}
// set the value in the cache associated with the current namespace
if (namespaceInfo.type === 'redis')
{
// use the Redis client
return await this.#redis.set(cacheKey, value);
}
return await this._cacheSet(cacheKey, value);
}
/**
* @func cacheDrop
* @memberof mcode.cache
* @desc Drops a key value from the cache based on the 'key' name.
* @param {string} key the app key to be droppped.
* @returns {number} the number of keys deleted from the cache.
* @api public
* @example
* const count = await mcode.cacheDrop(keyName);
*/
async cacheDrop(key)
{
// make the auto-generated cache key for the 'key' - drop from current namespace
const cacheKey = this.fileMakeKey(key);
// get the namespace info for the current namespace
const namespaceInfo = this._getNamespaceInfo(this.#cacheNamespace);
if (!namespaceInfo)
{
_log.warn(`Current namespace '${this.#cacheNamespace}' not found`, MODULE_NAME);
return 0;
}
// delete the value from the cache associated with the current namespace
if (namespaceInfo.type === 'redis')
{
// use the Redis client
return await this._redisDrop(cacheKey);
}
return await this._cacheDrop(cacheKey);
}
/**
* @func cacheDropAll
* @memberof mcode.cache
* @desc Drops all keys from the cache based on the App's namespace.
* @param {string} cache the cache to drop all keys from.
* @param {string} namespace the namespace to drop all keys from.
* @param {string} pattern the key pattern to drop all keys from.
* @returns {number} the number of keys deleted from the cache.
* @api public
* @example
* const result = await mcode.cacheDropAll();
* const result = await mcode.cacheDropAll({cache: 'redis', namespace: 'GM-GPS-eMITS-DB', pattern: '*'});
*/
async cacheDropAll({cache = '*', namespace = '*', pattern = '*'})
{
let result = 0;
for (const namespaceInfo of this.#cacheNamespaces)
{
if (namespaceInfo.name === namespace || namespace === '*')
{
if (namespaceInfo.type === 'node' && (cache === 'node' || cache === '*'))
{
// Get keys from the Node cache
const nodeKeys = await this._cacheKeys(`${namespaceInfo.name}:${pattern}`);
result += nodeKeys.length;
// Delete all keys from the Node cache
await Promise.all(nodeKeys.map(key => this.#cache.del(key)));
}
if (namespaceInfo.type === 'redis' && (cache === 'redis' || cache === '*'))
{
// Get keys from the Redis client
const redisKeys = await this.#redis.keys(`${namespaceInfo.name}:${pattern}`);
result += redisKeys.length;
// Delete all keys from the Redis cache
await Promise.all(redisKeys.map(key => this.#redis.del(key)));
}
}
}
// Return the total number of keys deleted
return result;
}
/**
* @func cacheListAll
* @memberof mcode.cache
* @desc Lists all keys from the cache based on the App's namespace.
* Includes timeout protection to prevent hanging on non-responsive caches (especially Redis).
* Provides graceful degradation - continues processing other namespaces if one fails.
* @param {string} cache the cache to list all keys from.
* @param {string} namespace the namespace to list all keys from.
* @param {string} pattern the key pattern to list all keys from.
* @param {boolean} includeErrors whether to include error information in the response.
* @returns {Array|Object} returns an array of keys, or an object with keys and errors if includeErrors=true.
* @api public
* @example
* const result = await mcode.cacheListAll();
* const result = await mcode.cacheListAll({cache: 'node', namespace: '*', pattern: '*'});
* const {keys, errors} = await mcode.cacheListAll({includeErrors: true});
*/
async cacheListAll({cache = '*', namespace = '*', pattern = '*', includeErrors = false})
{
let keys = [];
let errors = [];
let processedNamespaces = 0;
let failedNamespaces = 0;
_log.info(`Starting cacheListAll for cache: ${cache}, namespace: ${namespace}, pattern: ${pattern}`, MODULE_NAME);
for (const namespaceInfo of this.#cacheNamespaces)
{
if (namespaceInfo.name === namespace || namespace === '*')
{
if (namespaceInfo.type === cache || cache === '*')
{
processedNamespaces++;
_log.debug(`Processing namespace: ${namespaceInfo.name} (${namespaceInfo.type})`, MODULE_NAME);
try
{
let cacheKeys = [];
const startTime = Date.now();
// Get keys from the appropriate cache type with timeout protection
if (namespaceInfo.type === 'node')
{
// use the Node cache - NOTE: node-cache.keys() does not support wildcards
cacheKeys = await this._cacheKeys(`${namespaceInfo.name}:${pattern}`);
}
else if (namespaceInfo.type === 'redis')
{
// Check if Redis is connected before attempting operation
if (!this.#redisConnected)
{
throw new Error('Redis not connected');
}
// use the Redis client with timeout protection
const redisKeysPromise = this.#redis.keys(`${namespaceInfo.name}:${pattern}`);
cacheKeys = await this._withTimeout(redisKeysPromise, 5000, `Redis keys operation for ${namespaceInfo.name}`);
}
const keysTime = Date.now() - startTime;
_log.debug(`Retrieved ${cacheKeys.length} keys from ${namespaceInfo.name} in ${keysTime}ms`, MODULE_NAME);
// Process the keys using common logic with timeout protection
const listKeysPromise = this._listKeys(cacheKeys, namespaceInfo.name, namespaceInfo.type);
const keyList = await this._withTimeout(listKeysPromise, 10000, `Cache list processing for ${namespaceInfo.name}`);
keys = keys.concat(keyList);
const totalTime = Date.now() - startTime;
_log.debug(`Successfully processed ${keyList.length} keys from namespace ${namespaceInfo.name} in ${totalTime}ms`, MODULE_NAME);
}
catch (exp)
{
failedNamespaces++;
const errorInfo = {
namespace: namespaceInfo.name,
type: namespaceInfo.type,
error: exp.message,
timestamp: new Date().toISOString()
};
errors.push(errorInfo);
_log.warn(`Failed to get keys for namespace '${namespaceInfo.name}' (${namespaceInfo.type}): ${exp.message}`, MODULE_NAME);
// Add a placeholder entry to indicate this namespace had issues
if (includeErrors)
{
keys.push({
namespace: namespaceInfo.name,
key: '<ERROR>',
cache: namespaceInfo.type,
type: 'error',
preview: `Failed to retrieve keys: ${exp.message}`,
error: true,
errorDetails: errorInfo
});
}
// Continue with other namespaces instead of failing completely
}
}
}
}
const summary = `Processed ${processedNamespaces} namespaces, ${failedNamespaces} failed, returned ${keys.length} keys`;
_log.info(`cacheListAll completed: ${summary}`, MODULE_NAME);
// Return keys with optional error information
if (includeErrors)
{
return {
keys: keys,
errors: errors,
summary: {
totalNamespaces: processedNamespaces,
failedNamespaces: failedNamespaces,
successfulNamespaces: processedNamespaces - failedNamespaces,
totalKeys: keys.filter(k => !k.error).length,
errorKeys: keys.filter(k => k.error).length
}
};
}
return keys;
}
/**
* @func cacheOn
* @memberof mcode.cache
* @desc Turns ON caching for a specific namespace.
* @param {string} cacheName the name of the cache namespace to enable.
* @return {boolean} true if the namespace was found and enabled, false otherwise.
* @api public
*/
async cacheOn(cacheName)
{
const namespace = this.#cacheNamespaces.find(ns => ns.name === cacheName);
if (namespace)
{
namespace.enabled = true;
_log.success(`Enabled caching for namespace: ${cacheName}`, MODULE_NAME);
return true;
}
else
{
_log.warn(`Namespace '${cacheName}' not found`, MODULE_NAME);
return false;
}
}
/**
* @func cacheOff
* @memberof mcode.cache
* @desc Turns OFF caching for a specific namespace.
* @param {string} cacheName the name of the cache namespace to disable.
* @return {boolean} true if the namespace was found and disabled, false otherwise.
* @api public
*/
async cacheOff(cacheName)
{
const namespace = this.#cacheNamespaces.find(ns => ns.name === cacheName);
if (namespace)
{
namespace.enabled = false;
_log.success(`Disabled caching for namespace: ${cacheName}`, MODULE_NAME);
// Drop all keys from this specific namespace
this.cacheDropAll({cache: namespace.type, namespace: cacheName, pattern: '*'});
return true;
}
else
{
_log.warn(`Namespace '${cacheName}' not found`, MODULE_NAME);
return false;
}
}
/**
* @func cacheEnabled
* @memberof mcode.cache
* @desc Checks if caching is enabled for a specific namespace.
* @param {string} cacheName the name of the cache namespace to check.
* @returns {boolean} true if caching is enabled for the namespace, false otherwise.
* @api public
* @example
* const isEnabled = mcode.cacheEnabled('MicroCODE');
*/
cacheEnabled(cacheName)
{
const namespace = this.#cacheNamespaces.find(ns => ns.name === cacheName);
if (namespace)
{
return namespace.enabled;
}
else
{
_log.warn(`Namespace '${cacheName}' not found`, MODULE_NAME);
return false;
}
}
/**
* @func refreshCacheStatistics
* @memberof mcode.cache
* @desc Refreshes cache statistics for all Redis namespaces (async operation).
* @returns {Promise} Promise that resolves when statistics are updated.
* @api public
* @example
* await mcode.refreshCacheStatistics();
*/
async refreshCacheStatistics()
{
for (const namespace of this.#cacheNamespaces)
{
if (namespace.type === 'redis' && this.#redis && this.#redisConnected)
{
try
{
// Get keys for this specific namespace from Redis
const namespaceKeys = await this.#redis.keys(`${namespace.name}:*`);
namespace.keys = namespaceKeys.length;
// Calculate sizes for this namespace
let ksize = 0;
let vsize = 0;
for (const key of namespaceKeys)
{
ksize += Buffer.byteLength(key, 'utf8');
try
{
const value = await this.#redis.get(key);
if (value !== null)
{
vsize += Buffer.byteLength(value, 'utf8');
}
}
catch (error)
{
// Skip if key is not accessible
}
}
namespace.ksize = ksize;
namespace.vsize = vsize;
}
catch (error)
{
_log.warn(`Could not refresh statistics for Redis namespace '${namespace.name}'`, MODULE_NAME);
}
}
}
}
/**
* @func cacheClose
* @memberof mcode.cache
* @desc Closes the cache connection.
* @returns {status} the cache client connection.
* @api public
* @example
* const result = await mcode.cacheClose();
*/
async cacheClose()
{
if (this.#cache)
{
// Close the node-cache instance properly
this.#cache.close();
this.#cache = null;
}
if (this.#redis)
{
await this.#redis.quit();
this.#redis = null;
this.#redisConnected = false;
}
}
/**
* @func fileRead
* @memberof mcode
* @desc Reads a file from 'path' and caches its for future reference. The cache 'key' generated
* is based on the 'path' and the server's base URL (which is removed from the 'key' before caching).
* @api public
* @param {string} filePath a standard file system reference to the file to be read,
* @param {string} fileEncoding the encoding of the file to be read (default is 'utf8').
*
* NOTE: 'filePath' is reduced to the unique sub-folder path to the file being read on the server.
* Explicit paths to files outside the server's root directory are supported with
* the 'complete path' parameter becoming the unique key for the file.
*
* @returns {string} the contents of the file read from 'path'.
*
* @example
* const filePath = './data.json';
* const fileData = mcode.fileRead(path.join(__dirname, filePath);
*
* filePath: "D:\MicroCODE\GM-GPS-eMITS-UI\Source\backend\components\app\tool\tool.template.htmx",
* rootDir: "D:\MicroCODE\GM-GPS-eMITS-UI\Source\backend",
* keyPath: "\components\app\tool\tool.template.htmx",
* key: "GM-GPS-eMITS-UI:components:app:tool:tool.template.htmx"
*
* The 1st time 'mcode.fileRead()' is called, the file is read from disk and cached.
* The 2nd time 'mcode.fileRead()' is called, the file is read from the cache.
* The 'key' used to cache the file is based on the 'path' and the server's base URL
* and does not need to be provided by the caller, nor stored by the caller, it is transparent.
*
*/
async fileRead(filePath, fileEncoding = 'utf8')
{
try
{
// make the auto-generated cache key for the file
const cacheKey = this.fileMakeKey(filePath);
return this._cacheGet(cacheKey, async () =>
{
try
{
// Check if the file exists and is accessible
await fs.access(filePath, fs.constants.R_OK);
}
catch (exp)
{
_log.exp(`File is NOT READ accessible: ${filePath}`, MODULE_NAME, exp);
throw new Error(`File READ access error: ${filePath}`);
}
return await fs.readFile(filePath, fileEncoding);
});
}
catch (exp)
{
_log.exp(`Exception reading from disk for cache, file: ${filePath}`, MODULE_NAME, exp);
return null;
}
}
/**
* @func fileWrite
* @memberof mcode.cache
* @desc Writes 'fileData' to 'filePath' and caches it in the cache.
* @param {string} filePath a standard file system reference to the file to be read.
* @param {string} fileData the data to be written to the file.
* @param {string} fileEncoding the encoding of the file to be written (default is 'utf8').
* @returns {Promise} the file data written to disk.
*/
async fileWrite(filePath, fileData, fileEncoding = 'utf8')
{
try
{
// make the auto-generated cache key for the file
const cacheKey = this.fileMakeKey(filePath);
// the cached value is no longer valid, so drop it
this.cacheDrop(cacheKey);
// cache the new value
this._cacheSet(cacheKey, fileData);
try
{
// Check if the file exists and is accessible
await fs.access(filePath, fs.constants.W_OK);
}
catch (exp)
{
_log.exp(`File is NOT WRITE accessible: ${filePath}`, MODULE_NAME, exp);
throw new Error(`File WRITE access error: ${filePath}`);
}
// write the file to disk
return await fs.writeFile(filePath, fileData, {encoding: fileEncoding});
}
catch (exp)
{
_log.exp(`Exception writing to disk and cache, file: ${filePath}`, MODULE_NAME, exp);
return null;