Spaces:
Paused

File size: 17,665 Bytes
357bfdf
 
 
 
 
0743ddc
 
357bfdf
 
 
 
0743ddc
357bfdf
 
 
0743ddc
357bfdf
 
 
16a78e2
357bfdf
 
 
16a78e2
357bfdf
16a78e2
357bfdf
 
16a78e2
357bfdf
 
 
 
 
16a78e2
357bfdf
 
 
 
 
16a78e2
357bfdf
0743ddc
 
16a78e2
357bfdf
0743ddc
357bfdf
16a78e2
357bfdf
0743ddc
16a78e2
 
 
 
 
 
357bfdf
16a78e2
 
 
 
 
 
357bfdf
 
579285c
 
0743ddc
357bfdf
 
 
 
 
 
 
 
579285c
 
 
357bfdf
16a78e2
579285c
 
357bfdf
16a78e2
357bfdf
16a78e2
357bfdf
0743ddc
 
 
579285c
357bfdf
 
 
0743ddc
 
357bfdf
 
16a78e2
357bfdf
 
 
 
 
 
16a78e2
357bfdf
 
 
16a78e2
357bfdf
 
16a78e2
357bfdf
 
 
 
 
 
 
16a78e2
357bfdf
 
 
 
16a78e2
 
357bfdf
16a78e2
357bfdf
 
 
 
 
 
 
0743ddc
357bfdf
0743ddc
16a78e2
357bfdf
 
 
16a78e2
357bfdf
 
 
 
 
 
 
 
 
 
 
 
 
16a78e2
357bfdf
 
 
16a78e2
357bfdf
 
 
16a78e2
357bfdf
 
 
 
 
 
16a78e2
357bfdf
16a78e2
357bfdf
16a78e2
357bfdf
16a78e2
357bfdf
 
16a78e2
357bfdf
 
16a78e2
357bfdf
 
 
 
 
 
 
 
 
 
0743ddc
357bfdf
 
16a78e2
357bfdf
 
 
579285c
16a78e2
 
357bfdf
16a78e2
357bfdf
16a78e2
 
357bfdf
16a78e2
 
 
357bfdf
16a78e2
357bfdf
16a78e2
 
 
357bfdf
16a78e2
 
 
 
357bfdf
 
 
 
0743ddc
357bfdf
0743ddc
16a78e2
357bfdf
 
 
16a78e2
357bfdf
 
 
 
 
 
16a78e2
357bfdf
 
 
 
 
 
 
 
16a78e2
357bfdf
 
 
 
 
16a78e2
357bfdf
16a78e2
 
 
 
 
 
357bfdf
 
 
 
16a78e2
357bfdf
16a78e2
357bfdf
16a78e2
357bfdf
16a78e2
357bfdf
 
 
 
 
 
 
0743ddc
357bfdf
 
 
16a78e2
357bfdf
16a78e2
357bfdf
 
 
16a78e2
357bfdf
 
 
16a78e2
 
 
357bfdf
 
 
 
 
 
 
 
16a78e2
357bfdf
 
16a78e2
357bfdf
 
0743ddc
357bfdf
 
579285c
357bfdf
 
16a78e2
357bfdf
 
 
 
 
16a78e2
 
357bfdf
 
 
 
 
 
 
 
 
 
 
 
16a78e2
 
579285c
357bfdf
16a78e2
357bfdf
 
 
 
 
 
 
16a78e2
357bfdf
 
 
 
16a78e2
357bfdf
 
 
579285c
357bfdf
 
 
16a78e2
357bfdf
16a78e2
 
357bfdf
 
 
 
 
16a78e2
357bfdf
16a78e2
 
 
357bfdf
 
 
16a78e2
357bfdf
 
 
579285c
357bfdf
579285c
357bfdf
 
 
16a78e2
357bfdf
 
 
 
16a78e2
357bfdf
 
 
 
 
 
 
 
16a78e2
 
 
357bfdf
16a78e2
357bfdf
 
 
0743ddc
357bfdf
16a78e2
357bfdf
16a78e2
357bfdf
 
