|
| 1 | +"""SDK-internal cache façade. |
| 2 | +
|
| 3 | +SDK modules instantiate :class:`Cache` per-client and call its |
| 4 | +``get``/``set``/``evict``/``reset`` methods. The façade handles: |
| 5 | +
|
| 6 | +- Selecting the active backend (per-client override or global default). |
| 7 | +- Building namespaced, isolation-scoped keys. |
| 8 | +- Applying the expiry buffer before forwarding TTLs to the backend. |
| 9 | +- Honouring the ``enabled`` flag. |
| 10 | +
|
| 11 | +This class is **not part of the public API** and is not exported from |
| 12 | +``sap_cloud_sdk.cache``. Import it directly:: |
| 13 | +
|
| 14 | + from sap_cloud_sdk.cache._cache import Cache |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import logging |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +from sap_cloud_sdk.cache._config import CacheConfig, get_cache_config |
| 23 | +from sap_cloud_sdk.cache._isolation import build_isolation_key |
| 24 | +from sap_cloud_sdk.cache._lru_backend import InMemoryLRUBackend |
| 25 | +from sap_cloud_sdk.cache.exceptions import BackendError |
| 26 | + |
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
| 29 | + |
| 30 | +class Cache: |
| 31 | + """Per-client cache façade. |
| 32 | +
|
| 33 | + Args: |
| 34 | + config: Per-client override. When ``None``, the global config set via |
| 35 | + :func:`~sap_cloud_sdk.cache._config.configure_cache` is used. |
| 36 | + The config is snapshotted at construction time — subsequent calls |
| 37 | + to :func:`configure_cache` do not affect an existing ``Cache``. |
| 38 | + """ |
| 39 | + |
| 40 | + def __init__(self, config: CacheConfig | None = None) -> None: |
| 41 | + self._config: CacheConfig = config if config is not None else get_cache_config() |
| 42 | + self._backend = self._resolve_backend() |
| 43 | + |
| 44 | + # ------------------------------------------------------------------ |
| 45 | + # Public façade methods |
| 46 | + # ------------------------------------------------------------------ |
| 47 | + |
| 48 | + def get( |
| 49 | + self, |
| 50 | + namespace: str, |
| 51 | + key: str, |
| 52 | + tenant_id: str, |
| 53 | + user_id: str | None = None, |
| 54 | + ) -> Any | None: |
| 55 | + """Return a cached value, or ``None`` on miss or when disabled. |
| 56 | +
|
| 57 | + Args: |
| 58 | + namespace: Domain namespace, e.g. ``"destination"``. |
| 59 | + key: Domain-specific key, e.g. the destination name. |
| 60 | + tenant_id: Tenant identifier for isolation key derivation. |
| 61 | + user_id: Optional user identifier. Drives ``TENANT_USER`` |
| 62 | + isolation when present (and no explicit strategy override). |
| 63 | + """ |
| 64 | + if not self._config.enabled: |
| 65 | + return None |
| 66 | + |
| 67 | + full_key = self._make_full_key(namespace, key, tenant_id, user_id) |
| 68 | + try: |
| 69 | + return self._backend.get(full_key) |
| 70 | + except Exception as e: |
| 71 | + logger.warning("cache backend get() raised an exception: %s", e) |
| 72 | + return None |
| 73 | + |
| 74 | + def set( |
| 75 | + self, |
| 76 | + namespace: str, |
| 77 | + key: str, |
| 78 | + value: Any, |
| 79 | + ttl_seconds: int | None, |
| 80 | + tenant_id: str, |
| 81 | + user_id: str | None = None, |
| 82 | + ) -> None: |
| 83 | + """Store a value in the cache. |
| 84 | +
|
| 85 | + The effective TTL forwarded to the backend is: |
| 86 | + - *ttl_seconds* − ``expiry_buffer_seconds`` when *ttl_seconds* is given. |
| 87 | + - ``default_ttl_seconds`` − ``expiry_buffer_seconds`` as fallback. |
| 88 | +
|
| 89 | + The result is clamped to a minimum of 1 second. |
| 90 | +
|
| 91 | + Args: |
| 92 | + namespace: Domain namespace. |
| 93 | + key: Domain-specific key. |
| 94 | + value: Value to cache (must be serialisable by the backend). |
| 95 | + ttl_seconds: Natural TTL derived from the resource (e.g. token |
| 96 | + ``exp`` minus now). Pass ``None`` to use the configured |
| 97 | + default. |
| 98 | + tenant_id: Tenant identifier for isolation key derivation. |
| 99 | + user_id: Optional user identifier. |
| 100 | + """ |
| 101 | + if not self._config.enabled: |
| 102 | + return |
| 103 | + |
| 104 | + raw_ttl = ( |
| 105 | + ttl_seconds if ttl_seconds is not None else self._config.default_ttl_seconds |
| 106 | + ) |
| 107 | + effective_ttl = max(raw_ttl - self._config.expiry_buffer_seconds, 1) |
| 108 | + |
| 109 | + full_key = self._make_full_key(namespace, key, tenant_id, user_id) |
| 110 | + try: |
| 111 | + self._backend.set(full_key, value, effective_ttl) |
| 112 | + except Exception as e: |
| 113 | + raise BackendError(f"cache backend set() failed: {e}") from e |
| 114 | + |
| 115 | + def evict( |
| 116 | + self, |
| 117 | + namespace: str, |
| 118 | + key: str, |
| 119 | + tenant_id: str, |
| 120 | + user_id: str | None = None, |
| 121 | + ) -> None: |
| 122 | + """Remove a single entry (no-op if absent or cache is disabled). |
| 123 | +
|
| 124 | + Args: |
| 125 | + namespace: Domain namespace. |
| 126 | + key: Domain-specific key. |
| 127 | + tenant_id: Tenant identifier. |
| 128 | + user_id: Optional user identifier. |
| 129 | + """ |
| 130 | + if not self._config.enabled: |
| 131 | + return |
| 132 | + |
| 133 | + full_key = self._make_full_key(namespace, key, tenant_id, user_id) |
| 134 | + try: |
| 135 | + self._backend.delete(full_key) |
| 136 | + except Exception as e: |
| 137 | + logger.warning("cache backend delete() raised an exception: %s", e) |
| 138 | + |
| 139 | + def reset(self) -> None: |
| 140 | + """Clear all entries from the backend. |
| 141 | +
|
| 142 | + Use with care in production — this forces a full re-fetch of every |
| 143 | + cached resource on the next access. |
| 144 | + """ |
| 145 | + try: |
| 146 | + self._backend.clear() |
| 147 | + except Exception as e: |
| 148 | + logger.warning("cache backend clear() raised an exception: %s", e) |
| 149 | + |
| 150 | + # ------------------------------------------------------------------ |
| 151 | + # Private helpers |
| 152 | + # ------------------------------------------------------------------ |
| 153 | + |
| 154 | + def _resolve_backend(self) -> Any: |
| 155 | + if self._config.backend is not None: |
| 156 | + return self._config.backend |
| 157 | + return InMemoryLRUBackend( |
| 158 | + max_size=self._config.max_size, |
| 159 | + on_evict=self._config.on_evict, |
| 160 | + ) |
| 161 | + |
| 162 | + def _make_full_key( |
| 163 | + self, |
| 164 | + namespace: str, |
| 165 | + key: str, |
| 166 | + tenant_id: str, |
| 167 | + user_id: str | None, |
| 168 | + ) -> str: |
| 169 | + isolation_key = build_isolation_key( |
| 170 | + tenant_id=tenant_id, |
| 171 | + user_id=user_id, |
| 172 | + strategy=self._config.isolation_strategy, |
| 173 | + ) |
| 174 | + return f"{namespace}::{isolation_key}::{key}" |
0 commit comments