Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /ViperJuice_Code-Index-MCP /mcp_server /interfaces /shared_interfaces.py
| """ | |
| Shared Interfaces for MCP Server | |
| Cross-cutting interfaces and common types used across all modules. | |
| These interfaces define the contracts for logging, metrics, configuration, | |
| caching, events, and other shared concerns. | |
| """ | |
| from abc import ABC, abstractmethod | |
| from dataclasses import dataclass | |
| from datetime import datetime | |
| from enum import Enum | |
| from typing import ( | |
| Any, | |
| Awaitable, | |
| Callable, | |
| ContextManager, | |
| Dict, | |
| Generic, | |
| List, | |
| Optional, | |
| TypeVar, | |
| ) | |
| T = TypeVar("T") | |
| # ======================================== | |
| # Common Enums | |
| # ======================================== | |
| class LogLevel(Enum): | |
| """Log levels for the logging system""" | |
| DEBUG = "debug" | |
| INFO = "info" | |
| WARNING = "warning" | |
| ERROR = "error" | |
| CRITICAL = "critical" | |
| class IndexStatus(Enum): | |
| """Status of indexing operations""" | |
| PENDING = "pending" | |
| IN_PROGRESS = "in_progress" | |
| COMPLETED = "completed" | |
| FAILED = "failed" | |
| CANCELLED = "cancelled" | |
| class PluginStatus(Enum): | |
| """Status of plugin lifecycle""" | |
| UNLOADED = "unloaded" | |
| LOADING = "loading" | |
| READY = "ready" | |
| ERROR = "error" | |
| DISABLED = "disabled" | |
| # ======================================== | |
| # Common Data Types | |
| # ======================================== | |
| class Event: | |
| """Event data structure for the event bus""" | |
| event_type: str | |
| timestamp: datetime | |
| source: str | |
| data: Dict[str, Any] | |
| class Error: | |
| """Error information with context""" | |
| code: str | |
| message: str | |
| details: Dict[str, Any] | |
| timestamp: datetime | |
| class Result(Generic[T]): | |
| """Result wrapper for operations that can succeed or fail""" | |
| success: bool | |
| value: Optional[T] = None | |
| error: Optional[Error] = None | |
| metadata: Dict[str, Any] = None | |
| def success_result(cls, value: T, metadata: Dict[str, Any] = None) -> "Result[T]": | |
| """Create a successful result""" | |
| return cls(success=True, value=value, metadata=metadata or {}) | |
| def error_result(cls, error: Error, metadata: Dict[str, Any] = None) -> "Result[T]": | |
| """Create an error result""" | |
| return cls(success=False, error=error, metadata=metadata or {}) | |
| # ======================================== | |
| # Cross-Cutting Interfaces | |
| # ======================================== | |
| class ILogger(ABC): | |
| """Logging interface for all components""" | |
| def log(self, level: LogLevel, message: str, context: Dict[str, Any] = None) -> None: | |
| """Log a message with specified level and context""" | |
| def debug(self, message: str, context: Dict[str, Any] = None) -> None: | |
| """Log a debug message""" | |
| def info(self, message: str, context: Dict[str, Any] = None) -> None: | |
| """Log an info message""" | |
| def warning(self, message: str, context: Dict[str, Any] = None) -> None: | |
| """Log a warning message""" | |
| def error( | |
| self, message: str, exception: Exception = None, context: Dict[str, Any] = None | |
| ) -> None: | |
| """Log an error message with optional exception""" | |
| class IMetrics(ABC): | |
| """Metrics collection interface""" | |
| def increment(self, metric: str, value: int = 1, tags: Dict[str, str] = None) -> None: | |
| """Increment a counter metric""" | |
| def gauge(self, metric: str, value: float, tags: Dict[str, str] = None) -> None: | |
| """Set a gauge metric value""" | |
| def histogram(self, metric: str, value: float, tags: Dict[str, str] = None) -> None: | |
| """Record a histogram value""" | |
| def timer(self, metric: str, tags: Dict[str, str] = None) -> ContextManager[None]: | |
| """Create a timing context manager""" | |
| class IConfig(ABC): | |
| """Configuration management interface""" | |
| def get(self, key: str, default: Any = None) -> Any: | |
| """Get a configuration value""" | |
| def get_int(self, key: str, default: int = 0) -> int: | |
| """Get an integer configuration value""" | |
| def get_bool(self, key: str, default: bool = False) -> bool: | |
| """Get a boolean configuration value""" | |
| def get_str(self, key: str, default: str = "") -> str: | |
| """Get a string configuration value""" | |
| def get_dict(self, key: str, default: Dict[str, Any] = None) -> Dict[str, Any]: | |
| """Get a dictionary configuration value""" | |
| def reload(self) -> None: | |
| """Reload configuration from source""" | |
| class ICache(ABC): | |
| """Caching interface""" | |
| def get(self, key: str) -> Optional[Any]: | |
| """Get a value from cache""" | |
| def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None: | |
| """Set a value in cache with optional TTL""" | |
| def delete(self, key: str) -> None: | |
| """Delete a value from cache""" | |
| def exists(self, key: str) -> bool: | |
| """Check if a key exists in cache""" | |
| def clear(self) -> None: | |
| """Clear all cache entries""" | |
| class IEventBus(ABC): | |
| """Event bus interface for pub/sub messaging""" | |
| def publish(self, event: Event) -> None: | |
| """Publish an event""" | |
| def subscribe(self, event_type: str, handler: Callable[[Event], None]) -> None: | |
| """Subscribe to an event type""" | |
| def unsubscribe(self, event_type: str, handler: Callable[[Event], None]) -> None: | |
| """Unsubscribe from an event type""" | |
| # ======================================== | |
| # Security Interfaces | |
| # ======================================== | |
| class ISecurityContext(ABC): | |
| """Security context for requests""" | |
| def user_id(self) -> Optional[str]: | |
| """Get the current user ID""" | |
| def roles(self) -> List[str]: | |
| """Get the current user's roles""" | |
| def permissions(self) -> List[str]: | |
| """Get the current user's permissions""" | |
| def is_authenticated(self) -> bool: | |
| """Check if the user is authenticated""" | |
| def is_authorized(self, permission: str) -> bool: | |
| """Check if the user has a specific permission""" | |
| class IValidator(ABC): | |
| """Validation interface""" | |
| def validate(self, data: Any, schema: Any) -> Result[Any]: | |
| """Validate data against a schema""" | |
| def sanitize(self, data: Any) -> Any: | |
| """Sanitize input data""" | |
| # ======================================== | |
| # Async Support | |
| # ======================================== | |
| class IAsyncSupport(ABC): | |
| """Async utilities interface""" | |
| async def run_async(self, func: Callable, *args, **kwargs) -> Any: | |
| """Run a function asynchronously""" | |
| async def gather(self, *awaitables: Awaitable) -> List[Any]: | |
| """Gather multiple awaitables""" | |
| def create_task(self, coro) -> Any: | |
| """Create an async task""" | |
| # ======================================== | |
| # Repository Pattern | |
| # ======================================== | |
| class IRepository(ABC, Generic[T]): | |
| """Repository interface for data access""" | |
| def find(self, id: str) -> Optional[T]: | |
| """Find an entity by ID""" | |
| def find_all(self, filter_criteria: Dict[str, Any] = None) -> List[T]: | |
| """Find all entities matching criteria""" | |
| def save(self, entity: T) -> T: | |
| """Save an entity""" | |
| def delete(self, id: str) -> bool: | |
| """Delete an entity by ID""" | |
| def exists(self, id: str) -> bool: | |
| """Check if an entity exists""" | |
| class IAsyncRepository(ABC, Generic[T]): | |
| """Async repository interface for data access""" | |
| async def find(self, id: str) -> Optional[T]: | |
| """Find an entity by ID""" | |
| async def find_all(self, filter_criteria: Dict[str, Any] = None) -> List[T]: | |
| """Find all entities matching criteria""" | |
| async def save(self, entity: T) -> T: | |
| """Save an entity""" | |
| async def delete(self, id: str) -> bool: | |
| """Delete an entity by ID""" | |
| async def exists(self, id: str) -> bool: | |
| """Check if an entity exists""" | |
| # ======================================== | |
| # Factory Pattern | |
| # ======================================== | |
| class IFactory(ABC, Generic[T]): | |
| """Factory interface for creating objects""" | |
| def create(self, *args, **kwargs) -> T: | |
| """Create an object""" | |
| def create_from_config(self, config: Dict[str, Any]) -> T: | |
| """Create an object from configuration""" | |
| # ======================================== | |
| # Observer Pattern | |
| # ======================================== | |
| class IObserver(ABC): | |
| """Observer interface for the observer pattern""" | |
| def update(self, event: Event) -> None: | |
| """Handle an update event""" | |
| class IObservable(ABC): | |
| """Observable interface for the observer pattern""" | |
| def attach(self, observer: IObserver) -> None: | |
| """Attach an observer""" | |
| def detach(self, observer: IObserver) -> None: | |
| """Detach an observer""" | |
| def notify(self, event: Event) -> None: | |
| """Notify all observers""" | |
| # ======================================== | |
| # Common Exceptions | |
| # ======================================== | |
| class ValidationError(Exception): | |
| """Validation error exception""" | |
| def __init__(self, field: str, value: Any, constraint: str): | |
| self.field = field | |
| self.value = value | |
| self.constraint = constraint | |
| super().__init__(f"Validation error for field '{field}': {constraint}") | |
| class NotFoundError(Exception): | |
| """Resource not found exception""" | |
| def __init__(self, resource_type: str, resource_id: str): | |
| self.resource_type = resource_type | |
| self.resource_id = resource_id | |
| super().__init__(f"{resource_type} with ID '{resource_id}' not found") | |
| class PermissionError(Exception): | |
| """Permission denied exception""" | |
| def __init__(self, required_permission: str, user_id: str): | |
| self.required_permission = required_permission | |
| self.user_id = user_id | |
| super().__init__(f"User '{user_id}' lacks permission '{required_permission}'") | |
| class ConfigurationError(Exception): | |
| """Configuration error exception""" | |
| def __init__(self, config_key: str, expected_type: str, actual_value: Any): | |
| self.config_key = config_key | |
| self.expected_type = expected_type | |
| self.actual_value = actual_value | |
| super().__init__( | |
| f"Config key '{config_key}' expected {expected_type}, got {type(actual_value).__name__}" | |
| ) | |
| class PluginError(Exception): | |
| """Plugin operation error exception""" | |
| def __init__(self, plugin_name: str, operation: str, cause: Exception = None): | |
| self.plugin_name = plugin_name | |
| self.operation = operation | |
| self.cause = cause | |
| super().__init__(f"Plugin '{plugin_name}' failed during '{operation}': {cause}") | |
Xet Storage Details
- Size:
- 11.6 kB
- Xet hash:
- f6c8c061508143e04a825f6d6e53853e961c2493a912995854b0d93e28c76fa1
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.