Files
mtusi2026labs/openspec/changes/archive/2026-10-28-add-lab3-load-balanced-replicas/proposal.md
T
ArtyomandClaude Opus 5.5 b0f463ac5c Carry over the agent context and openspec history from lab 3
Bring the Claude Code settings, the lint hook, the opsx commands and
skills, the architecture notes, the lab 1 to lab 3 specs and the
archived lab 1 to lab 3 changes into the lab 4 skeleton, so lab 4
continues the same spec history instead of starting from scratch. The
files come from the lab 3 solution commit 61c0c28.

Rewrite AGENTS.md and the openspec context and rules for lab 4: image
attachments with metadata in PostgreSQL and bytes in a private RustFS
bucket inside the stand, a third domain zone for attachments that asks
the messaging zone about chat membership through a port wired in
main.py, upload limits applied before unbounded reading or decoding,
201 only after both the object write and the commit, Out of scope moved
to labs 5-7 plus presigned uploads, and rules on the write order between
the two stores and on root S3 keys staying out of the API.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:16:50 +03:00

34 lines
4.2 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.
## Why
Решение лабы 2 — один контейнер API с опубликованным портом. Рубрика «3» `README.md` требует ≥2 взаимозаменяемых реплик за одной точкой входа, разные реплики на одном токене, запись ≤10 с после остановки любой реплики и повтор сообщения без дубля; контракт 1.3.0 вводит `X-Instance-Id` и `Idempotency-Key`. Изменение закрывает уровень «3» и строки 3.1–3.5 `REPORT.md`.
## What Changes
- Каждый ответ API несёт `X-Instance-Id` — hostname контейнера, один на все воркеры.
- `POST /api/v1/chats/{chat_id}/messages` требует `Idempotency-Key` (`^[A-Za-z0-9._:-]{1,128}$`, иначе `400`). Повтор того же JSON тем же пользователем в том же чате в течение `IDEMPOTENCY_TTL_SECONDS` (≥24 ч) возвращает исходный `201` и тот же `Message`, другой JSON — `409`. Ключ и сообщение — одна транзакция PostgreSQL; `4xx` и `5xx` не сохраняются.
- Новая аддитивная миграция `0002_idempotency_keys.sql`.
- Стенд: HAProxy 3.2 LTS (`lb`) — единственный опубликованный порт; `api` с `deploy.replicas: ${API_REPLICAS:-2}` без портов; проверка `GET /health/ready`, Docker DNS, round robin без sticky; `api-shortttl` с портом в обход LB удаляется.
- Хуки `scripts/stop-one.sh`, `scripts/restart.sh`, `scripts/restore.sh`, `scripts/lb-wait.sh` и зонд `scripts/probe.py check`.
## Capabilities
### New Capabilities
- `lab3-load-balancing`: единственная точка входа, ≥2 реплики без локального состояния, балансировка без sticky, проверка готовности и DNS-обновление backend, политика повторов LB, хуки остановки реплики и рестарта стенда.
- `lab3-idempotent-messages`: обязательный ключ, область, replay/`409`/`400`, TTL, атомарность, конкурентный повтор, повтор после неопределённого исхода.
### Modified Capabilities
- `lab1-messenger-history`: «Отправка сообщения» требует `Idempotency-Key`.
- `lab1-service-operability`: «Сквозной идентификатор запроса» дополняется `X-Instance-Id`; «Корректное завершение по сигналу» — срок внутри `stop_grace_period`; «Контейнерная поставка» — API доступен через LB.
- `lab2-persistent-storage`: «Воспроизводимый стенд» — наружу только LB, реплики без портов; «Версионируемые миграции» — аддитивные и совместимые с работающей версией; «Данные и сессии переживают рестарт» — рестарт включает LB.
## Impact
- Код: платформа (`X-Instance-Id`), зона `messaging` (идемпотентная отправка), миграция `0002`.
- Стенд: `compose.yaml`, `infra/haproxy/haproxy.cfg`, `scripts/`, `Makefile`, `.env.example`, `pyproject.toml` (ruff для `scripts/*.py`), CI.
- Тесты: заголовки, идемпотентность, гонка ключа в реальном PostgreSQL.
- Отчёт: строки 3.1–3.5 и переноса lab2 в `REPORT.md`, `evidence/`.
## Non-goals
Время обнаружения, поочерёдный отказ под нагрузкой, rolling update и измерения лимитов — уровень «4»; серии 1/2/4 реплик — трек «5»; оба — следующие изменения. Из Out of scope не появляется ничего: Swarm, HA PostgreSQL и LB, непрозрачный alias реплики (лаба 7), вложения (лаба 4).