ЛР 5 — асинхронная обработка и версии pipeline
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE users
|
||||
(
|
||||
id uuid PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),
|
||||
username VARCHAR(32) UNIQUE NOT NULL,
|
||||
display_name VARCHAR(100) NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
|
||||
CONSTRAINT users_username_format_check CHECK (username COLLATE "C" ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_length_check CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
CONSTRAINT users_display_name_not_blank_check CHECK (char_length(btrim(display_name)) > 0),
|
||||
CONSTRAINT users_password_hash_not_empty_check CHECK (char_length(password_hash) > 0)
|
||||
|
||||
);
|
||||
|
||||
|
||||
|
||||
CREATE TABLE chats
|
||||
(
|
||||
id UUID PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),
|
||||
title VARCHAR(100) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
|
||||
CONSTRAINT chats_title_length_check CHECK (char_length(title) BETWEEN 1 AND 100 ),
|
||||
CONSTRAINT chats_title_not_blank_check CHECK (char_length(btrim(title)) > 0)
|
||||
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members
|
||||
(
|
||||
chat_id UUID NOT NULL REFERENCES chats (id),
|
||||
user_id UUID NOT NULL REFERENCES users (id),
|
||||
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_user_chat_id ON chat_members (user_id, chat_id);
|
||||
|
||||
|
||||
CREATE TABLE messages
|
||||
(
|
||||
id UUID PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),
|
||||
chat_id UUID NOT NULL,
|
||||
sender_id UUID NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
|
||||
FOREIGN KEY (chat_id, sender_id)
|
||||
REFERENCES chat_members (chat_id, user_id),
|
||||
|
||||
CONSTRAINT messages_text_length_check CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
CONSTRAINT messages_text_not_blank_check CHECK (char_length(btrim(text)) > 0)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_messages_chat_created_id ON messages (chat_id, created_at, id);
|
||||
|
||||
|
||||
CREATE TABLE sessions
|
||||
(
|
||||
token_hash BYTEA PRIMARY KEY NOT NULL,
|
||||
user_id UUID NOT NULL REFERENCES users (id),
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked_at TIMESTAMPTZ NULL,
|
||||
|
||||
CONSTRAINT sessions_expiry_after_creation_check CHECK (expires_at > created_at)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_session_user_id ON sessions (user_id);
|
||||
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE IF EXISTS sessions;
|
||||
DROP TABLE IF EXISTS messages;
|
||||
DROP TABLE IF EXISTS chat_members;
|
||||
DROP TABLE IF EXISTS chats;
|
||||
DROP TABLE IF EXISTS users;
|
||||
@@ -0,0 +1,20 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE users
|
||||
ALTER COLUMN created_at SET DEFAULT now();
|
||||
ALTER TABLE chats
|
||||
ALTER COLUMN created_at SET DEFAULT now();
|
||||
ALTER TABLE messages
|
||||
ALTER COLUMN created_at SET DEFAULT now();
|
||||
ALTER TABLE sessions
|
||||
ALTER COLUMN created_at SET DEFAULT now();
|
||||
|
||||
-- +goose Down
|
||||
|
||||
ALTER TABLE sessions
|
||||
ALTER COLUMN created_at DROP DEFAULT;
|
||||
ALTER TABLE messages
|
||||
ALTER COLUMN created_at DROP DEFAULT;
|
||||
ALTER TABLE chats
|
||||
ALTER COLUMN created_at DROP DEFAULT;
|
||||
ALTER TABLE users
|
||||
ALTER COLUMN created_at DROP DEFAULT;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- +goose Up
|
||||
DROP TABLE IF EXISTS sessions;
|
||||
|
||||
-- +goose Down
|
||||
-- Restore the schema at version 2; deleted session data cannot be recovered.
|
||||
CREATE TABLE sessions
|
||||
(
|
||||
token_hash BYTEA PRIMARY KEY NOT NULL,
|
||||
user_id UUID NOT NULL REFERENCES users (id),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked_at TIMESTAMPTZ NULL,
|
||||
|
||||
CONSTRAINT sessions_expiry_after_creation_check CHECK (expires_at > created_at)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_session_user_id ON sessions (user_id);
|
||||
@@ -0,0 +1,23 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE message_idempotency
|
||||
(
|
||||
user_id UUID NOT NULL REFERENCES users(id),
|
||||
chat_id UUID NOT NULL REFERENCES chats(id),
|
||||
idempotency_key VARCHAR(128) NOT NULL,
|
||||
message_id UUID NOT NULL REFERENCES messages(id),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ NOT NULL DEFAULT (now() + interval '24 hours'),
|
||||
|
||||
PRIMARY KEY (user_id, chat_id, idempotency_key),
|
||||
UNIQUE (message_id),
|
||||
|
||||
CONSTRAINT message_idempotency_key_format_check
|
||||
CHECK (idempotency_key COLLATE "C" ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
CONSTRAINT message_idempotency_expiry_check
|
||||
CHECK (expires_at > created_at)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE IF EXISTS message_idempotency;
|
||||
@@ -0,0 +1,54 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE attachments
|
||||
(
|
||||
id UUID PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),
|
||||
chat_id UUID NOT NULL,
|
||||
owner_id UUID NOT NULL,
|
||||
filename text NOT NULL,
|
||||
object_key text UNIQUE NOT NULL,
|
||||
content_type VARCHAR(10) NOT NULL,
|
||||
size_bytes bigint NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
|
||||
CONSTRAINT fk_attachments_chat_member FOREIGN KEY (chat_id, owner_id)
|
||||
REFERENCES chat_members(chat_id, user_id),
|
||||
CONSTRAINT attachments_sha256_format_check CHECK (sha256 COLLATE "C" ~ '^[0-9a-f]{64}$'),
|
||||
CONSTRAINT attachments_content_type_check CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
CONSTRAINT attachments_filename_check CHECK (
|
||||
char_length(filename) BETWEEN 1 AND 255
|
||||
AND filename !~ '[/\\]'
|
||||
),
|
||||
CONSTRAINT attachments_size_bytes_check CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
CONSTRAINT attachments_id_chat_unique UNIQUE (id, chat_id),
|
||||
CONSTRAINT attachments_object_key_length_check CHECK (char_length(object_key) > 0)
|
||||
|
||||
);
|
||||
|
||||
ALTER TABLE messages
|
||||
ADD CONSTRAINT messages_id_chat_unique UNIQUE (id, chat_id);
|
||||
|
||||
CREATE TABLE messages_attachments
|
||||
(
|
||||
message_id UUID NOT NULL ,
|
||||
attachment_id UUID NOT NULL ,
|
||||
chat_id UUID NOT NULL,
|
||||
position SMALLINT NOT NULL,
|
||||
|
||||
|
||||
CONSTRAINT message_attachments_pk PRIMARY KEY (message_id, attachment_id),
|
||||
CONSTRAINT message_attachments_position_unique UNIQUE (message_id, position),
|
||||
CONSTRAINT message_attachments_position_check CHECK (position BETWEEN 0 AND 9),
|
||||
|
||||
CONSTRAINT message_attachments_message_chat_fk
|
||||
FOREIGN KEY (message_id, chat_id) REFERENCES messages(id, chat_id),
|
||||
CONSTRAINT message_attachments_attachment_chat_fk
|
||||
FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments(id, chat_id)
|
||||
);
|
||||
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS messages_attachments;
|
||||
DROP TABLE IF EXISTS attachments;
|
||||
ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_id_chat_unique;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE messages
|
||||
DROP CONSTRAINT messages_text_length_check,
|
||||
DROP CONSTRAINT messages_text_not_blank_check;
|
||||
|
||||
ALTER TABLE messages
|
||||
ADD CONSTRAINT messages_text_length_check
|
||||
CHECK (char_length(text) <= 4000);
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE messages
|
||||
DROP CONSTRAINT messages_text_length_check;
|
||||
|
||||
ALTER TABLE messages
|
||||
ADD CONSTRAINT messages_text_length_check
|
||||
CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
ADD CONSTRAINT messages_text_not_blank_check
|
||||
CHECK (char_length(btrim(text)) > 0);
|
||||
@@ -0,0 +1,144 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE attachments
|
||||
ADD COLUMN status TEXT NOT NULL DEFAULT 'queued',
|
||||
ADD COLUMN error_code TEXT,
|
||||
ADD COLUMN staging_key TEXT,
|
||||
ADD COLUMN pipeline_version INT NOT NULL DEFAULT 1,
|
||||
ALTER COLUMN object_key DROP NOT NULL;
|
||||
|
||||
-- Retain the original download path while the copied synchronous API is in use.
|
||||
UPDATE attachments SET staging_key = object_key;
|
||||
|
||||
ALTER TABLE attachments
|
||||
ADD CONSTRAINT attachments_status_check
|
||||
CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
|
||||
ADD CONSTRAINT attachments_pipeline_check CHECK (pipeline_version > 0),
|
||||
ADD CONSTRAINT attachments_staging_key_check CHECK (length(staging_key) > 0),
|
||||
ADD CONSTRAINT attachments_object_state_check CHECK (
|
||||
(status NOT IN ('queued', 'processing') OR staging_key IS NOT NULL)
|
||||
AND (status <> 'ready' OR object_key IS NOT NULL)
|
||||
),
|
||||
ADD CONSTRAINT attachments_error_check CHECK (
|
||||
(status = 'failed') = (error_code IS NOT NULL)
|
||||
AND (error_code IS NULL OR error_code COLLATE "C" ~ '^[a-z][a-z0-9_]{0,49}$')
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX attachments_staging_key_unique ON attachments (staging_key)
|
||||
WHERE staging_key IS NOT NULL;
|
||||
|
||||
CREATE TABLE attachment_jobs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id),
|
||||
pipeline_version INT NOT NULL CHECK (pipeline_version > 0),
|
||||
attempts_started INT NOT NULL DEFAULT 0,
|
||||
max_attempts INT NOT NULL DEFAULT 5,
|
||||
next_attempt_at TIMESTAMPTZ DEFAULT now(),
|
||||
lease_generation INT NOT NULL DEFAULT 0 CHECK (lease_generation >= 0),
|
||||
lease_until TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (attachment_id, pipeline_version),
|
||||
CHECK (attempts_started >= 0 AND max_attempts > 0 AND attempts_started <= max_attempts),
|
||||
CHECK (lease_until IS NULL OR next_attempt_at IS NULL)
|
||||
);
|
||||
|
||||
CREATE INDEX attachment_jobs_expired_lease_idx ON attachment_jobs (lease_until, id)
|
||||
WHERE lease_until IS NOT NULL;
|
||||
|
||||
CREATE TABLE attachment_variants (
|
||||
attachment_id UUID NOT NULL,
|
||||
pipeline_version INT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
object_key TEXT NOT NULL UNIQUE CHECK (length(object_key) > 0),
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes BIGINT NOT NULL CHECK (size_bytes > 0),
|
||||
width INT NOT NULL CHECK (width > 0),
|
||||
height INT NOT NULL CHECK (height > 0),
|
||||
sha256 TEXT NOT NULL CHECK (sha256 COLLATE "C" ~ '^[0-9a-f]{64}$'),
|
||||
PRIMARY KEY (attachment_id, pipeline_version, name),
|
||||
FOREIGN KEY (attachment_id, pipeline_version)
|
||||
REFERENCES attachment_jobs(attachment_id, pipeline_version),
|
||||
CHECK (
|
||||
(name IN ('thumbnail', 'crop') AND content_type = 'image/jpeg')
|
||||
OR (name = 'optimized' AND content_type = 'image/webp')
|
||||
)
|
||||
);
|
||||
|
||||
CREATE TABLE attachment_attempts (
|
||||
job_id UUID NOT NULL REFERENCES attachment_jobs(id),
|
||||
lease_generation INT NOT NULL CHECK (lease_generation > 0),
|
||||
attempt INT NOT NULL CHECK (attempt > 0),
|
||||
started_at TIMESTAMPTZ NOT NULL,
|
||||
finished_at TIMESTAMPTZ,
|
||||
outcome TEXT CHECK (outcome IN ('ready', 'retry', 'failed', 'lease_expired')),
|
||||
error_code TEXT CHECK (error_code COLLATE "C" ~ '^[a-z][a-z0-9_]{0,49}$'),
|
||||
PRIMARY KEY (job_id, lease_generation),
|
||||
UNIQUE (job_id, attempt),
|
||||
CHECK ((outcome IS NULL) = (finished_at IS NULL))
|
||||
);
|
||||
|
||||
CREATE TABLE attachment_replays (
|
||||
request_id UUID PRIMARY KEY,
|
||||
job_id UUID NOT NULL REFERENCES attachment_jobs(id),
|
||||
operator_id TEXT NOT NULL CHECK (length(btrim(operator_id)) > 0),
|
||||
reason TEXT NOT NULL CHECK (length(btrim(reason)) > 0),
|
||||
extra_attempts INT NOT NULL CHECK (extra_attempts BETWEEN 1 AND 5),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE outbox (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
job_id UUID NOT NULL REFERENCES attachment_jobs(id),
|
||||
payload JSONB NOT NULL,
|
||||
available_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
sent_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
dedup_key TEXT UNIQUE NOT NULL CHECK (length(dedup_key) > 0)
|
||||
);
|
||||
|
||||
CREATE INDEX outbox_pending_idx ON outbox (available_at, id) WHERE sent_at IS NULL;
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION attachment_job_payload(uuid, uuid, integer, integer, timestamptz)
|
||||
RETURNS jsonb LANGUAGE sql STABLE
|
||||
AS $$
|
||||
SELECT jsonb_build_object(
|
||||
'schema_version', 1,
|
||||
'type', 'attachment.process.v1',
|
||||
'job_id', $1,
|
||||
'attachment_id', $2,
|
||||
'pipeline_version', $3,
|
||||
'attempt', $4,
|
||||
'created_at', to_char($5 AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')
|
||||
);
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
WITH jobs AS (
|
||||
INSERT INTO attachment_jobs (attachment_id, pipeline_version)
|
||||
SELECT id, pipeline_version FROM attachments
|
||||
RETURNING *
|
||||
)
|
||||
INSERT INTO outbox (job_id, payload, dedup_key)
|
||||
SELECT id, attachment_job_payload(id, attachment_id, pipeline_version, 1, created_at),
|
||||
'initial/' || id
|
||||
FROM jobs;
|
||||
|
||||
-- +goose Down
|
||||
-- Restore the legacy reference when the staging original is the only copy.
|
||||
-- SET NOT NULL aborts the rollback if an original no longer exists.
|
||||
UPDATE attachments SET object_key = staging_key WHERE object_key IS NULL;
|
||||
ALTER TABLE attachments ALTER COLUMN object_key SET NOT NULL;
|
||||
|
||||
DROP FUNCTION attachment_job_payload(uuid, uuid, integer, integer, timestamptz);
|
||||
DROP TABLE outbox;
|
||||
DROP TABLE attachment_replays;
|
||||
DROP TABLE attachment_attempts;
|
||||
DROP TABLE attachment_variants;
|
||||
DROP TABLE attachment_jobs;
|
||||
|
||||
ALTER TABLE attachments
|
||||
DROP COLUMN status,
|
||||
DROP COLUMN error_code,
|
||||
DROP COLUMN staging_key,
|
||||
DROP COLUMN pipeline_version;
|
||||
@@ -0,0 +1,27 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE attachment_jobs ADD COLUMN published_original_key TEXT
|
||||
CHECK (length(published_original_key) > 0);
|
||||
|
||||
UPDATE attachment_jobs AS j
|
||||
SET published_original_key = a.object_key
|
||||
FROM attachments AS a
|
||||
WHERE a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version
|
||||
AND a.status = 'ready';
|
||||
|
||||
CREATE INDEX attachment_jobs_published_original_idx ON attachment_jobs (published_original_key)
|
||||
WHERE published_original_key IS NOT NULL;
|
||||
|
||||
ALTER TABLE attachment_attempts
|
||||
DROP CONSTRAINT attachment_attempts_outcome_check,
|
||||
ADD CONSTRAINT attachment_attempts_outcome_check
|
||||
CHECK (outcome IN ('ready', 'retry', 'failed', 'lease_expired', 'superseded'));
|
||||
|
||||
-- +goose Down
|
||||
UPDATE attachment_attempts SET outcome = 'failed' WHERE outcome = 'superseded';
|
||||
|
||||
ALTER TABLE attachment_attempts
|
||||
DROP CONSTRAINT attachment_attempts_outcome_check,
|
||||
ADD CONSTRAINT attachment_attempts_outcome_check
|
||||
CHECK (outcome IN ('ready', 'retry', 'failed', 'lease_expired'));
|
||||
|
||||
ALTER TABLE attachment_jobs DROP COLUMN published_original_key;
|
||||
@@ -0,0 +1,9 @@
|
||||
package migrations
|
||||
|
||||
import "embed"
|
||||
|
||||
// Files contains the SQL shipped with this exact migrator build.
|
||||
// Add schema changes as new numbered files; do not edit applied migrations.
|
||||
//
|
||||
//go:embed *.sql
|
||||
var Files embed.FS
|
||||
@@ -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;
|
||||
@@ -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 *;
|
||||
@@ -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;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- name: CreateChatMember :exec
|
||||
INSERT INTO chat_members(chat_id, user_id)
|
||||
VALUES ($1, $2);
|
||||
@@ -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);
|
||||
@@ -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();
|
||||
@@ -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);
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
Reference in New Issue
Block a user