Compare commits
3 Commits
master
..
268b195810
| Author | SHA1 | Date | |
|---|---|---|---|
| 268b195810 | |||
| 4ede56d716 | |||
| fee93bc855 |
+6
-1
@@ -41,4 +41,9 @@ request-module/migrations/scripts/attachments/
|
|||||||
*.zip
|
*.zip
|
||||||
*.sig
|
*.sig
|
||||||
*.sec
|
*.sec
|
||||||
*.eml
|
*.eml
|
||||||
|
|
||||||
|
request-module/migrations/scripts/*.json
|
||||||
|
|
||||||
|
dev-doc
|
||||||
|
*.patch
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
# AGENTS.md
|
||||||
|
|
||||||
|
## Назначение проекта
|
||||||
|
|
||||||
|
Проект представляет собой модульную платформу, к которой могут подключаться независимые функциональные модули.
|
||||||
|
|
||||||
|
Платформа и модули должны иметь возможность поставляться:
|
||||||
|
|
||||||
|
- отдельно;
|
||||||
|
- в составе пакетов;
|
||||||
|
- в произвольных комбинациях.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Основные принципы архитектуры
|
||||||
|
|
||||||
|
## 1. Платформа не зависит от модулей
|
||||||
|
|
||||||
|
Запрещено:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from request_module import RequestService
|
||||||
|
```
|
||||||
|
|
||||||
|
Разрешено:
|
||||||
|
|
||||||
|
```python
|
||||||
|
module = registry.get("request")
|
||||||
|
module.install()
|
||||||
|
module.start()
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Модули не должны быть жёстко связаны друг с другом
|
||||||
|
|
||||||
|
Запрещено:
|
||||||
|
|
||||||
|
```python
|
||||||
|
crm.create_customer()
|
||||||
|
warehouse.reserve_goods()
|
||||||
|
```
|
||||||
|
|
||||||
|
Предпочтительно:
|
||||||
|
|
||||||
|
```python
|
||||||
|
event_bus.publish(
|
||||||
|
"customer.created",
|
||||||
|
payload
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Бизнес-логика не должна находиться в ядре платформы
|
||||||
|
|
||||||
|
Ядро платформы отвечает только за:
|
||||||
|
|
||||||
|
- авторизацию;
|
||||||
|
- права доступа;
|
||||||
|
- реестр модулей;
|
||||||
|
- журналирование;
|
||||||
|
- аудит;
|
||||||
|
- маршрутизацию;
|
||||||
|
- события;
|
||||||
|
- уведомления.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Структура репозитория
|
||||||
|
|
||||||
|
```text
|
||||||
|
platform-project/
|
||||||
|
|
||||||
|
├── platform/
|
||||||
|
│ ├── backend/
|
||||||
|
│ ├── frontend/
|
||||||
|
│ └── frontend-user/
|
||||||
|
│
|
||||||
|
├── modules/
|
||||||
|
│ ├── request-module/
|
||||||
|
│ ├── crm-module/
|
||||||
|
│ └── ...
|
||||||
|
│
|
||||||
|
└── dev-doc/
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Документация
|
||||||
|
|
||||||
|
Вся документация хранится в каталоге:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/dev-doc/
|
||||||
|
```
|
||||||
|
|
||||||
|
Структура:
|
||||||
|
|
||||||
|
```text
|
||||||
|
dev-doc/
|
||||||
|
|
||||||
|
├── technical_task_001.txt
|
||||||
|
├── technical_task_002.txt
|
||||||
|
├── technical_task_003.txt
|
||||||
|
│
|
||||||
|
├── implementation_report_001.md
|
||||||
|
├── implementation_report_002.md
|
||||||
|
├── implementation_report_003.md
|
||||||
|
│
|
||||||
|
├── ADR/
|
||||||
|
├── architecture/
|
||||||
|
└── roadmap.md
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Технические задания
|
||||||
|
|
||||||
|
Каждое техническое задание должно находиться в файле:
|
||||||
|
|
||||||
|
```text
|
||||||
|
dev-doc/technical_task_XXX.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
Например:
|
||||||
|
|
||||||
|
```text
|
||||||
|
dev-doc/technical_task_001.txt
|
||||||
|
dev-doc/technical_task_002.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Отчёт исполнителя
|
||||||
|
|
||||||
|
После выполнения задачи исполнитель обязан создать файл:
|
||||||
|
|
||||||
|
```text
|
||||||
|
dev-doc/implementation_report_XXX.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Номер отчёта обязан совпадать с номером технического задания.
|
||||||
|
|
||||||
|
Например:
|
||||||
|
|
||||||
|
```text
|
||||||
|
technical_task_005.txt
|
||||||
|
implementation_report_005.md
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Обязательная структура отчёта
|
||||||
|
|
||||||
|
## Общая информация
|
||||||
|
|
||||||
|
- номер задачи;
|
||||||
|
- дата выполнения;
|
||||||
|
- исполнитель;
|
||||||
|
- ветка;
|
||||||
|
- коммит.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Выполненные работы
|
||||||
|
|
||||||
|
Список реализованных функций.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Изменённые файлы
|
||||||
|
|
||||||
|
Полный список изменённых файлов.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Новые файлы
|
||||||
|
|
||||||
|
Полный список новых файлов и каталогов.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Архитектурные решения
|
||||||
|
|
||||||
|
Описание принятых решений.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Технический долг
|
||||||
|
|
||||||
|
Список известных ограничений.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Риски
|
||||||
|
|
||||||
|
Потенциальные проблемы.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Проверка
|
||||||
|
|
||||||
|
Команды для проверки результата.
|
||||||
|
|
||||||
|
Например:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pytest
|
||||||
|
|
||||||
|
uvicorn app.main:app --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Критерии завершения задачи
|
||||||
|
|
||||||
|
Задача считается выполненной только в том случае, если:
|
||||||
|
|
||||||
|
- код реализован;
|
||||||
|
- тесты проходят;
|
||||||
|
- создан implementation_report;
|
||||||
|
- обновлена документация;
|
||||||
|
- отсутствуют критические ошибки.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Правила работы агента
|
||||||
|
|
||||||
|
Агент обязан:
|
||||||
|
|
||||||
|
1. Изучить техническое задание.
|
||||||
|
2. Изучить предыдущий отчёт.
|
||||||
|
3. Не изменять бизнес-логику без отдельного указания.
|
||||||
|
4. Не изменять структуру базы данных без отдельного указания.
|
||||||
|
5. Не удалять существующий функционал.
|
||||||
|
6. Документировать архитектурные решения.
|
||||||
|
7. Создать implementation_report.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Запрещено
|
||||||
|
|
||||||
|
Запрещается:
|
||||||
|
|
||||||
|
- менять API без ТЗ;
|
||||||
|
- менять структуру БД без ТЗ;
|
||||||
|
- удалять существующие функции;
|
||||||
|
- игнорировать технический долг;
|
||||||
|
- завершать задачу без отчёта.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Приоритет документов
|
||||||
|
|
||||||
|
Приоритет документов следующий:
|
||||||
|
|
||||||
|
1. AGENTS.md
|
||||||
|
2. technical_task_XXX.txt
|
||||||
|
3. implementation_report_XXX.md
|
||||||
|
4. комментарии в коде
|
||||||
|
|
||||||
|
При конфликте документов приоритет имеет документ с более высоким уровнем.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Request module package."""
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"id": "request",
|
||||||
|
"name": "Request Management",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"author": "Atlas-R",
|
||||||
|
"license_required": false,
|
||||||
|
"description": "Модуль управления заявками"
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
"""Request Management Module."""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional
|
||||||
|
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 __init__(self):
|
||||||
|
self._module_dir = Path(__file__).parent
|
||||||
|
|
||||||
|
def routers(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",
|
||||||
|
]
|
||||||
|
|
||||||
|
def static_path(self) -> Optional[Path]:
|
||||||
|
"""Return path to static files directory."""
|
||||||
|
static = self._module_dir / "static"
|
||||||
|
return static if static.exists() else None
|
||||||
|
|
||||||
|
def templates_path(self) -> Optional[Path]:
|
||||||
|
"""Return path to templates directory."""
|
||||||
|
templates = self._module_dir / "templates"
|
||||||
|
return templates if templates.exists() else None
|
||||||
|
|
||||||
|
async def startup(self) -> None:
|
||||||
|
"""Initialize request module resources."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def shutdown(self) -> None:
|
||||||
|
"""Cleanup request module resources."""
|
||||||
|
pass
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""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,
|
||||||
|
enabled status, router count, and declared permissions.
|
||||||
|
"""
|
||||||
|
registry = get_module_registry()
|
||||||
|
modules = registry.all()
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"id": m.id,
|
||||||
|
"name": m.name,
|
||||||
|
"version": m.version,
|
||||||
|
"description": m.description,
|
||||||
|
"enabled": m.enabled,
|
||||||
|
"routers": len(m.routers()),
|
||||||
|
"permissions": m.permissions(),
|
||||||
|
}
|
||||||
|
for m in modules
|
||||||
|
]
|
||||||
@@ -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")
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
"""Module auto-discovery and loading."""
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
import inspect
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
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 _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
|
||||||
|
│ ├── manifest.json
|
||||||
|
│ ├── static/
|
||||||
|
│ ├── templates/
|
||||||
|
│ └── migrations/
|
||||||
|
└── ...
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
# 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
|
||||||
|
|
||||||
|
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"]
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""Base module class for platform modules."""
|
||||||
|
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from pathlib import Path
|
||||||
|
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
|
||||||
|
enabled: Whether the module is enabled
|
||||||
|
"""
|
||||||
|
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
version: str
|
||||||
|
description: str = ""
|
||||||
|
enabled: bool = True
|
||||||
|
|
||||||
|
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:
|
||||||
|
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 []
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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})>"
|
||||||
@@ -1,11 +1,17 @@
|
|||||||
"""Platform - Main Application."""
|
"""Platform - Main Application."""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
from app.settings import get_settings
|
from app.settings import get_settings
|
||||||
from app.core.database import init_db
|
from app.core.database import init_db
|
||||||
from app.api.v1 import auth, users, roles, modules, health
|
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(
|
app = FastAPI(
|
||||||
title=get_settings().APP_NAME,
|
title=get_settings().APP_NAME,
|
||||||
@@ -24,18 +30,55 @@ app.add_middleware(
|
|||||||
allow_headers=["*"],
|
allow_headers=["*"],
|
||||||
)
|
)
|
||||||
|
|
||||||
# Routes
|
# Platform Routes
|
||||||
app.include_router(health.router, prefix="/api/v1")
|
app.include_router(health.router, prefix="/api/v1")
|
||||||
app.include_router(auth.router, prefix="/api/v1")
|
app.include_router(auth.router, prefix="/api/v1")
|
||||||
app.include_router(users.router, prefix="/api/v1")
|
app.include_router(users.router, prefix="/api/v1")
|
||||||
app.include_router(roles.router, prefix="/api/v1")
|
app.include_router(roles.router, prefix="/api/v1")
|
||||||
app.include_router(modules.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")
|
@app.on_event("startup")
|
||||||
async def startup():
|
async def startup():
|
||||||
init_db()
|
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}")
|
||||||
|
|
||||||
|
# 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()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Module startup error: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_event("shutdown")
|
||||||
|
async def shutdown():
|
||||||
|
try:
|
||||||
|
await shutdown_modules()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Module shutdown error: {e}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
|||||||
Reference in New Issue
Block a user