Проверять соединение PostgreSQL перед рабочей транзакцией

This commit is contained in:
2026-11-27 12:32:27 +03:00
parent 0076659224
commit af4410497c
4 changed files with 10322 additions and 0 deletions
+63
View File
@@ -39,6 +39,68 @@ def snapshot():
return result
def closed_peer_checkout():
"""A server-closed idle socket is replaced before business SQL begins."""
name = "checkout_probe_" + uuid4().hex
code = """
import json,sys,time
from src.pipeline import database
db=database()
try:
with db.connection() as conn:
conn.execute("SELECT set_config('application_name',%s,false)",(sys.argv[1],))
pid=conn.execute("SELECT pg_backend_pid() pid").fetchone()["pid"]
print(json.dumps({"pid":pid}),flush=True)
sys.stdin.readline()
start=time.monotonic()
with db.connection() as conn:
assert conn.execute("SELECT 1 n").fetchone()["n"]==1
print(json.dumps({"query_success":True,"seconds":time.monotonic()-start,
"connections_lost":db.pool.get_stats().get("connections_lost",0)}),flush=True)
finally:
db.close()
"""
process = subprocess.Popen(
[
"docker",
"compose",
"exec",
"-T",
"worker",
"python",
"-c",
code,
name,
],
cwd=ROOT,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
try:
# Database.open has its own finite startup bound. No session credentials
# or diagnostic exception messages are copied into evidence.
pid = int(json.loads(process.stdout.readline())["pid"])
assert (
sql(
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
f"WHERE pid={pid} AND application_name='{name}'"
)
== "t"
)
output, _ = process.communicate(input="continue\n", timeout=15)
assert process.returncode == 0, "Closed-peer checkout probe failed"
result = json.loads(output)
assert result["query_success"] and result["connections_lost"] >= 1
assert result["seconds"] < 8
return result
finally:
if process.poll() is None:
process.kill()
process.wait(timeout=5)
def exercise(client, session, chat, action, *, seconds=15):
path = f"/api/v1/chats/{chat['id']}/messages"
observations, confirmed, errors, reads = [], {}, 0, 0
@@ -148,6 +210,7 @@ def main():
initial = snapshot()
apis = [c for c in initial if c["role"] == "api"]
assert len(apis) == 2 and len({c["pid"] for c in apis}) == 2
report["closed_peer_pool_checkout"] = closed_peer_checkout()
report["before"] = initial
with httpx.Client(
base_url=BASE,