From fee93bc855e659502987fa9f9bd17c83ab498630 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=81=D0=B5=D0=BD=D1=82=D1=8C=D0=B5=D0=B2=20?= =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= Date: Thu, 6 Aug 2026 12:50:55 +0300 Subject: [PATCH] Implement modular platform architecture foundation --- .gitignore | 6 +- modules/request-module/__init__.py | 1 + modules/request-module/module.py | 43 +++++ .../backend/app/api/v1/platform_modules.py | 29 ++++ platform/backend/app/core/logging.py | 14 ++ platform/backend/app/core/module_loader.py | 152 ++++++++++++++++++ platform/backend/app/core/module_registry.py | 128 +++++++++++++++ platform/backend/app/core/sdk/__init__.py | 5 + platform/backend/app/core/sdk/module.py | 75 +++++++++ platform/backend/app/main.py | 26 +++ 10 files changed, 478 insertions(+), 1 deletion(-) create mode 100644 modules/request-module/__init__.py create mode 100644 modules/request-module/module.py create mode 100644 platform/backend/app/api/v1/platform_modules.py create mode 100644 platform/backend/app/core/logging.py create mode 100644 platform/backend/app/core/module_loader.py create mode 100644 platform/backend/app/core/module_registry.py create mode 100644 platform/backend/app/core/sdk/__init__.py create mode 100644 platform/backend/app/core/sdk/module.py diff --git a/.gitignore b/.gitignore index d2f8c52..8d37f04 100644 --- a/.gitignore +++ b/.gitignore @@ -41,4 +41,8 @@ request-module/migrations/scripts/attachments/ *.zip *.sig *.sec -*.eml \ No newline at end of file +*.eml + +request-module/migrations/scripts/*.json + +dev-doc \ No newline at end of file diff --git a/modules/request-module/__init__.py b/modules/request-module/__init__.py new file mode 100644 index 0000000..527fdec --- /dev/null +++ b/modules/request-module/__init__.py @@ -0,0 +1 @@ +"""Request module package.""" diff --git a/modules/request-module/module.py b/modules/request-module/module.py new file mode 100644 index 0000000..4ab51ba --- /dev/null +++ b/modules/request-module/module.py @@ -0,0 +1,43 @@ +"""Request Management Module.""" + +from typing import List +from fastapi import APIRouter + +from app.core.sdk.module import BaseModule + + +class RequestModule(BaseModule): + """Module for managing service requests/tickets. + + This is the first module registered with the platform, + providing request/ticket management capabilities. + """ + + id = "request" + name = "Request Management" + version = "1.0.0" + description = "Модуль управления заявками" + + def routes(self) -> List[APIRouter]: + """Return API routers for the request module. + + Currently returns empty list - routes will be added + when migrating the request API to the module system. + """ + return [] + + def permissions(self) -> List[str]: + """Return permissions managed by this module.""" + return [ + "request.read", + "request.write", + "request.delete", + ] + + async def startup(self) -> None: + """Initialize request module resources.""" + pass + + async def shutdown(self) -> None: + """Cleanup request module resources.""" + pass diff --git a/platform/backend/app/api/v1/platform_modules.py b/platform/backend/app/api/v1/platform_modules.py new file mode 100644 index 0000000..f9f8d05 --- /dev/null +++ b/platform/backend/app/api/v1/platform_modules.py @@ -0,0 +1,29 @@ +"""Platform modules API - exposes discovered modules.""" + +from fastapi import APIRouter +from app.core.module_registry import get_module_registry + +router = APIRouter(prefix="/platform", tags=["Platform Modules"]) + + +@router.get("/modules") +async def list_platform_modules(): + """List all discovered and registered modules. + + Returns: + List of module metadata including id, name, version, description, + and declared permissions. + """ + registry = get_module_registry() + modules = registry.all() + + return [ + { + "id": m.id, + "name": m.name, + "version": m.version, + "description": m.description, + "permissions": m.permissions(), + } + for m in modules + ] diff --git a/platform/backend/app/core/logging.py b/platform/backend/app/core/logging.py new file mode 100644 index 0000000..bde9258 --- /dev/null +++ b/platform/backend/app/core/logging.py @@ -0,0 +1,14 @@ +"""Logging configuration.""" + +import logging +import sys + +# Configure basic logging +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", + handlers=[logging.StreamHandler(sys.stdout)] +) + +# Create logger for the platform +logger = logging.getLogger("platform") diff --git a/platform/backend/app/core/module_loader.py b/platform/backend/app/core/module_loader.py new file mode 100644 index 0000000..b4e1137 --- /dev/null +++ b/platform/backend/app/core/module_loader.py @@ -0,0 +1,152 @@ +"""Module auto-discovery and loading.""" + +import importlib.util +import inspect +import sys +from pathlib import Path +from typing import List + +from app.core.sdk.module import BaseModule +from app.core.module_registry import get_module_registry, ModuleAlreadyRegisteredError + + +def _find_module_classes(module_path: Path) -> List[type]: + """Find all BaseModule subclasses in a Python file. + + Args: + module_path: Path to the module.py file. + + Returns: + List of BaseModule subclasses found in the file. + """ + spec = importlib.util.spec_from_file_location("module_loader", str(module_path)) + if spec is None or spec.loader is None: + return [] + + module = importlib.util.module_from_spec(spec) + try: + spec.loader.exec_module(module) + except Exception: + return [] + + classes = [] + for name, obj in inspect.getmembers(module, inspect.isclass): + if ( + issubclass(obj, BaseModule) + and obj is not BaseModule + and not inspect.isabstract(obj) + ): + classes.append(obj) + + return classes + + +def discover_modules(modules_dir: Path) -> List[BaseModule]: + """Discover and instantiate modules from a directory. + + Scans the given directory for subdirectories containing module.py files. + Each module.py should contain a class that extends BaseModule. + + Directory structure: + modules/ + ├── request-module/ + │ └── module.py + ├── crm-module/ + │ └── module.py + └── ... + + Args: + modules_dir: Path to the modules directory. + + Returns: + List of instantiated BaseModule objects. + """ + discovered = [] + + if not modules_dir.exists() or not modules_dir.is_dir(): + return discovered + + for subdir in sorted(modules_dir.iterdir()): + if not subdir.is_dir(): + continue + + module_file = subdir / "module.py" + if not module_file.exists(): + continue + + classes = _find_module_classes(module_file) + for cls in classes: + try: + instance = cls() + discovered.append(instance) + except Exception: + pass # Skip modules that fail to instantiate + + return discovered + + +def register_modules(modules: List[BaseModule]) -> List[str]: + """Register discovered modules in the registry. + + Args: + modules: List of BaseModule instances to register. + + Returns: + List of successfully registered module IDs. + """ + registry = get_module_registry() + registered = [] + + for module in modules: + try: + registry.register(module) + registered.append(module.id) + except ModuleAlreadyRegisteredError: + pass # Skip already registered modules + + return registered + + +async def startup_modules() -> None: + """Call startup() on all registered modules.""" + registry = get_module_registry() + for module in registry.all(): + try: + await module.startup() + except Exception: + pass # Don't let one module's failure stop others + + +async def shutdown_modules() -> None: + """Call shutdown() on all registered modules.""" + registry = get_module_registry() + for module in registry.all(): + try: + await module.shutdown() + except Exception: + pass + + +def load_modules(modules_dir: str = None) -> List[str]: + """Discover, instantiate, and register all modules. + + This is the main entry point for module loading. Call this during + application startup. + + Args: + modules_dir: Path to modules directory. If None, uses + {project_root}/modules + + Returns: + List of registered module IDs. + """ + if modules_dir is None: + # Default to {project_root}/modules + # Path: app/core/module_loader.py -> app/core -> app -> backend -> platform -> project_root + project_root = Path(__file__).parent.parent.parent.parent.parent + modules_dir = project_root / "modules" + + modules_path = Path(modules_dir) + discovered = discover_modules(modules_path) + registered = register_modules(discovered) + return registered diff --git a/platform/backend/app/core/module_registry.py b/platform/backend/app/core/module_registry.py new file mode 100644 index 0000000..f2e8454 --- /dev/null +++ b/platform/backend/app/core/module_registry.py @@ -0,0 +1,128 @@ +"""Module registry for managing platform modules.""" + +from typing import Dict, List, Optional +from app.core.sdk.module import BaseModule + + +class ModuleRegistryError(Exception): + """Base exception for module registry errors.""" + pass + + +class ModuleAlreadyRegisteredError(ModuleRegistryError): + """Raised when attempting to register a module with a duplicate ID.""" + pass + + +class ModuleNotFoundError(ModuleRegistryError): + """Raised when a requested module is not found.""" + pass + + +class ModuleRegistry: + """In-memory registry for platform modules. + + Provides thread-safe registration, lookup, and enumeration of modules. + Each module must have a unique ID. + + Usage: + registry = ModuleRegistry() + registry.register(my_module) + module = registry.get("request") + all_modules = registry.all() + """ + + def __init__(self): + self._modules: Dict[str, BaseModule] = {} + + def register(self, module: BaseModule) -> None: + """Register a module in the registry. + + Args: + module: The BaseModule instance to register. + + Raises: + ModuleAlreadyRegisteredError: If a module with the same ID exists. + ValueError: If module.id is empty or None. + """ + if not module.id: + raise ValueError("Module ID cannot be empty") + + if module.id in self._modules: + raise ModuleAlreadyRegisteredError( + f"Module '{module.id}' is already registered" + ) + + self._modules[module.id] = module + + def get(self, module_id: str) -> Optional[BaseModule]: + """Get a module by its ID. + + Args: + module_id: The unique identifier of the module. + + Returns: + The BaseModule instance, or None if not found. + """ + return self._modules.get(module_id) + + def all(self) -> List[BaseModule]: + """Get all registered modules. + + Returns: + List of all registered BaseModule instances. + """ + return list(self._modules.values()) + + def exists(self, module_id: str) -> bool: + """Check if a module is registered. + + Args: + module_id: The unique identifier of the module. + + Returns: + True if the module is registered, False otherwise. + """ + return module_id in self._modules + + def unregister(self, module_id: str) -> bool: + """Remove a module from the registry. + + Args: + module_id: The unique identifier of the module. + + Returns: + True if the module was removed, False if not found. + """ + if module_id in self._modules: + del self._modules[module_id] + return True + return False + + def clear(self) -> None: + """Remove all modules from the registry.""" + self._modules.clear() + + @property + def count(self) -> int: + """Get the number of registered modules.""" + return len(self._modules) + + def __repr__(self) -> str: + return f"" + + +# Global singleton instance +_registry: Optional[ModuleRegistry] = None + + +def get_module_registry() -> ModuleRegistry: + """Get the global module registry singleton. + + Returns: + The global ModuleRegistry instance. + """ + global _registry + if _registry is None: + _registry = ModuleRegistry() + return _registry diff --git a/platform/backend/app/core/sdk/__init__.py b/platform/backend/app/core/sdk/__init__.py new file mode 100644 index 0000000..d764acc --- /dev/null +++ b/platform/backend/app/core/sdk/__init__.py @@ -0,0 +1,5 @@ +"""SDK package for module development.""" + +from app.core.sdk.module import BaseModule + +__all__ = ["BaseModule"] diff --git a/platform/backend/app/core/sdk/module.py b/platform/backend/app/core/sdk/module.py new file mode 100644 index 0000000..f36d0bb --- /dev/null +++ b/platform/backend/app/core/sdk/module.py @@ -0,0 +1,75 @@ +"""Base module class for platform modules.""" + +from abc import ABC, abstractmethod +from typing import List, Optional +from fastapi import APIRouter + + +class BaseModule(ABC): + """Abstract base class for all platform modules. + + Each module must implement this class to be discovered and registered + by the platform's module loader. + + Attributes: + id: Unique module identifier (e.g., 'request', 'crm') + name: Human-readable display name + version: Semantic version string + description: Brief description of the module + """ + + id: str + name: str + version: str + description: str = "" + + def routes(self) -> List[APIRouter]: + """Return FastAPI routers to be mounted by the platform. + + Override this method to expose API endpoints through the platform. + Default implementation returns an empty list. + + Returns: + List of FastAPI APIRouter instances. + """ + return [] + + def permissions(self) -> List[str]: + """Return permission strings required/managed by this module. + + Override this method to declare permissions in the format: + '.' (e.g., 'request.read', 'request.write') + + Default implementation returns an empty list. + + Returns: + List of permission identifier strings. + """ + return [] + + async def startup(self) -> None: + """Lifecycle hook called when the platform starts. + + Override this to perform initialization tasks such as: + - Database migrations + - Background job scheduling + - External service connections + + Default implementation does nothing. + """ + pass + + async def shutdown(self) -> None: + """Lifecycle hook called when the platform shuts down. + + Override this to perform cleanup tasks such as: + - Closing connections + - Stopping background jobs + - Flushing buffers + + Default implementation does nothing. + """ + pass + + def __repr__(self) -> str: + return f"" diff --git a/platform/backend/app/main.py b/platform/backend/app/main.py index 9e87cf1..5de252e 100644 --- a/platform/backend/app/main.py +++ b/platform/backend/app/main.py @@ -6,6 +6,9 @@ from fastapi.responses import JSONResponse from app.settings import get_settings from app.core.database import init_db from app.api.v1 import auth, users, roles, modules, health +from app.api.v1 import platform_modules +from app.core.module_loader import load_modules, startup_modules, shutdown_modules +from app.core.logging import logger app = FastAPI( title=get_settings().APP_NAME, @@ -30,12 +33,35 @@ app.include_router(auth.router, prefix="/api/v1") app.include_router(users.router, prefix="/api/v1") app.include_router(roles.router, prefix="/api/v1") app.include_router(modules.router, prefix="/api/v1") +app.include_router(platform_modules.router, prefix="/api/v1") @app.on_event("startup") async def startup(): init_db() + # Load and register modules + try: + registered = load_modules() + logger.info(f"Modules loaded: {registered}") + except Exception as e: + logger.error(f"Module loading error: {e}") + + # Call module startup hooks + try: + await startup_modules() + except Exception as e: + logger.error(f"Module startup error: {e}") + + +@app.on_event("shutdown") +async def shutdown(): + # Call module shutdown hooks + try: + await shutdown_modules() + except Exception as e: + logger.error(f"Module shutdown error: {e}") + if __name__ == "__main__": import uvicorn