Skip to content

Commit 1211bf6

Browse files
committed
feat(cache): requested changes
1 parent c7bd8fb commit 1211bf6

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

infisical_sdk/resources/secrets.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,9 @@ def update_secret_by_name(
189189

190190
cache_key = self.cache.compute_cache_key(CACHE_KEY_SINGLE_SECRET, **cache_params)
191191
self.cache.unset(cache_key)
192-
192+
193+
# Invalidates all list secret cache
194+
self.cache.invalidate_operation(CACHE_KEY_LIST_SECRETS)
193195

194196
return result.data.secret
195197

@@ -224,4 +226,7 @@ def delete_secret_by_name(
224226
cache_key = self.cache.compute_cache_key(CACHE_KEY_SINGLE_SECRET, **cache_params)
225227
self.cache.unset(cache_key)
226228

229+
# Invalidates all list secret cache
230+
self.cache.invalidate_operation(CACHE_KEY_LIST_SECRETS)
231+
227232
return result.data.secret

infisical_sdk/util/secrets_cache.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
from hashlib import sha256
88
import pickle
99

10+
MAX_CACHE_SIZE = 1000
11+
1012
class SecretsCache:
1113
def __init__(self, ttl_seconds: int = 300) -> None:
1214
if ttl_seconds is None or ttl_seconds <= 0:
@@ -29,7 +31,7 @@ def compute_cache_key(self, operation_name: str, **kwargs) -> str:
2931
sorted_kwargs = sorted(kwargs.items())
3032
json_str = json.dumps(sorted_kwargs)
3133

32-
return sha256(f"{operation_name}:{json_str}".encode()).hexdigest()
34+
return f"{operation_name}-{sha256(json_str.encode()).hexdigest()}"
3335

3436
def get(self, cache_key: str) -> Any:
3537
if not self.enabled:
@@ -55,13 +57,28 @@ def set(self, cache_key: str, value: Any) -> None:
5557
serialized_value = pickle.dumps(value)
5658
self.cache[cache_key] = (serialized_value, time.time())
5759

60+
if len(self.cache) > MAX_CACHE_SIZE:
61+
oldest_key = min(self.cache.keys(), key=lambda k: self.cache[k][1]) # oldest key based on timestamp
62+
self.cache.pop(oldest_key)
63+
64+
65+
5866
def unset(self, cache_key: str) -> None:
5967
if not self.enabled:
6068
return
6169

6270
with self.lock:
6371
self.cache.pop(cache_key, None)
6472

73+
def invalidate_operation(self, operation_name: str) -> None:
74+
if not self.enabled:
75+
return
76+
77+
with self.lock:
78+
for key in list(self.cache.keys()):
79+
if key.startswith(operation_name):
80+
self.cache.pop(key, None)
81+
6582

6683
def _cleanup_expired_items(self) -> None:
6784
"""Remove all expired items from the cache."""

0 commit comments

Comments
 (0)