add level 3 and 4

This commit is contained in:
Матвей
2026-11-05 22:23:52 +03:00
parent 66026d3ec9
commit 45c7aa0085
30 changed files with 1370 additions and 68 deletions
+33 -7
View File
@@ -11,6 +11,7 @@ from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError
from ..errors import ApiError
from .. import telemetry as tel
ROOT = Path(__file__).resolve().parents[2]
@@ -316,11 +317,16 @@ class PostgresStore:
All attachment writers must participate in this protocol.
"""
try:
async with self.pool.acquire() as connection, connection.transaction():
await connection.execute("SET LOCAL lock_timeout = '5s'")
lock = "pg_advisory_xact_lock" if maintenance else "pg_advisory_xact_lock_shared"
await connection.execute(f"SELECT {lock}(41004, 1)")
yield connection
with tel.tracer.start_as_current_span("postgres.attachment_transaction", kind=tel.SpanKind.CLIENT, record_exception=False, set_status_on_exception=False) as span:
try:
async with self.pool.acquire() as connection, connection.transaction():
await connection.execute("SET LOCAL lock_timeout = '5s'")
lock = "pg_advisory_xact_lock" if maintenance else "pg_advisory_xact_lock_shared"
await connection.execute(f"SELECT {lock}(41004, 1)")
yield connection
except Exception:
span.set_status(tel.Status(tel.StatusCode.ERROR))
raise
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
@@ -333,7 +339,7 @@ class PostgresStore:
attachment_id, chat_id, owner_id, filename, content_type, size_bytes, digest, staging_key,
)
await (connection or self.pool).execute(
"INSERT INTO attachment_jobs (job_id, attachment_id) VALUES ($1, $2)", job_id, attachment_id
"INSERT INTO attachment_jobs (job_id, attachment_id, trace_context) VALUES ($1, $2, $3::jsonb)", job_id, attachment_id, json.dumps(tel.carrier())
)
payload = {
"schema_version": 1, "job_id": str(job_id), "type": "attachment.process.v1",
@@ -464,7 +470,7 @@ class PostgresStore:
async def due_outbox_events(self, limit: int = 20) -> list[dict]:
try:
return [{**dict(row), 'payload': json.loads(row['payload']) if isinstance(row['payload'], str) else row['payload']} for row in await self.pool.fetch(
"SELECT id, payload FROM attachment_outbox WHERE published_at IS NULL ORDER BY created_at LIMIT $1", limit
"SELECT o.id, o.payload, j.trace_context FROM attachment_outbox o JOIN attachment_jobs j ON j.job_id=o.job_id WHERE o.published_at IS NULL ORDER BY o.created_at LIMIT $1", limit
)]
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
@@ -529,3 +535,23 @@ class PostgresStore:
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
return {row["object_key"]: row["id"] for row in rows}
# Span names describe operations only; never export SQL, parameters, credentials or IDs.
def _trace_db(method):
from functools import wraps
@wraps(method)
async def wrapped(*args, **kwargs):
with tel.tracer.start_as_current_span('postgres.' + method.__name__, kind=tel.SpanKind.CLIENT,
record_exception=False, set_status_on_exception=False) as span:
try:
return await method(*args, **kwargs)
except Exception:
span.set_status(tel.Status(tel.StatusCode.ERROR))
raise
return wrapped
for _name in ('ready', 'create_user', 'authenticate', 'create_session', 'user_for_token', 'revoke_session',
'create_chat', 'get_chat_for_member', 'list_chats_for_member', 'create_message_idempotent',
'list_messages_for_member', 'create_attachment', 'attachment_for_member', 'claim_attachment_job',
'complete_attachment_job', 'retry_attachment_job'):
setattr(PostgresStore, _name, _trace_db(getattr(PostgresStore, _name)))