docker
This commit is contained in:
+5
-3
@@ -19,11 +19,13 @@ COPY openapi.yaml ./openapi.yaml
|
||||
# процесса только конфигурация из окружения (FR-006, NFR-008).
|
||||
USER appuser
|
||||
ENV HOST=0.0.0.0 \
|
||||
PORT=8000 \
|
||||
PORT=8010 \
|
||||
WORKERS=2
|
||||
|
||||
EXPOSE 8000
|
||||
EXPOSE 8010
|
||||
# Порт берётся из PORT (совпадает с привязкой uvicorn в ENTRYPOINT);
|
||||
# urlopen бросает исключение при отказе/не-2xx → ненулевой код → unhealthy.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD ["python", "-c", "import urllib.request,sys; r=urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3); sys.exit(0 if r.status==200 else 1)"]
|
||||
CMD ["python", "-c", "import os,urllib.request,sys; urllib.request.urlopen('http://127.0.0.1:%s/health' % os.environ.get('PORT', '8010'), timeout=3); sys.exit(0)"]
|
||||
|
||||
ENTRYPOINT ["sh", "-c", "exec uvicorn app.main:create_app --factory --no-access-log --host ${HOST} --port ${PORT} --workers ${WORKERS}"]
|
||||
|
||||
@@ -86,7 +86,8 @@ export APP_API_KEY=dev-key
|
||||
Машиночитаемая копия контракта — [`openapi.yaml`](openapi.yaml) в корне
|
||||
(OpenAPI 3.0.3: multipart-схемы, повторяемая часть `reference`, единый
|
||||
формат ошибок, apiKey-схема `X-API-Key`). Живой сервис отдаёт её на
|
||||
`/openapi.json`, интерактивная Swagger-UI — `/docs`. Для генерации Java-клиента:
|
||||
`/api/openapi.json`, Swagger UI — `/api/docs`, ReDoc — `/api/redoc`.
|
||||
Для генерации Java-клиента:
|
||||
`openapi-generator-cli generate -i openapi.yaml -g java -o gen/`.
|
||||
|
||||
### Структура
|
||||
|
||||
+10
-1
@@ -48,7 +48,16 @@ def create_app(config: Config | None = None) -> FastAPI:
|
||||
log_event(logger, logging.ERROR, "CV core not ready", reasons=app.state.cv.ready_reasons)
|
||||
yield
|
||||
|
||||
app = FastAPI(title="open_cv", version="1.0.0", lifespan=lifespan)
|
||||
# Документация под префиксом /api: при проксировании наружу только /api/*
|
||||
# Swagger, ReDoc и спека остаются достижимы (эндпоинты API — /api/v1/*).
|
||||
app = FastAPI(
|
||||
title="open_cv",
|
||||
version="1.0.0",
|
||||
lifespan=lifespan,
|
||||
docs_url="/api/docs",
|
||||
redoc_url="/api/redoc",
|
||||
openapi_url="/api/openapi.json",
|
||||
)
|
||||
app.state.config = config
|
||||
app.state.cv = CvService(config)
|
||||
app.state.ready = False
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
services:
|
||||
opencv-service:
|
||||
image: git.gorodar.ru/gorodar/open_cv:latest
|
||||
ports:
|
||||
- "8010:8010"
|
||||
#env_file: .env # секреты не коммитятся
|
||||
environment:
|
||||
PORT: 8010
|
||||
APP_API_KEY: 4c15963f-2802-4d22-aaab-11db2ffe0eed
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
replicas: 1 # stateless: реплики за балансировщиком
|
||||
+3
-3
@@ -20,9 +20,9 @@ info:
|
||||
признаки извлекаются на лету); смешивание допустимо;
|
||||
* `settings` — form-часть с JSON-строкой ≤ 4 КБ; строгая валидация:
|
||||
неизвестные ключи/профили и значения вне диапазонов отвергаются.
|
||||
servers:
|
||||
- url: http://localhost:8000
|
||||
description: Локальная разработка (uvicorn / docker compose)
|
||||
|
||||
Блок `servers` намеренно отсутствует: Swagger UI («Try it out») и клиенты
|
||||
работают относительно того хоста, с которого получена спецификация.
|
||||
|
||||
security:
|
||||
- ApiKeyAuth: []
|
||||
|
||||
@@ -58,6 +58,11 @@ class TestSpecFile:
|
||||
):
|
||||
assert name in headers, name
|
||||
|
||||
def test_no_hardcoded_servers(self, spec):
|
||||
"""Без блока servers: Swagger UI «Try it out» и клиенты работают
|
||||
относительно хоста, с которого получена спецификация (любой порт/деплой)."""
|
||||
assert "servers" not in spec
|
||||
|
||||
def test_error_schema_codes(self, spec):
|
||||
codes = set(spec["components"]["schemas"]["Error"]["properties"]["code"]["enum"])
|
||||
# все коды из таблицы docs/05 §5.3
|
||||
@@ -81,8 +86,8 @@ class TestSpecFile:
|
||||
|
||||
class TestSpecServed:
|
||||
def test_openapi_json_serves_file_spec(self, client: TestClient):
|
||||
"""Живой сервис отдаёт /openapi.json из openapi.yaml, а не автогенерацию."""
|
||||
response = client.get("/openapi.json")
|
||||
"""Живой сервис отдаёт /api/openapi.json из openapi.yaml, а не автогенерацию."""
|
||||
response = client.get("/api/openapi.json")
|
||||
assert response.status_code == 200
|
||||
served = response.json()
|
||||
assert served["paths"].keys() == yaml.safe_load(SPEC_PATH.read_text())["paths"].keys()
|
||||
@@ -90,6 +95,15 @@ class TestSpecServed:
|
||||
assert served["components"]["securitySchemes"]["ApiKeyAuth"]["name"] == "X-API-Key"
|
||||
|
||||
def test_docs_ui_available(self, client: TestClient):
|
||||
response = client.get("/docs")
|
||||
response = client.get("/api/docs")
|
||||
assert response.status_code == 200
|
||||
assert "swagger" in response.text.lower()
|
||||
|
||||
def test_docs_moved_from_root(self, client: TestClient):
|
||||
"""Swagger живёт под /api/docs; корневой /docs больше не отдаётся."""
|
||||
assert client.get("/docs").status_code == 404
|
||||
|
||||
def test_redoc_available(self, client: TestClient):
|
||||
response = client.get("/api/redoc")
|
||||
assert response.status_code == 200
|
||||
assert "redoc" in response.text.lower()
|
||||
|
||||
Reference in New Issue
Block a user