@umituz/react-native-storage 2.6.22 → 2.6.24

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.
@@ -0,0 +1,154 @@
1
+ # Cache Module
2
+
3
+ High-performance in-memory cache system with TTL and multiple eviction strategies.
4
+
5
+ ## Overview
6
+
7
+ The cache module provides a comprehensive in-memory caching solution with TTL (Time To Live), LRU, LFU, and FIFO eviction strategies. Located at `src/cache/`.
8
+
9
+ ## Architecture
10
+
11
+ ```
12
+ cache/
13
+ ├── domain/ # Business logic and entities
14
+ │ ├── Cache.ts # Main Cache class
15
+ │ ├── CacheManager.ts # Singleton cache manager
16
+ │ ├── CacheStatsTracker.ts
17
+ │ ├── PatternMatcher.ts
18
+ │ ├── ErrorHandler.ts
19
+ │ ├── strategies/ # Eviction strategies
20
+ │ └── types/ # TypeScript types
21
+ ├── infrastructure/ # Infrastructure implementation
22
+ │ └── TTLCache.ts
23
+ └── presentation/ # React integration
24
+ ├── useCache.ts
25
+ └── useCachedValue.ts
26
+ ```
27
+
28
+ ## Strategies
29
+
30
+ ### Cache Organization
31
+ - Use CacheManager for multiple named caches
32
+ - Create separate caches for different data types
33
+ - Use environment-specific configurations
34
+ - Implement cache hierarchy for performance
35
+
36
+ ### Eviction Strategy Selection
37
+ - Use LRU for frequently accessed recent data
38
+ - Use LFU for popularity-based caching
39
+ - Use FIFO for simple queue-based caching
40
+ - Use TTL for time-based expiration
41
+
42
+ ### React Integration
43
+ - Use useCache hook for manual cache management
44
+ - Use useCachedValue for automatic value caching
45
+ - Share cache instances across components
46
+ - Implement cleanup on component unmount
47
+
48
+ ### Performance Optimization
49
+ - Monitor cache hit rates and adjust sizes
50
+ - Use appropriate TTL based on data change frequency
51
+ - Implement cache warmup for critical data
52
+ - Use pattern-based invalidation for bulk operations
53
+
54
+ ## Restrictions
55
+
56
+ ### Cache Creation
57
+ - DO NOT create unlimited cache sizes without max limit
58
+ - DO NOT use zero or negative TTL values
59
+ - DO NOT mix unrelated data types in same cache
60
+ - DO NOT create caches without considering eviction strategy
61
+
62
+ ### Memory Management
63
+ - DO NOT cache large objects (> 100KB) without size limits
64
+ - DO NOT cache frequently changing data with long TTL
65
+ - DO NOT ignore memory warnings from cache statistics
66
+ - DO NOT let caches grow unbounded
67
+
68
+ ### Pattern Usage
69
+ - DO NOT use broad patterns (e.g., `*`) for invalidation
70
+ - DO NOT mix different separators in cache keys
71
+ - DO NOT create ambiguous key structures
72
+ - DO NOT use patterns without documenting structure
73
+
74
+ ### React Integration
75
+ - DO NOT create new cache instances on every render
76
+ - DO NOT use cache hooks without proper cleanup
77
+ - DO NOT share cache state between unrelated components
78
+ - DO NOT ignore loading and error states
79
+
80
+ ## Rules
81
+
82
+ ### Cache Configuration
83
+ - MUST specify maxSize for all caches
84
+ - MUST set defaultTTL based on data characteristics
85
+ - MUST provide onEvict callback in development
86
+ - MUST document cache purpose and data type
87
+
88
+ ### Cache Operations
89
+ - MUST use get() for retrieving values
90
+ - MUST use set() for storing values with optional TTL
91
+ - MUST use has() to check key existence
92
+ - MUST use delete() to remove specific keys
93
+ - MUST use clear() to remove all entries
94
+
95
+ ### Cache Keys
96
+ - MUST use consistent key structure (e.g., `entity:id:attribute`)
97
+ - MUST use descriptive key names
98
+ - MUST document key patterns in code comments
99
+ - MUST avoid key collisions across different data types
100
+
101
+ ### Eviction Strategy
102
+ - MUST choose appropriate strategy for use case
103
+ - MUST configure strategy parameters correctly
104
+ - MUST monitor eviction statistics
105
+ - MUST test eviction behavior under load
106
+
107
+ ### TTL Management
108
+ - MUST set TTL based on data freshness requirements
109
+ - MUST use TIME_MS constants for time values
110
+ - MUST consider stale data impact
111
+ - MUST implement refresh mechanisms for critical data
112
+
113
+ ### Error Handling
114
+ - MUST handle cache errors gracefully
115
+ - MUST log cache operation failures
116
+ - MUST provide fallback for cache misses
117
+ - MUST not throw exceptions from cache operations
118
+
119
+ ### Statistics Tracking
120
+ - MUST track hits, misses, and evictions
121
+ - MUST calculate hit rate correctly
122
+ - MUST provide getStats() method
123
+ - MUST reset statistics in tests
124
+
125
+ ### Pattern-Based Operations
126
+ - MUST use `invalidatePattern()` for bulk invalidation
127
+ - MUST use `:` as default separator
128
+ - MUST support `*` wildcard
129
+ - MUST return count of invalidated keys
130
+
131
+ ### React Hooks
132
+ - MUST follow React rules of hooks
133
+ - MUST cleanup cache on unmount
134
+ - MUST provide loading states for async operations
135
+ - MUST handle errors in fetcher functions
136
+
137
+ ### Testing Requirements
138
+ - MUST clear cache before each test
139
+ - MUST test hit/miss scenarios
140
+ - MUST test eviction behavior
141
+ - MUST test TTL expiration
142
+ - MUST test pattern matching
143
+
144
+ ### Type Safety
145
+ - MUST use generic type parameter for cached values
146
+ - MUST enforce type consistency
147
+ - MUST provide type inference
148
+ - MUST avoid `any` types
149
+
150
+ ### Performance Monitoring
151
+ - MUST monitor cache hit rate
152
+ - MUST alert on low hit rates (< 50%)
153
+ - MUST track memory usage
154
+ - MUST log performance anomalies
@@ -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,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,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