TT-002: modular router registration and module infrastructure

This commit is contained in:
Арсентьев Александр
2026-08-06 13:21:26 +03:00
parent fee93bc855
commit 4ede56d716
8 changed files with 391 additions and 11 deletions
@@ -12,7 +12,7 @@ async def list_platform_modules():
Returns:
List of module metadata including id, name, version, description,
and declared permissions.
enabled status, router count, and declared permissions.
"""
registry = get_module_registry()
modules = registry.all()
@@ -23,6 +23,8 @@ async def list_platform_modules():
"name": m.name,
"version": m.version,
"description": m.description,
"enabled": m.enabled,
"routers": len(m.routers()),
"permissions": m.permissions(),
}
for m in modules
+48 -4
View File
@@ -2,9 +2,10 @@
import importlib.util
import inspect
import json
import sys
from pathlib import Path
from typing import List
from typing import List, Optional
from app.core.sdk.module import BaseModule
from app.core.module_registry import get_module_registry, ModuleAlreadyRegisteredError
@@ -41,18 +42,43 @@ def _find_module_classes(module_path: Path) -> List[type]:
return classes
def _read_manifest(module_dir: Path) -> Optional[dict]:
"""Read manifest.json from a module directory.
Args:
module_dir: Path to the module directory.
Returns:
Parsed manifest dict, or None if not found/invalid.
"""
manifest_path = module_dir / "manifest.json"
if not manifest_path.exists():
return None
try:
with open(manifest_path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return None
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.
If a manifest.json exists in the module directory, its metadata will
be used to override the module's class attributes.
Directory structure:
modules/
├── request-module/
│ └── module.py
├── crm-module/
│ └── module.py
│ ├── module.py
│ ├── manifest.json
│ ├── static/
│ ├── templates/
│ └── migrations/
└── ...
Args:
@@ -74,10 +100,28 @@ def discover_modules(modules_dir: Path) -> List[BaseModule]:
if not module_file.exists():
continue
# Read manifest if available
manifest = _read_manifest(subdir)
classes = _find_module_classes(module_file)
for cls in classes:
try:
instance = cls()
# Apply manifest metadata
if manifest:
if "id" in manifest and manifest["id"]:
instance.id = manifest["id"]
if "name" in manifest and manifest["name"]:
instance.name = manifest["name"]
if "version" in manifest and manifest["version"]:
instance.version = manifest["version"]
if "description" in manifest and manifest["description"]:
instance.description = manifest["description"]
# Set module directory for static/templates
instance._module_dir = subdir
discovered.append(instance)
except Exception:
pass # Skip modules that fail to instantiate
+34 -2
View File
@@ -1,6 +1,7 @@
"""Base module class for platform modules."""
from abc import ABC, abstractmethod
from pathlib import Path
from typing import List, Optional
from fastapi import APIRouter
@@ -16,17 +17,22 @@ class BaseModule(ABC):
name: Human-readable display name
version: Semantic version string
description: Brief description of the module
enabled: Whether the module is enabled
"""
id: str
name: str
version: str
description: str = ""
enabled: bool = True
def routes(self) -> List[APIRouter]:
"""Return FastAPI routers to be mounted by the platform.
def routers(self) -> List[APIRouter]:
"""Return FastAPI routers to be auto-mounted by the platform.
Override this method to expose API endpoints through the platform.
All routers returned here will be automatically included in the
FastAPI application without manual registration in main.py.
Default implementation returns an empty list.
Returns:
@@ -47,6 +53,32 @@ class BaseModule(ABC):
"""
return []
def static_path(self) -> Optional[Path]:
"""Return path to the module's static files directory.
Override this method to serve static files (CSS, JS, images)
through the platform. The platform will mount this directory
at /modules/{module_id}/static
Default implementation returns None.
Returns:
Path to static directory, or None if not applicable.
"""
return None
def templates_path(self) -> Optional[Path]:
"""Return path to the module's templates directory.
Override this method to serve HTML templates through the platform.
Default implementation returns None.
Returns:
Path to templates directory, or None if not applicable.
"""
return None
async def startup(self) -> None:
"""Lifecycle hook called when the platform starts.
+19 -2
View File
@@ -1,13 +1,16 @@
"""Platform - Main Application."""
from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
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.module_registry import get_module_registry
from app.core.logging import logger
app = FastAPI(
@@ -27,7 +30,7 @@ app.add_middleware(
allow_headers=["*"],
)
# Routes
# Platform Routes
app.include_router(health.router, prefix="/api/v1")
app.include_router(auth.router, prefix="/api/v1")
app.include_router(users.router, prefix="/api/v1")
@@ -47,6 +50,21 @@ async def startup():
except Exception as e:
logger.error(f"Module loading error: {e}")
# Auto-connect module routers and static files
registry = get_module_registry()
for module in registry.all():
# Mount routers
for router in module.routers():
app.include_router(router)
logger.info(f"Mounted router from module '{module.id}'")
# Mount static files
static = module.static_path()
if static and Path(static).exists():
mount_path = f"/modules/{module.id}/static"
app.mount(mount_path, StaticFiles(directory=str(static)), name=f"{module.id}-static")
logger.info(f"Mounted static for module '{module.id}' at {mount_path}")
# Call module startup hooks
try:
await startup_modules()
@@ -56,7 +74,6 @@ async def startup():
@app.on_event("shutdown")
async def shutdown():
# Call module shutdown hooks
try:
await shutdown_modules()
except Exception as e: