Лаба 6: OpenTelemetry + Grafana наблюдаемость (оценка 4)

Переиспользован стек lab5. API/worker шлют OTLP (traces/metrics/logs) в
otel-collector -> Prometheus/Loki/Tempo; Grafana с provisioning датасорсов,
дашборда и alert rules в Git. W3C trace context переносится через поле
traceparent в задании очереди (API producer span -> worker consumer span
в одном trace, подтверждено прямым запросом к Tempo). Три контролируемых
инцидента прогнаны и задокументированы (worker down -> queue lag + alert,
DB down отличим от медленного handler по error-span, telemetry backend down
не роняет API/Collector). В процессе найдены и исправлены 4 реальных бага
(middleware после старта приложения, detached span context, замерзающая
метрика очереди при падении её единственного источника, неатомарный
XACK+XDEL) — см. REPORT.md и evidence/.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 01:59:33 +03:00
co-authored by Claude Sonnet 5
parent 470d9d6f1e
commit 6c50a63743
40 changed files with 3032 additions and 17 deletions
+33
View File
@@ -0,0 +1,33 @@
-- Initial schema: users, chats, membership, messages.
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
username TEXT NOT NULL UNIQUE,
display_name TEXT NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS chats (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members (user_id);
CREATE TABLE IF NOT EXISTS messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id),
text TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Keyset pagination over (chat_id, created_at, id) avoids a full scan per page.
CREATE INDEX IF NOT EXISTS messages_chat_keyset_idx ON messages (chat_id, created_at, id);
+15
View File
@@ -0,0 +1,15 @@
-- Idempotency store for POST message: scope = (user, method, path, key).
CREATE TABLE IF NOT EXISTS idempotency_keys (
user_id UUID NOT NULL,
method TEXT NOT NULL,
path TEXT NOT NULL,
idem_key TEXT NOT NULL,
request_hash TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
response_status INT,
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, method, path, idem_key)
);
CREATE INDEX IF NOT EXISTS idempotency_keys_created_idx ON idempotency_keys (created_at);
+25
View File
@@ -0,0 +1,25 @@
-- Attachment metadata lives in Postgres; bytes live in private S3. s3_key is
-- server-generated and never derived from the user-supplied filename.
CREATE TABLE IF NOT EXISTS attachments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
owner_id UUID NOT NULL REFERENCES users(id),
filename TEXT NOT NULL,
content_type TEXT NOT NULL,
size_bytes BIGINT NOT NULL,
sha256 TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'ready',
error_code TEXT,
s3_key TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments (chat_id);
-- Many-to-many: a message can reference up to 10 attachments of its own chat.
CREATE TABLE IF NOT EXISTS message_attachments (
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
attachment_id UUID NOT NULL REFERENCES attachments(id),
PRIMARY KEY (message_id, attachment_id)
);
+53
View File
@@ -0,0 +1,53 @@
-- Variant outputs (thumbnail/crop/optimized) produced by the worker.
CREATE TABLE IF NOT EXISTS attachment_variants (
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
name TEXT NOT NULL,
content_type TEXT NOT NULL,
size_bytes BIGINT NOT NULL,
width INT NOT NULL,
height INT NOT NULL,
sha256 TEXT NOT NULL,
s3_key TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (attachment_id, name)
);
-- Transactional outbox: written in the SAME transaction as the attachments
-- INSERT, so a crash between COMMIT and broker publish leaves a recoverable
-- row instead of a lost job. A relay (in-process background task) publishes
-- unpublished rows and marks them, so publish is retried, not re-created.
CREATE TABLE IF NOT EXISTS job_outbox (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
job_id UUID NOT NULL,
pipeline_version INT NOT NULL DEFAULT 1,
attempt INT NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS job_outbox_unpublished_idx ON job_outbox (created_at) WHERE published_at IS NULL;
-- Durable delayed-retry schedule (Redis Streams has no native delay): a
-- failed attempt is parked here with a next_attempt_at instead of sleeping
-- in-process, so a worker crash during the backoff window does not lose the
-- retry -- any worker's scheduler tick will still publish it on time.
CREATE TABLE IF NOT EXISTS job_retry_schedule (
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
job_id UUID NOT NULL,
attempt INT NOT NULL,
next_attempt_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (attachment_id, job_id)
);
CREATE INDEX IF NOT EXISTS job_retry_schedule_due_idx ON job_retry_schedule (next_attempt_at);
-- Explicit failure record for DLQ-style operator visibility and replay.
CREATE TABLE IF NOT EXISTS job_failures (
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
job_id UUID NOT NULL,
attempt INT NOT NULL,
error_code TEXT NOT NULL,
failed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (attachment_id, job_id)
);