kwork-api/docs/ARCHITECTURE.md
root 0975b68334 feat: complete Kwork API client with 45+ endpoints
Initial release:
- Complete async API client (45+ endpoints)
- Pydantic models for all responses
- Two-step authentication
- Comprehensive error handling
- 92% test coverage
- Gitea Actions CI/CD
- Semantic release configured
2026-03-29 00:42:54 +00:00

8.5 KiB
Raw Blame History

Architecture — kwork-api

📐 Обзор

kwork-api — асинхронный Python клиент для Kwork.ru API с полной типизацией и документацией.


🏗️ Архитектура

┌─────────────────────────────────────────────────────────┐
│                    User Application                      │
└─────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────┐
│                   KworkClient                            │
│  ┌──────────────────────────────────────────────────┐  │
│  │  Authentication Layer                             │  │
│  │  - login() / token auth                           │  │
│  │  - Session management                             │  │
│  └──────────────────────────────────────────────────┘  │
│  ┌──────────────────────────────────────────────────┐  │
│  │  API Groups                                       │  │
│  │  - catalog, projects, user, reference, ...       │  │
│  └──────────────────────────────────────────────────┘  │
│  ┌──────────────────────────────────────────────────┐  │
│  │  HTTP Layer (httpx)                               │  │
│  │  - HTTP/2 support                                 │  │
│  │  - Timeout handling                               │  │
│  │  - Error handling                                 │  │
│  └──────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────┐
│              Kwork.ru API (HTTPS)                        │
└─────────────────────────────────────────────────────────┘

📁 Структура проекта

kwork-api/
├── src/kwork_api/
│   ├── __init__.py          # Public API
│   ├── client.py            # KworkClient + API groups
│   ├── models.py            # Pydantic models
│   └── errors.py            # Exception classes
│
├── tests/
│   ├── test_client.py       # Client tests
│   ├── test_models.py       # Model tests
│   └── test_all_endpoints.py # Endpoint tests
│
├── docs/
│   ├── index.md             # Quick start
│   ├── api-reference.md     # API docs
│   ├── RELEASE.md           # Release guide
│   └── ARCHITECTURE.md      # This file
│
├── .github/workflows/
│   └── ci.yml               # CI/CD pipeline
│
├── pyproject.toml           # Project config
├── uv.lock                  # Dependencies lock
└── README.md                # Main documentation

🔑 Компоненты

1. KworkClient

Ответственность: Основное взаимодействие с API

Функции:

  • Аутентификация (login / token)
  • Управление сессией
  • Делегирование API группам

API Groups:

client.catalog      # CatalogAPI
client.projects     # ProjectsAPI
client.user         # UserAPI
client.reference    # ReferenceAPI
client.notifications # NotificationsAPI
client.other        # OtherAPI

2. Models (Pydantic)

Ответственность: Валидация и типизация ответов API

Категории:

  • User models: KworkUser, AuthResponse
  • Kwork models: Kwork, KworkDetails, KworkCategory
  • Project models: Project, ProjectsResponse
  • Review models: Review, ReviewsResponse
  • Notification models: Notification, Dialog
  • Reference models: City, Country, TimeZone, Feature, Badge
  • Error models: ErrorDetail, APIErrorResponse

3. Errors

Ответственность: Обработка ошибок API

Иерархия:

KworkError (base)
├── KworkAuthError      # 401, 403
├── KworkApiError       # 4xx, 5xx
│   ├── KworkNotFoundError    # 404
│   ├── KworkRateLimitError   # 429
│   └── KworkValidationError  # 400
└── KworkNetworkError   # Network issues

4. HTTP Layer (httpx)

Ответственность: HTTP запросы

Функции:

  • HTTP/2 поддержка
  • Таймауты
  • Cookies management
  • Token authentication
  • Error handling

🔄 Flow: Аутентификация

User → KworkClient.login(username, password)
                │
                ▼
        POST /signIn (cookies)
                │
                ▼
        POST /getWebAuthToken (token)
                │
                ▼
        Store token + cookies
                │
                ▼
        Return authenticated client

🔄 Flow: API Request

User → client.catalog.get_list(page=1)
                │
                ▼
        CatalogAPI.get_list()
                │
                ▼
        KworkClient._request()
                │
                ▼
        httpx.AsyncClient.post()
                │
                ▼
        KworkClient._handle_response()
                │
                ▼
        CatalogResponse.model_validate()
                │
                ▼
        Return typed response

🚀 CI/CD Pipeline

Push/Tag → GitHub Actions
    │
    ├── Test Job
    │   ├── Install UV + Python
    │   ├── Run linters (ruff)
    │   ├── Run tests (pytest)
    │   └── Upload coverage
    │
    ├── Build Job
    │   ├── Build wheel + sdist
    │   └── Upload artifacts
    │
    ├── Publish Job (on tag)
    │   ├── Download artifacts
    │   └── Publish to Gitea Registry
    │
    └── Docs Job
        ├── Build MkDocs
        └── Upload site

📊 Зависимости

Runtime

  • httpx[http2]>=0.26.0 — HTTP client
  • pydantic>=2.0.0 — Data validation
  • structlog>=24.0.0 — Logging

Development

  • pytest>=8.0.0 — Testing
  • pytest-cov>=4.0.0 — Coverage
  • pytest-asyncio>=0.23.0 — Async tests
  • respx>=0.20.0 — HTTP mocking
  • ruff>=0.3.0 — Linting
  • mkdocs + mkdocstrings — Documentation

🔒 Безопасность

  • Токены: Не сохраняются в логах
  • Пароли: Передаются только при login()
  • Сессии: Token + cookies хранятся в клиенте
  • HTTPS: Все запросы через HTTPS

📈 Производительность

  • Async/Await: Неблокирующие запросы
  • HTTP/2: Multiplexing запросов
  • Connection pooling: Переиспользование соединений
  • Timeouts: Защита от зависаний

🧪 Тестирование

  • Unit тесты: 92% coverage
  • Mock HTTP: respx для изоляции
  • Async tests: pytest-asyncio
  • CI: Автоматический прогон при каждом коммите

📝 Лицензия

MIT License — свободное использование с указанием авторства.