docs: sync backend docs with refactored MOEX, health envelope, and operations/sync endpoint

This commit is contained in:
Sergey Krylov 2026-06-25 22:00:44 +03:00
parent b87ed761ed
commit 0e7ecbb1ef
3 changed files with 48 additions and 30 deletions

View File

@ -92,9 +92,17 @@
**Response:** **Response:**
```json ```json
{ {
"data": {
"status": "ok", "status": "ok",
"timestamp": "2026-06-13T12:00:00.000Z", "timestamp": "2026-06-25T12:00:00.000Z",
"uptime": 1234.56 "uptime": 1234.56,
"checks": [
{ "name": "database", "status": "ok" },
{ "name": "moex", "status": "ok" },
{ "name": "tbank", "status": "ok" }
]
},
"meta": { "fromCache": false, "cachedAt": null }
} }
``` ```
@ -403,5 +411,5 @@ codegen types.
| `/api/v1/broker/accounts/:accountId/portfolio` | GET | Портфель счёта: позиции, cash, метаданные | | `/api/v1/broker/accounts/:accountId/portfolio` | GET | Портфель счёта: позиции, cash, метаданные |
| `/api/v1/broker/accounts/:accountId/events` | GET | События и будущие выплаты (дивиденды, купоны) с фильтром по датам | | `/api/v1/broker/accounts/:accountId/events` | GET | События и будущие выплаты (дивиденды, купоны) с фильтром по датам |
| `/api/v1/broker/accounts/:accountId/operations` | GET | История операций (cursor pagination) | | `/api/v1/broker/accounts/:accountId/operations` | GET | История операций (cursor pagination) |
| `/api/v1/broker/accounts/:accountId/operations/refresh` | POST | Принудительная синхронизация операций из T-Bank | | `/api/v1/broker/accounts/:accountId/operations/sync` | POST | Принудительная синхронизация операций из T-Bank |
| `/api/v1/broker/accounts/:accountId/positions` | GET | Позиции счёта (с пагинацией) | | `/api/v1/broker/accounts/:accountId/positions` | GET | Позиции счёта (с пагинацией) |

View File

@ -25,20 +25,20 @@ flowchart TB
PrismaService["PrismaService"] PrismaService["PrismaService"]
CacheService["CacheService"] CacheService["CacheService"]
MoexClientService["MoexClientService"] MoexHttpClient["MoexHttpClient"]
TBankClientService["TBankClientService"] TBankClientService["TBankClientService"]
PrismaModule --> PrismaService PrismaModule --> PrismaService
CacheModule --> CacheService CacheModule --> CacheService
MoexClientModule --> MoexClientService MoexClientModule --> MoexHttpClient
AuthModule --> PrismaService AuthModule --> PrismaService
PortfolioModule --> PrismaService PortfolioModule --> PrismaService
PortfolioModule --> CacheService PortfolioModule --> CacheService
PortfolioModule --> MoexClientService PortfolioModule --> MoexHttpClient
MarketModules --> CacheService MarketModules --> CacheService
MarketModules --> MoexClientService MarketModules --> MoexHttpClient
TBankModule --> CacheService TBankModule --> CacheService
TBankModule --> PrismaService TBankModule --> PrismaService
@ -79,17 +79,17 @@ flowchart TB
### MoexClientModule ### MoexClientModule
Глобальный HTTP-клиент для MOEX ISS. Глобальный модуль для MOEX ISS, разделённый на `MoexHttpClient` и domain-specific клиенты.
- Rate limiter: p-queue (10 req/s по умолчанию, настраивается через `MOEX_RATE_LIMIT`) - `MoexHttpClient` — rate limiter (p-queue, 10 req/s), circuit breaker (5 errors → 30s open), ISS JSON parsing.
- Circuit breaker: открывается после 5 ошибок, сбрасывается через 30s - Domain clients — `MoexSecuritiesClient`, `MoexMarketDataClient`, `MoexCandlesClient`, `MoexHistoryClient`, `MoexDividendsClient`.
- Все ответы нормализуются из табличного формата MOEX в доменные типы - Все ответы нормализуются из табличного формата MOEX в доменные типы.
### HealthModule ### HealthModule
Проверка состояния сервиса. Проверка состояния сервиса.
- `GET /api/v1/health``{ status: 'ok', timestamp, uptime }` - `GET /api/v1/health``{ data: { status, timestamp, uptime, checks }, meta }`
### AuthModule ### AuthModule

