|
| 1 | +package com.flockyou.ai |
| 2 | + |
| 3 | +import android.util.Log |
| 4 | +import java.util.concurrent.ConcurrentHashMap |
| 5 | +import javax.inject.Inject |
| 6 | +import javax.inject.Singleton |
| 7 | + |
| 8 | +/** |
| 9 | + * In-memory cache for enriched detector data associated with detections. |
| 10 | + * |
| 11 | + * When monitors (Cellular, GNSS, WiFi, Ultrasonic, etc.) create detections, they also |
| 12 | + * store the detailed heuristics analysis here. When the LLM analyzes a detection, it |
| 13 | + * retrieves this enriched data to provide more accurate and contextual analysis. |
| 14 | + * |
| 15 | + * Features: |
| 16 | + * - Thread-safe using ConcurrentHashMap |
| 17 | + * - Time-based expiry (configurable TTL) |
| 18 | + * - Size-limited to prevent memory issues |
| 19 | + * - Automatic cleanup of expired entries |
| 20 | + */ |
| 21 | +@Singleton |
| 22 | +class EnrichedDataCache @Inject constructor() { |
| 23 | + |
| 24 | + companion object { |
| 25 | + private const val TAG = "EnrichedDataCache" |
| 26 | + private const val DEFAULT_TTL_MS = 5 * 60 * 1000L // 5 minutes |
| 27 | + private const val MAX_CACHE_SIZE = 200 |
| 28 | + private const val CLEANUP_THRESHOLD = 250 |
| 29 | + } |
| 30 | + |
| 31 | + private data class CacheEntry( |
| 32 | + val data: EnrichedDetectorData, |
| 33 | + val timestamp: Long = System.currentTimeMillis(), |
| 34 | + val ttlMs: Long = DEFAULT_TTL_MS |
| 35 | + ) { |
| 36 | + fun isExpired(): Boolean = System.currentTimeMillis() - timestamp > ttlMs |
| 37 | + } |
| 38 | + |
| 39 | + private val cache = ConcurrentHashMap<String, CacheEntry>() |
| 40 | + |
| 41 | + /** |
| 42 | + * Store enriched data for a detection. |
| 43 | + * |
| 44 | + * @param detectionId The unique ID of the detection |
| 45 | + * @param data The enriched detector data (CellularAnomalyAnalysis, GnssAnomalyAnalysis, etc.) |
| 46 | + * @param ttlMs Optional custom TTL in milliseconds (default 5 minutes) |
| 47 | + */ |
| 48 | + fun put(detectionId: String, data: EnrichedDetectorData, ttlMs: Long = DEFAULT_TTL_MS) { |
| 49 | + // Clean up if cache is getting too large |
| 50 | + if (cache.size > CLEANUP_THRESHOLD) { |
| 51 | + cleanup() |
| 52 | + } |
| 53 | + |
| 54 | + cache[detectionId] = CacheEntry(data, ttlMs = ttlMs) |
| 55 | + Log.d(TAG, "Cached enriched data for detection: $detectionId (type: ${data.javaClass.simpleName})") |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * Retrieve enriched data for a detection. |
| 60 | + * Returns null if not found or expired. |
| 61 | + * |
| 62 | + * @param detectionId The unique ID of the detection |
| 63 | + * @return The enriched data, or null if not found/expired |
| 64 | + */ |
| 65 | + fun get(detectionId: String): EnrichedDetectorData? { |
| 66 | + val entry = cache[detectionId] |
| 67 | + |
| 68 | + if (entry == null) { |
| 69 | + Log.d(TAG, "No enriched data found for detection: $detectionId") |
| 70 | + return null |
| 71 | + } |
| 72 | + |
| 73 | + if (entry.isExpired()) { |
| 74 | + cache.remove(detectionId) |
| 75 | + Log.d(TAG, "Enriched data expired for detection: $detectionId") |
| 76 | + return null |
| 77 | + } |
| 78 | + |
| 79 | + Log.d(TAG, "Retrieved enriched data for detection: $detectionId (type: ${entry.data.javaClass.simpleName})") |
| 80 | + return entry.data |
| 81 | + } |
| 82 | + |
| 83 | + /** |
| 84 | + * Store cellular anomaly analysis for a detection. |
| 85 | + */ |
| 86 | + fun putCellular(detectionId: String, analysis: com.flockyou.service.CellularMonitor.CellularAnomalyAnalysis) { |
| 87 | + put(detectionId, EnrichedDetectorData.Cellular(analysis)) |
| 88 | + } |
| 89 | + |
| 90 | + /** |
| 91 | + * Store GNSS anomaly analysis for a detection. |
| 92 | + */ |
| 93 | + fun putGnss(detectionId: String, analysis: com.flockyou.monitoring.GnssSatelliteMonitor.GnssAnomalyAnalysis) { |
| 94 | + put(detectionId, EnrichedDetectorData.Gnss(analysis)) |
| 95 | + } |
| 96 | + |
| 97 | + /** |
| 98 | + * Store ultrasonic beacon analysis for a detection. |
| 99 | + */ |
| 100 | + fun putUltrasonic(detectionId: String, analysis: com.flockyou.service.UltrasonicDetector.BeaconAnalysis) { |
| 101 | + put(detectionId, EnrichedDetectorData.Ultrasonic(analysis)) |
| 102 | + } |
| 103 | + |
| 104 | + /** |
| 105 | + * Store WiFi following analysis for a detection. |
| 106 | + */ |
| 107 | + fun putWifiFollowing(detectionId: String, analysis: com.flockyou.service.RogueWifiMonitor.FollowingNetworkAnalysis) { |
| 108 | + put(detectionId, EnrichedDetectorData.WifiFollowing(analysis)) |
| 109 | + } |
| 110 | + |
| 111 | + /** |
| 112 | + * Store satellite/NTN enriched data for a detection. |
| 113 | + */ |
| 114 | + fun putSatellite( |
| 115 | + detectionId: String, |
| 116 | + detectorType: String, |
| 117 | + metadata: Map<String, String>, |
| 118 | + signalCharacteristics: Map<String, String>, |
| 119 | + riskIndicators: List<String>, |
| 120 | + timestamp: Long = System.currentTimeMillis() |
| 121 | + ) { |
| 122 | + put(detectionId, EnrichedDetectorData.Satellite( |
| 123 | + detectorType = detectorType, |
| 124 | + metadata = metadata, |
| 125 | + signalCharacteristics = signalCharacteristics, |
| 126 | + riskIndicators = riskIndicators, |
| 127 | + timestamp = timestamp |
| 128 | + )) |
| 129 | + } |
| 130 | + |
| 131 | + /** |
| 132 | + * Remove enriched data for a detection. |
| 133 | + */ |
| 134 | + fun remove(detectionId: String) { |
| 135 | + cache.remove(detectionId) |
| 136 | + } |
| 137 | + |
| 138 | + /** |
| 139 | + * Clear all cached data. |
| 140 | + */ |
| 141 | + fun clear() { |
| 142 | + cache.clear() |
| 143 | + Log.d(TAG, "Cache cleared") |
| 144 | + } |
| 145 | + |
| 146 | + /** |
| 147 | + * Get the current cache size. |
| 148 | + */ |
| 149 | + fun size(): Int = cache.size |
| 150 | + |
| 151 | + /** |
| 152 | + * Clean up expired entries and trim to max size. |
| 153 | + */ |
| 154 | + fun cleanup() { |
| 155 | + val expiredCount = cache.entries.count { it.value.isExpired() } |
| 156 | + cache.entries.removeIf { it.value.isExpired() } |
| 157 | + |
| 158 | + // If still over max size, remove oldest entries |
| 159 | + if (cache.size > MAX_CACHE_SIZE) { |
| 160 | + val toRemove = cache.entries |
| 161 | + .sortedBy { it.value.timestamp } |
| 162 | + .take(cache.size - MAX_CACHE_SIZE) |
| 163 | + .map { it.key } |
| 164 | + |
| 165 | + toRemove.forEach { cache.remove(it) } |
| 166 | + Log.d(TAG, "Removed ${toRemove.size} oldest entries to maintain max size") |
| 167 | + } |
| 168 | + |
| 169 | + if (expiredCount > 0) { |
| 170 | + Log.d(TAG, "Cleaned up $expiredCount expired entries, current size: ${cache.size}") |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + /** |
| 175 | + * Get statistics about the cache. |
| 176 | + */ |
| 177 | + fun getStats(): CacheStats { |
| 178 | + val now = System.currentTimeMillis() |
| 179 | + var expiredCount = 0 |
| 180 | + var cellularCount = 0 |
| 181 | + var gnssCount = 0 |
| 182 | + var ultrasonicCount = 0 |
| 183 | + var wifiCount = 0 |
| 184 | + var satelliteCount = 0 |
| 185 | + |
| 186 | + cache.values.forEach { entry -> |
| 187 | + if (entry.isExpired()) expiredCount++ |
| 188 | + when (entry.data) { |
| 189 | + is EnrichedDetectorData.Cellular -> cellularCount++ |
| 190 | + is EnrichedDetectorData.Gnss -> gnssCount++ |
| 191 | + is EnrichedDetectorData.Ultrasonic -> ultrasonicCount++ |
| 192 | + is EnrichedDetectorData.WifiFollowing -> wifiCount++ |
| 193 | + is EnrichedDetectorData.Satellite -> satelliteCount++ |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + return CacheStats( |
| 198 | + totalEntries = cache.size, |
| 199 | + expiredEntries = expiredCount, |
| 200 | + cellularEntries = cellularCount, |
| 201 | + gnssEntries = gnssCount, |
| 202 | + ultrasonicEntries = ultrasonicCount, |
| 203 | + wifiEntries = wifiCount, |
| 204 | + satelliteEntries = satelliteCount |
| 205 | + ) |
| 206 | + } |
| 207 | + |
| 208 | + data class CacheStats( |
| 209 | + val totalEntries: Int, |
| 210 | + val expiredEntries: Int, |
| 211 | + val cellularEntries: Int, |
| 212 | + val gnssEntries: Int, |
| 213 | + val ultrasonicEntries: Int, |
| 214 | + val wifiEntries: Int, |
| 215 | + val satelliteEntries: Int |
| 216 | + ) |
| 217 | +} |
0 commit comments