Implement modular platform architecture foundation

This commit is contained in:
Арсентьев Александр
2026-08-06 12:50:55 +03:00
parent 07dbde2a0e
commit fee93bc855
10 changed files with 478 additions and 1 deletions
+4
View File
@@ -42,3 +42,7 @@ request-module/migrations/scripts/attachments/
*.sig
*.sec
*.eml
request-module/migrations/scripts/*.json
dev-doc
+1
View File
@@ -0,0 +1 @@
"""Request module package."""
+43
View File
@@ -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
@@ -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
]
+14
View File
@@ -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")
+152
View File
@@ -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
@@ -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"<ModuleRegistry(count={self.count})>"
# 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
@@ -0,0 +1,5 @@
"""SDK package for module development."""
from app.core.sdk.module import BaseModule
__all__ = ["BaseModule"]
+75
View File
@@ -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:
'<module_id>.<action>' (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"<Module(id={self.id}, name={self.name}, version={self.version})>"
+26
View File
@@ -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