Spaces:
Sleeping
Sleeping
File size: 13,464 Bytes
5868187 |
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 |
"""
存储适配器,提供统一的接口来处理Redis、MongoDB和本地文件存储。
根据配置自动选择存储后端,优先级:Redis > MongoDB > 本地文件。
"""
import asyncio
import os
import json
from typing import Dict, Any, List, Optional, Protocol
from log import log
class StorageBackend(Protocol):
"""存储后端协议"""
async def initialize(self) -> None:
"""初始化存储后端"""
...
async def close(self) -> None:
"""关闭存储后端"""
...
# 凭证管理
async def store_credential(self, filename: str, credential_data: Dict[str, Any]) -> bool:
"""存储凭证数据"""
...
async def get_credential(self, filename: str) -> Optional[Dict[str, Any]]:
"""获取凭证数据"""
...
async def list_credentials(self) -> List[str]:
"""列出所有凭证文件名"""
...
async def delete_credential(self, filename: str) -> bool:
"""删除凭证"""
...
# 状态管理
async def update_credential_state(self, filename: str, state_updates: Dict[str, Any]) -> bool:
"""更新凭证状态"""
...
async def get_credential_state(self, filename: str) -> Dict[str, Any]:
"""获取凭证状态"""
...
async def get_all_credential_states(self) -> Dict[str, Dict[str, Any]]:
"""获取所有凭证状态"""
...
# 配置管理
async def set_config(self, key: str, value: Any) -> bool:
"""设置配置项"""
...
async def get_config(self, key: str, default: Any = None) -> Any:
"""获取配置项"""
...
async def get_all_config(self) -> Dict[str, Any]:
"""获取所有配置"""
...
async def delete_config(self, key: str) -> bool:
"""删除配置项"""
...
# 使用统计管理
async def update_usage_stats(self, filename: str, stats_updates: Dict[str, Any]) -> bool:
"""更新使用统计"""
...
async def get_usage_stats(self, filename: str) -> Dict[str, Any]:
"""获取使用统计"""
...
async def get_all_usage_stats(self) -> Dict[str, Dict[str, Any]]:
"""获取所有使用统计"""
...
class StorageAdapter:
"""存储适配器,根据配置选择存储后端"""
def __init__(self):
self._backend: Optional["StorageBackend"] = None
self._initialized = False
self._lock = asyncio.Lock()
async def initialize(self) -> None:
"""初始化存储适配器"""
async with self._lock:
if self._initialized:
return
# 按优先级检查存储后端:Redis > MongoDB > 本地文件
redis_uri = os.getenv("REDIS_URI", "")
mongodb_uri = os.getenv("MONGODB_URI", "")
# 优先尝试Redis存储
if redis_uri:
try:
from .storage.redis_manager import RedisManager
self._backend = RedisManager()
await self._backend.initialize()
log.info("Using Redis storage backend")
except ImportError as e:
log.error(f"Failed to import Redis backend: {e}")
log.info("Falling back to next available storage backend")
except Exception as e:
log.error(f"Failed to initialize Redis backend: {e}")
log.info("Falling back to next available storage backend")
# 如果Redis不可用或未配置,接下来尝试Postgres(优先级低于Redis)
postgres_dsn = os.getenv("POSTGRES_DSN", "")
if not self._backend and postgres_dsn:
try:
from .storage.postgres_manager import PostgresManager
self._backend = PostgresManager()
await self._backend.initialize()
log.info("Using Postgres storage backend")
except ImportError as e:
log.error(f"Failed to import Postgres backend: {e}")
log.info("Falling back to next available storage backend")
except Exception as e:
log.error(f"Failed to initialize Postgres backend: {e}")
log.info("Falling back to next available storage backend")
# 如果Redis和Postgres不可用,尝试MongoDB存储
if not self._backend and mongodb_uri:
try:
from .storage.mongodb_manager import MongoDBManager
self._backend = MongoDBManager()
await self._backend.initialize()
log.info("Using MongoDB storage backend")
except ImportError as e:
log.error(f"Failed to import MongoDB backend: {e}")
log.info("Falling back to file storage backend")
except Exception as e:
log.error(f"Failed to initialize MongoDB backend: {e}")
log.info("Falling back to file storage backend")
# 如果Redis和MongoDB都不可用,使用文件存储
if not self._backend:
from .storage.file_storage_manager import FileStorageManager
self._backend = FileStorageManager()
await self._backend.initialize()
log.info("Using file storage backend")
self._initialized = True
async def close(self) -> None:
"""关闭存储适配器"""
if self._backend:
await self._backend.close()
self._backend = None
self._initialized = False
def _ensure_initialized(self):
"""确保存储适配器已初始化"""
if not self._initialized or not self._backend:
raise RuntimeError("Storage adapter not initialized")
# ============ 凭证管理 ============
async def store_credential(self, filename: str, credential_data: Dict[str, Any]) -> bool:
"""存储凭证数据"""
self._ensure_initialized()
return await self._backend.store_credential(filename, credential_data)
async def get_credential(self, filename: str) -> Optional[Dict[str, Any]]:
"""获取凭证数据"""
self._ensure_initialized()
return await self._backend.get_credential(filename)
async def list_credentials(self) -> List[str]:
"""列出所有凭证文件名"""
self._ensure_initialized()
return await self._backend.list_credentials()
async def delete_credential(self, filename: str) -> bool:
"""删除凭证"""
self._ensure_initialized()
return await self._backend.delete_credential(filename)
# ============ 状态管理 ============
async def update_credential_state(self, filename: str, state_updates: Dict[str, Any]) -> bool:
"""更新凭证状态"""
self._ensure_initialized()
return await self._backend.update_credential_state(filename, state_updates)
async def get_credential_state(self, filename: str) -> Dict[str, Any]:
"""获取凭证状态"""
self._ensure_initialized()
return await self._backend.get_credential_state(filename)
async def get_all_credential_states(self) -> Dict[str, Dict[str, Any]]:
"""获取所有凭证状态"""
self._ensure_initialized()
return await self._backend.get_all_credential_states()
# ============ 配置管理 ============
async def set_config(self, key: str, value: Any) -> bool:
"""设置配置项"""
self._ensure_initialized()
return await self._backend.set_config(key, value)
async def get_config(self, key: str, default: Any = None) -> Any:
"""获取配置项"""
self._ensure_initialized()
return await self._backend.get_config(key, default)
async def get_all_config(self) -> Dict[str, Any]:
"""获取所有配置"""
self._ensure_initialized()
return await self._backend.get_all_config()
async def delete_config(self, key: str) -> bool:
"""删除配置项"""
self._ensure_initialized()
return await self._backend.delete_config(key)
# ============ 使用统计管理 ============
async def update_usage_stats(self, filename: str, stats_updates: Dict[str, Any]) -> bool:
"""更新使用统计"""
self._ensure_initialized()
return await self._backend.update_usage_stats(filename, stats_updates)
async def get_usage_stats(self, filename: str) -> Dict[str, Any]:
"""获取使用统计"""
self._ensure_initialized()
return await self._backend.get_usage_stats(filename)
async def get_all_usage_stats(self) -> Dict[str, Dict[str, Any]]:
"""获取所有使用统计"""
self._ensure_initialized()
return await self._backend.get_all_usage_stats()
# ============ 工具方法 ============
async def export_credential_to_json(self, filename: str, output_path: str = None) -> bool:
"""将凭证导出为JSON文件"""
self._ensure_initialized()
if hasattr(self._backend, 'export_credential_to_json'):
return await self._backend.export_credential_to_json(filename, output_path)
# MongoDB后端的fallback实现
credential_data = await self.get_credential(filename)
if credential_data is None:
return False
if output_path is None:
output_path = f"{filename}.json"
import aiofiles
try:
async with aiofiles.open(output_path, "w", encoding="utf-8") as f:
await f.write(json.dumps(credential_data, indent=2, ensure_ascii=False))
return True
except Exception:
return False
async def import_credential_from_json(self, json_path: str, filename: str = None) -> bool:
"""从JSON文件导入凭证"""
self._ensure_initialized()
if hasattr(self._backend, 'import_credential_from_json'):
return await self._backend.import_credential_from_json(json_path, filename)
# MongoDB后端的fallback实现
try:
import aiofiles
async with aiofiles.open(json_path, "r", encoding="utf-8") as f:
content = await f.read()
credential_data = json.loads(content)
if filename is None:
filename = os.path.basename(json_path)
return await self.store_credential(filename, credential_data)
except Exception:
return False
def get_backend_type(self) -> str:
"""获取当前存储后端类型"""
if not self._backend:
return "none"
# 检查后端类型
backend_class_name = self._backend.__class__.__name__
if "File" in backend_class_name or "file" in backend_class_name.lower():
return "file"
elif "MongoDB" in backend_class_name or "mongo" in backend_class_name.lower():
return "mongodb"
elif "Redis" in backend_class_name or "redis" in backend_class_name.lower():
return "redis"
else:
return "unknown"
async def get_backend_info(self) -> Dict[str, Any]:
"""获取存储后端信息"""
self._ensure_initialized()
backend_type = self.get_backend_type()
info = {
"backend_type": backend_type,
"initialized": self._initialized
}
# 获取底层存储信息
if hasattr(self._backend, 'get_database_info'):
try:
db_info = await self._backend.get_database_info()
info.update(db_info)
except Exception as e:
info["database_error"] = str(e)
else:
backend_type = self.get_backend_type()
if backend_type == "file":
info.update({
"credentials_dir": getattr(self._backend, '_credentials_dir', None),
"state_file": getattr(self._backend, '_state_file', None),
"config_file": getattr(self._backend, '_config_file', None)
})
elif backend_type == "redis":
info.update({
"redis_url": getattr(self._backend, '_redis_url', None),
"connection_pool_size": getattr(self._backend, '_pool_size', None)
})
return info
# 全局存储适配器实例
_storage_adapter: Optional[StorageAdapter] = None
async def get_storage_adapter() -> StorageAdapter:
"""获取全局存储适配器实例"""
global _storage_adapter
if _storage_adapter is None:
_storage_adapter = StorageAdapter()
await _storage_adapter.initialize()
return _storage_adapter
async def close_storage_adapter():
"""关闭全局存储适配器"""
global _storage_adapter
if _storage_adapter:
await _storage_adapter.close()
_storage_adapter = None
|