Files
ChatBot/docs/architecture/overview.md
Leonid Pershin e5e69470f8
All checks were successful
SonarQube / Build and analyze (push) Successful in 3m22s
add docs
2025-10-21 05:08:40 +03:00

211 lines
7.0 KiB
Markdown
Raw 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.
# 🏗️ Архитектура проекта
## 📐 Общая архитектура
ChatBot построен на принципах **Clean Architecture** с четким разделением ответственности.
## 🔄 Диаграмма слоев
```
┌─────────────────────────────────────────────┐
│ Presentation Layer │
│ (Telegram Bot, Commands, Handlers) │
├─────────────────────────────────────────────┤
│ Service Layer │
│ (ChatService, AIService, Compression) │
├─────────────────────────────────────────────┤
│ Data Access Layer │
│ (Repositories, DbContext, Entities) │
├─────────────────────────────────────────────┤
│ Infrastructure Layer │
│ (PostgreSQL, Ollama, Telegram) │
└─────────────────────────────────────────────┘
```
## 🎯 Принципы проектирования
### SOLID
- **S**ingle Responsibility - Каждый класс имеет одну ответственность
- **O**pen/Closed - Открыт для расширения, закрыт для модификации
- **L**iskov Substitution - Интерфейсы взаимозаменяемы
- **I**nterface Segregation - Мелкие специализированные интерфейсы
- **D**ependency Inversion - Зависимость от абстракций
### Design Patterns
- **Repository Pattern** - `IChatSessionRepository`
- **Dependency Injection** - Microsoft.Extensions.DependencyInjection
- **Strategy Pattern** - `ISessionStorage` (In-Memory/Database)
- **Command Pattern** - Telegram команды
- **Adapter Pattern** - `OllamaClientAdapter`
## 📦 Компоненты системы
### 1. Presentation Layer
**Telegram Bot Integration:**
- `TelegramBotService` - Основной сервис бота
- `TelegramMessageHandler` - Обработка сообщений
- `TelegramCommandProcessor` - Обработка команд
- `TelegramErrorHandler` - Обработка ошибок
- Commands: `StartCommand`, `HelpCommand`, `ClearCommand`, etc.
### 2. Service Layer
**Core Services:**
- `ChatService` - Управление диалогами
- `AIService` - Генерация ответов AI
- `HistoryCompressionService` - Сжатие истории
- `SystemPromptService` - Загрузка системного промпта
- `ModelService` - Управление AI моделями
**Storage Services:**
- `DatabaseSessionStorage` - Хранение в БД
- `InMemorySessionStorage` - Хранение в памяти
### 3. Data Access Layer
**Repositories:**
- `ChatSessionRepository` - Работа с сессиями
- `ChatBotDbContext` - EF Core контекст
**Entities:**
- `ChatSessionEntity` - Сессия чата
- `ChatMessageEntity` - Сообщение чата
### 4. Infrastructure
**External Services:**
- PostgreSQL - База данных
- Ollama - AI модели
- Telegram Bot API - Telegram интеграция
## 🔌 Dependency Injection
```csharp
// Telegram Services
services.AddSingleton<ITelegramBotClient>
services.AddSingleton<ITelegramBotService>
services.AddSingleton<ITelegramMessageHandler>
// Core Services
services.AddSingleton<IAIService, AIService>
services.AddScoped<ChatService>
services.AddScoped<ISessionStorage, DatabaseSessionStorage>
// Data Access
services.AddDbContext<ChatBotDbContext>
services.AddScoped<IChatSessionRepository, ChatSessionRepository>
```
## 🔄 Data Flow
### Обработка сообщения пользователя
```
User Message
TelegramBotService (получение update)
TelegramMessageHandler (валидация)
TelegramCommandProcessor (проверка команды)
↓ (если не команда)
ChatService (обработка сообщения)
SessionStorage (получение/создание сессии)
AIService (генерация ответа)
OllamaClient (запрос к AI)
AIService (получение ответа)
ChatService (сохранение в историю)
SessionStorage (сохранение сессии)
TelegramMessageSender (отправка ответа)
User receives response
```
## 🗂️ Структура проекта
```
ChatBot/
├── Common/ # Общие константы
│ └── Constants/
├── Data/ # Слой доступа к данным
│ ├── Interfaces/
│ ├── Repositories/
│ └── ChatBotDbContext.cs
├── Models/ # Модели и конфигурация
│ ├── Configuration/
│ ├── Dto/
│ ├── Entities/
│ └── ChatSession.cs
├── Services/ # Бизнес-логика
│ ├── HealthChecks/
│ ├── Interfaces/
│ ├── Telegram/
│ └── *.cs
├── Migrations/ # EF Core миграции
├── Prompts/ # AI промпты
└── Program.cs # Точка входа
```
## 📊 Диаграмма классов (упрощенная)
```
┌─────────────────────┐
│ ChatService │
├─────────────────────┤
│ + ProcessMessage() │
│ + ClearHistory() │
└──────────┬──────────┘
├──> IAIService
├──> ISessionStorage
└──> IHistoryCompressionService
┌─────────────────────┐
│ AIService │
├─────────────────────┤
│ + GenerateChat() │
└──────────┬──────────┘
└──> IOllamaClient
```
## 🔐 Security Architecture
- Секреты в переменных окружения
- Валидация входных данных
- SQL инъекции предотвращены (EF Core)
- Безопасное логирование (без секретов)
## 📈 Scalability
**Готовность к масштабированию:**
- Stateless сервисы
- Database session storage
- Async/await везде
- Connection pooling
- Health checks
## 🎛️ Configuration Management
```
Environment Variables → .env
appsettings.json
IOptions<T>
Validation (FluentValidation)
Services
```