View File

@ -2,9 +2,21 @@
## Обзор ## Обзор
`MoexClientService` (`apps/backend/src/modules/moex-client/moex-client.service.ts`) — HTTP-клиент для MOEX ISS API. MOEX integration is split into a shared HTTP infrastructure client and focused domain clients under
`apps/backend/src/modules/moex-client/`:
## Rate limiting - `MoexHttpClient` — request queue, rate limiting, circuit breaker, ISS JSON parsing.
- `MoexSecuritiesClient` — security search and descriptions.
- `MoexMarketDataClient` — share/bond market data and batch position enrichment.
- `MoexCandlesClient` — candle history.
- `MoexHistoryClient` — share and bond history.
- `MoexDividendsClient` — dividend calendar.
## `MoexHttpClient`
Базовый HTTP-клиент, используемый всеми domain-клиентами. Реализован в `moex-http-client.service.ts`.
### Rate limiting
Использует `p-queue`: Использует `p-queue`:
@ -17,7 +29,7 @@ this.queue = new PQueue({
Все запросы к MOEX проходят через очередь — не более `MOEX_RATE_LIMIT` запросов в секунду. Все запросы к MOEX проходят через очередь — не более `MOEX_RATE_LIMIT` запросов в секунду.
## Circuit breaker ### Circuit breaker
Состояние: закрыт → открыт → полуоткрыт (через таймаут). Состояние: закрыт → открыт → полуоткрыт (через таймаут).
@ -30,7 +42,7 @@ private circuitErrorCount = 0;
- В открытом состоянии все запросы мгновенно падают с ошибкой `"Circuit breaker is open"` - В открытом состоянии все запросы мгновенно падают с ошибкой `"Circuit breaker is open"`
- Через `MOEX_CIRCUIT_BREAKER_RESET_SECONDS` (30) автоматически сбрасывается - Через `MOEX_CIRCUIT_BREAKER_RESET_SECONDS` (30) автоматически сбрасывается
## Метод request ### Метод request
```typescript ```typescript
private async request<T>(path: string, params?: Record<string, string>): Promise<T> private async request<T>(path: string, params?: Record<string, string>): Promise<T>
@ -40,7 +52,7 @@ private async request<T>(path: string, params?: Record<string, string>): Promise
- Устанавливает `iss.meta=off` (отключает метаданные) - Устанавливает `iss.meta=off` (отключает метаданные)
- Таймаут: 10s - Таймаут: 10s
## Разбор response ### Разбор response
MOEX возвращает данные в табличном формате: MOEX возвращает данные в табличном формате:
@ -55,19 +67,17 @@ MOEX возвращает данные в табличном формате:
Метод `extractTable` преобразует это в массив объектов по колонкам. Метод `extractTable` преобразует это в массив объектов по колонкам.
## Доступные методы MOEX ## Domain clients
| Метод | MOEX path | Описание | Каждый domain-клиент использует `MoexHttpClient` для HTTP и предоставляет свои методы:
|---|---|---|
| `searchSecurities` | `/securities?q=` | Поиск инструментов | | Client | Методы |
| `getSecurityDescription` | `/securities/{secid}` | Спецификация | |---|---|
| `getShareMarketData` | `/engines/stock/markets/shares/securities/{secid}` | Рыночные данные акции (board: TQBR) | | `MoexSecuritiesClient` | `searchSecurities`, `getSecurityDescription` |
| `getBondData` | `/engines/stock/markets/bonds/securities/{secid}` | Данные облигации (board: TQCB) | | `MoexMarketDataClient` | `getShareMarketData`, `getBondMarketData`, `batchPositions` |
| `getBondMarketData` | `/engines/stock/markets/bonds/securities/{secid}` | Рыночные данные облигации | | `MoexCandlesClient` | `getCandles` |
| `getDividends` | `/securities/{secid}/dividends` | Дивиденды | | `MoexHistoryClient` | `getShareHistory`, `getBondHistory` |
| `getCandles` | `/engines/{engine}/markets/{market}/securities/{secid}/candles` | Свечи | | `MoexDividendsClient` | `getDividends` |
| `getHistory` | `/engines/stock/markets/shares/securities/{secid}` | История акций |
| `getBondHistory` | `/engines/stock/markets/bonds/securities/{secid}` | История облигаций |
## MOEX ISS types ## MOEX ISS types