@umituz/react-native-design-system 2.8.7 → 2.8.8

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 (128) hide show
  1. package/package.json +5 -6
  2. package/src/device/infrastructure/repositories/LegacyDeviceIdRepository.ts +1 -1
  3. package/src/device/infrastructure/services/DeviceFeatureService.ts +1 -1
  4. package/src/exception/infrastructure/services/ExceptionLogger.ts +1 -1
  5. package/src/exception/infrastructure/storage/ExceptionStore.ts +1 -1
  6. package/src/exports/filesystem.ts +1 -0
  7. package/src/exports/storage.ts +1 -0
  8. package/src/filesystem/domain/constants/FileConstants.ts +20 -0
  9. package/src/filesystem/domain/entities/File.ts +20 -0
  10. package/src/filesystem/domain/types/FileTypes.ts +43 -0
  11. package/src/filesystem/domain/utils/FileUtils.ts +86 -0
  12. package/src/filesystem/index.ts +23 -0
  13. package/src/filesystem/infrastructure/services/FileSystemService.ts +45 -0
  14. package/src/filesystem/infrastructure/services/cache.service.ts +48 -0
  15. package/src/filesystem/infrastructure/services/directory.service.ts +66 -0
  16. package/src/filesystem/infrastructure/services/download.constants.ts +6 -0
  17. package/src/filesystem/infrastructure/services/download.service.ts +74 -0
  18. package/src/filesystem/infrastructure/services/download.types.ts +7 -0
  19. package/src/filesystem/infrastructure/services/encoding.service.ts +25 -0
  20. package/src/filesystem/infrastructure/services/file-info.service.ts +52 -0
  21. package/src/filesystem/infrastructure/services/file-manager.service.ts +81 -0
  22. package/src/filesystem/infrastructure/services/file-path.service.ts +22 -0
  23. package/src/filesystem/infrastructure/services/file-reader.service.ts +52 -0
  24. package/src/filesystem/infrastructure/services/file-writer.service.ts +32 -0
  25. package/src/filesystem/infrastructure/utils/blob.utils.ts +20 -0
  26. package/src/image/infrastructure/services/ImageStorageService.ts +1 -1
  27. package/src/index.ts +9 -0
  28. package/src/molecules/alerts/AlertStore.ts +1 -1
  29. package/src/molecules/calendar/infrastructure/storage/EventActions.ts +1 -1
  30. package/src/molecules/calendar/infrastructure/stores/storageAdapter.ts +1 -1
  31. package/src/offline/infrastructure/storage/OfflineStore.ts +1 -1
  32. package/src/onboarding/infrastructure/storage/OnboardingStore.ts +2 -2
  33. package/src/onboarding/infrastructure/storage/__tests__/OnboardingStore.test.ts +1 -1
  34. package/src/onboarding/infrastructure/storage/actions/answerActions.ts +1 -1
  35. package/src/onboarding/infrastructure/storage/actions/storageHelpers.ts +1 -1
  36. package/src/storage/README.md +185 -0
  37. package/src/storage/__tests__/integration.test.ts +391 -0
  38. package/src/storage/__tests__/mocks/asyncStorage.mock.ts +52 -0
  39. package/src/storage/__tests__/performance.test.tsx +352 -0
  40. package/src/storage/__tests__/setup.ts +63 -0
  41. package/src/storage/application/README.md +158 -0
  42. package/src/storage/application/ports/IStorageRepository.ts +61 -0
  43. package/src/storage/application/ports/README.md +127 -0
  44. package/src/storage/cache/README.md +154 -0
  45. package/src/storage/cache/__tests__/PerformanceAndMemory.test.ts +387 -0
  46. package/src/storage/cache/__tests__/setup.ts +19 -0
  47. package/src/storage/cache/domain/Cache.ts +146 -0
  48. package/src/storage/cache/domain/CacheManager.md +83 -0
  49. package/src/storage/cache/domain/CacheManager.ts +48 -0
  50. package/src/storage/cache/domain/CacheStatsTracker.md +169 -0
  51. package/src/storage/cache/domain/CacheStatsTracker.ts +49 -0
  52. package/src/storage/cache/domain/CachedValue.md +97 -0
  53. package/src/storage/cache/domain/ErrorHandler.md +99 -0
  54. package/src/storage/cache/domain/ErrorHandler.ts +42 -0
  55. package/src/storage/cache/domain/PatternMatcher.md +122 -0
  56. package/src/storage/cache/domain/PatternMatcher.ts +30 -0
  57. package/src/storage/cache/domain/README.md +118 -0
  58. package/src/storage/cache/domain/__tests__/Cache.test.ts +293 -0
  59. package/src/storage/cache/domain/__tests__/CacheManager.test.ts +276 -0
  60. package/src/storage/cache/domain/__tests__/ErrorHandler.test.ts +303 -0
  61. package/src/storage/cache/domain/__tests__/PatternMatcher.test.ts +261 -0
  62. package/src/storage/cache/domain/strategies/EvictionStrategy.ts +9 -0
  63. package/src/storage/cache/domain/strategies/FIFOStrategy.ts +12 -0
  64. package/src/storage/cache/domain/strategies/LFUStrategy.ts +22 -0
  65. package/src/storage/cache/domain/strategies/LRUStrategy.ts +22 -0
  66. package/src/storage/cache/domain/strategies/README.md +117 -0
  67. package/src/storage/cache/domain/strategies/TTLStrategy.ts +23 -0
  68. package/src/storage/cache/domain/strategies/__tests__/EvictionStrategies.test.ts +293 -0
  69. package/src/storage/cache/domain/types/Cache.ts +28 -0
  70. package/src/storage/cache/domain/types/README.md +107 -0
  71. package/src/storage/cache/index.ts +28 -0
  72. package/src/storage/cache/infrastructure/README.md +126 -0
  73. package/src/storage/cache/infrastructure/TTLCache.ts +103 -0
  74. package/src/storage/cache/infrastructure/__tests__/TTLCache.test.ts +303 -0
  75. package/src/storage/cache/presentation/README.md +123 -0
  76. package/src/storage/cache/presentation/__tests__/ReactHooks.test.ts +514 -0
  77. package/src/storage/cache/presentation/useCache.ts +76 -0
  78. package/src/storage/cache/presentation/useCachedValue.ts +88 -0
  79. package/src/storage/cache/types.d.ts +3 -0
  80. package/src/storage/domain/README.md +128 -0
  81. package/src/storage/domain/constants/CacheDefaults.ts +64 -0
  82. package/src/storage/domain/constants/README.md +105 -0
  83. package/src/storage/domain/entities/CachedValue.ts +86 -0
  84. package/src/storage/domain/entities/README.md +109 -0
  85. package/src/storage/domain/entities/StorageResult.ts +75 -0
  86. package/src/storage/domain/entities/__tests__/CachedValue.test.ts +149 -0
  87. package/src/storage/domain/entities/__tests__/StorageResult.test.ts +122 -0
  88. package/src/storage/domain/errors/README.md +126 -0
  89. package/src/storage/domain/errors/StorageError.ts +81 -0
  90. package/src/storage/domain/errors/__tests__/StorageError.test.ts +127 -0
  91. package/src/storage/domain/factories/README.md +138 -0
  92. package/src/storage/domain/factories/StoreFactory.ts +59 -0
  93. package/src/storage/domain/types/README.md +522 -0
  94. package/src/storage/domain/types/Store.ts +44 -0
  95. package/src/storage/domain/utils/CacheKeyGenerator.ts +66 -0
  96. package/src/storage/domain/utils/README.md +127 -0
  97. package/src/storage/domain/utils/__tests__/devUtils.test.ts +97 -0
  98. package/src/storage/domain/utils/devUtils.ts +37 -0
  99. package/src/storage/domain/value-objects/README.md +120 -0
  100. package/src/storage/domain/value-objects/StorageKey.ts +60 -0
  101. package/src/storage/index.ts +175 -0
  102. package/src/storage/infrastructure/README.md +165 -0
  103. package/src/storage/infrastructure/adapters/README.md +175 -0
  104. package/src/storage/infrastructure/adapters/StorageService.md +103 -0
  105. package/src/storage/infrastructure/adapters/StorageService.ts +49 -0
  106. package/src/storage/infrastructure/repositories/AsyncStorageRepository.ts +98 -0
  107. package/src/storage/infrastructure/repositories/BaseStorageOperations.ts +100 -0
  108. package/src/storage/infrastructure/repositories/BatchStorageOperations.ts +42 -0
  109. package/src/storage/infrastructure/repositories/README.md +121 -0
  110. package/src/storage/infrastructure/repositories/StringStorageOperations.ts +44 -0
  111. package/src/storage/infrastructure/repositories/__tests__/AsyncStorageRepository.test.ts +170 -0
  112. package/src/storage/infrastructure/repositories/__tests__/BaseStorageOperations.test.ts +201 -0
  113. package/src/storage/presentation/README.md +181 -0
  114. package/src/storage/presentation/hooks/CacheStorageOperations.ts +94 -0
  115. package/src/storage/presentation/hooks/README.md +128 -0
  116. package/src/storage/presentation/hooks/__tests__/usePersistentCache.test.ts +405 -0
  117. package/src/storage/presentation/hooks/__tests__/useStorage.test.ts +247 -0
  118. package/src/storage/presentation/hooks/__tests__/useStorageState.test.ts +293 -0
  119. package/src/storage/presentation/hooks/useCacheState.ts +53 -0
  120. package/src/storage/presentation/hooks/usePersistentCache.ts +154 -0
  121. package/src/storage/presentation/hooks/useStorage.ts +102 -0
  122. package/src/storage/presentation/hooks/useStorageState.ts +71 -0
  123. package/src/storage/presentation/hooks/useStore.ts +15 -0
  124. package/src/storage/types/README.md +103 -0
  125. package/src/theme/infrastructure/globalThemeStore.ts +1 -1
  126. package/src/theme/infrastructure/storage/ThemeStorage.ts +1 -1
  127. package/src/theme/infrastructure/stores/themeStore.ts +1 -1
  128. package/src/utilities/sharing/infrastructure/services/SharingService.ts +1 -1
