ЛР 5 — асинхронная обработка и версии pipeline

This commit is contained in:
2026-11-16 02:38:13 +03:00
parent 276dbdad8a
commit 1f535f1b5b
163 changed files with 17194 additions and 24 deletions
+11
View File
@@ -0,0 +1,11 @@
-- name: CreateAttachmentVariant :exec
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9
);
-- name: ListAttachmentVariants :many
SELECT * FROM attachment_variants
WHERE attachment_id = $1 AND pipeline_version = $2
ORDER BY name;
+69
View File
@@ -0,0 +1,69 @@
-- name: CreateAttachment :one
-- Compatibility for the synchronous API until CreateQueuedAttachment is wired in.
WITH legacy AS (
INSERT INTO attachments
(chat_id, owner_id, filename, object_key, staging_key, content_type, size_bytes, sha256)
VALUES (sqlc.arg(chat_id), sqlc.arg(owner_id), sqlc.arg(filename),
sqlc.arg(object_key)::text, sqlc.arg(object_key)::text,
sqlc.arg(content_type), sqlc.arg(size_bytes), sqlc.arg(sha256))
RETURNING *
), job AS (
INSERT INTO attachment_jobs (attachment_id, pipeline_version)
SELECT id, pipeline_version FROM legacy
RETURNING *
), event AS (
INSERT INTO outbox (job_id, payload, dedup_key)
SELECT id, attachment_job_payload(id, attachment_id, pipeline_version, 1, created_at),
'initial/' || id
FROM job
RETURNING job_id
)
SELECT legacy.* FROM legacy CROSS JOIN event;
-- name: GetAttachmentForUser :one
SELECT a.*
FROM attachments AS a
JOIN chat_members AS cm ON cm.chat_id = a.chat_id
WHERE a.id = sqlc.arg(attachment_id)
AND cm.user_id = sqlc.arg(user_id);
-- name: GetAttachmentsForMessages :many
SELECT message_id, attachment_id, position
FROM messages_attachments
WHERE message_id = ANY(sqlc.arg(message_ids)::uuid[])
ORDER BY message_id, position;
-- name: AttachmentExistsByObjectKey :one
SELECT EXISTS (
SELECT 1 FROM attachments
WHERE object_key = sqlc.arg(object_key)::text OR staging_key = sqlc.arg(object_key)::text
UNION ALL
SELECT 1 FROM attachment_variants WHERE object_key = sqlc.arg(object_key)::text
UNION ALL
SELECT 1 FROM attachment_jobs WHERE published_original_key = sqlc.arg(object_key)::text
);
-- name: TryLockAttachmentObjectKey :one
SELECT pg_try_advisory_xact_lock(
hashtextextended(sqlc.arg(object_key)::text, 0)
)::boolean AS locked;
-- name: ListAttachmentKeys :many
SELECT id, object_key, created_at
FROM attachments
WHERE object_key > sqlc.arg(after_key)
ORDER BY object_key
LIMIT sqlc.arg(page_size);
-- name: GetAttachmentByID :one
SELECT * FROM attachments WHERE id = sqlc.arg(attachment_id);
-- name: CreateQueuedAttachment :one
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type, size_bytes, sha256, staging_key, status
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, 'queued'
) RETURNING *;
+197
View File
@@ -0,0 +1,197 @@
-- name: CreateAttachmentJob :one
INSERT INTO attachment_jobs (attachment_id, pipeline_version, next_attempt_at, max_attempts)
VALUES (sqlc.arg(attachment_id), sqlc.arg(pipeline_version),
sqlc.arg(available_at)::timestamptz, sqlc.arg(max_attempts))
RETURNING *;
-- name: ClaimJob :one
WITH claimed AS (
UPDATE attachment_jobs AS j
SET lease_generation = j.lease_generation + 1,
lease_until = sqlc.arg(new_lease_until)::timestamptz,
attempts_started = j.attempts_started + 1,
next_attempt_at = NULL,
updated_at = clock_timestamp()
FROM attachments AS a
WHERE j.id = sqlc.arg(job_id)
AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version
AND j.attempts_started < j.max_attempts
AND sqlc.arg(new_lease_until)::timestamptz > clock_timestamp()
AND (
(a.status = 'queued' AND j.lease_until IS NULL AND j.next_attempt_at <= clock_timestamp())
OR (a.status = 'processing' AND j.lease_until <= clock_timestamp())
)
RETURNING j.*
), expired AS (
UPDATE attachment_attempts AS attempt
SET outcome = 'lease_expired', error_code = 'lease_expired', finished_at = claimed.updated_at
FROM claimed
WHERE attempt.job_id = claimed.id
AND attempt.lease_generation = claimed.lease_generation - 1 AND attempt.finished_at IS NULL
), recorded AS (
INSERT INTO attachment_attempts (job_id, lease_generation, attempt, started_at)
SELECT id, lease_generation, attempts_started, updated_at FROM claimed
RETURNING job_id
), processing AS (
UPDATE attachments AS a
SET status = 'processing', updated_at = claimed.updated_at
FROM claimed
WHERE a.id = claimed.attachment_id
RETURNING a.id
)
SELECT claimed.* FROM claimed JOIN recorded ON recorded.job_id = claimed.id
JOIN processing ON processing.id = claimed.attachment_id;
-- name: LockActiveAttachmentJob :one
-- Hold this lock through variant insertion and CompleteJob. Roll back on a zero-row completion.
SELECT j.*
FROM attachment_jobs AS j JOIN attachments AS a ON a.id = j.attachment_id
WHERE j.id = sqlc.arg(job_id)
AND j.lease_generation = sqlc.arg(lease_generation)
AND j.lease_until > clock_timestamp()
AND a.status = 'processing' AND a.pipeline_version = j.pipeline_version
FOR UPDATE OF j;
-- name: CompleteJob :execrows
WITH completed AS (
UPDATE attachment_jobs AS j
SET lease_until = NULL, next_attempt_at = NULL, updated_at = clock_timestamp(),
published_original_key = sqlc.arg(object_key)::text
FROM attachments AS a
WHERE j.id = sqlc.arg(job_id)
AND j.lease_generation = sqlc.arg(lease_generation) AND j.lease_until > clock_timestamp()
AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version AND a.status = 'processing'
AND (SELECT count(*) FROM attachment_variants AS v
WHERE v.attachment_id = a.id AND v.pipeline_version = j.pipeline_version) = 3
RETURNING j.*
), recorded AS (
UPDATE attachment_attempts AS attempt
SET outcome = 'ready', finished_at = completed.updated_at
FROM completed
WHERE attempt.job_id = completed.id AND attempt.lease_generation = completed.lease_generation
)
UPDATE attachments AS a
SET status = 'ready', object_key = sqlc.arg(object_key)::text, updated_at = completed.updated_at
FROM completed
WHERE a.id = completed.attachment_id;
-- name: ScheduleRetry :execrows
WITH scheduled AS (
UPDATE attachment_jobs AS j
SET lease_until = NULL, next_attempt_at = sqlc.arg(available_at)::timestamptz,
updated_at = clock_timestamp()
FROM attachments AS a
WHERE j.id = sqlc.arg(job_id)
AND j.lease_generation = sqlc.arg(lease_generation) AND j.lease_until > clock_timestamp()
AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version AND a.status = 'processing'
AND j.attempts_started < j.max_attempts
AND sqlc.arg(available_at)::timestamptz > clock_timestamp()
RETURNING j.*
), recorded AS (
UPDATE attachment_attempts AS attempt
SET outcome = 'retry', error_code = sqlc.arg(error_code)::text, finished_at = scheduled.updated_at
FROM scheduled
WHERE attempt.job_id = scheduled.id AND attempt.lease_generation = scheduled.lease_generation
), event AS (
INSERT INTO outbox (job_id, payload, available_at, dedup_key)
SELECT id, attachment_job_payload(id, attachment_id, pipeline_version, attempts_started + 1, updated_at),
next_attempt_at, 'retry/' || id || '/' || (attempts_started + 1)
FROM scheduled
)
UPDATE attachments AS a
SET status = 'queued', updated_at = scheduled.updated_at
FROM scheduled WHERE a.id = scheduled.attachment_id;
-- name: FailJob :execrows
WITH failed AS (
UPDATE attachment_jobs AS j
SET lease_until = NULL, next_attempt_at = NULL, updated_at = clock_timestamp()
FROM attachments AS a
WHERE j.id = sqlc.arg(job_id)
AND j.lease_generation = sqlc.arg(lease_generation)
AND (
j.lease_until > clock_timestamp()
OR (j.lease_until <= clock_timestamp() AND j.attempts_started = j.max_attempts
AND sqlc.arg(error_code)::text = 'retry_exhausted')
)
AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version AND a.status = 'processing'
RETURNING j.*
), recorded AS (
UPDATE attachment_attempts AS attempt
SET outcome = 'failed', error_code = sqlc.arg(error_code)::text, finished_at = failed.updated_at
FROM failed
WHERE attempt.job_id = failed.id AND attempt.lease_generation = failed.lease_generation
)
UPDATE attachments AS a
SET status = 'failed', error_code = sqlc.arg(error_code)::text, updated_at = failed.updated_at
FROM failed WHERE a.id = failed.attachment_id;
-- name: ReplayFailed :execrows
WITH replayed AS (
UPDATE attachment_jobs AS j
SET max_attempts = j.attempts_started + sqlc.arg(extra_attempts)::int,
next_attempt_at = clock_timestamp(), updated_at = clock_timestamp()
FROM attachments AS a
WHERE j.id = sqlc.arg(job_id)
AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version
AND a.status = 'failed' AND a.staging_key IS NOT NULL
AND j.lease_until IS NULL AND j.next_attempt_at IS NULL
AND NOT EXISTS (
SELECT 1 FROM attachment_replays AS r WHERE r.request_id = sqlc.arg(request_id)::uuid
)
RETURNING j.*
), recorded AS (
INSERT INTO attachment_replays (request_id, job_id, operator_id, reason, extra_attempts)
SELECT sqlc.arg(request_id)::uuid, id, sqlc.arg(operator_id), sqlc.arg(reason), sqlc.arg(extra_attempts)
FROM replayed
), event AS (
INSERT INTO outbox (job_id, payload, available_at, dedup_key)
SELECT id, attachment_job_payload(id, attachment_id, pipeline_version, attempts_started + 1, updated_at),
next_attempt_at, 'replay/' || id || '/' || sqlc.arg(request_id)::uuid
FROM replayed
)
UPDATE attachments AS a
SET status = 'queued', error_code = NULL, updated_at = replayed.updated_at
FROM replayed WHERE a.id = replayed.attachment_id;
-- name: GetAttachmentJobState :one
SELECT
j.id, j.attachment_id, j.pipeline_version,
CASE WHEN a.pipeline_version = j.pipeline_version THEN a.status ELSE 'superseded' END::text AS status,
j.lease_generation,
j.lease_until,
coalesce(j.lease_until <= clock_timestamp(), false)::boolean AS lease_expired,
j.attempts_started,
j.max_attempts,
j.next_attempt_at
FROM attachment_jobs AS j
JOIN attachments AS a ON a.id = j.attachment_id
WHERE j.id = sqlc.arg(job_id)::uuid;
-- name: ListFailedAttachmentJobs :many
SELECT j.id, j.attachment_id, j.attempts_started, a.error_code, a.updated_at
FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version
WHERE a.status = 'failed'
ORDER BY a.updated_at DESC, j.id
LIMIT sqlc.arg(batch_size);
-- name: LockAttachmentJobForPipeline :one
SELECT j.*
FROM attachment_jobs j
WHERE j.attachment_id = $1 AND j.pipeline_version = $2
FOR UPDATE;
-- name: LockAttachmentJobForReplay :one
SELECT j.*
FROM attachment_jobs j WHERE j.id = $1
FOR UPDATE;
-- name: ClearStagingReference :execrows
UPDATE attachments
SET object_key = CASE WHEN status = 'failed' AND object_key = staging_key THEN NULL ELSE object_key END,
staging_key = NULL
WHERE id = sqlc.arg(id) AND staging_key = sqlc.arg(staging_key);
-- name: GetAttachmentByStagingKey :one
SELECT * FROM attachments WHERE staging_key = sqlc.arg(staging_key)::text;
+3
View File
@@ -0,0 +1,3 @@
-- name: CreateChatMember :exec
INSERT INTO chat_members(chat_id, user_id)
VALUES ($1, $2);
+34
View File
@@ -0,0 +1,34 @@
-- name: CreateChat :one
INSERT INTO chats (title)
VALUES ($1)
RETURNING id, title, created_at;
-- name: GetChatByID :one
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id)::uuid[] AS member_ids
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE c.id = $1
GROUP BY c.id;
-- name: GetChatsByUserID :many
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id)::uuid[] AS member_ids
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE EXISTS (SELECT 1
FROM chat_members membership
WHERE membership.chat_id = c.id
AND membership.user_id = sqlc.arg(user_id))
AND (
sqlc.narg(after_created_at)::timestamptz IS NULL
OR (c.created_at, c.id) >
(
sqlc.narg(after_created_at)::timestamptz,
sqlc.narg(after_id)::uuid
)
)
GROUP BY c.id
ORDER BY c.created_at ASC, c.id ASC
LIMIT sqlc.arg(limit_count);
+22
View File
@@ -0,0 +1,22 @@
-- name: InsertMessageIdempotency :execrows
INSERT INTO message_idempotency(user_id, chat_id, idempotency_key, message_id)
VALUES ($1, $2, $3, $4)
ON CONFLICT (user_id, chat_id, idempotency_key) DO NOTHING;
-- name: GetIdempotentMessage :one
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM message_idempotency AS i
JOIN messages AS m ON m.id = i.message_id
WHERE i.user_id = $1
AND i.chat_id = $2
AND i.idempotency_key = $3;
-- name: LockMessageRequest :exec
SELECT pg_advisory_xact_lock(hashtextextended(
'message/' || (sqlc.arg(user_id)::uuid)::text || '/' ||
(sqlc.arg(chat_id)::uuid)::text || '/' || sqlc.arg(idempotency_key)::text, 0));
-- name: DeleteExpiredMessageIdempotency :exec
DELETE FROM message_idempotency
WHERE user_id = $1 AND chat_id = $2 AND idempotency_key = $3 AND expires_at <= now();
+19
View File
@@ -0,0 +1,19 @@
-- name: CreateMessage :one
INSERT INTO messages (chat_id, sender_id, text)
VALUES ($1, $2, $3)
RETURNING *;
-- name: GetMessagesByChatID :many
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = sqlc.arg(chat_id)
AND (
sqlc.narg(after_created_at)::timestamptz IS NULL
OR (created_at, id) >
(sqlc.narg(after_created_at)::timestamptz,
sqlc.narg(after_id)::uuid
)
)
ORDER BY created_at ASC, id ASC
LIMIT sqlc.arg(limit_count);
+16
View File
@@ -0,0 +1,16 @@
-- name: CreateMessagesAttachments :execrows
INSERT INTO messages_attachments (message_id, attachment_id, chat_id, position)
SELECT $1, $2, $3, $4
FROM attachments
WHERE id = $2 AND chat_id = $3;
-- name: GetMessagesAttachments :many
SELECT attachment_id, position
FROM messages_attachments
WHERE message_id = sqlc.arg(message_id)
ORDER BY position ASC;
-- name: LockAttachmentsForMessage :many
SELECT id, status FROM attachments
WHERE chat_id = sqlc.arg(chat_id) AND id = ANY(sqlc.arg(attachment_ids)::uuid[])
ORDER BY id FOR SHARE;
+39
View File
@@ -0,0 +1,39 @@
-- name: CreateInitialOutboxEvent :exec
INSERT INTO outbox (job_id, payload, available_at, dedup_key)
SELECT id, attachment_job_payload(id, attachment_id, pipeline_version, 1, created_at),
next_attempt_at, 'initial/' || id
FROM attachment_jobs WHERE id = sqlc.arg(job_id)::uuid;
-- name: EnqueueExpiredLeases :many
WITH expired AS (
SELECT j.*, 'recovery/' || j.id || '/' || j.lease_generation AS recovery_key
FROM attachment_jobs AS j
JOIN attachments AS a ON a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version
WHERE a.status = 'processing' AND j.lease_until <= clock_timestamp()
AND NOT EXISTS (
SELECT 1 FROM outbox AS o WHERE o.dedup_key = 'recovery/' || j.id || '/' || j.lease_generation
)
ORDER BY j.lease_until, j.id
LIMIT sqlc.arg(batch_size)
FOR UPDATE OF j SKIP LOCKED
)
INSERT INTO outbox (job_id, payload, dedup_key)
SELECT id, attachment_job_payload(id, attachment_id, pipeline_version,
LEAST(attempts_started + 1, max_attempts), clock_timestamp()),
recovery_key
FROM expired
ON CONFLICT (dedup_key) DO NOTHING
RETURNING *;
-- name: NextPendingOutboxEvent :one
SELECT id, job_id, payload, available_at, sent_at, created_at, dedup_key
FROM outbox
WHERE sent_at IS NULL AND available_at <= statement_timestamp()
ORDER BY available_at, id
LIMIT 1
FOR UPDATE SKIP LOCKED;
-- name: MarkOutboxEventSent :execrows
UPDATE outbox SET sent_at = clock_timestamp()
WHERE id = sqlc.arg(id) AND sent_at IS NULL;
+21
View File
@@ -0,0 +1,21 @@
-- name: CreateUser :one
INSERT INTO users (username, display_name, password_hash)
VALUES ($1, $2, $3)
RETURNING id, username, display_name, password_hash, created_at;
-- name: GetUserByID :one
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE id = $1;
-- name: GetUserByUsername :one
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE username = $1;
+30
View File
@@ -0,0 +1,30 @@
-- name: SupersedeAttachmentJob :exec
WITH superseded AS (
UPDATE attachment_jobs
SET lease_until = NULL, next_attempt_at = NULL, updated_at = clock_timestamp()
WHERE id = sqlc.arg(job_id)::uuid
RETURNING id, updated_at
)
UPDATE attachment_attempts AS attempt
SET outcome = 'superseded', error_code = 'superseded', finished_at = superseded.updated_at
FROM superseded
WHERE attempt.job_id = superseded.id AND attempt.finished_at IS NULL;
-- name: QueueAttachmentUpgrade :one
UPDATE attachments
SET pipeline_version = 2, status = 'queued', staging_key = sqlc.arg(source_key)::text,
object_key = NULL, error_code = NULL, updated_at = clock_timestamp()
WHERE id = sqlc.arg(id)::uuid AND pipeline_version = 1
RETURNING *;
-- name: GetPipelineJobID :one
SELECT id FROM attachment_jobs
WHERE attachment_id = sqlc.arg(attachment_id)::uuid AND pipeline_version = sqlc.arg(pipeline_version)::int;
-- name: GetPublishedOriginalKey :one
SELECT published_original_key FROM attachment_jobs
WHERE attachment_id = sqlc.arg(attachment_id)::uuid AND pipeline_version = sqlc.arg(pipeline_version)::int
AND published_original_key IS NOT NULL;
-- name: IsPublishedOriginalKey :one
SELECT EXISTS (SELECT 1 FROM attachment_jobs WHERE published_original_key = sqlc.arg(object_key)::text);