fix: answer 503 when PostgreSQL refuses connections with too many clients
SQLSTATE 53300 (too_many_connections) joins UNAVAILABLE_SQLSTATES, so a refused pool connection gives 503 unavailable instead of 500. New fault check fills max_connections through the failure stand hook and expects 503 in the contract format. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -20,6 +20,11 @@
|
||||
моменту уже вставлен в той же транзакции)
|
||||
clear-fail-messages убрать триггер
|
||||
count-chats <title> число чатов с этим названием
|
||||
fill-connections <секунд> занять все слоты max_connections сессиями
|
||||
psql (`SELECT pg_sleep`) и оборвать
|
||||
соединения API: их пулы переподключаются
|
||||
и получают «too many clients» (53300)
|
||||
clear-connections освободить слоты и дождаться подключения
|
||||
|
||||
Пароли не печатает: valkey-cli берёт пароль из VALKEYCLI_AUTH
|
||||
контейнера, psql работает от POSTGRES_USER контейнера. Только stdlib.
|
||||
@@ -92,6 +97,57 @@ DROP FUNCTION IF EXISTS fault_fail_messages();
|
||||
"""
|
||||
COUNT_CHATS_SQL = "SELECT count(*) FROM chats WHERE title = :'title';\n"
|
||||
|
||||
# Заполнение слотов: отвязанный sh в контейнере Postgres. Сначала столько
|
||||
# попыток, сколько слотов, затем новая попытка раз в 0,05 с до конца
|
||||
# срока: слот, освободившийся после обрыва соединения API, сразу занимает
|
||||
# снова psql, а не переподключение пула. Лишние попытки получают отказ и
|
||||
# выходят. Сессии — через сокет ([local]), пользователь контейнера.
|
||||
FILL_PID = "/tmp/fault-fill.pid"
|
||||
FILL_SH = f"""\
|
||||
echo $$ > {FILL_PID}
|
||||
hold() {{
|
||||
PGAPPNAME=fault_fill psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -XAtq \\
|
||||
-c "SELECT pg_sleep($1)" >/dev/null 2>&1 &
|
||||
}}
|
||||
end=$(( $(date +%s) + $1 ))
|
||||
slots=$(psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -XAtq \\
|
||||
-c 'SHOW max_connections')
|
||||
i=0
|
||||
while [ "$i" -lt "$slots" ]; do hold "$1"; i=$((i + 1)); done
|
||||
while [ "$(date +%s)" -lt "$end" ]; do hold "$1"; sleep 0.05; done
|
||||
"""
|
||||
# Обрыв соединений по TCP (это пулы API) сигналом SIGTERM — то же, что
|
||||
# pg_terminate_backend, но без своего слота. Заголовок процесса backend —
|
||||
# «postgres: <user> <db> <адрес>(<порт>) <состояние>»; сокет ([local]) и
|
||||
# проверку готовности с 127.0.0.1 не трогаем. Печатает число оборванных.
|
||||
KILL_TCP_SH = """\
|
||||
n=0
|
||||
for d in /proc/[0-9]*; do
|
||||
t=$(tr '\\0' ' ' < "$d/cmdline" 2>/dev/null) || continue
|
||||
case "$t" in
|
||||
"postgres: "*" 127.0.0.1("*) ;;
|
||||
"postgres: "*"("*")"*) kill -TERM "${d#/proc/}" 2>/dev/null \\
|
||||
&& n=$((n + 1)) ;;
|
||||
esac
|
||||
done
|
||||
echo "$n"
|
||||
"""
|
||||
CLEAR_FILL_SH = f"""\
|
||||
[ -f {FILL_PID} ] && kill "$(cat {FILL_PID})" 2>/dev/null
|
||||
rm -f {FILL_PID}
|
||||
for d in /proc/[0-9]*; do
|
||||
t=$(tr '\\0' ' ' < "$d/cmdline" 2>/dev/null) || continue
|
||||
case "$t" in
|
||||
"postgres: "*" [local] "*) kill -TERM "${{d#/proc/}}" 2>/dev/null ;;
|
||||
esac
|
||||
done
|
||||
"""
|
||||
PROBE_SQL_SH = (
|
||||
'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -XAtq -c "SELECT 1"'
|
||||
)
|
||||
TOO_MANY = "too many clients"
|
||||
FILL_TIMEOUT_S = 20
|
||||
|
||||
|
||||
class HookError(Exception):
|
||||
"""Неверный вызов или проект: код 2 и сообщение в stderr."""
|
||||
@@ -231,6 +287,76 @@ def cache_has_chat(project: str, chat_id: str) -> str:
|
||||
return valkey(project, "EXISTS", key)
|
||||
|
||||
|
||||
def postgres_sh(project: str, script: str, *args: str) -> str:
|
||||
return compose(
|
||||
project,
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
script,
|
||||
"sh",
|
||||
*args,
|
||||
)
|
||||
|
||||
|
||||
def probe_connect(project: str) -> subprocess.CompletedProcess[str]:
|
||||
"""Новое подключение psql и `SELECT 1`."""
|
||||
return compose_run(
|
||||
project,
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
PROBE_SQL_SH,
|
||||
)
|
||||
|
||||
|
||||
def slots_full(project: str) -> bool:
|
||||
"""Новое подключение получает «too many clients»."""
|
||||
probe = probe_connect(project)
|
||||
return probe.returncode != 0 and TOO_MANY in probe.stderr
|
||||
|
||||
|
||||
def fill_connections(project: str, seconds: str) -> str:
|
||||
"""Все слоты заняты psql, соединений API не осталось.
|
||||
|
||||
Готово, когда новое подключение получает отказ, а обрывать уже
|
||||
некого: пул API, переподключаясь, получит 53300.
|
||||
"""
|
||||
if int(seconds) <= 0:
|
||||
raise HookError("seconds must be positive")
|
||||
compose(
|
||||
project,
|
||||
"exec",
|
||||
"-d",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
FILL_SH,
|
||||
"sh",
|
||||
str(int(seconds)),
|
||||
)
|
||||
deadline = time.monotonic() + FILL_TIMEOUT_S
|
||||
while time.monotonic() < deadline:
|
||||
if slots_full(project) and postgres_sh(project, KILL_TCP_SH) == "0":
|
||||
return ""
|
||||
time.sleep(0.1)
|
||||
raise HookError(f"connections are not filled in {FILL_TIMEOUT_S}s")
|
||||
|
||||
|
||||
def clear_connections(project: str) -> str:
|
||||
deadline = time.monotonic() + FILL_TIMEOUT_S
|
||||
while time.monotonic() < deadline:
|
||||
postgres_sh(project, CLEAR_FILL_SH)
|
||||
if probe_connect(project).returncode == 0:
|
||||
return ""
|
||||
time.sleep(0.2)
|
||||
raise HookError(f"connections are not freed in {FILL_TIMEOUT_S}s")
|
||||
|
||||
|
||||
def run(project: str, action: str, args: list[str]) -> str:
|
||||
"""Выполнить действие; синтаксис без match: hook запускают и 3.9."""
|
||||
if action in ("stop", "pause") and len(args) == 1:
|
||||
@@ -257,6 +383,10 @@ def run(project: str, action: str, args: list[str]) -> str:
|
||||
return psql(project, CLEAR_FAIL_MESSAGES_SQL)
|
||||
if action == "count-chats" and len(args) == 1:
|
||||
return psql(project, COUNT_CHATS_SQL, title=args[0])
|
||||
if action == "fill-connections" and len(args) == 1:
|
||||
return fill_connections(project, args[0])
|
||||
if action == "clear-connections" and not args:
|
||||
return clear_connections(project)
|
||||
raise HookError(f"unknown action or arguments: {action} {args}")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user