Files
platform-project/dev-doc/architecture_verification_007.md

371 lines
12 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# TT-007 Source Verification — Remote + Distributed Architecture
## 1. Executive Summary
| Пункт | Статус |
|-------|--------|
| Дата | 2026-08-06 |
| Базовая точка | TT-006 / commit 3849064 |
| Тип | READ-ONLY analysis |
| Код изменён | НЕТ |
**Главный вывод:** Текущая архитектура **PARTIALLY SUPPORTED** для remote deployment. Критическое ограничение — `app.include_router()` монтирует модульные роутеры на Platform Backend.
---
## 2. Current Architecture
```
Platform Backend (:8000)
├── Auth / Users / Roles API
├── Module Registry (in-memory)
├── Module Loader (filesystem scan)
└── Module Routers (app.include_router)
Request Module Backend (:8001)
└── request_app (business logic)
Platform Frontend (:5173)
└── /api → Platform Backend :8000
Request Module Frontend (:5174)
├── /api → Request Backend :8001
└── /platform-api → Platform Backend :8000
```
---
## 3. Module Contract
**File:** `platform/backend/app/core/sdk/module.py`
| Аспект | Факт |
|--------|------|
| Базовый класс | `BaseModule(ABC)` |
| Обязательные поля | `id`, `name`, `version` |
| Optional поля | `description`, `enabled`, `frontend` |
| Lifecycle hooks | `startup()`, `shutdown()` |
| Router exposure | `routers() → List[APIRouter]` |
| Permissions | `permissions() → List[str]` |
| Static | `static_path()`, `templates_path()` |
| Metadata | `module_info() → dict` |
**Критично для remote:** `routers()` возвращает `APIRouter` объекты, которые должны быть смонтированы в FastAPI process. Это **同进程** контракт.
---
## 4. Module Loader
**File:** `platform/backend/app/core/module_loader.py`
**Flow:**
```
startup()
→ load_modules()
→ discover_modules(modules_dir)
→ scan modules/ directory
→ find module.py in each subdir
→ read manifest.json
→ import module.py → find BaseModule subclass
→ instantiate
→ register_modules()
→ registry.register()
→ for module in registry:
→ app.include_router(router)
→ app.mount(static)
→ startup_modules()
```
**Критические зависимости:**
- `modules/` — локальная файловая система
- `module.py` — Python import в том же процессе
- `app.include_router()` — монтирование в Platform FastAPI instance
---
## 5. Module Registry
**File:** `platform/backend/app/core/module_registry.py`
| Аспект | Статус |
|--------|--------|
| Тип | Runtime in-memory dict |
| Singleton | Да (`get_module_registry()`) |
| Persistence | НЕТ |
| Storage | `Dict[str, BaseModule]` |
**API:** `GET /api/v1/platform/modules` → `module_info()` для каждого модуля.
**Frontend metadata** хранится в `BaseModule.frontend` (in-memory), НЕ в БД.
---
## 6. Router Mounting
**File:** `platform/backend/app/main.py:57-58`
```python
for router in module.routers():
app.include_router(router)
```
**Критично:** Это монтирует module routers НА Platform Backend. Module API становится частью Platform API.
**Последствие:** Module не может быть на отдельном сервере с отдельным FastAPI процессом.
---
## 7. Platform → Module Communication
| Путь | Механизм | Файл |
|------|----------|------|
| Platform → Module sync | HTTP POST | `platform/backend/app/api/v1/users.py` |
| Module → Platform auth | JWT validation | `request_app/core/security.py` |
| Module → Platform validate | HTTP POST | `request_app/core/auth.py` |
**Module → Platform:**
- Module валидирует JWT через `PLATFORM_JWT_PUBLIC_KEY`
- Module может вызвать `/api/v1/auth/validate`
**Platform → Module:**
- Platform вызывает `/api/v1/users/sync` при изменении пользователя
- Platform вызывает `/api/v1/reference/roles` при синхронизации
---
## 8. Authentication
**Login flow:**
```
User → POST /auth/login → Platform Backend
→ verify password
→ create JWT (HS256, 8h lifetime)
→ return { access_token, user }
```
**JWT validation in Module:**
```
Module receives JWT
→ decode_platform_token()
→ try PLATFORM_JWT_PUBLIC_KEY (platform key)
→ try JWT_SECRET_KEY (local fallback)
→ extract user_id, email, roles
```
**Критично:** Module может валидировать JWT локально (через shared secret). Не нужен HTTP call к Platform для каждого запроса.
---
## 9. Permission Propagation
**Где вычисляются:** `platform/backend/app/api/v1/auth.py:17-67` — `_build_user_response()`
**Модель:**
```
User → Roles → Permissions
```
**Platform permissions:** `platform.dashboard.read`, `platform.users.read/write`, etc.
**Module permissions:** `{module_id}.read/write/delete`
**В JWT:** Permissions НЕ в JWT. Только roles и module_roles.
**Module проверка:** Module проверяет roles через `PlatformUser.has_role()`.
**Security boundary:** Backend authorization. Frontend guard — UX only.
---
## 10. Health
| Endpoint | Сервис | Ответ |
|----------|--------|-------|
| `/api/v1/health` | Platform | `{"status":"healthy"}` |
| `/api/v1/request/health` | Request Module | `{"status":"healthy","service":"Service Request System"}` |
| `/api/v1/request/module/info` | Request Module | Module metadata |
**Remote deployment:** Health endpoints существуют и могут быть использованы для remote health checking.
---
## 11. Configuration
| Параметр | Источник | Значение | Remote-sensitive |
|----------|----------|----------|-----------------|
| `PLATFORM_API_URL` | `.env` | `http://localhost:8000` | ДА |
| `PLATFORM_JWT_PUBLIC_KEY` | `.env` | shared secret | НЕТ |
| `DATABASE_URL` | `.env` | SQLite | ДА |
| `APP_CORS_ORIGINS` | `.env` | localhost URLs | ДА |
**Hardcoded:**
- Ports: 8000, 8001, 5173, 5174 в vite.config.ts
- `localhost` в frontend proxy configs
---
## 12. Database
| Компонент | DB | Тип |
|-----------|-----|-----|
| Platform | `platform.db` | SQLite |
| Request Module | `service_request.db` | SQLite |
**Разделены:** Да, отдельные файлы.
**Shared tables:** НЕТ.
**Remote-compatible:** Да, при замене SQLite на PostgreSQL.
---
## 13. Storage / Attachments
| Компонент | Тип | Файл |
|-----------|-----|------|
| Module static | Filesystem | `modules/request-module/static/` |
| Module templates | Filesystem | `modules/request-module/templates/` |
| Uploaded files | Filesystem | `request_app/` internal |
**Dependency:** `business logic → local filesystem`. Требуется Object Storage для remote.
---
## 14. Frontend Topology Dependencies
| Frontend | Proxy | Target | Hardcoded |
|----------|-------|--------|-----------|
| Platform :5173 | `/api` | `http://localhost:8000` | Да |
| Request :5174 | `/api` | `http://localhost:8001` | Да |
| Request :5174 | `/platform-api` | `http://localhost:8000` | Да |
**Module iframe:** `module.frontend.dev_url` — может быть remote URL.
**Вопрос:** Может ли frontend работать с remote module?
**Ответ:** ДА — iframe использует `dev_url` напрямую. Frontend может открыть remote module frontend.
---
## 15. Failure Handling
| Сценарий | Текущее поведение |
|----------|-------------------|
| Module не запускается | Platform продолжает работать |
| Module router import error | Platform загружает остальные |
| Module API timeout | НЕТ (нет HTTP calls к module API) |
| Module health | НЕТ автоматической проверки |
---
## 16. Observability
| Компонент | Статус |
|-----------|--------|
| Request ID | НЕТ |
| Correlation ID | НЕТ |
| Structured logging | Частично (Python logging) |
| Module identity | Да (в логах) |
| Request timing | НЕТ |
---
## 17. Remote Deployment Gap Analysis
| Capability | Local | Remote | Required Change |
|------------|-------|--------|-----------------|
| Module registry | ✅ | ✅ | Нет |
| Endpoint discovery | ⚠️ static | ❌ | Runtime discovery |
| Routing | ✅ include_router | ❌ | Proxy-based routing |
| Service auth | ✅ shared JWT | ⚠️ | Service-to-service auth |
| Identity propagation | ✅ JWT | ✅ | Нет |
| Permission enforcement | ✅ | ⚠️ | Remote validation |
| Health | ✅ | ⚠️ | Health check polling |
| Timeout | ❌ | ❌ | HTTP client timeouts |
| Retry | ❌ | ❌ | Retry logic |
| Observability | ⚠️ | ❌ | Distributed tracing |
| Configuration | ✅ .env | ⚠️ | Service discovery |
| Database independence | ⚠️ SQLite | ✅ | PostgreSQL |
| Storage independence | ❌ | ❌ | Object Storage |
| Frontend independence | ✅ iframe | ✅ | Нет |
---
## 18. Architectural Risks
| Риск | Current Assumption | Consequence | Severity |
|------|-------------------|-------------|----------|
| R1 Router mounting | Same process | Remote impossible | HIGH |
| R2 Module discovery | Local filesystem | Remote needs API | HIGH |
| R3 JWT validation | Shared secret | Works for remote | LOW |
| R4 Database | SQLite local | Need PostgreSQL | MEDIUM |
| R5 File storage | Local filesystem | Need Object Storage | MEDIUM |
| R6 CORS | localhost only | Need domain config | LOW |
| R7 Health | No polling | Need health checks | MEDIUM |
---
## 19. ADR Candidates
| ADR | Why Needed | Priority |
|-----|------------|----------|
| ADR-005 Remote Module Contract | Define how remote modules register and communicate | HIGH |
| ADR-006 Service-to-Service Auth | Define authentication between Platform and remote Module | HIGH |
| ADR-007 Module Routing | Define proxy-based routing for remote modules | HIGH |
| ADR-008 Deployment Metadata | Define how endpoints are discovered at runtime | MEDIUM |
| ADR-009 Health/Readiness | Define health check protocol for remote modules | MEDIUM |
| ADR-010 Identity Propagation | Define how JWT flows through proxy | LOW |
---
## 20. Future Compatibility
Текущая архитектура **НЕ закрывает** следующие направления:
- Infrastructure Discovery
- Module Deployment Agent
- Health Check / Readiness
- Standby / Failover
- Geo-distribution
- DB replication
- Object Storage
- PWA / Mobile
- n8n integration
**Но требуется refactoring** router mounting для поддержки remote modules.
---
## 21. Recommended Implementation Sequence
```
1. ADR-005 Remote Module Contract
2. ADR-006 Service-to-Service Auth
3. Refactor router mounting → proxy-based
4. Add module endpoint discovery
5. Add health check polling
6. Add HTTP client timeouts/retry
7. PostgreSQL migration
8. Object Storage integration
9. Distributed tracing
```
---
## 22. Conclusion
**Remote Deployment Verdict: PARTIALLY SUPPORTED**
Текущая архитектура поддерживает:
- ✅ Module Contract (BaseModule)
- ✅ JWT-based identity propagation
- ✅ Separate databases
- ✅ Frontend iframe embedding
Текущая архитектура НЕ поддерживает:
- ❌ Remote router mounting (`app.include_router`)
- ❌ Runtime endpoint discovery
- ❌ HTTP-based module communication
- ❌ Health check polling
- ❌ Distributed tracing
**Критический gap:** `app.include_router()` в `main.py:58` делает remote deployment невозможным без refactoring.
**Рекомендация:** Начать с ADR-005 (Remote Module Contract) и refactoring router mounting на proxy-based approach.