@@ -0,0 +1,146 @@
1
+ /**
2
+ * In-Memory Cache
3
+ */
4
+
5
+ import type { CacheEntry, CacheConfig, CacheStats, EvictionStrategy } from './types/Cache';
6
+ import { CacheStatsTracker } from './CacheStatsTracker';
7
+ import { PatternMatcher } from './PatternMatcher';
8
+ import { LRUStrategy } from './strategies/LRUStrategy';
9
+ import { LFUStrategy } from './strategies/LFUStrategy';
10
+ import { FIFOStrategy } from './strategies/FIFOStrategy';
11
+ import { TTLStrategy } from './strategies/TTLStrategy';
12
+
13
+ export class Cache<T = unknown> {
14
+ private store = new Map<string, CacheEntry<T>>();
15
+ private config: Required<CacheConfig>;
16
+ private statsTracker = new CacheStatsTracker();
17
+ private strategies = {
18
+ lru: new LRUStrategy<T>(),
19
+ lfu: new LFUStrategy<T>(),
20
+ fifo: new FIFOStrategy<T>(),
21
+ ttl: new TTLStrategy<T>(),
22
+ };
23
+
24
+ constructor(config: CacheConfig = {}) {
25
+ this.config = {
26
+ maxSize: config.maxSize || 100,
27
+ defaultTTL: config.defaultTTL || 5 * 60 * 1000,
28
+ onEvict: config.onEvict || (() => { }),
29
+ onExpire: config.onExpire || (() => { }),
30
+ };
31
+ }
32
+
33
+ set(key: string, value: T, ttl?: number): void {
34
+ if (this.store.size >= this.config.maxSize && !this.store.has(key)) {
35
+ this.evictOne('lru');
36
+ }
37
+
38
+ const entry: CacheEntry<T> = {
39
+ value,
40
+ timestamp: Date.now(),
41
+ ttl: ttl || this.config.defaultTTL,
42
+ accessCount: 0,
43
+ lastAccess: Date.now(),
44
+ };
45
+
46
+ this.store.set(key, entry);
47
+ this.statsTracker.updateSize(this.store.size);
48
+
49
+ if (typeof __DEV__ !== 'undefined' && __DEV__ && typeof console !== 'undefined' && console.log) {
50
+ console.log(`Cache: Set key "${key}" with TTL ${entry.ttl}ms`);
51
+ }
52
+ }
53
+
54
+ get(key: string): T | undefined {
55
+ const entry = this.store.get(key);
56
+
57
+ if (!entry) {
58
+ this.statsTracker.recordMiss();
59
+ return undefined;
60
+ }
61
+
62
+ if (this.isExpired(entry)) {
63
+ this.delete(key);
64
+ this.statsTracker.recordMiss();
65
+ this.statsTracker.recordExpiration();
66
+ this.config.onExpire(key, entry);
67
+ return undefined;
68
+ }
69
+
70
+ entry.accessCount++;
71
+ entry.lastAccess = Date.now();
72
+ this.statsTracker.recordHit();
73
+ return entry.value;
74
+ }
75
+
76
+ has(key: string): boolean {
77
+ const entry = this.store.get(key);
78
+ if (!entry) return false;
79
+ if (this.isExpired(entry)) {
80
+ this.delete(key);
81
+ return false;
82
+ }
83
+ return true;
84
+ }
85
+
86
+ delete(key: string): boolean {
87
+ const deleted = this.store.delete(key);
88
+ if (deleted) {
89
+ this.statsTracker.updateSize(this.store.size);
90
+ }
91
+ return deleted;
92
+ }
93
+
94
+ invalidatePattern(pattern: string): number {
95
+ const regex = PatternMatcher.convertPatternToRegex(pattern);
96
+ let invalidatedCount = 0;
97
+
98
+ for (const key of this.store.keys()) {
99
+ if (regex.test(key)) {
100
+ this.store.delete(key);
101
+ invalidatedCount++;
102
+ }
103
+ }
104
+
105
+ this.statsTracker.updateSize(this.store.size);
106
+ return invalidatedCount;
107
+ }
108
+
109
+ clear(): void {
110
+ this.store.clear();
111
+ this.statsTracker.reset();
112
+ }
113
+
114
+ getStats(): CacheStats {
115
+ return this.statsTracker.getStats();
116
+ }
117
+
118
+ keys(): string[] {
119
+ return Array.from(this.store.keys());
120
+ }
121
+
122
+ private isExpired(entry: CacheEntry<T>): boolean {
123
+ return Date.now() - entry.timestamp > entry.ttl;
124
+ }
125
+
126
+ private evictOne(strategy: EvictionStrategy): void {
127
+ const evictionStrategy = this.strategies[strategy];
128
+ if (!evictionStrategy) return;
129
+
130
+ const keyToEvict = evictionStrategy.findKeyToEvict(this.store);
131
+ if (keyToEvict) {
132
+ const entry = this.store.get(keyToEvict);
133
+ this.store.delete(keyToEvict);
134
+ this.statsTracker.recordEviction();
135
+ this.statsTracker.updateSize(this.store.size);
136
+
137
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
138
+ console.log(`Cache: Evicted key "${keyToEvict}" using ${strategy} strategy`);
139
+ }
140
+
141
+ if (entry) {
142
+ this.config.onEvict(keyToEvict, entry);
143
+ }
144
+ }
145
+ }
146
+ }
@@ -0,0 +1,83 @@
1
+ # Cache Manager
2
+
3
+ Centralized singleton manager for multiple named cache instances with lifecycle management.
4
+
5
+ ## Overview
6
+
7
+ CacheManager provides centralized management for multiple named cache instances. Located at `src/cache/domain/CacheManager.ts`.
8
+
9
+ ## Strategies
10
+
11
+ ### Cache Separation
12
+ - Use separate cache instances for different data types or domains
13
+ - Create environment-specific caches (development vs production)
14
+ - Implement feature-flagged caches for experimental functionality
15
+ - Use cache hierarchy patterns (L1/L2) for performance optimization
16
+
17
+ ### Lifecycle Management
18
+ - Initialize caches on first access (lazy loading)
19
+ - Implement cache warmup strategies for critical data
20
+ - Monitor cache statistics for performance optimization
21
+ - Clean up unused caches periodically
22
+
23
+ ### Multi-Cache Patterns
24
+ - Use cache segmentation by data type or domain
25
+ - Implement namespaced cache organization
26
+ - Apply cache hierarchy with promotion/demotion
27
+ - Use preset configurations for different TTL ranges
28
+
29
+ ## Restrictions
30
+
31
+ ### Cache Creation
32
+ - DO NOT create duplicate caches with the same name
33
+ - DO NOT use generic or non-descriptive cache names
34
+ - DO NOT mix unrelated data types in the same cache
35
+ - DO NOT create caches without considering TTL requirements
36
+
37
+ ### Cache Deletion
38
+ - DO NOT delete caches that might be in use
39
+ - DO NOT rely on manual cleanup without automated strategy
40
+ - DO NOT delete caches during critical operations
41
+
42
+ ### Configuration
43
+ - DO NOT use extremely short TTLs (< 1 second) as they're ineffective
44
+ - DO NOT use extremely long TTLs (> 1 year) to avoid stale data
45
+ - DO NOT ignore cache size limits
46
+
47
+ ## Rules
48
+
49
+ ### Cache Naming
50
+ - MUST use descriptive names indicating cached data type
51
+ - MUST use consistent naming convention (kebab-case or camelCase)
52
+ - MUST include domain/business context in cache name
53
+ - MUST document cache purpose in code comments
54
+
55
+ ### Cache Configuration
56
+ - MUST specify appropriate maxSize for expected data volume
57
+ - MUST set defaultTTL based on data change frequency
58
+ - MUST provide onEvict callback for monitoring in development
59
+ - MUST use preset configurations for standard TTL ranges
60
+
61
+ ### Cache Access
62
+ - MUST use `getCache()` to retrieve or create cache instances
63
+ - MUST check if cache exists before operations when appropriate
64
+ - MUST call `deleteCache()` to remove unused caches
65
+ - MUST use `getCacheNames()` to monitor active caches
66
+
67
+ ### Cache Lifecycle
68
+ - MUST implement warmup for frequently-accessed data
69
+ - MUST monitor cache statistics (hit rate, size) periodically
70
+ - MUST clean up unused caches in long-running applications
71
+ - MUST call `clearAll()` in test beforeEach hooks
72
+
73
+ ### Testing
74
+ - MUST clear all caches in test setup
75
+ - MUST use isolated cache names in tests
76
+ - MUST delete test caches after test completion
77
+ - MUST test cache creation, retrieval, and deletion
78
+
79
+ ### Error Handling
80
+ - MUST handle cache deletion failures gracefully
81
+ - MUST log cache creation with configuration
82
+ - MUST monitor cache statistics for anomalies
83
+ - MUST implement fallback for cache manager failures
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Cache Manager
3
+ * Manages multiple cache instances
4
+ */
5
+
6
+ import { Cache } from './Cache';
7
+ import type { CacheConfig } from './types/Cache';
8
+
9
+ export class CacheManager {
10
+ private static instance: CacheManager;
11
+ private caches = new Map<string, Cache<any>>();
12
+
13
+ private constructor() {}
14
+
15
+ static getInstance(): CacheManager {
16
+ if (!CacheManager.instance) {
17
+ CacheManager.instance = new CacheManager();
18
+ }
19
+ return CacheManager.instance;
20
+ }
21
+
22
+ getCache<T>(name: string, config?: CacheConfig): Cache<T> {
23
+ if (!this.caches.has(name)) {
24
+ this.caches.set(name, new Cache<T>(config));
25
+ }
26
+ return this.caches.get(name)!;
27
+ }
28
+
29
+ deleteCache(name: string): boolean {
30
+ const cache = this.caches.get(name);
31
+ if (cache) {
32
+ cache.clear();
33
+ return this.caches.delete(name);
34
+ }
35
+ return false;
36
+ }
37
+
38
+ clearAll(): void {
39
+ this.caches.forEach((cache) => cache.clear());
40
+ this.caches.clear();
41
+ }
42
+
43
+ getCacheNames(): string[] {
44
+ return Array.from(this.caches.keys());
45
+ }
46
+ }
47
+
48
+ export const cacheManager = CacheManager.getInstance();
@@ -0,0 +1,169 @@
1
+ # Cache Statistics Tracking
2
+
3
+ Real-time monitoring and metrics for cache performance and health.
4
+
5
+ ## Overview
6
+
7
+ Cache statistics tracker for monitoring cache operations and performance. Located at `src/cache/domain/`.
8
+
9
+ ## Strategies
10
+
11
+ ### Metrics Collection
12
+ - Use CacheStatsTracker for real-time statistics
13
+ - Track hits, misses, evictions, and expirations
14
+ - Calculate hit rate automatically
15
+ - Monitor cache size changes
16
+
17
+ ### Performance Monitoring
18
+ - Monitor hit rate for cache effectiveness
19
+ - Track eviction rates for capacity issues
20
+ - Monitor expiration rates for TTL optimization
21
+ - Track size changes for memory management
22
+
23
+ ### Health Analysis
24
+ - Use hit rate as primary health indicator
25
+ - Monitor eviction rate for capacity planning
26
+ - Track expiration patterns for TTL tuning
27
+ - Compare metrics over time for trends
28
+
29
+ ### Alerting
30
+ - Set thresholds for critical metrics
31
+ - Alert on low hit rates
32
+ - Alert on high eviction rates
33
+ - Alert on abnormal expiration patterns
34
+
35
+ ## Restrictions
36
+
37
+ ### Statistics Tracking
38
+ - DO NOT track statistics without cache instance
39
+ - DO NOT ignore statistics in production
40
+ - DO NOT reset statistics without clear reason
41
+ - DO NOT track sensitive data in statistics
42
+
43
+ ### Performance Impact
44
+ - DO NOT track statistics with high overhead
45
+ - DO NOT collect statistics synchronously
46
+ - DO NOT store unlimited history
47
+ - DO NOT impact cache performance for statistics
48
+
49
+ ### Alert Configuration
50
+ - DO NOT set thresholds without baseline data
51
+ - DO NOT alert on single metric violations
52
+ - DO NOT create alert storms
53
+ - DO NOT ignore alert fatigue
54
+
55
+ ### Data Collection
56
+ - DO NOT collect PII in statistics
57
+ - DO NOT store raw cache data in stats
58
+ - DO NOT expose detailed stats in production logs
59
+ - DO NOT aggregate without retention policy
60
+
61
+ ## Rules
62
+
63
+ ### CacheStatsTracker Implementation
64
+ - MUST provide recordHit() method
65
+ - MUST provide recordMiss() method
66
+ - MUST provide recordEviction() method
67
+ - MUST provide recordExpiration() method
68
+ - MUST provide updateSize() method
69
+ - MUST provide getStats() method
70
+ - MUST provide reset() method
71
+
72
+ ### CacheStats Interface
73
+ - MUST include size: number (current entry count)
74
+ - MUST include hits: number (total cache hits)
75
+ - MUST include misses: number (total cache misses)
76
+ - MUST include evictions: number (total evictions)
77
+ - MUST include expirations: number (total expirations)
78
+ - MUST include hitRate: number (calculated ratio 0-1)
79
+
80
+ ### Hit Rate Calculation
81
+ - MUST calculate as hits / (hits + misses)
82
+ - MUST return 0 when no operations recorded
83
+ - MUST handle division by zero
84
+ - MUST provide value between 0 and 1
85
+ - MUST update on every hit or miss
86
+
87
+ ### Statistics Updates
88
+ - MUST update statistics atomically
89
+ - MUST increment counters for each operation
90
+ - MUST recalculate hit rate after each hit/miss
91
+ - MUST update size on cache modifications
92
+ - MUST not lose updates on concurrent operations
93
+
94
+ ### Reset Behavior
95
+ - MUST reset all counters to zero
96
+ - MUST reset hit rate to 0
97
+ - MUST be callable after cache clear
98
+ - MUST not affect cache data
99
+ - MUST be idempotent
100
+
101
+ ### Thread Safety
102
+ - MUST handle concurrent record operations
103
+ - MUST not corrupt statistics on parallel updates
104
+ - MUST provide consistent reads
105
+ - MUST use atomic operations for counters
106
+ - MUST prevent race conditions
107
+
108
+ ### Performance Requirements
109
+ - MUST have minimal overhead on cache operations
110
+ - MUST not block cache operations
111
+ - MUST use efficient data structures
112
+ - MUST not cause memory leaks
113
+ - MUST be suitable for production use
114
+
115
+ ### Monitoring Integration
116
+ - MUST provide access to current statistics
117
+ - MUST support statistics export
118
+ - MUST enable real-time monitoring
119
+ - MUST support custom metrics
120
+ - MUST integrate with logging systems
121
+
122
+ ### Health Check Support
123
+ - MUST enable health assessment
124
+ - MUST support threshold-based alerts
125
+ - MUST provide trend analysis capability
126
+ - MUST enable performance diagnostics
127
+ - MUST support optimization recommendations
128
+
129
+ ### Data Retention
130
+ - MUST provide current statistics
131
+ - MUST not store unlimited historical data
132
+ - MUST support snapshot capability
133
+ - MUST enable time-series analysis
134
+ - MUST handle memory limits
135
+
136
+ ### Type Safety
137
+ - MUST provide TypeScript types
138
+ - MUST use numeric types for metrics
139
+ - MUST ensure type-safe operations
140
+ - MUST prevent type coercion errors
141
+ - MUST support generic usage
142
+
143
+ ### Export and Serialization
144
+ - MUST support JSON serialization
145
+ - MUST provide readable format
146
+ - MUST include all metrics
147
+ - MUST preserve data types
148
+ - MUST enable external analysis
149
+
150
+ ### Best Practices Compliance
151
+ - MUST follow performance monitoring best practices
152
+ - MUST enable observability
153
+ - MUST support debugging
154
+ - MUST provide actionable insights
155
+ - MUST not impact cache functionality
156
+
157
+ ### Documentation Requirements
158
+ - MUST document all metrics clearly
159
+ - MUST explain hit rate calculation
160
+ - MUST provide usage guidance
161
+ - MUST specify performance characteristics
162
+ - MUST not include code examples in documentation
163
+
164
+ ### Testing Requirements
165
+ - MUST test all recording methods
166
+ - MUST test hit rate calculation accuracy
167
+ - MUST test reset functionality
168
+ - MUST test concurrent operations
169
+ - MUST verify thread safety
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Cache Statistics Tracker
3
+ */
4
+
5
+ import type { CacheStats } from './types/Cache';
6
+
7
+ export class CacheStatsTracker {
8
+ private stats: CacheStats = {
9
+ size: 0,
10
+ hits: 0,
11
+ misses: 0,
12
+ evictions: 0,
13
+ expirations: 0,
14
+ };
15
+
16
+ recordHit(): void {
17
+ this.stats.hits++;
18
+ }
19
+
20
+ recordMiss(): void {
21
+ this.stats.misses++;
22
+ }
23
+
24
+ recordEviction(): void {
25
+ this.stats.evictions++;
26
+ }
27
+
28
+ recordExpiration(): void {
29
+ this.stats.expirations++;
30
+ }
31
+
32
+ updateSize(size: number): void {
33
+ this.stats.size = size;
34
+ }
35
+
36
+ getStats(): CacheStats {
37
+ return { ...this.stats };
38
+ }
39
+
40
+ reset(): void {
41
+ this.stats = {
42
+ size: 0,
43
+ hits: 0,
44
+ misses: 0,
45
+ evictions: 0,
46
+ expirations: 0,
47
+ };
48
+ }
49
+ }
@@ -0,0 +1,97 @@
1
+ # Cache Entry (CachedValue)
2
+
3
+ Cached value entity with TTL and metadata for time-based expiration.
4
+
5
+ ## Overview
6
+
7
+ CachedValue represents a single cached entry with value, timestamp, TTL, and access tracking. Located at `src/cache/domain/CachedValue.ts`.
8
+
9
+ ## Strategies
10
+
11
+ ### TTL Management
12
+ - Set TTL based on data change frequency
13
+ - Use shorter TTL for frequently changing data
14
+ - Use longer TTL for static or rarely changing data
15
+ - Consider sliding expiration for frequently accessed data
16
+
17
+ ### Metadata Tracking
18
+ - Track creation timestamp for age calculation
19
+ - Track TTL for expiration checking
20
+ - Optionally track access count for analytics
21
+ - Optionally track last access time for LRU eviction
22
+
23
+ ### Validation Strategy
24
+ - Always validate TTL is within reasonable bounds
25
+ - Check expiration before returning cached values
26
+ - Validate structure when deserializing from storage
27
+ - Implement type guards for type safety
28
+
29
+ ## Restrictions
30
+
31
+ ### TTL Values
32
+ - DO NOT use negative TTL values
33
+ - DO NOT use zero TTL (data expires immediately)
34
+ - DO NOT use extremely short TTLs (< 1000ms)
35
+ - DO NOT use extremely long TTLs (> 10 years)
36
+
37
+ ### Metadata Modification
38
+ - DO NOT modify timestamp after creation (except for sliding expiration)
39
+ - DO NOT manually adjust TTL to extend cache lifetime
40
+ - DO NOT alter data property directly (use cache methods)
41
+ - DO NOT assume timestamp is in seconds (it's milliseconds)
42
+
43
+ ### Serialization
44
+ - DO NOT serialize without validating structure first
45
+ - DO NOT deserialize without type checking
46
+ - DO NOT assume cached values are always valid JSON
47
+ - DO NOT mix different data types in same cache entry
48
+
49
+ ## Rules
50
+
51
+ ### Creation
52
+ - MUST use `createCachedValue()` factory function
53
+ - MUST specify TTL in milliseconds
54
+ - MUST capture current timestamp in milliseconds
55
+ - MUST include all required fields (data, timestamp, ttl)
56
+
57
+ ### Expiration Checking
58
+ - MUST use `isCacheExpired()` before accessing cached data
59
+ - MUST compare timestamp + ttl against current time
60
+ - MUST treat expired entries as non-existent
61
+ - MUST remove expired entries from cache
62
+
63
+ ### TTL Calculation
64
+ - MUST use `getRemainingTTL()` to check time until expiration
65
+ - MUST return 0 or negative for expired entries
66
+ - MUST use milliseconds for all time calculations
67
+ - MUST handle edge cases (zero, negative, very large TTL)
68
+
69
+ ### Age Tracking
70
+ - MUST use `getCacheAge()` to determine entry age
71
+ - MUST calculate age as (current time - timestamp)
72
+ - MUST return age in milliseconds
73
+ - MUST use age for analytics and monitoring
74
+
75
+ ### Serialization/Deserialization
76
+ - MUST validate structure after deserialization
77
+ - MUST use TypeScript type guards for type safety
78
+ - MUST handle JSON parsing errors gracefully
79
+ - MUST preserve timestamp and TTL during serialization
80
+
81
+ ### Type Safety
82
+ - MUST use generic type parameter for data field
83
+ - MUST enforce type checking with `isValidCachedValue()`
84
+ - MUST validate data structure when loading from storage
85
+ - MUST handle type mismatches gracefully
86
+
87
+ ### Error Handling
88
+ - MUST handle invalid TTL values gracefully
89
+ - MUST throw descriptive errors for malformed entries
90
+ - MUST log expiration warnings in development
91
+ - MUST provide fallback for corrupted cache entries
92
+
93
+ ### Testing
94
+ - MUST test expiration logic with various TTL values
95
+ - MUST test edge cases (zero, negative, very large TTL)
96
+ - MUST test serialization/deserialization roundtrip
97
+ - MUST test type validation with type guards
@@ -0,0 +1,99 @@
1
+ # Cache Error Handler
2
+
3
+ Centralized error handling for cache operations with recovery and monitoring.
4
+
5
+ ## Overview
6
+
7
+ ErrorHandler provides unified error handling for cache operations with logging, recovery, and alerting capabilities. Located at `src/cache/domain/ErrorHandler.ts`.
8
+
9
+ ## Strategies
10
+
11
+ ### Error Handling Strategy
12
+ - Use silent failure for non-critical cache operations
13
+ - Implement retry logic for transient failures
14
+ - Provide fallback values for degraded operation
15
+ - Use graceful degradation when cache fails
16
+
17
+ ### Recovery Strategy
18
+ - Implement auto-recovery for corrupted cache data
19
+ - Clear and rebuild cache on unrecoverable errors
20
+ - Use fallback storage mechanism when primary fails
21
+ - Implement circuit breaker pattern for repeated failures
22
+
23
+ ### Monitoring Strategy
24
+ - Track error counts by error type
25
+ - Aggregate recent errors for pattern analysis
26
+ - Alert on error threshold exceeded
27
+ - Log errors with context for debugging
28
+
29
+ ## Restrictions
30
+
31
+ ### Error Handling
32
+ - DO NOT silently swallow all errors
33
+ - DO NOT throw errors from error handlers (recursive)
34
+ - DO NOT block application on cache errors
35
+ - DO NOT retry indefinitely on persistent failures
36
+
37
+ ### Error Reporting
38
+ - DO NOT log sensitive data in error messages
39
+ - DO NOT include full stack traces in production logs
40
+ - DO NOT send errors to remote services without rate limiting
41
+ - DO NOT overwhelm logging with duplicate errors
42
+
43
+ ### Recovery Attempts
44
+ - DO NOT attempt recovery more than configured retry limit
45
+ - DO NOT clear cache without logging reason
46
+ - DO NOT fall back to insecure storage mechanisms
47
+ - DO NOT continue operations after critical failures
48
+
49
+ ## Rules
50
+
51
+ ### Error Creation
52
+ - MUST use `CacheError` class for all cache errors
53
+ - MUST include descriptive error message
54
+ - MUST specify error code from standard codes
55
+ - MUST attach cause error when wrapping exceptions
56
+
57
+ ### Error Codes
58
+ - MUST use `CACHE_ERROR` for generic cache errors
59
+ - MUST use `CACHE_FULL` when cache at capacity
60
+ - MUST use `CACHE_INVALID_KEY` for invalid keys
61
+ - MUST use `CACHE_EXPIRED` for expiration errors
62
+ - MUST use `CACHE_SERIALIZATION` for serialization failures
63
+ - MUST use `CACHE_DESERIALIZATION` for deserialization failures
64
+
65
+ ### Error Handling
66
+ - MUST call `ErrorHandler.handle()` for all caught errors
67
+ - MUST include context information when available
68
+ - MUST log errors before recovery attempts
69
+ - MUST not throw from error handlers
70
+
71
+ ### Error Logging
72
+ - MUST log error code and message
73
+ - MUST log operation context (get/set/delete)
74
+ - MUST log cache name when applicable
75
+ - MUST log cause error if present
76
+
77
+ ### Error Recovery
78
+ - MUST implement maximum retry limit
79
+ - MUST log recovery attempts
80
+ - MUST fall back to safe state on failure
81
+ - MUST notify monitoring after recovery
82
+
83
+ ### Error Tracking
84
+ - MUST increment error counter for each error type
85
+ - MUST alert when error count exceeds threshold
86
+ - MUST reset counters after alert or periodically
87
+ - MUST aggregate recent errors for analysis
88
+
89
+ ### Context Enrichment
90
+ - MUST include operation type in error context
91
+ - MUST include cache key when applicable
92
+ - MUST include cache name for multi-cache scenarios
93
+ - MUST include timestamp for error correlation
94
+
95
+ ### Testing
96
+ - MUST test error handling with mock errors
97
+ - MUST test recovery logic with failure scenarios
98
+ - MUST test error tracking with repeated errors
99
+ - MUST test logging output format