16a78e2
 
 
 
 
 
 
 
 
357bfdf
16a78e2
357bfdf
 
 
 
 
 
 
16a78e2
357bfdf
 
 
 
 
 
 
 
 
 
383d839
 
 
 
 
 
 
357bfdf
 
 
 
 
 
 
 
0743ddc
 
 
 
357bfdf
 
 
16a78e2
 
 
 
357bfdf
16a78e2
357bfdf
16a78e2
357bfdf
 
 
 
 
16a78e2
357bfdf
 
 
0743ddc
357bfdf
 
16a78e2
 
357bfdf
16a78e2
357bfdf
16a78e2
 
357bfdf
 
 
 
 
 
16a78e2
357bfdf
 
16a78e2
357bfdf
 
 
 
 
 
 
 
16a78e2
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
"""
YAZ Care Platform - Advanced Caching Service
Comprehensive multi-tier caching with Redis backend for healthcare data
"""

import asyncio
import hashlib
import json
import pickle
from datetime import datetime, timedelta
from functools import wraps
from typing import Any, Callable, Dict, List, Optional, Union

import redis.asyncio as redis
import structlog
from redis.exceptions import ConnectionError, TimeoutError

logger = structlog.get_logger(__name__)


class CacheManager:
    """
    Multi-tier caching manager with healthcare-specific optimizations

    Tier 1: In-memory LRU cache (fastest, smallest capacity)
    Tier 2: Redis cache (fast, distributed)
    Tier 3: Database cache tables (persistent, largest capacity)
    """

    def __init__(
        self,
        redis_url: str = "redis://localhost:6379",
        memory_cache_size: int = 1000,
        default_ttl: int = 300,  # 5 minutes
        healthcare_compliance: bool = True,
    ):
        self.redis_url = redis_url
        self.memory_cache_size = memory_cache_size
        self.default_ttl = default_ttl
        self.healthcare_compliance = healthcare_compliance

        # Memory cache (LRU)
        self._memory_cache: dict[str, dict] = {}
        self._memory_access_order: list[str] = []

        # Redis connection
        self._redis: redis.Redis | None = None
        self._redis_connected = False

        # Cache statistics
        self.stats: dict[str, Any] = {
            "memory_hits": 0,
            "redis_hits": 0,
            "misses": 0,
            "sets": 0,
            "deletes": 0,
            "errors": 0,
        }

        logger.info(
            "Cache manager initialized",
            memory_size=memory_cache_size,
            healthcare_compliance=healthcare_compliance,
        )

    async def initialize(self):
        """Initialize Redis connection with bounded timeout."""
        import asyncio

        try:
            self._redis = redis.from_url(
                self.redis_url,
                encoding="utf-8",
                decode_responses=False,  # We'll handle encoding ourselves
                socket_keepalive=True,
                socket_keepalive_options={},
                health_check_interval=30,
                retry_on_timeout=False,  # Never retry indefinitely — fail fast
                socket_connect_timeout=3,
                socket_timeout=3,
            )

            # Test connection with hard 5s timeout so startup never hangs
            await asyncio.wait_for(self._redis.ping(), timeout=5.0)
            self._redis_connected = True

            logger.info("Redis cache connected successfully", url=self.redis_url)

        except Exception as e:
            logger.warning(
                "Redis cache unavailable — continuing with memory-only cache", error=str(e)
            )
            self._redis = None
            self._redis_connected = False

    async def get(
        self, key: str, namespace: str = "default", healthcare_context: dict | None = None
    ) -> Any | None:
        """
        Get value from cache with tier fallback

        Args:
            key: Cache key
            namespace: Cache namespace for organization
            healthcare_context: Healthcare-specific context for compliance
        """
        cache_key = self._build_cache_key(key, namespace)

        # Tier 1: Memory cache
        memory_result = self._get_from_memory(cache_key)
        if memory_result is not None:
            self.stats["memory_hits"] += 1
            logger.debug("Cache hit (memory)", key=cache_key)
            return memory_result

        # Tier 2: Redis cache
        if self._redis_connected:
            try:
                redis_result = await self._get_from_redis(cache_key)
                if redis_result is not None:
                    # Promote to memory cache
                    self._set_in_memory(cache_key, redis_result, self.default_ttl)
                    self.stats["redis_hits"] += 1
                    logger.debug("Cache hit (redis)", key=cache_key)
                    return redis_result
            except Exception as e:
                logger.warning("Redis get failed", key=cache_key, error=str(e))
                self.stats["errors"] += 1

        # Cache miss
        self.stats["misses"] += 1
        logger.debug("Cache miss", key=cache_key)
        return None

    async def set(
        self,
        key: str,
        value: Any,
        ttl: int | None = None,
        namespace: str = "default",
        healthcare_context: dict | None = None,
        tier_preference: str = "all",  # "memory", "redis", "all"
    ) -> bool:
        """
        Set value in cache with healthcare compliance checks

        Args:
            key: Cache key
            value: Value to cache
            ttl: Time to live in seconds
            namespace: Cache namespace
            healthcare_context: Healthcare compliance context
            tier_preference: Which cache tiers to use
        """
        if self.healthcare_compliance and healthcare_context:
            # Check if data contains PHI/PII
            if self._contains_phi(value, healthcare_context):
                logger.warning("Attempting to cache PHI data", key=key)
                return False

        cache_key = self._build_cache_key(key, namespace)
        ttl = ttl or self.default_ttl
        success = True

        # Set in memory cache
        if tier_preference in ["memory", "all"]:
            self._set_in_memory(cache_key, value, ttl)

        # Set in Redis cache
        if tier_preference in ["redis", "all"] and self._redis_connected:
            try:
                success &= await self._set_in_redis(cache_key, value, ttl)
            except Exception as e:
                logger.warning("Redis set failed", key=cache_key, error=str(e))
                self.stats["errors"] += 1
                success = False

        if success:
            self.stats["sets"] += 1
            logger.debug("Cache set", key=cache_key, ttl=ttl)

        return success

    async def delete(self, key: str, namespace: str = "default", pattern: bool = False) -> bool:
        """Delete key(s) from all cache tiers"""
        cache_key = self._build_cache_key(key, namespace)

        if pattern:
            return await self._delete_pattern(cache_key)
        else:
            return await self._delete_single(cache_key)

    async def clear_namespace(self, namespace: str) -> bool:
        """Clear all keys in a namespace"""
        pattern = f"{namespace}:*"
        return await self._delete_pattern(pattern)

    async def get_stats(self) -> dict[str, Any]:
        """Get cache statistics"""
        stats = self.stats.copy()

        # Add Redis info if connected
        if self._redis_connected:
            try:
                redis_info = await self._redis.info("memory")  # type: ignore[union-attr]
                stats["redis_memory_used"] = redis_info.get("used_memory_human", "N/A")
                stats["redis_connected"] = True
            except Exception:
                stats["redis_connected"] = False
        else:
            stats["redis_connected"] = False

        # Add memory cache info
        stats["memory_cache_size"] = len(self._memory_cache)
        stats["memory_cache_capacity"] = self.memory_cache_size

        # Calculate hit ratios
        total_requests = sum([stats["memory_hits"], stats["redis_hits"], stats["misses"]])
        if total_requests > 0:
            stats["hit_ratio"] = (stats["memory_hits"] + stats["redis_hits"]) / total_requests
            stats["memory_hit_ratio"] = stats["memory_hits"] / total_requests
            stats["redis_hit_ratio"] = stats["redis_hits"] / total_requests
        else:
            stats["hit_ratio"] = 0.0
            stats["memory_hit_ratio"] = 0.0
            stats["redis_hit_ratio"] = 0.0

        return stats

    def cache(
        self,
        ttl: int | None = None,
        namespace: str = "default",
        key_func: Callable | None = None,
        healthcare_safe: bool = True,
    ):
        """
        Decorator for caching function results

        Usage:
            @cache_manager.cache(ttl=300, namespace="topsis")
            async def calculate_topsis(alternatives, criteria):
                # Expensive calculation
                return result
        """

        def decorator(func: Callable):
            @wraps(func)
            async def wrapper(*args, **kwargs):
                # Generate cache key
                if key_func:
                    cache_key = key_func(*args, **kwargs)
                else:
                    cache_key = self._generate_function_key(func, args, kwargs)

                # Try to get from cache
                cached_result = await self.get(cache_key, namespace)
                if cached_result is not None:
                    logger.debug("Function cache hit", function=func.__name__, key=cache_key)
                    return cached_result

                # Execute function
                result = (
                    await func(*args, **kwargs)
                    if asyncio.iscoroutinefunction(func)
                    else func(*args, **kwargs)
                )

                # Cache result if healthcare safe
                healthcare_context = None
                if healthcare_safe:
                    healthcare_context = {"function": func.__name__, "safe": True}

                await self.set(cache_key, result, ttl, namespace, healthcare_context)

                return result

            return wrapper

        return decorator

    # Private methods
    def _build_cache_key(self, key: str, namespace: str) -> str:
        """Build namespaced cache key"""
        return f"{namespace}:{key}"

    def _get_from_memory(self, key: str) -> Any | None:
        """Get from in-memory cache"""
        if key in self._memory_cache:
            entry = self._memory_cache[key]

            # Check expiration
            if datetime.now() > entry["expires"]:
                del self._memory_cache[key]
                self._memory_access_order.remove(key)
                return None

            # Update access order (LRU)
            self._memory_access_order.remove(key)
            self._memory_access_order.append(key)

            return entry["value"]

        return None

    def _set_in_memory(self, key: str, value: Any, ttl: int):
        """Set in memory cache with LRU eviction"""
        # Evict if at capacity
        while len(self._memory_cache) >= self.memory_cache_size:
            oldest_key = self._memory_access_order.pop(0)
            del self._memory_cache[oldest_key]

        # Set new entry
        expires = datetime.now() + timedelta(seconds=ttl)
        self._memory_cache[key] = {"value": value, "expires": expires}
        self._memory_access_order.append(key)

    async def _get_from_redis(self, key: str) -> Any | None:
        """Get from Redis cache"""
        try:
            data = await self._redis.get(key)  # type: ignore[union-attr]
            if data is None:
                return None

            # Try to deserialize
            try:
                return pickle.loads(data)
            except (pickle.UnpicklingError, TypeError):
                # Fallback to JSON
                return json.loads(data.decode("utf-8"))

        except Exception as e:
            logger.warning("Redis get error", key=key, error=str(e))
            return None

    async def _set_in_redis(self, key: str, value: Any, ttl: int) -> bool:
        """Set in Redis cache"""
        try:
            # Serialize value
            try:
                data = pickle.dumps(value)
            except (pickle.PicklingError, TypeError):
                # Fallback to JSON
                data = json.dumps(value).encode("utf-8")

            await self._redis.setex(key, ttl, data)  # type: ignore[union-attr]
            return True

        except Exception as e:
            logger.warning("Redis set error", key=key, error=str(e))
            return False

    async def _delete_single(self, key: str) -> bool:
        """Delete single key from all tiers"""
        success = True

        # Delete from memory
        if key in self._memory_cache:
            del self._memory_cache[key]
            self._memory_access_order.remove(key)

        # Delete from Redis
        if self._redis_connected:
            try:
                await self._redis.delete(key)  # type: ignore[union-attr]
            except Exception as e:
                logger.warning("Redis delete error", key=key, error=str(e))
                success = False

        if success:
            self.stats["deletes"] += 1

        return success

    async def _delete_pattern(self, pattern: str) -> bool:
        """Delete keys matching pattern"""
        success = True

        # Delete from memory cache
        keys_to_delete = [
            key for key in self._memory_cache.keys() if self._pattern_match(key, pattern)
        ]
        for key in keys_to_delete:
            del self._memory_cache[key]
            self._memory_access_order.remove(key)

        # Delete from Redis
        if self._redis_connected:
            try:
                keys = await self._redis.keys(pattern)  # type: ignore[union-attr]
                if keys:
                    await self._redis.delete(*keys)  # type: ignore[union-attr]
            except Exception as e:
                logger.warning("Redis pattern delete error", pattern=pattern, error=str(e))
                success = False

        return success

    def _pattern_match(self, key: str, pattern: str) -> bool:
        """Simple pattern matching for cache keys"""
        if pattern.endswith("*"):
            prefix = pattern[:-1]
            return key.startswith(prefix)
        return key == pattern

    def _generate_function_key(self, func: Callable, args: tuple, kwargs: dict) -> str:
        """Generate cache key for function call"""
        # Create a hash of function name and arguments
        key_data = {
            "function": func.__name__,
            "args": args,
            "kwargs": sorted(kwargs.items()),  # Sort for consistency
        }

        key_string = json.dumps(key_data, sort_keys=True, default=str)
        return hashlib.md5(key_string.encode()).hexdigest()

    def _contains_phi(self, value: Any, healthcare_context: dict) -> bool:
        """Check if value contains Protected Health Information"""
        if not healthcare_context or healthcare_context.get("safe", False):
            return False

        # Simple PHI detection (extend based on requirements)
        phi_indicators = [
            "ssn",
            "social_security",
            "patient_id",
            "medical_record",
            "phone",
            "email",
            "address",
            "birth_date",
            "dob",
        ]

        value_str = str(value).lower()
        return any(indicator in value_str for indicator in phi_indicators)


