Leave the rotation before closing the listener on SIGTERM

On SIGTERM gunicorn closed the listener at once, so a request already
queued on the closing socket reached the balancer as a dropped
connection after sending: a retry for GET and keyed messages, a 502
for user, chat and login posts. Now each worker first raises a
draining flag and keeps serving for DRAIN_SECONDS (2 s by default,
above the 1.5 s worst detection of a 503): readiness answers 503
unavailable, liveness stays 200, and the balancer takes the replica
out while it is still healthy. Only then uvicorn closes the listener
and finishes accepted requests within SHUTDOWN_TIMEOUT_SECONDS minus
the window, so gunicorn graceful_timeout stays 5 s.

The worker runs a uvicorn Server subclass whose main loop adds the
window after the exit signal; UvicornWorker._serve is overridden to
use it. Tests check readiness under the flag and run real gunicorn on
a free port: during the window ready is 503 and live 200, the port
closes after the window, a registration accepted before SIGTERM and
finished after the port closed still gets 201, and the master exits
with code 0 before the shutdown limit.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Artyom
2026-10-28 19:33:02 +03:00
co-authored by Claude Opus 5.5
parent 6e4c387e50
commit 6fb4587ef6
4 changed files with 145 additions and 6 deletions
@@ -1,9 +1,9 @@
## 1. Остановка и готовность (платформа)
- [ ] 1.1 `DRAINING` в `shared/entrypoints/health.py`: `/health/ready` отвечает `503 unavailable`, пока флаг поднят
- [ ] 1.2 `DrainingServer` и `MessengerWorker._serve` в `gunicorn_conf.py`: окно `DRAIN_SECONDS`, затем штатная остановка; uvicorn дообрабатывает `SHUTDOWN_TIMEOUT_SECONDS − DRAIN_SECONDS`
- [ ] 1.3 Пинг readiness: 0,4 с на соединение и 0,4 с на запрос
- [ ] 1.4 Проверка группы: тесты — ready `503` при флаге и live `200`; настоящий gunicorn по `SIGTERM` держит окно, закрывает порт и выходит с кодом 0 за срок
- [x] 1.1 `DRAINING` в `shared/entrypoints/health.py`: `/health/ready` отвечает `503 unavailable`, пока флаг поднят
- [x] 1.2 `DrainingServer` и `MessengerWorker._serve` в `gunicorn_conf.py`: окно `DRAIN_SECONDS`, затем штатная остановка; uvicorn дообрабатывает `SHUTDOWN_TIMEOUT_SECONDS − DRAIN_SECONDS`
- [x] 1.3 Пинг readiness: 0,4 с на соединение и 0,4 с на запрос
- [x] 1.4 Проверка группы: тесты — ready `503` при флаге и live `200`; настоящий gunicorn по `SIGTERM` держит окно, закрывает порт и выходит с кодом 0 за срок
## 2. Стенд и таймауты