Инициализировать проект elexam-core

Добавлена базовая конфигурация проекта: pyproject.toml с hatchling и индексом Gitea,
README с документацией модулей, .gitignore, .python-version и структура исходного кода.
This commit is contained in:
Returner_org 2026-06-27 22:44:07 +03:00
commit 68e70026cc
6 changed files with 459 additions and 0 deletions

336
.gitignore vendored Normal file
View File

@ -0,0 +1,336 @@
### VisualStudioCode template
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### VirtualEnv template
# Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
.Python
[Bb]in
[Ii]nclude
[Ll]ib
[Ll]ib64
[Ll]ocal
[Ss]cripts
pyvenv.cfg
.venv
pip-selfcheck.json
### Backup template
*.bak
*.gho
*.ori
*.orig
*.tmp
### PuTTY template
# Private key
*.ppk
### Vim template
# Swap
[._]*.s[a-v][a-z]
!*.svg # comment out if you don't need vector files
[._]*.sw[a-p]
[._]s[a-rt-v][a-z]
[._]ss[a-gi-z]
[._]sw[a-p]
# Session
Session.vim
Sessionx.vim
# Temporary
.netrwhist
*~
# Auto-generated tag files
tags
# Persistent undo
[._]*.un~
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
### SublimeText template
# Cache files for Sublime Text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
# Workspace files are user-specific
*.sublime-workspace
# Project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using Sublime Text
# *.sublime-project
# SFTP configuration file
sftp-config.json
sftp-config-alt*.json
# Package control specific files
Package Control.last-run
Package Control.ca-list
Package Control.ca-bundle
Package Control.system-ca-bundle
Package Control.cache/
Package Control.ca-certs/
Package Control.merged-ca-bundle
Package Control.user-ca-bundle
oscrypto-ca-bundle.crt
bh_unicode_properties.cache
# Sublime-github package stores a github token in this file
# https://packagecontrol.io/packages/sublime-github
GitHub.sublime-settings

1
.python-version Normal file
View File

@ -0,0 +1 @@
3.14

104
README.md Normal file
View File

@ -0,0 +1,104 @@
# elexam-core
Общая библиотека платформы **Elexam** — единый источник правды для envelope ответа, trace_id, structlog, каталога ошибок, ULID и http-клиента. Все сервисы зависят от конкретной версии этой библиотеки, чтобы поведение было гарантированно одинаковым.
---
## Что внутри
| Модуль | Назначение |
|---|---|
| `elexam_core.context` | `ContextVar[str]` для хранения `trace_id` в пределах async-запроса (async-safe). Используется остальными модулями внутри. |
| `elexam_core.middleware` | `TraceMiddleware` для FastAPI/Starlette — генерирует `trace_id` (ULID) или подхватывает его из входящего заголовка `X-Trace-Id`, кладёт в `ContextVar`. |
| `elexam_core.envelope` | `success()` / `error()` — сборка стандартного конверта ответа API с `trace_id`, `event`, `processed_at`. |
| `elexam_core.errors` | `ErrorCode` — Enum-каталог кодов ошибок вида `exam.not_found`; `ERROR_META` — HTTP-статус и severity для каждого кода. |
| `elexam_core.logging` | Настройка `structlog`: JSON в stdout, `trace_id` автоматически в каждой строке лога. |
| `elexam_core.ulid` | Утилита генерации ULID — монотонный, URL-safe, лексикографически сортируемый идентификатор. Используется везде вместо UUID. |
| `elexam_core.http_client` | `httpx`-обёртка для межсервисных вызовов: автоматически пробрасывает текущий `trace_id` из `ContextVar` в заголовок `X-Trace-Id` исходящего запроса. |
---
## Установка
### Через uv с приватным Gitea PyPI-индексом
Сначала добавь индекс в `pyproject.toml` своего сервиса (или убедись, что он уже объявлен):
```toml
[[tool.uv.index]]
name = "elexam"
url = "https://git.dregomor.ru/api/packages/Returner_org/pypi/simple"
```
Затем установи пакет:
```bash
uv add elexam-core==0.1.0
```
### Напрямую из git по тегу
До того, как пакет залит в registry, или для точного закрепления на конкретном коммите:
```bash
uv add "elexam-core @ git+https://git.dregomor.ru/Returner_org/elexam-core.git@v0.1.0"
```
---
## Быстрый пример
```python
from fastapi import FastAPI
from fastapi.responses import JSONResponse
import structlog
import elexam_core.logging # инициализирует structlog один раз при импорте
from elexam_core.middleware import TraceMiddleware
from elexam_core.envelope import success, error
from elexam_core.errors import ErrorCode, ERROR_META
app = FastAPI()
app.add_middleware(TraceMiddleware) # с этого момента trace_id есть в каждом запросе
log = structlog.get_logger()
@app.get("/exams/{exam_id}")
async def get_exam(exam_id: str):
exam = None # здесь был бы запрос к БД
if exam is None:
log.warning("exam not found", exam_id=exam_id)
# structlog выведет в stdout:
# {"level": "warning", "trace_id": "01J7XR...", "exam_id": "...", "event": "exam not found", ...}
meta = ERROR_META[ErrorCode.EXAM_NOT_FOUND]
return JSONResponse(
status_code=meta["http"],
content=error(
message="Экзамен не найден",
errors=[{"field": "exam_id", "code": ErrorCode.EXAM_NOT_FOUND}],
event_type="exam.get",
),
)
return success(data=exam, event_type="exam.get")
```
Ответ при успехе:
```json
{
"status": "success",
"data": { "id": "01J7XR...", "title": "Математика" },
"message": "OK",
"errors": null,
"meta": null,
"trace_id": "01J7XRQP2E...",
"event": { "id": "01J7XRQP2F...", "type": "exam.get" },
"processed_at": "2026-06-27T12:34:56.789Z"
}
```
Один и тот же `trace_id` попадает в заголовок `X-Trace-Id` ответа, в тело JSON, в каждую строку лога. Найти по нему всю цепочку запроса через все сервисы можно одним грепом по stdout.

18
pyproject.toml Normal file
View File

@ -0,0 +1,18 @@
[project]
name = "elexam-core"
version = "0.1.0"
description = "Общая библиотека платформы Elexam: envelope ответа, trace_id, structlog, каталог ошибок, ULID, http-клиент"
readme = "README.md"
requires-python = ">=3.14"
dependencies = []
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/elexam_core"]
[[tool.uv.index]]
name = "elexam"
url = "https://git.dregomor.ru/api/packages/Returner_org/pypi/simple"

0
src/.gitkeep Normal file
View File

0
src/elexam_core/.gitkeep Normal file
View File