-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathCacheManager.cls
More file actions
600 lines (508 loc) · 23.2 KB
/
CacheManager.cls
File metadata and controls
600 lines (508 loc) · 23.2 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
//---------------------------------------------------------------------------------------------------//
// This file is part of the Nebula Cache Manager project, released under the MIT License. //
// See LICENSE file or go to https://github.com/jongpie/NebulaCacheManager for full license details. //
//---------------------------------------------------------------------------------------------------//
@SuppressWarnings('PMD.ApexDoc, PMD.AvoidDebugStatements, PMD.AvoidGlobalModifier, PMD.ExcessivePublicCount, PMD.PropertyNamingConventions, PMD.CognitiveComplexity')
global without sharing class CacheManager {
@TestVisible
private static final Map<String, Cacheable> CONFIGURATION_DEVELOPER_NAME_TO_CACHEABLE_INSTANCE = new Map<String, Cacheable>();
@TestVisible
private static final String CURRENT_VERSION_NUMBER = 'v1.0.3';
@TestVisible
private static final String PLATFORM_CACHE_NULL_VALUE = '<{(CACHE_VALUE_IS_NULL)}>'; // Presumably, no one will ever use this as an actual value
// Load predefined cache values from "Cache Value" custom metadata. They will be always available in cache.
@TestVisible
private static final List<CacheValue__mdt> CONFIGURED_CACHE_VALUES = Schema.CacheValue__mdt.getAll().values();
// Load partitions configurations from "Cache Configuration" custom metadata.
@TestVisible
private static final CacheConfiguration__mdt ORGANIZATION_CACHE_CONFIGURATION = Schema.CacheConfiguration__mdt.getInstance('Organization').clone();
@TestVisible
private static final CacheConfiguration__mdt SESSION_CACHE_CONFIGURATION = Schema.CacheConfiguration__mdt.getInstance('Session').clone();
@TestVisible
private static final CacheConfiguration__mdt TRANSACTION_CACHE_CONFIGURATION = Schema.CacheConfiguration__mdt.getInstance('Transaction').clone();
private static Map<PlatformCachePartitionType, PlatformCachePartitionProxy> cacheTypeToMockPartitionProxy = new Map<PlatformCachePartitionType, PlatformCachePartitionProxy>();
private static final System.Pattern ALPHANUMERIC_REGEX_PATTERN {
get {
if (ALPHANUMERIC_REGEX_PATTERN == null) {
ALPHANUMERIC_REGEX_PATTERN = System.Pattern.compile('^[a-zA-Z0-9]+$');
}
return ALPHANUMERIC_REGEX_PATTERN;
}
private set;
}
static {
System.debug(System.LoggingLevel.INFO, 'Nebula Cache Manager - Version Number: ' + CURRENT_VERSION_NUMBER);
}
@TestVisible
private enum PlatformCachePartitionType {
ORGANIZATION,
SESSION
}
/**
* @description Interface used to define caches that can be used to store values via different mechanisms
*/
global interface Cacheable {
/**
* @description Indicates if the specified key has already been added to the cache
* @param key The `String` key to check for within the cache
* @return The `Boolean` result that indicates if the specified key is contained in the cache
*/
Boolean contains(String key);
/**
* @description Indicates if the specified keys have already been added to the cache
* @param keys The Set of `String` keys to check for within the cache
* @return The `Map<String, Boolean>` result that indicates if the specified key is contained in the cache
*/
Map<String, Boolean> contains(Set<String> keys);
/**
* @description Indicates if the specified keys have already been added to the cache
* @param keys The Set of `String` keys to check for within the cache
* @return The `Boolean` result that indicates if all given keys are contained in the cache
*/
Boolean containsAll(Set<String> keys);
/**
* @description Returns the cached value for the specified key, or `null` if the specified key does not exist in the cache
* @param key The `String` key to check for within the cache
* @return The `Object` cached value, or `null` if no cached value is found for the specified key
*/
Object get(String key);
/**
* @description Returns the cached value for the specified key, or `null` if the specified key does not exist in the cache
* @param key The `String` key to check for within the cache
* @param cacheBuilderClass Instance of cacheBuilderClass
* @return The cached value, or `null` if no cached value is found for the specified key
*/
Object get(String key, System.Type cacheBuilderClass);
/**
* @description Returns the cached values for the specified keys, or `null` if the specified key does not exist in the cache
* @param keys The Set of `String` keys to check for within the cache
* @return The `Map<String, Object>` with cached value, or `null` if no cached value is found for the specified key
*/
Map<String, Object> get(Set<String> keys);
/**
* @description Returns all cached values
* @return The `Map<String, Object>` with all cached values
*/
Map<String, Object> getAll();
/**
* @description Returns all Keys stored in cache.
* @return `Set<String>` with all keys of cache entries.
*/
Set<String> getKeys();
/**
* @description Check if cache is Available for use (enabled and configured)
* @return `Boolean`
*/
Boolean isAvailable();
/**
* @description Check if cache was configured in Custom Metadata as Enabled.
* @return `Boolean`
*/
Boolean isEnabled();
/**
* @description Check if cache was configured in Custom Metadata as Immutable.
* @return `Boolean`
*/
Boolean isImmutable();
/**
* @description Adds the provided `Object` value to the cache, using the specified `String` key
* @param key The `String` key to add to the cache
* @param value The `Object` value to cache for the specified key
*/
void put(String key, Object value);
/**
* @description Adds the provided `Object` values to the cache, using the specified `String` keys.
* @param keyToValue The Map of `String` keys to add to the cache with the `Object` values for that keys.
*/
void put(Map<String, Object> keyToValue);
/**
* @description Removes the specified `String` key from the cache
* @param key The `String` key to remove from the cache
*/
void remove(String key);
/**
* @description Removes the specified Set of `String` keys from the cache
* @param keys The Set of `String` keys to remove from the cache
*/
void remove(Set<String> keys);
/**
* @description Removes all keys from cache. Clear cache.
*/
void removeAll();
}
/**
* @description The instance of `Cacheable` used for any organization-specific caching via Platform Cache.
* When Platform Cache is disabled or not available, the transaction cache is instead used.
* @return The singleton instance of `Cacheable`
*/
global static Cacheable getOrganizationCache() {
return getOrganizationCache(ORGANIZATION_CACHE_CONFIGURATION);
}
/**
* @description The instance of `Cacheable` used for any organization-specific caching via Platform Cache.
* When Platform Cache is disabled or not available, the transaction cache is instead used.
* @param configuration Configuration stored in Custom Metadata record for Organization Cache
* @return The singleton instance of `Cacheable`
*/
global static Cacheable getOrganizationCache(CacheConfiguration__mdt configuration) {
return getPlatformCache(configuration, PlatformCachePartitionType.ORGANIZATION);
}
/**
* @description The instance of `Cacheable` used for any session-specific caching via Platform Cache.
* When Platform Cache is disabled or not available, the transaction cache is instead used.
* @return The singleton instance of `Cacheable`
*/
global static Cacheable getSessionCache() {
return getSessionCache(SESSION_CACHE_CONFIGURATION);
}
/**
* @description The instance of `Cacheable` used for any organization-specific caching via Platform Cache.
* When Platform Cache is disabled or not available, the transaction cache is instead used.
* @param configuration Configuration stored in Custom Metadata record for Session Cache
* @return The singleton instance of `Cacheable`
*/
global static Cacheable getSessionCache(CacheConfiguration__mdt configuration) {
return getPlatformCache(configuration, PlatformCachePartitionType.SESSION);
}
/**
* @description The instance of `Cacheable` used for any transaction-specific caching.
* Cached data is stored internally in-memory for the duration of the transaction.
* @return The singleton instance of `Cacheable`
*/
global static Cacheable getTransactionCache() {
if (CONFIGURATION_DEVELOPER_NAME_TO_CACHEABLE_INSTANCE.containsKey(TRANSACTION_CACHE_CONFIGURATION.DeveloperName)) {
return CONFIGURATION_DEVELOPER_NAME_TO_CACHEABLE_INSTANCE.get(TRANSACTION_CACHE_CONFIGURATION.DeveloperName);
}
TransactionCache transactionCacheInstance = new TransactionCache(TRANSACTION_CACHE_CONFIGURATION);
CONFIGURATION_DEVELOPER_NAME_TO_CACHEABLE_INSTANCE.put(TRANSACTION_CACHE_CONFIGURATION.DeveloperName, transactionCacheInstance);
return transactionCacheInstance;
}
@TestVisible
private static void setMockPartitionProxy(PlatformCachePartitionType cacheType, PlatformCachePartitionProxy mockPartitionProxy) {
cacheTypeToMockPartitionProxy.put(cacheType, mockPartitionProxy);
}
/**
* @description Validate if given key is alphanumeric without any special characters. Allowed characters a-z A-Z 0-9
* @param key String to be checked.
* @exception Exception is thrown if key contains not allowed characters.
*/
@TestVisible
private static void validateKey(String key) {
Matcher regexMatcher = ALPHANUMERIC_REGEX_PATTERN.matcher(key);
if (regexMatcher.matches() == false) {
throw new IllegalArgumentException('Key must be alphanumeric, received key: ' + key);
}
}
private static Cacheable getPlatformCache(CacheConfiguration__mdt configuration, PlatformCachePartitionType cacheType) {
if (CONFIGURATION_DEVELOPER_NAME_TO_CACHEABLE_INSTANCE.containsKey(configuration.DeveloperName)) {
return CONFIGURATION_DEVELOPER_NAME_TO_CACHEABLE_INSTANCE.get(configuration.DeveloperName);
}
PlatformCachePartitionProxy partitionProxy = new PlatformCachePartitionProxy(cacheType, configuration.PlatformCachePartitionName__c);
if (cacheTypeToMockPartitionProxy.containsKey(cacheType)) {
partitionProxy = cacheTypeToMockPartitionProxy.get(cacheType);
}
CacheConfiguration__mdt localTransactionCacheConfiguration = new CacheConfiguration__mdt(
IsEnabled__c = true,
IsImmutable__c = configuration.IsImmutable__c
);
PlatformCache platformCache = new PlatformCache(configuration, new TransactionCache(localTransactionCacheConfiguration), partitionProxy);
CONFIGURATION_DEVELOPER_NAME_TO_CACHEABLE_INSTANCE.put(configuration.DeveloperName, platformCache);
return platformCache;
}
/**
* @description Check if given cache type is enabled and load permanent cache values from "Cache Value" custom metadata.
* Values are loaded for given type of Cache and only if they are enabled.
* @param cacheConfiguration Custom Metadata record
* @return `Map<String, Object>` Map of key to cache value.
*/
private static Map<String, Object> loadConfiguredCacheValues(CacheConfiguration__mdt cacheConfiguration) {
Map<String, Object> keyToCacheValue = new Map<String, Object>();
if (cacheConfiguration.IsEnabled__c == false) {
return keyToCacheValue;
}
for (CacheValue__mdt configuredCacheValue : CONFIGURED_CACHE_VALUES) {
if (configuredCacheValue.Cache__c == cacheConfiguration.Id && configuredCacheValue.IsEnabled__c == true) {
System.Type dataType = System.Type.forName(configuredCacheValue.DataType__c);
Boolean isString = configuredCacheValue.DataType__c == String.class.getName();
Object castedValue = isString ? configuredCacheValue.Value__c : System.JSON.deserialize(configuredCacheValue.Value__c, dataType);
keyToCacheValue.put(configuredCacheValue.Key__c, castedValue);
}
}
return keyToCacheValue;
}
/**
* @description Manages interacting with platform cache. The provided transaction cache instance is used internally as the primary
* caching method, and is further augmented by using Platform Cache to provide caching that spans multiple transactions.
*/
@SuppressWarnings('PMD.CognitiveComplexity, PMD.CyclomaticComplexity')
private class PlatformCache implements Cacheable {
private final PlatformCachePartitionProxy cachePartitionProxy;
private final CacheConfiguration__mdt configuration;
private final TransactionCache fallbackTransactionCache;
private PlatformCache(CacheConfiguration__mdt configuration, transactionCache transactionCache, PlatformCachePartitionProxy cachePartitionProxy) {
this.configuration = configuration;
this.fallbackTransactionCache = transactionCache;
this.cachePartitionProxy = cachePartitionProxy;
this.put(loadConfiguredCacheValues(this.configuration));
}
public Boolean contains(String key) {
if (this.configuration.IsEnabled__c == false || this.fallbackTransactionCache.contains(key) == true || this.cachePartitionProxy.isAvailable() == false) {
return this.fallbackTransactionCache.contains(key);
} else {
return this.cachePartitionProxy.contains(key);
}
}
public Map<String, Boolean> contains(Set<String> keys) {
Map<String, Boolean> keyToContainsResult = this.cachePartitionProxy.contains(keys);
keyToContainsResult.putAll(this.fallbackTransactionCache.contains(keys));
return keyToContainsResult;
}
public Boolean containsAll(Set<String> keys) {
Map<String, Boolean> keyToContainsResult = this.contains(keys);
if (keyToContainsResult.isEmpty() == true) {
return false;
}
for (String key : keyToContainsResult.keySet()) {
Boolean containsKey = keyToContainsResult.get(key);
if (containsKey == false) {
return false;
}
}
return true;
}
public Object get(String key) {
if (this.fallbackTransactionCache.contains(key) || this.cachePartitionProxy.isAvailable() == false) {
return this.fallbackTransactionCache.get(key);
} else {
Object value = this.cachePartitionProxy.get(key);
// Platform cache does not support storing null values, so a predefined value is used as a substitute
if (value == PLATFORM_CACHE_NULL_VALUE) {
value = null;
}
this.fallbackTransactionCache.put(key, value);
return value;
}
}
public Object get(String key, System.Type cacheBuilderClass) {
if (this.fallbackTransactionCache.contains(key)) {
return this.fallbackTransactionCache.get(key);
} else if (this.cachePartitionProxy.isAvailable() == false) {
return this.fallbackTransactionCache.get(key, cacheBuilderClass);
} else {
// Cache.CacheBuilder.doLoad method can return null
Object value = this.cachePartitionProxy.get(key, cacheBuilderClass);
this.fallbackTransactionCache.put(key, value);
return value;
}
}
public Map<String, Object> get(Set<String> keys) {
Map<String, Object> keyToValue = this.cachePartitionProxy.get(keys);
if (keyToValue == null) {
keyToValue = new Map<String, Object>();
}
keyToValue.putAll(this.fallbackTransactionCache.get(keys));
return keyToValue;
}
public Map<String, Object> getAll() {
return this.get(this.getKeys());
}
public Set<String> getKeys() {
Set<String> keys = this.cachePartitionProxy.getKeys();
if (keys == null) {
keys = new Set<String>();
}
keys.addAll(this.fallbackTransactionCache.getKeys());
return keys;
}
public Boolean isAvailable() {
return this.isEnabled() && this.cachePartitionProxy.isAvailable() == true;
}
public Boolean isEnabled() {
return this.configuration?.IsEnabled__c == true;
}
public Boolean isImmutable() {
return this.configuration?.IsImmutable__c == true;
}
public void put(String key, Object value) {
if (this.isEnabled() == false) {
return;
}
validateKey(key);
this.fallbackTransactionCache.put(key, value);
if (this.isAvailable() == true && this.isImmutable() == false || this.contains(key) == false) {
// Platform cache does not support storing null values, so a predefined value is used as a substitute
if (value == null) {
value = PLATFORM_CACHE_NULL_VALUE;
}
Cache.Visibility visibility = Cache.Visibility.valueOf(this.configuration.PlatformCacheVisibility__c.toUpperCase());
this.cachePartitionProxy.put(key, value, this.configuration.PlatformCacheTimeToLive__c.intValue(), visibility, this.configuration.IsImmutable__c);
}
}
public void put(Map<String, Object> keyToValue) {
for (String key : keyToValue.keySet()) {
this.put(key, keyToValue.get(key));
}
}
public void remove(String key) {
if (this.isImmutable() == true) {
return;
}
this.fallbackTransactionCache.remove(key);
if (this.isAvailable() == true) {
this.cachePartitionProxy.remove(key);
}
}
public void remove(Set<String> keys) {
for (String key : keys) {
this.remove(key);
}
}
public void removeAll() {
for (String key : this.getKeys()) {
this.remove(key);
}
}
}
@TestVisible
private virtual class PlatformCachePartitionProxy {
private final Cache.Partition platformCachePartition;
@SuppressWarnings('PMD.EmptyCatchBlock')
protected PlatformCachePartitionProxy(PlatformCachePartitionType cacheType, String partitionName) {
// If the specified partition name is not found, the platform automatically throws a runtime exception, which isn't ideal.
// It seems better to eat the exceptions & fallback to the transaction cache (which doesn't rely on Platform Cache).
try {
switch on cacheType {
when ORGANIZATION {
this.platformCachePartition = Cache.Org.getPartition(partitionName);
}
when SESSION {
this.platformCachePartition = Cache.Session.getPartition(partitionName);
}
}
} catch (Cache.Org.OrgCacheException orgCacheException) {
System.Debug(LoggingLevel.WARN, '@#@ ⚠️ Organization Cache partition named ' + partitionName + ' not found.');
// No-op if the partition can't be found - the rest of the code will fallback to using the transaction cache
} catch (Cache.Session.SessionCacheException sessionCacheException) {
System.Debug(LoggingLevel.WARN, '@#@ ⚠️ Session Cache partition named ' + partitionName + ' not found.');
// No-op if the partition can't be found - the rest of the code will fallback to using the transaction cache
}
}
public virtual Boolean contains(String key) {
return this.platformCachePartition?.contains(key) == true;
}
public Map<String, Boolean> contains(Set<String> keys) {
Map<String, Boolean> keyToContainsResult = this.platformCachePartition?.contains(keys);
if (keyToContainsResult == null) {
keyToContainsResult = new Map<String, Boolean>();
}
if (keyToContainsResult.isEmpty() == true) {
for (String key : keys) {
keyToContainsResult.put(key, false);
}
}
return keyToContainsResult;
}
public virtual Object get(String key) {
return this.platformCachePartition?.get(key);
}
public virtual Object get(String key, System.Type cacheBuilderClass) {
return this.platformCachePartition?.get(cacheBuilderClass, key);
}
public virtual Map<String, Object> get(Set<String> keys) {
return this.platformCachePartition?.get(keys);
}
public virtual Set<String> getKeys() {
return this.platformCachePartition?.getKeys();
}
public virtual Boolean isAvailable() {
return this.platformCachePartition?.isAvailable() == true;
}
@SuppressWarnings('PMD.ExcessiveParameterList')
public virtual void put(String key, Object value, Integer cacheTtlSeconds, Cache.Visibility cacheVisiblity, Boolean isCacheImmutable) {
this.platformCachePartition?.put(key, value, cacheTtlSeconds, cacheVisiblity, isCacheImmutable);
}
public virtual void remove(String key) {
this.platformCachePartition?.remove(key);
}
}
private class TransactionCache implements Cacheable {
private final CacheConfiguration__mdt configuration;
private final Map<String, Object> keyToValue = new Map<String, Object>();
private TransactionCache(CacheConfiguration__mdt configuration) {
this.configuration = configuration;
this.put(loadConfiguredCacheValues(this.configuration));
}
public Boolean contains(String key) {
return this.keyToValue.containsKey(key);
}
public Map<String, Boolean> contains(Set<String> keys) {
Map<String, Boolean> keyToContainsResult = new Map<String, Boolean>();
for (String key : keys) {
keyToContainsResult.put(key, this.contains(key));
}
return keyToContainsResult;
}
public Boolean containsAll(Set<String> keys) {
return this.keyToValue.keySet().containsAll(keys);
}
public Object get(String key) {
return this.keyToValue.get(key);
}
public Object get(String key, System.Type cacheBuilderClass) {
if (this.contains(key) == false) {
Cache.CacheBuilder cacheBuilder = (Cache.CacheBuilder) cacheBuilderClass.newInstance();
Object value = cacheBuilder.doLoad(key);
this.put(key, value);
}
return this.get(key);
}
public Map<String, Object> get(Set<String> keys) {
Map<String, Object> matchingKeyToValue = new Map<String, Object>();
for (String key : keys) {
matchingKeyToValue.put(key, this.get(key));
}
return matchingKeyToValue;
}
public Map<String, Object> getAll() {
return this.keyToValue.clone();
}
public Set<String> getKeys() {
return this.keyToValue.keySet();
}
public Boolean isAvailable() {
return this.isEnabled() == true;
}
public Boolean isEnabled() {
return this.configuration?.IsEnabled__c == true;
}
public Boolean isImmutable() {
return this.configuration?.IsImmutable__c == true;
}
public void put(String key, Object value) {
if (this.isEnabled() == true || (this.isImmutable() == false || this.contains(key) == false)) {
validateKey(key);
this.keyToValue.put(key, value);
}
}
public void put(Map<String, Object> keyToValue) {
for (String key : keyToValue.keySet()) {
this.put(key, keyToValue.get(key));
}
}
public void remove(String key) {
if (this.isEnabled() == true && this.isImmutable() == false) {
this.keyToValue.remove(key);
}
}
public void remove(Set<String> keys) {
for (String key : keys) {
this.remove(key);
}
}
public void removeAll() {
if (this.isEnabled() == true && this.isImmutable() == false) {
this.keyToValue.clear();
}
}
}
}