forked from mtusi2026/mtusi2026lab4
ЛР4: S3-вложения, приватный bucket и согласованность хранилищ (трек 2)
This commit is contained in:
@@ -0,0 +1,184 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/model"
|
||||
)
|
||||
|
||||
// AttachmentRecord is the database view of an attachment. ObjectKey is an
|
||||
// internal server detail and is never serialised into the public API.
|
||||
type AttachmentRecord struct {
|
||||
model.Attachment
|
||||
ObjectKey string
|
||||
}
|
||||
|
||||
// ReconcileAttachment is the minimal row the offline reconciler needs. It is
|
||||
// intentionally not an API shape.
|
||||
type ReconcileAttachment struct {
|
||||
ID string
|
||||
ObjectKey string
|
||||
Status string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// CreatePendingAttachment records the upload intent before the S3 PUT. If the
|
||||
// process dies after this insert, the row is still accounted for and the
|
||||
// reconciler can remove it after the grace period; it is never returned by the
|
||||
// public API because only ready rows are visible.
|
||||
func (s *Store) CreatePendingAttachment(ctx context.Context, record AttachmentRecord, createdAt time.Time) error {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, object_key, created_at, updated_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7,
|
||||
'pending', NULL, $8, $9, $9)`,
|
||||
record.ID, record.ChatID, record.OwnerID, record.Filename,
|
||||
record.ContentType, record.SizeBytes, record.SHA256, record.ObjectKey, createdAt,
|
||||
)
|
||||
return s.classify(err)
|
||||
}
|
||||
|
||||
// MarkAttachmentReady promotes the pending row after the original bytes are in
|
||||
// S3. If the update fails, the row stays pending and the object remains
|
||||
// accounted; the reconciler owns the cleanup. Nothing is deleted here because
|
||||
// an ambiguous commit must never destroy a successfully stored original.
|
||||
func (s *Store) MarkAttachmentReady(ctx context.Context, id string, updatedAt time.Time) (time.Time, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
var stored time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', updated_at = $2
|
||||
WHERE id = $1::uuid AND status = 'pending'
|
||||
RETURNING updated_at`, id, updatedAt).Scan(&stored)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return time.Time{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return time.Time{}, s.classify(err)
|
||||
}
|
||||
return stored.UTC(), nil
|
||||
}
|
||||
|
||||
// ReadyAttachmentForUser applies the ACL in SQL: the row is returned only when
|
||||
// the caller is a member of the attachment's chat and the attachment is ready.
|
||||
// A foreign and a nonexistent attachment are indistinguishable.
|
||||
func (s *Store) ReadyAttachmentForUser(ctx context.Context, attachmentID, userID string) (AttachmentRecord, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
var record AttachmentRecord
|
||||
var createdAt, updatedAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT a.id::text, a.chat_id::text, a.owner_id::text, a.filename,
|
||||
a.content_type, a.size_bytes, a.sha256, a.status, a.error_code,
|
||||
a.object_key, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2::uuid
|
||||
WHERE a.id = $1::uuid AND a.status = 'ready'`,
|
||||
attachmentID, userID,
|
||||
).Scan(&record.ID, &record.ChatID, &record.OwnerID, &record.Filename,
|
||||
&record.ContentType, &record.SizeBytes, &record.SHA256, &record.Status, &record.ErrorCode,
|
||||
&record.ObjectKey, &createdAt, &updatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return AttachmentRecord{}, ErrNotFound
|
||||
}
|
||||
return AttachmentRecord{}, s.classify(err)
|
||||
}
|
||||
record.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
record.UpdatedAt = model.Time{Time: updatedAt.UTC()}
|
||||
record.Variants = []model.Variant{}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
// DeleteAttachmentRow removes a pending upload intent. It is used only after a
|
||||
// failed S3 PUT or by the reconciler; ready rows are never deleted here.
|
||||
func (s *Store) DeleteAttachmentRow(ctx context.Context, id string) error {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(ctx, `DELETE FROM attachments WHERE id = $1::uuid`, id)
|
||||
return s.classify(err)
|
||||
}
|
||||
|
||||
// ListAttachmentsForReconcile returns every row, including internal pending
|
||||
// upload intents. Only the offline reconciler calls it.
|
||||
func (s *Store) ListAttachmentsForReconcile(ctx context.Context) ([]ReconcileAttachment, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id::text, object_key, status, created_at, updated_at
|
||||
FROM attachments
|
||||
ORDER BY created_at, id`)
|
||||
if err != nil {
|
||||
return nil, s.classify(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
result := make([]ReconcileAttachment, 0, 128)
|
||||
for rows.Next() {
|
||||
var item ReconcileAttachment
|
||||
if err := rows.Scan(&item.ID, &item.ObjectKey, &item.Status, &item.CreatedAt, &item.UpdatedAt); err != nil {
|
||||
return nil, s.classify(err)
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, s.classify(err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// AttachmentByObjectKey reports whether a row still references the key. The
|
||||
// reconciler re-checks this immediately before deleting an object, so a
|
||||
// concurrent upload that committed between the snapshot and the delete is not
|
||||
// destroyed.
|
||||
func (s *Store) AttachmentByObjectKey(ctx context.Context, key string) (bool, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&exists); err != nil {
|
||||
return false, s.classify(err)
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
// AttachmentState re-reads the status and key before a mutation. A pending row
|
||||
// that became ready while the reconciler was scanning must not be deleted.
|
||||
func (s *Store) AttachmentState(ctx context.Context, id string) (string, string, time.Time, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
var status, objectKey string
|
||||
var updatedAt time.Time
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT status, object_key, updated_at FROM attachments WHERE id = $1::uuid`, id,
|
||||
).Scan(&status, &objectKey, &updatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", "", time.Time{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return "", "", time.Time{}, s.classify(err)
|
||||
}
|
||||
return status, objectKey, updatedAt.UTC(), nil
|
||||
}
|
||||
|
||||
// DeleteAttachmentIfPending deletes the row only while it is still pending.
|
||||
// The status predicate is the last line of defence against deleting a row that
|
||||
// a concurrent request has already promoted to ready.
|
||||
func (s *Store) DeleteAttachmentIfPending(ctx context.Context, id string) (bool, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
tag, err := s.pool.Exec(ctx,
|
||||
`DELETE FROM attachments WHERE id = $1::uuid AND status = 'pending'`, id)
|
||||
if err != nil {
|
||||
return false, s.classify(err)
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFiles embed.FS
|
||||
|
||||
// advisoryLockKey is a fixed application-wide key. pg_advisory_lock serialises
|
||||
// concurrent API replicas that start at the same time; it is released when the
|
||||
// dedicated connection is returned or the session ends.
|
||||
const advisoryLockKey int64 = 0x6d74756c616233 // "mtulab3"
|
||||
|
||||
type migration struct {
|
||||
version int
|
||||
name string
|
||||
checksum string
|
||||
sql string
|
||||
}
|
||||
|
||||
// Migrate applies every embedded migration exactly once and records its
|
||||
// checksum. Re-running it is a no-op, which is what the restart hook relies on.
|
||||
// A changed migration file is a startup error rather than a silent divergence.
|
||||
func (s *Store) Migrate(ctx context.Context) error {
|
||||
conn, err := s.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
defer conn.Release()
|
||||
|
||||
if _, err := conn.Exec(ctx, `SELECT pg_advisory_lock($1)`, advisoryLockKey); err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
defer func() {
|
||||
// Use a background context: the request context may already be
|
||||
// cancelled when a startup timeout fires, but the lock still has to be
|
||||
// released explicitly before the connection is returned to the pool.
|
||||
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, advisoryLockKey)
|
||||
}()
|
||||
|
||||
if _, err := conn.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version integer PRIMARY KEY,
|
||||
name text NOT NULL,
|
||||
checksum text NOT NULL,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)`); err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
|
||||
migrations, err := loadMigrations()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, item := range migrations {
|
||||
var existing string
|
||||
err := conn.QueryRow(ctx, `SELECT checksum FROM schema_migrations WHERE version = $1`, item.version).Scan(&existing)
|
||||
switch {
|
||||
case err == nil:
|
||||
if existing != item.checksum {
|
||||
return fmt.Errorf("migration %04d_%s was modified after it was applied", item.version, item.name)
|
||||
}
|
||||
continue
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return s.classify(err)
|
||||
}
|
||||
|
||||
tx, err := conn.Begin(ctx)
|
||||
if err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, item.sql); err != nil {
|
||||
_ = tx.Rollback(context.Background())
|
||||
return fmt.Errorf("apply migration %04d_%s: %w", item.version, item.name, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO schema_migrations (version, name, checksum) VALUES ($1, $2, $3)`,
|
||||
item.version, item.name, item.checksum,
|
||||
); err != nil {
|
||||
_ = tx.Rollback(context.Background())
|
||||
return s.classify(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadMigrations() ([]migration, error) {
|
||||
entries, err := fs.ReadDir(migrationFiles, "migrations")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]migration, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
|
||||
continue
|
||||
}
|
||||
name := entry.Name()
|
||||
if len(name) < 9 {
|
||||
return nil, fmt.Errorf("migration %q has no NNNN_ prefix", name)
|
||||
}
|
||||
version, err := strconv.Atoi(name[:4])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("migration %q has no numeric prefix", name)
|
||||
}
|
||||
data, err := migrationFiles.ReadFile("migrations/" + name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
items = append(items, migration{
|
||||
version: version,
|
||||
name: strings.TrimSuffix(name[5:], ".sql"),
|
||||
checksum: hex.EncodeToString(sum[:]),
|
||||
sql: string(data),
|
||||
})
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool { return items[i].version < items[j].version })
|
||||
for i := 1; i < len(items); i++ {
|
||||
if items[i].version == items[i-1].version {
|
||||
return nil, fmt.Errorf("duplicate migration version %d", items[i].version)
|
||||
}
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadMigrations(t *testing.T) {
|
||||
migrations, err := loadMigrations()
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations: %v", err)
|
||||
}
|
||||
if len(migrations) != 5 {
|
||||
t.Fatalf("loaded %d migrations, want 5", len(migrations))
|
||||
}
|
||||
for index, item := range migrations {
|
||||
if item.version != index+1 {
|
||||
t.Fatalf("migration order at %d = %d", index, item.version)
|
||||
}
|
||||
}
|
||||
for _, item := range migrations {
|
||||
if len(item.checksum) != 64 {
|
||||
t.Fatalf("checksum for %d has length %d", item.version, len(item.checksum))
|
||||
}
|
||||
lower := strings.ToLower(item.sql)
|
||||
if !strings.Contains(lower, "create ") && !strings.Contains(lower, "alter ") {
|
||||
t.Fatalf("migration %d has no schema statements", item.version)
|
||||
}
|
||||
}
|
||||
// The checksum must be stable across process runs: it is what detects an
|
||||
// edited migration after it has been applied.
|
||||
again, err := loadMigrations()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for index := range migrations {
|
||||
if migrations[index].checksum != again[index].checksum {
|
||||
t.Fatal("migration checksums are not deterministic")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationsContainRequiredDomainObjects(t *testing.T) {
|
||||
migrations, err := loadMigrations()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
all := ""
|
||||
for _, item := range migrations {
|
||||
all += item.sql
|
||||
}
|
||||
for _, required := range []string{
|
||||
"CREATE TABLE users",
|
||||
"CREATE TABLE chats",
|
||||
"CREATE TABLE chat_members",
|
||||
"CREATE TABLE messages",
|
||||
"CREATE UNIQUE INDEX users_username_key",
|
||||
"messages_sender_membership_fk",
|
||||
"messages_chat_created_id_idx",
|
||||
"CREATE TABLE message_idempotency",
|
||||
"PRIMARY KEY (user_id, method, path, key)",
|
||||
"CREATE TABLE attachments",
|
||||
"CREATE TABLE message_attachments",
|
||||
"attachments_object_key_unique",
|
||||
"message_attachments_attachment_chat_fk",
|
||||
} {
|
||||
if !strings.Contains(all, required) {
|
||||
t.Fatalf("migrations do not contain %q", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
-- Lab2 schema. PostgreSQL is the source of truth for users, chats, chat
|
||||
-- membership and messages. Sessions intentionally live in Valkey with a TTL.
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT users_username_format
|
||||
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_length
|
||||
CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
CONSTRAINT users_password_hash_present
|
||||
CHECK (length(password_hash) > 0)
|
||||
);
|
||||
|
||||
-- Uniqueness is enforced by the database, not by a read-then-insert check, so
|
||||
-- two concurrent registrations of the same username cannot both succeed.
|
||||
CREATE UNIQUE INDEX users_username_key ON users (username);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT chats_title_length
|
||||
CHECK (char_length(title) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position integer NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
CONSTRAINT chat_members_position_nonnegative CHECK (position >= 0)
|
||||
);
|
||||
|
||||
-- "Chats of the current user" walks chat_members by user_id.
|
||||
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT messages_text_length
|
||||
CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
CONSTRAINT messages_chat_fk
|
||||
FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE,
|
||||
-- The sender must be a member of the chat at the database level too, not
|
||||
-- only in the HTTP handler.
|
||||
CONSTRAINT messages_sender_membership_fk
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Indexes justified by the two keyset queries of the contract.
|
||||
--
|
||||
-- Message history:
|
||||
-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
-- ORDER BY created_at, id LIMIT $4
|
||||
-- The three-column index lets PostgreSQL start at the cursor position inside
|
||||
-- one chat instead of scanning the whole history for every page.
|
||||
CREATE INDEX messages_chat_created_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
|
||||
-- Chat list:
|
||||
-- ORDER BY created_at, id LIMIT $1
|
||||
-- after joining chat_members for the current user.
|
||||
CREATE INDEX chats_created_id_idx
|
||||
ON chats (created_at, id);
|
||||
@@ -0,0 +1,28 @@
|
||||
-- Lab3: shared idempotency records for POST /api/v1/chats/{chat_id}/messages.
|
||||
--
|
||||
-- The primary key is exactly the contract scope: acting user + HTTP method +
|
||||
-- chat message path + Idempotency-Key. Different users or chats may reuse the
|
||||
-- same key independently. request_hash lets a replay distinguish the same
|
||||
-- semantic body (201 + original message) from a different body (409).
|
||||
--
|
||||
-- A row is written in the same transaction as the message it references, so a
|
||||
-- committed row always has a committed message and an aborted request leaves
|
||||
-- neither. created_at supports the 24-hour retention prune; contract requires
|
||||
-- at least 24 h, this stand prunes only records older than that bound.
|
||||
CREATE TABLE message_idempotency (
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
method text NOT NULL,
|
||||
path text NOT NULL,
|
||||
key text NOT NULL,
|
||||
request_hash bytea NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, method, path, key),
|
||||
CONSTRAINT message_idempotency_method_post CHECK (method = 'POST'),
|
||||
CONSTRAINT message_idempotency_key_length CHECK (char_length(key) BETWEEN 1 AND 128),
|
||||
CONSTRAINT message_idempotency_path_length CHECK (char_length(path) BETWEEN 1 AND 256)
|
||||
);
|
||||
|
||||
-- Retention housekeeping walks old rows; new inserts stay cheap.
|
||||
CREATE INDEX message_idempotency_created_at_idx
|
||||
ON message_idempotency (created_at);
|
||||
@@ -0,0 +1,75 @@
|
||||
-- Lab4: attachment metadata lives in PostgreSQL; the original bytes live in
|
||||
-- the private S3 bucket. The only public state in the mandatory lab4 contract
|
||||
-- is ready. pending exists solely as an internal, server-side upload intent:
|
||||
-- it is written before the S3 PUT and promoted in the same request after the
|
||||
-- PUT. A crash or a database failure between the two steps therefore leaves an
|
||||
-- accounted row, never an anonymous object. The reconciler removes stale
|
||||
-- pending rows and their objects after a documented grace period.
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
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,
|
||||
error_code text,
|
||||
object_key text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT attachments_filename_length
|
||||
CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
CONSTRAINT attachments_content_type
|
||||
CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
CONSTRAINT attachments_size
|
||||
CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
CONSTRAINT attachments_sha256
|
||||
CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
CONSTRAINT attachments_status
|
||||
CHECK (status IN ('pending', 'ready')),
|
||||
CONSTRAINT attachments_ready_error
|
||||
CHECK ((status = 'ready' AND error_code IS NULL) OR status = 'pending'),
|
||||
CONSTRAINT attachments_object_key
|
||||
CHECK (object_key LIKE 'attachments/%'),
|
||||
CONSTRAINT attachments_object_key_unique UNIQUE (object_key),
|
||||
-- Referenced by the composite foreign key of message_attachments so the
|
||||
-- database itself rejects a link to an attachment of another chat.
|
||||
CONSTRAINT attachments_id_chat_unique UNIQUE (id, chat_id)
|
||||
);
|
||||
|
||||
-- The only attachment query on the hot path is "attachment of this chat".
|
||||
CREATE INDEX attachments_chat_created_idx
|
||||
ON attachments (chat_id, created_at, id);
|
||||
|
||||
-- The reconciler scans all rows by state and age. It never runs on the HTTP
|
||||
-- hot path.
|
||||
CREATE INDEX attachments_status_updated_idx
|
||||
ON attachments (status, updated_at);
|
||||
|
||||
-- messages.id is already the primary key; this unique constraint is the
|
||||
-- target required by the composite foreign keys below, not a second identity.
|
||||
-- It must exist before the foreign key that references (id, chat_id).
|
||||
ALTER TABLE messages
|
||||
ADD CONSTRAINT messages_id_chat_unique UNIQUE (id, chat_id);
|
||||
|
||||
-- A message and its attachment links share one transaction. The composite
|
||||
-- foreign keys make "file of another chat" impossible at the database level
|
||||
-- even if a future handler forgets the application check.
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL,
|
||||
attachment_id uuid NOT NULL,
|
||||
chat_id uuid NOT NULL,
|
||||
position integer NOT NULL,
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
CONSTRAINT message_attachments_position_unique UNIQUE (message_id, position),
|
||||
CONSTRAINT message_attachments_position_nonnegative CHECK (position >= 0),
|
||||
CONSTRAINT message_attachments_message_chat_fk
|
||||
FOREIGN KEY (message_id, chat_id) REFERENCES messages (id, chat_id) ON DELETE CASCADE,
|
||||
CONSTRAINT message_attachments_attachment_chat_fk
|
||||
FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments (id, chat_id)
|
||||
);
|
||||
|
||||
-- Reconciler lookup: "is this object key still referenced by any row?".
|
||||
CREATE INDEX message_attachments_attachment_idx
|
||||
ON message_attachments (attachment_id);
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Lab4 contract: a message may carry text = "" when it references at least one
|
||||
-- attachment of the chat (contracts/README.md, "Вложения"). The HTTP handler
|
||||
-- still rejects empty or blank text without attachments; the database
|
||||
-- constraint only widens to permit the documented attachment-only message.
|
||||
ALTER TABLE messages
|
||||
DROP CONSTRAINT messages_text_length;
|
||||
|
||||
ALTER TABLE messages
|
||||
ADD CONSTRAINT messages_text_length
|
||||
CHECK (char_length(text) BETWEEN 0 AND 4000);
|
||||
@@ -0,0 +1,702 @@
|
||||
// Package store is the PostgreSQL repository. Every statement uses positional
|
||||
// parameters; identifiers are never interpolated into SQL. The pool is
|
||||
// bounded and every operation carries a context timeout.
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/puddle/v2"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/cursor"
|
||||
"mtusi.ru/messenger-lab4/internal/model"
|
||||
"mtusi.ru/messenger-lab4/internal/uuid"
|
||||
)
|
||||
|
||||
// Domain errors. The HTTP layer maps them to the contract's status codes.
|
||||
var (
|
||||
ErrNotFound = errors.New("object not found")
|
||||
ErrUsernameTaken = errors.New("username already taken")
|
||||
ErrUnknownMember = errors.New("unknown chat member")
|
||||
ErrUnavailable = errors.New("database unavailable")
|
||||
ErrIdempotencyConflict = errors.New("idempotency key reused with a different request body")
|
||||
ErrAttachmentNotReady = errors.New("attachment is not ready")
|
||||
)
|
||||
|
||||
// Options bounds the pool and every query. Zero values fall back to safe
|
||||
// defaults so the store is still testable from small programs.
|
||||
type Options struct {
|
||||
MaxConns int32
|
||||
MinConns int32
|
||||
ConnectTimeout time.Duration
|
||||
StatementTimeout time.Duration
|
||||
QueryTimeout time.Duration
|
||||
}
|
||||
|
||||
// Store owns a bounded pgx pool.
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
queryTimeout time.Duration
|
||||
}
|
||||
|
||||
// Open parses the DSN and creates the pool. Parse errors deliberately do not
|
||||
// echo the DSN: it contains the database password.
|
||||
func Open(ctx context.Context, dsn string, options Options) (*Store, error) {
|
||||
config, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, errors.New("DATABASE_URL is not a valid PostgreSQL URL")
|
||||
}
|
||||
applyDefaults(&options)
|
||||
config.MaxConns = options.MaxConns
|
||||
config.MinConns = options.MinConns
|
||||
config.MaxConnLifetime = 30 * time.Minute
|
||||
config.MaxConnIdleTime = 5 * time.Minute
|
||||
config.HealthCheckPeriod = 30 * time.Second
|
||||
config.ConnConfig.ConnectTimeout = options.ConnectTimeout
|
||||
config.ConnConfig.RuntimeParams["application_name"] = "messenger-lab4"
|
||||
// A statement timeout in the server session is the last line of defence
|
||||
// against a runaway query; the caller's context is the first.
|
||||
config.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(options.StatementTimeout.Milliseconds(), 10)
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
|
||||
}
|
||||
return &Store{pool: pool, queryTimeout: options.QueryTimeout}, nil
|
||||
}
|
||||
|
||||
func applyDefaults(options *Options) {
|
||||
if options.MaxConns <= 0 {
|
||||
options.MaxConns = 8
|
||||
}
|
||||
if options.MinConns < 0 {
|
||||
options.MinConns = 0
|
||||
}
|
||||
if options.MinConns > options.MaxConns {
|
||||
options.MinConns = options.MaxConns
|
||||
}
|
||||
if options.ConnectTimeout <= 0 {
|
||||
options.ConnectTimeout = 3 * time.Second
|
||||
}
|
||||
if options.StatementTimeout <= 0 {
|
||||
options.StatementTimeout = 3 * time.Second
|
||||
}
|
||||
if options.QueryTimeout <= 0 {
|
||||
options.QueryTimeout = 3 * time.Second
|
||||
}
|
||||
}
|
||||
|
||||
// Ping is used by /health/ready and by the startup readiness loop.
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
return s.pool.Ping(ctx)
|
||||
}
|
||||
|
||||
// Close waits for in-flight queries and closes the pool.
|
||||
func (s *Store) Close() { s.pool.Close() }
|
||||
|
||||
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
if s.queryTimeout <= 0 {
|
||||
return ctx, func() {}
|
||||
}
|
||||
return context.WithTimeout(ctx, s.queryTimeout)
|
||||
}
|
||||
|
||||
// classify separates a dependency outage (contract 503 unavailable) from a
|
||||
// genuine application bug (500 internal_error). Only the error class is mapped;
|
||||
// the original error is logged server-side and never sent to a client.
|
||||
func (s *Store) classify(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch {
|
||||
case strings.HasPrefix(pgErr.Code, "08"), // connection exception
|
||||
pgErr.Code == "57P01", // admin shutdown
|
||||
pgErr.Code == "57P02", // crash shutdown
|
||||
pgErr.Code == "57P03", // cannot connect now
|
||||
pgErr.Code == "57014", // query cancelled (statement_timeout)
|
||||
strings.HasPrefix(pgErr.Code, "53"): // insufficient resources
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, puddle.ErrClosedPool) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key"
|
||||
}
|
||||
|
||||
func isForeignKeyViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23503"
|
||||
}
|
||||
|
||||
func isIdempotencyViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505" &&
|
||||
pgErr.ConstraintName == "message_idempotency_pkey"
|
||||
}
|
||||
|
||||
// CreateUser inserts a user and relies on the unique index for both ordinary
|
||||
// duplicates and concurrent registrations of the same username.
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
id := uuid.New()
|
||||
createdAt := time.Now().UTC()
|
||||
var stored time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5)
|
||||
RETURNING created_at`,
|
||||
id, username, displayName, passwordHash, createdAt,
|
||||
).Scan(&stored)
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return model.User{}, ErrUsernameTaken
|
||||
}
|
||||
return model.User{}, s.classify(err)
|
||||
}
|
||||
return model.User{
|
||||
ID: id,
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: model.Time{Time: stored.UTC()},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UserByUsername returns the public user and the Argon2id hash. The hash is
|
||||
// used only by the login handler and is never serialised.
|
||||
func (s *Store) UserByUsername(ctx context.Context, username string) (model.User, string, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user model.User
|
||||
var passwordHash string
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, password_hash, created_at
|
||||
FROM users WHERE username = $1`, username,
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &passwordHash, &createdAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, "", ErrNotFound
|
||||
}
|
||||
return model.User{}, "", s.classify(err)
|
||||
}
|
||||
user.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
|
||||
// UserByID resolves the identity stored in a server-side session.
|
||||
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user model.User
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, created_at
|
||||
FROM users WHERE id = $1::uuid`, id,
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &createdAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrNotFound
|
||||
}
|
||||
return model.User{}, s.classify(err)
|
||||
}
|
||||
user.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// CreateChat inserts the chat and its membership in one transaction. A caller
|
||||
// cannot observe a chat without members: either both are committed or neither.
|
||||
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string, callerID string) (model.Chat, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
|
||||
var existing int
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT count(*) FROM users
|
||||
WHERE id IN (SELECT value::uuid FROM unnest($1::text[]) AS value)`, memberIDs,
|
||||
).Scan(&existing); err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
if existing != len(memberIDs) {
|
||||
return model.Chat{}, ErrUnknownMember
|
||||
}
|
||||
|
||||
id := uuid.New()
|
||||
createdAt := time.Now().UTC()
|
||||
var stored time.Time
|
||||
if err := tx.QueryRow(ctx, `
|
||||
INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)
|
||||
RETURNING created_at`, id, title, createdAt,
|
||||
).Scan(&stored); err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
|
||||
batch := &pgx.Batch{}
|
||||
for position, memberID := range memberIDs {
|
||||
batch.Queue(`INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1::uuid, $2::uuid, $3)`,
|
||||
id, memberID, position)
|
||||
}
|
||||
results := tx.SendBatch(ctx, batch)
|
||||
for range memberIDs {
|
||||
if _, err := results.Exec(); err != nil {
|
||||
_ = results.Close()
|
||||
if isForeignKeyViolation(err) {
|
||||
return model.Chat{}, ErrUnknownMember
|
||||
}
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
}
|
||||
if err := results.Close(); err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
|
||||
return model.Chat{
|
||||
ID: id,
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
CreatedAt: model.Time{Time: stored.UTC()},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// IsChatMember is used before parsing query parameters so a foreign chat is
|
||||
// always 404, independent of the submitted cursor or limit.
|
||||
func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
var member bool
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid
|
||||
)`, chatID, userID).Scan(&member)
|
||||
if err != nil {
|
||||
return false, s.classify(err)
|
||||
}
|
||||
return member, nil
|
||||
}
|
||||
|
||||
// ChatForUser returns a chat only when the user is a member. A missing chat and
|
||||
// a foreign chat are indistinguishable to the caller.
|
||||
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (model.Chat, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
var chat model.Chat
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
array_agg(cm.user_id::text ORDER BY cm.position)
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2::uuid
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1::uuid
|
||||
GROUP BY c.id`, chatID, userID,
|
||||
).Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrNotFound
|
||||
}
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
const chatsPageSelect = `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
array_agg(cm.user_id::text ORDER BY cm.position)
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1::uuid
|
||||
JOIN chat_members cm ON cm.chat_id = c.id`
|
||||
|
||||
// Chats returns one keyset page of chats visible to the user.
|
||||
func (s *Store) Chats(ctx context.Context, userID string, position *cursor.Cursor, limit int) (model.ChatPage, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
query := chatsPageSelect + `
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2`
|
||||
args := []any{userID, limit + 1}
|
||||
if position != nil {
|
||||
query = chatsPageSelect + `
|
||||
WHERE (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`
|
||||
args = []any{userID, position.At, position.ID, limit + 1}
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return model.ChatPage{}, s.classify(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]model.Chat, 0, limit)
|
||||
for rows.Next() {
|
||||
var chat model.Chat
|
||||
var createdAt time.Time
|
||||
if err := rows.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
|
||||
return model.ChatPage{}, s.classify(err)
|
||||
}
|
||||
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
items = append(items, chat)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return model.ChatPage{}, s.classify(err)
|
||||
}
|
||||
|
||||
page := model.ChatPage{Items: items}
|
||||
if len(items) > limit {
|
||||
page.Items = items[:limit]
|
||||
next := cursor.ForChat(page.Items[len(page.Items)-1])
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// PoolStats is a point-in-time snapshot of the bounded pgx pool. It is used
|
||||
// only by the operator-only metrics listener, never by the public API.
|
||||
type PoolStats struct {
|
||||
MaxConns int32 `json:"max_conns"`
|
||||
TotalConns int32 `json:"total_conns"`
|
||||
AcquiredConns int32 `json:"acquired_conns"`
|
||||
IdleConns int32 `json:"idle_conns"`
|
||||
EmptyAcquireCount int64 `json:"empty_acquire_count"`
|
||||
CanceledAcquireCount int64 `json:"canceled_acquire_count"`
|
||||
AcquireCount int64 `json:"acquire_count"`
|
||||
AcquireDurationMillis int64 `json:"acquire_duration_ms_total"`
|
||||
NewConnsCount int64 `json:"new_conns_count"`
|
||||
MaxLifetimeDestroyCount int64 `json:"max_lifetime_destroy_count"`
|
||||
MaxIdleDestroyCount int64 `json:"max_idle_destroy_count"`
|
||||
}
|
||||
|
||||
// PoolStats reports saturation signals for the connection pool. EmptyAcquire
|
||||
// Count is the number of calls that had to wait for a free connection; a fast
|
||||
// rising value while the API CPU is below its limit points at the database or
|
||||
// the pool size, not at the HTTP layer.
|
||||
func (s *Store) PoolStats() PoolStats {
|
||||
stat := s.pool.Stat()
|
||||
return PoolStats{
|
||||
MaxConns: stat.MaxConns(),
|
||||
TotalConns: stat.TotalConns(),
|
||||
AcquiredConns: stat.AcquiredConns(),
|
||||
IdleConns: stat.IdleConns(),
|
||||
EmptyAcquireCount: stat.EmptyAcquireCount(),
|
||||
CanceledAcquireCount: stat.CanceledAcquireCount(),
|
||||
AcquireCount: stat.AcquireCount(),
|
||||
AcquireDurationMillis: stat.AcquireDuration().Milliseconds(),
|
||||
NewConnsCount: stat.NewConnsCount(),
|
||||
MaxLifetimeDestroyCount: stat.MaxLifetimeDestroyCount(),
|
||||
MaxIdleDestroyCount: stat.MaxIdleDestroyCount(),
|
||||
}
|
||||
}
|
||||
|
||||
// CreateMessageIdempotent appends a message, its attachment links and the
|
||||
// idempotency result in one PostgreSQL transaction. A committed transaction
|
||||
// therefore always contains the message, every link and the key record; a
|
||||
// failed one contains none of them. The idempotency unique index serialises
|
||||
// concurrent replays: the loser blocks, then rolls back and reads the committed
|
||||
// winner, so a concurrent repeat can never create a second message.
|
||||
//
|
||||
// Behavior derived from contracts/README.md:
|
||||
// - a new (user, method, path, key) creates a message and its record, 201;
|
||||
// - the same semantic body replays the stored message and links, 201;
|
||||
// - a different body with the same key is a conflict, 409;
|
||||
// - a transient failure touches neither table, so the client may safely
|
||||
// retry the same key and never observe a duplicate side effect.
|
||||
func (s *Store) CreateMessageIdempotent(ctx context.Context, chatID, senderID, method, path, key string, requestHash []byte, text string, attachmentIDs []string) (model.Message, bool, error) {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
message := model.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
// A non-nil empty slice is required: the public Message schema has
|
||||
// attachment_ids: [] as an array, never null.
|
||||
AttachmentIDs: append([]string{}, attachmentIDs...),
|
||||
}
|
||||
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, false, s.classify(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
|
||||
// Validate every attachment against the message chat before writing any
|
||||
// row. The composite foreign key is the second line of defence; this query
|
||||
// lets the handler distinguish "foreign/unknown" (404) from "not ready"
|
||||
// (409) without leaking whether a foreign attachment id exists.
|
||||
if len(attachmentIDs) > 0 {
|
||||
rows, queryErr := tx.Query(ctx, `
|
||||
SELECT id::text, status
|
||||
FROM attachments
|
||||
WHERE chat_id = $1::uuid
|
||||
AND id IN (SELECT value::uuid FROM unnest($2::text[]) AS value)`,
|
||||
chatID, attachmentIDs)
|
||||
if queryErr != nil {
|
||||
return model.Message{}, false, s.classify(queryErr)
|
||||
}
|
||||
statuses := make(map[string]string, len(attachmentIDs))
|
||||
for rows.Next() {
|
||||
var id, status string
|
||||
if scanErr := rows.Scan(&id, &status); scanErr != nil {
|
||||
rows.Close()
|
||||
return model.Message{}, false, s.classify(scanErr)
|
||||
}
|
||||
statuses[id] = status
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
rows.Close()
|
||||
return model.Message{}, false, s.classify(rows.Err())
|
||||
}
|
||||
rows.Close()
|
||||
if len(statuses) != len(attachmentIDs) {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
for _, status := range statuses {
|
||||
if status != "ready" {
|
||||
return model.Message{}, false, ErrAttachmentNotReady
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
created := time.Now().UTC()
|
||||
var stored time.Time
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
RETURNING created_at`,
|
||||
message.ID, chatID, senderID, text, created,
|
||||
).Scan(&stored)
|
||||
if err != nil {
|
||||
if isForeignKeyViolation(err) {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
return model.Message{}, false, s.classify(err)
|
||||
}
|
||||
|
||||
if len(attachmentIDs) > 0 {
|
||||
batch := &pgx.Batch{}
|
||||
for position, attachmentID := range attachmentIDs {
|
||||
batch.Queue(`
|
||||
INSERT INTO message_attachments (message_id, attachment_id, chat_id, position)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4)`,
|
||||
message.ID, attachmentID, chatID, position)
|
||||
}
|
||||
results := tx.SendBatch(ctx, batch)
|
||||
for range attachmentIDs {
|
||||
if _, execErr := results.Exec(); execErr != nil {
|
||||
_ = results.Close()
|
||||
if isForeignKeyViolation(execErr) {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
return model.Message{}, false, s.classify(execErr)
|
||||
}
|
||||
}
|
||||
if closeErr := results.Close(); closeErr != nil {
|
||||
if isForeignKeyViolation(closeErr) {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
return model.Message{}, false, s.classify(closeErr)
|
||||
}
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO message_idempotency
|
||||
(user_id, method, path, key, request_hash, message_id, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5, $6::uuid, $7)`,
|
||||
senderID, method, path, key, requestHash, message.ID, created)
|
||||
if err != nil {
|
||||
if isIdempotencyViolation(err) {
|
||||
// This transaction never committed. Roll it back explicitly before
|
||||
// reading the winner; PostgreSQL has already released the row lock
|
||||
// when it reported the unique violation.
|
||||
_ = tx.Rollback(ctx)
|
||||
storedHash, storedMessage, found, replayErr := s.replayIdempotent(ctx, senderID, method, path, key)
|
||||
if replayErr != nil {
|
||||
return model.Message{}, false, replayErr
|
||||
}
|
||||
if !found {
|
||||
return model.Message{}, false, fmt.Errorf("%w: idempotency record vanished", ErrUnavailable)
|
||||
}
|
||||
if !bytes.Equal(storedHash, requestHash) {
|
||||
return model.Message{}, false, ErrIdempotencyConflict
|
||||
}
|
||||
return storedMessage, true, nil
|
||||
}
|
||||
return model.Message{}, false, s.classify(err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, false, s.classify(err)
|
||||
}
|
||||
message.CreatedAt = model.Time{Time: stored.UTC()}
|
||||
return message, false, nil
|
||||
}
|
||||
|
||||
func (s *Store) replayIdempotent(ctx context.Context, userID, method, path, key string) ([]byte, model.Message, bool, error) {
|
||||
var storedHash []byte
|
||||
var message model.Message
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT i.request_hash,
|
||||
m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
|
||||
COALESCE((
|
||||
SELECT array_agg(ma.attachment_id::text ORDER BY ma.position)
|
||||
FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id
|
||||
), '{}')
|
||||
FROM message_idempotency i
|
||||
JOIN messages m ON m.id = i.message_id
|
||||
WHERE i.user_id = $1::uuid AND i.method = $2 AND i.path = $3 AND i.key = $4`,
|
||||
userID, method, path, key,
|
||||
).Scan(&storedHash, &message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &message.AttachmentIDs)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, model.Message{}, false, nil
|
||||
}
|
||||
return nil, model.Message{}, false, s.classify(err)
|
||||
}
|
||||
if message.AttachmentIDs == nil {
|
||||
message.AttachmentIDs = []string{}
|
||||
}
|
||||
message.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return storedHash, message, true, nil
|
||||
}
|
||||
|
||||
// PruneIdempotency removes records older than the contract's minimum
|
||||
// retention. It runs opportunistically from every replica; the statement is
|
||||
// safe to execute concurrently and is bounded to keep one delete short.
|
||||
func (s *Store) PruneIdempotency(ctx context.Context, olderThan time.Duration) (int64, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
DELETE FROM message_idempotency
|
||||
WHERE ctid IN (
|
||||
SELECT ctid FROM message_idempotency
|
||||
WHERE created_at < now() - $1::interval
|
||||
LIMIT 500
|
||||
)`, fmt.Sprintf("%d seconds", int(olderThan.Seconds())))
|
||||
if err != nil {
|
||||
return 0, s.classify(err)
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const messagesPageSelect = `
|
||||
SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
|
||||
COALESCE((
|
||||
SELECT array_agg(ma.attachment_id::text ORDER BY ma.position)
|
||||
FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id
|
||||
), '{}')
|
||||
FROM (`
|
||||
|
||||
// Messages returns one keyset page of a chat history. The caller has already
|
||||
// verified membership; the query itself never loads the whole history.
|
||||
func (s *Store) Messages(ctx context.Context, chatID string, position *cursor.Cursor, limit int) (model.MessagePage, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
where := `WHERE chat_id = $1::uuid`
|
||||
args := []any{chatID, limit + 1}
|
||||
order := `ORDER BY created_at, id
|
||||
LIMIT $2`
|
||||
if position != nil {
|
||||
where = `WHERE chat_id = $1::uuid
|
||||
AND (created_at, id) > ($2::timestamptz, $3::uuid)`
|
||||
args = []any{chatID, position.At, position.ID, limit + 1}
|
||||
order = `ORDER BY created_at, id
|
||||
LIMIT $4`
|
||||
}
|
||||
query := messagesPageSelect + `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
` + where + `
|
||||
` + order + `
|
||||
) m
|
||||
LEFT JOIN message_attachments ma ON ma.message_id = m.id
|
||||
GROUP BY m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
ORDER BY m.created_at, m.id`
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return model.MessagePage{}, s.classify(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]model.Message, 0, limit)
|
||||
for rows.Next() {
|
||||
var message model.Message
|
||||
var createdAt time.Time
|
||||
if err := rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &message.AttachmentIDs); err != nil {
|
||||
return model.MessagePage{}, s.classify(err)
|
||||
}
|
||||
if message.AttachmentIDs == nil {
|
||||
message.AttachmentIDs = []string{}
|
||||
}
|
||||
message.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
items = append(items, message)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return model.MessagePage{}, s.classify(err)
|
||||
}
|
||||
|
||||
page := model.MessagePage{Items: items}
|
||||
if len(items) > limit {
|
||||
page.Items = items[:limit]
|
||||
next := cursor.ForMessage(page.Items[len(page.Items)-1])
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
Reference in New Issue
Block a user