Files
dify/api/core/helper/provider_cache.py

136 lines
4.8 KiB
Python

import json
from abc import ABC, abstractmethod
from typing import Any, override
from pydantic import JsonValue, TypeAdapter, ValidationError
from extensions.ext_redis import RedisClientWrapper, redis_client
# Plugins define their own keys; the cache owns only the JSON object shape.
type CachedProviderCredentials = dict[str, JsonValue]
_credentials_adapter = TypeAdapter(CachedProviderCredentials)
class ProviderCredentialsCache(ABC):
"""Base class for provider credentials cache"""
def __init__(self, *, redis: RedisClientWrapper | None = None, **kwargs: Any) -> None:
"""Use the supplied Redis wrapper, or the application wrapper if omitted."""
self._redis = redis_client if redis is None else redis
self.cache_key = self._generate_cache_key(**kwargs)
@abstractmethod
def _generate_cache_key(self, **kwargs: Any) -> str:
"""Generate cache key based on subclass implementation"""
pass
def get(self) -> dict[str, Any] | None:
"""Read provider credentials from the initialized Redis client.
Return a JSON object with arbitrary values, or None for a missing,
malformed, non-UTF-8, or non-object entry. Never mutate cached data;
Redis failures propagate so callers can distinguish an outage from a miss.
"""
cached_credentials = self._redis.get(self.cache_key)
if cached_credentials:
try:
return _credentials_adapter.validate_json(cached_credentials.decode("utf-8"))
except (ValidationError, UnicodeDecodeError):
return None
return None
def set(self, config: dict[str, Any]) -> None:
"""Cache provider credentials"""
self._redis.setex(self.cache_key, 86400, json.dumps(config))
def delete(self) -> None:
"""Delete cached provider credentials"""
self._redis.delete(self.cache_key)
class SingletonProviderCredentialsCache(ProviderCredentialsCache):
"""Cache for tool single provider credentials"""
def __init__(self, tenant_id: str, provider_type: str, provider_identity: str):
super().__init__(
tenant_id=tenant_id,
provider_type=provider_type,
provider_identity=provider_identity,
)
@override
def _generate_cache_key(self, **kwargs: Any) -> str:
tenant_id = kwargs["tenant_id"]
provider_type = kwargs["provider_type"]
identity_name = kwargs["provider_identity"]
identity_id = f"{provider_type}.{identity_name}"
return f"{provider_type}_credentials:tenant_id:{tenant_id}:id:{identity_id}"
class ToolProviderCredentialsCache(ProviderCredentialsCache):
"""Cache for tool provider credentials"""
def __init__(
self,
tenant_id: str,
provider: str,
credential_id: str,
*,
fingerprint: str | None = None,
redis: RedisClientWrapper | None = None,
) -> None:
"""Select a snapshot with a fingerprint, or the legacy entry without one.
When no Redis wrapper is supplied, use the application wrapper.
"""
super().__init__(redis=redis, tenant_id=tenant_id, provider=provider, credential_id=credential_id)
self._legacy_cache_key = self.cache_key
self._fingerprint = fingerprint
if fingerprint is not None:
self.cache_key += ":snapshot"
@override
def get(self) -> dict[str, Any] | None:
cached = super().get()
if self._fingerprint is None or cached is None:
return cached
credentials = cached.get("credentials")
if cached.get("fingerprint") == self._fingerprint and isinstance(credentials, dict):
return credentials
return None
@override
def set(self, config: dict[str, Any]) -> None:
if self._fingerprint is not None:
config = {"fingerprint": self._fingerprint, "credentials": config}
super().set(config)
@override
def delete(self) -> None:
# Separate commands also work when Redis Cluster puts the entries in different slots.
self._redis.delete(self._legacy_cache_key)
self._redis.delete(f"{self._legacy_cache_key}:snapshot")
@override
def _generate_cache_key(self, **kwargs: Any) -> str:
tenant_id = kwargs["tenant_id"]
provider = kwargs["provider"]
credential_id = kwargs["credential_id"]
return f"tool_credentials:tenant_id:{tenant_id}:provider:{provider}:credential_id:{credential_id}"
class NoOpProviderCredentialCache:
"""No-op provider credential cache"""
def get(self) -> dict[str, Any] | None:
"""Get cached provider credentials"""
return None
def set(self, config: dict[str, Any]) -> None:
"""Cache provider credentials"""
pass
def delete(self) -> None:
"""Delete cached provider credentials"""
pass