# Healthcare-specific cache namespaces
class HealthcareCacheNamespaces:
    """Predefined cache namespaces for healthcare data"""

    TOPSIS_RESULTS = "topsis"
    PATIENT_DATA = "patient"  # Be very careful with PHI
    MEDICATION_INFO = "medication"
    VITAL_SIGNS = "vitals"
    APPOINTMENTS = "appointments"
    ANALYTICS = "analytics"
    REPORTS = "reports"
    USER_SESSIONS = "sessions"
    CALCULATIONS = "calculations"
    CONFIGURATIONS = "config"
    # Surgical / Surgio engine namespaces
    CASE_SCHEDULES = "case_schedules"
    CLINICAL_DATA = "clinical_data"
    SURVIVAL_ANALYSIS = "survival_analysis"
    SURVIVAL_PREDICTIONS = "survival_predictions"
    # Finance / Banko engine namespaces
    FINANCIAL_DATA = "financial_data"


# Global cache manager instance
cache_manager = CacheManager()


# Utility functions for common caching patterns
async def cache_topsis_result(
    alternatives: list[dict],
    criteria: list[dict],
    result: dict,
    ttl: int = 3600,  # 1 hour
) -> bool:
    """Cache TOPSIS calculation result"""
    key_data = {
        "alternatives": len(alternatives),
        "criteria": len(criteria),
        "alt_hash": hashlib.md5(str(alternatives).encode()).hexdigest()[:8],
        "crit_hash": hashlib.md5(str(criteria).encode()).hexdigest()[:8],
    }

    cache_key = f"topsis_{key_data['alt_hash']}_{key_data['crit_hash']}"

    return await cache_manager.set(
        cache_key,
        result,
        ttl=ttl,
        namespace=HealthcareCacheNamespaces.TOPSIS_RESULTS,
        healthcare_context={"safe": True, "type": "calculation"},
    )


async def get_cached_topsis_result(alternatives: list[dict], criteria: list[dict]) -> dict | None:
    """Get cached TOPSIS calculation result"""
    key_data = {
        "alt_hash": hashlib.md5(str(alternatives).encode()).hexdigest()[:8],
        "crit_hash": hashlib.md5(str(criteria).encode()).hexdigest()[:8],
    }

    cache_key = f"topsis_{key_data['alt_hash']}_{key_data['crit_hash']}"

    return await cache_manager.get(cache_key, namespace=HealthcareCacheNamespaces.TOPSIS_RESULTS)


# Cache warming functions
async def warm_cache():
    """Warm up cache with frequently accessed data"""
    logger.info("Starting cache warming process")

    # Warm common configuration
    # This would be implemented based on your specific data access patterns

    logger.info("Cache warming completed")


# Cache maintenance
async def cleanup_expired_cache():
    """Clean up expired cache entries (run periodically)"""
    # Memory cache cleanup happens automatically
    # Redis cleanup could be implemented here if needed
    pass