feat: add bounded observability and verified SLO incident alerts

This commit is contained in:
Vladislav Agapov
2026-10-29 18:01:11 +03:00
parent 470d9d6f1e
commit 6c7601802d
325 changed files with 24988 additions and 44 deletions
+71
View File
@@ -0,0 +1,71 @@
package postgres
import (
"context"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
)
const attachmentBaseColumns = `id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status,object_key,created_at,updated_at`
const attachmentColumns = attachmentBaseColumns + ",variants,error_code,pipeline_version"
// Reserve creates durable intent before any S3 PUT.
func (s *Store) Reserve(ctx context.Context, a dto.Attachment) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
_, err := s.pool.Exec(ctx, `INSERT INTO attachments (`+attachmentBaseColumns+`) VALUES(@id,@chat,@owner,@filename,@mime,@size,@sha,@status,@key,@created,@updated)`, pgx.StrictNamedArgs{
"id": a.ID,
"chat": a.ChatID,
"owner": a.OwnerID,
"filename": a.Filename,
"mime": a.ContentType,
"size": a.SizeBytes,
"sha": a.SHA256,
"status": a.Status,
"key": a.ObjectKey,
"created": a.CreatedAt,
"updated": a.UpdatedAt,
})
return normalize(err)
}
// Publish atomically exposes a completed object without changing its immutable key.
func (s *Store) Publish(ctx context.Context, id uuid.UUID) (dto.Attachment, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return scanAttachment(s.pool.QueryRow(ctx, `UPDATE attachments SET status='ready',updated_at=clock_timestamp() WHERE id=@id AND status='uploading' RETURNING `+attachmentColumns, pgx.StrictNamedArgs{"id": id}))
}
// Attachment reads one immutable metadata record.
func (s *Store) Attachment(ctx context.Context, id uuid.UUID) (dto.Attachment, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return scanAttachment(s.pool.QueryRow(ctx, `SELECT `+attachmentColumns+` FROM attachments WHERE id=@id`, pgx.StrictNamedArgs{"id": id}))
}
// scanAttachment decodes explicit columns shared by read and publication.
func scanAttachment(row pgx.Row) (dto.Attachment, error) {
var a dto.Attachment
err := row.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status, &a.ObjectKey, &a.CreatedAt, &a.UpdatedAt, &a.Variants, &a.ErrorCode, &a.PipelineVersion)
return a, normalize(err)
}
// validateAttachments locks referenced metadata before inserting the message.
func validateAttachments(ctx context.Context, tx pgx.Tx, message dto.MessageDTO) error {
for _, id := range message.AttachmentIDs {
var status string
err := tx.QueryRow(ctx, `SELECT status FROM attachments WHERE id=@id AND chat_id=@chat FOR SHARE`, pgx.StrictNamedArgs{"id": id, "chat": message.ChatID}).Scan(&status)
if err != nil {
return err
}
if status != "ready" && status != "queued" && status != "processing" {
return store.ErrConflict
}
}
return nil
}
+167
View File
@@ -0,0 +1,167 @@
package postgres
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/media"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
)
// fixtureAttachment reserves an independent attachment for a real SQL scenario.
func fixtureAttachment(t *testing.T, s *Store) dto.Attachment {
t.Helper()
user := fixtureUser(t, s)
chat := fixtureChat(t, s, user)
id := uuid.New()
a := dto.Attachment{
ID: id,
ChatID: chat.ID,
OwnerID: user.ID,
Filename: "test.png",
ContentType: "image/png",
SizeBytes: 32,
SHA256: "synthetic-checksum",
Status: "uploading",
ObjectKey: "original/" + id.String(),
CreatedAt: time.Now().UTC().Add(-2 * time.Hour),
UpdatedAt: time.Now().UTC(),
}
if err := s.Reserve(t.Context(), a); err != nil {
t.Fatal(err)
}
return a
}
// TestAttachmentPublication verifies stored metadata survives a fresh read after commit.
func TestAttachmentPublication(t *testing.T) {
s := testStore(t)
a := fixtureAttachment(t, s)
published, err := s.Publish(t.Context(), a.ID)
if err != nil || published.Status != "ready" {
t.Fatalf("publish: %v", err)
}
got, err := s.Attachment(t.Context(), a.ID)
if err != nil || got.ObjectKey != a.ObjectKey || got.Status != "ready" {
t.Fatalf("stored metadata: %v", err)
}
}
// TestAttachmentMessageScope checks a foreign chat cannot reference another chat's file.
func TestAttachmentMessageScope(t *testing.T) {
s := testStore(t)
a := fixtureAttachment(t, s)
if _, err := s.Publish(t.Context(), a.ID); err != nil {
t.Fatal(err)
}
foreignUser := fixtureUser(t, s)
foreignChat := fixtureChat(t, s, foreignUser)
_, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: foreignChat.ID, SenderID: foreignUser.ID, AttachmentIDs: []string{a.ID.String()}, IdempotencyKey: "foreign"})
if !errors.Is(err, store.ErrNotFound) {
t.Fatalf("foreign attachment: %v", err)
}
}
// TestAttachmentRetryConflict verifies attachment identity participates in the immutable request.
func TestAttachmentRetryConflict(t *testing.T) {
s := testStore(t)
a := fixtureAttachment(t, s)
if _, err := s.Publish(t.Context(), a.ID); err != nil {
t.Fatal(err)
}
m := dto.MessageDTO{ID: uuid.New(), ChatID: a.ChatID, SenderID: a.OwnerID, Text: "same", AttachmentIDs: []string{a.ID.String()}, IdempotencyKey: "retry"}
if _, err := s.CreateMessage(t.Context(), m); err != nil {
t.Fatal(err)
}
m.AttachmentIDs = nil
_, err := s.CreateMessage(t.Context(), m)
if !errors.Is(err, store.ErrConflict) {
t.Fatalf("changed attachment list: %v", err)
}
}
// TestReclaimExcludesPublication demonstrates the durable cleanup state closes the publish race.
func TestReclaimExcludesPublication(t *testing.T) {
s := testStore(t)
a := fixtureAttachment(t, s)
claimed, err := s.Reclaim(t.Context(), a.ID, time.Now().Add(-time.Hour), false)
if err != nil || !claimed {
t.Fatalf("claim: %v", err)
}
if _, err := s.Publish(t.Context(), a.ID); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("late publication: %v", err)
}
removed, err := s.Reclaim(t.Context(), a.ID, time.Now().Add(-time.Hour), true)
if err != nil || !removed {
t.Fatalf("cleanup: %v", err)
}
}
// TestReclaimProtectsFreshReservation ensures a concurrent valid upload stays intact.
func TestReclaimProtectsFreshReservation(t *testing.T) {
s := testStore(t)
a := fixtureAttachment(t, s)
_, err := s.pool.Exec(t.Context(), `UPDATE attachments SET created_at=clock_timestamp() WHERE id=@id`, pgx.StrictNamedArgs{"id": a.ID})
if err != nil {
t.Fatal(err)
}
claimed, err := s.Reclaim(t.Context(), a.ID, time.Now().Add(-time.Hour), false)
if err != nil || claimed {
t.Fatalf("fresh reservation removed: %v", err)
}
}
// TestMetadataReconciliation detects missing originals without deleting referenced metadata.
func TestMetadataReconciliation(t *testing.T) {
s := testStore(t)
a := fixtureAttachment(t, s)
if _, err := s.Publish(t.Context(), a.ID); err != nil {
t.Fatal(err)
}
objects := &reconcileObjects{exists: false}
dry, err := media.Reconcile(t.Context(), s, objects, uuid.Nil, time.Hour, false)
if err != nil || dry.Missing != 1 || dry.Changed != 0 {
t.Fatalf("dry run: %+v %v", dry, err)
}
applied, err := media.Reconcile(t.Context(), s, objects, uuid.Nil, time.Hour, true)
if err != nil || applied.Changed != 1 {
t.Fatalf("repair: %+v %v", applied, err)
}
again, err := media.Reconcile(t.Context(), s, objects, uuid.Nil, time.Hour, true)
if err != nil || again.Changed != 0 {
t.Fatalf("repeat changed state: %+v %v", again, err)
}
objects.exists = true
restored, err := media.Reconcile(t.Context(), s, objects, uuid.Nil, time.Hour, true)
if err != nil || restored.Changed != 1 {
t.Fatalf("restore: %+v %v", restored, err)
}
}
// TestObjectReservationLookup protects unfinished uploads from orphan deletion.
func TestObjectReservationLookup(t *testing.T) {
s := testStore(t)
a := fixtureAttachment(t, s)
exists, err := s.HasObject(t.Context(), a.ObjectKey)
if err != nil || !exists {
t.Fatalf("reservation not protected: %v", err)
}
exists, err = s.HasObject(t.Context(), "original/"+uuid.NewString())
if err != nil || exists {
t.Fatalf("unknown object considered reserved: %v", err)
}
}
// TestInventoryStopsAtUnavailableDatabase rejects a scan rather than reporting an empty inventory.
func TestInventoryStopsAtUnavailableDatabase(t *testing.T) {
s := testStore(t)
s.Close()
if _, err := s.Scan(t.Context(), uuid.Nil, 1000); err == nil {
t.Fatal("closed database reported empty inventory")
}
}
+58
View File
@@ -0,0 +1,58 @@
package postgres
import (
"context"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
)
// CreateChat commits the chat and every member together, rolling back on any failure.
func (s *Store) CreateChat(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
if err := tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES(@id,@title) RETURNING created_at`, pgx.StrictNamedArgs{"id": chat.ID, "title": chat.Title}).Scan(&chat.CreatedAt); err != nil {
return err
}
_, err := tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) SELECT @chat,id FROM unnest(@members::uuid[]) AS member(id)`, pgx.StrictNamedArgs{"chat": chat.ID, "members": chat.MemberIDs})
return err
})
return chat, normalize(err)
}
// Chat reads a chat and its immutable membership in one snapshot.
func (s *Store) Chat(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var chat dto.ChatDTO
err := s.pool.QueryRow(ctx, `SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)
FROM chats c WHERE c.id=@id`, pgx.StrictNamedArgs{"id": id}).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
return chat, normalize(err)
}
// Chats returns the requested keyset page of chats visible to a user.
func (s *Store) Chats(ctx context.Context, userID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rows, err := s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)
FROM chats c JOIN chat_members m ON m.chat_id=c.id
WHERE m.user_id=@user AND (c.created_at,c.id)>(@time,@id) ORDER BY c.created_at,c.id LIMIT @limit`, pgx.StrictNamedArgs{
"user": userID, "time": position.CreatedAt, "id": position.ID, "limit": limit,
})
if err != nil {
return nil, normalize(err)
}
defer rows.Close()
chats := make([]dto.ChatDTO, 0)
for rows.Next() {
var chat dto.ChatDTO
if err := rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
return nil, normalize(err)
}
chats = append(chats, chat)
}
return chats, normalize(rows.Err())
}
+52
View File
@@ -0,0 +1,52 @@
package postgres
import (
"context"
"errors"
"fmt"
"io"
"net"
"testing"
"github.com/jackc/pgx/v5/pgconn"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
)
// TestNormalizeUnavailable classifies dependency failures while retaining their causes.
func TestNormalizeUnavailable(t *testing.T) {
cases := []struct {
name string
err error
}{
{"deadline", context.DeadlineExceeded},
{"closed stream", io.EOF},
{"truncated stream", io.ErrUnexpectedEOF},
{"network", &net.OpError{Op: "dial", Net: "tcp", Err: errors.New("refused")}},
{"connection exception", &pgconn.PgError{Code: "08006"}},
{"connection limit", &pgconn.PgError{Code: "53300"}},
{"shutdown", &pgconn.PgError{Code: "57P01"}},
{"crash", &pgconn.PgError{Code: "57P02"}},
{"starting", &pgconn.PgError{Code: "57P03"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := normalize(fmt.Errorf("operation failed: %w", tc.err))
if !errors.Is(err, store.ErrUnavailable) || !errors.Is(err, tc.err) {
t.Fatalf("failure category or cause lost: %T", tc.err)
}
})
}
}
// TestNormalizeUnexpected preserves programming errors instead of misclassifying them as outages.
func TestNormalizeUnexpected(t *testing.T) {
for _, code := range []string{"42601", "23503", "42P01"} {
t.Run(code, func(t *testing.T) {
err := &pgconn.PgError{Code: code}
if normalize(err) != err {
t.Fatal("unexpected SQL error was reclassified")
}
})
}
}
+52
View File
@@ -0,0 +1,52 @@
package postgres
import (
"context"
"errors"
"slices"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
)
// replayMessage serializes one chat and returns an unexpired original response.
func replayMessage(ctx context.Context, tx pgx.Tx, message dto.MessageDTO) (dto.MessageDTO, bool, error) {
var locked string
if err := tx.QueryRow(ctx, "SELECT id FROM chats WHERE id=@chat FOR UPDATE", pgx.StrictNamedArgs{"chat": message.ChatID}).Scan(&locked); err != nil {
return dto.MessageDTO{}, false, err
}
if message.IdempotencyKey == "" {
return dto.MessageDTO{}, false, nil
}
args := pgx.StrictNamedArgs{"user": message.SenderID, "chat": message.ChatID, "key": message.IdempotencyKey}
if _, err := tx.Exec(ctx, `DELETE FROM message_idempotency WHERE user_id=@user AND chat_id=@chat AND key=@key AND expires_at<=clock_timestamp()`, args); err != nil {
return dto.MessageDTO{}, false, err
}
var original dto.MessageDTO
err := tx.QueryRow(ctx, `SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,m.attachment_ids FROM message_idempotency i JOIN messages m ON m.id=i.message_id
WHERE i.user_id=@user AND i.chat_id=@chat AND i.key=@key`, args).Scan(&original.ID, &original.ChatID, &original.SenderID, &original.Text, &original.CreatedAt, &original.AttachmentIDs)
if errors.Is(err, pgx.ErrNoRows) {
return dto.MessageDTO{}, false, nil
}
if err != nil {
return dto.MessageDTO{}, false, err
}
if original.Text != message.Text || !slices.Equal(original.AttachmentIDs, message.AttachmentIDs) {
return dto.MessageDTO{}, false, store.ErrConflict
}
return original, true, nil
}
// rememberMessage stores the result in the same transaction as the message insert.
func rememberMessage(ctx context.Context, tx pgx.Tx, message dto.MessageDTO) error {
if message.IdempotencyKey == "" {
return nil
}
_, err := tx.Exec(ctx, `INSERT INTO message_idempotency(user_id,chat_id,key,message_id,expires_at)
VALUES(@user,@chat,@key,@id,clock_timestamp()+interval '24 hours')`, pgx.StrictNamedArgs{
"user": message.SenderID, "chat": message.ChatID, "key": message.IdempotencyKey, "id": message.ID,
})
return err
}
+139
View File
@@ -0,0 +1,139 @@
package postgres
import (
"errors"
"sync"
"testing"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
)
// TestMessageRetryRace verifies concurrent attempts commit exactly one message and replay its response.
func TestMessageRetryRace(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
chat := fixtureChat(t, s, user)
var wg sync.WaitGroup
outcomes := make(chan dto.MessageDTO, 12)
failures := make(chan error, 12)
for range 12 {
wg.Go(func() {
message, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: user.ID, Text: "same", IdempotencyKey: "retry"})
if err != nil {
failures <- err
return
}
outcomes <- message
})
}
wg.Wait()
close(failures)
close(outcomes)
for err := range failures {
t.Error(err)
}
var original dto.MessageDTO
for m := range outcomes {
if original.ID == uuid.Nil {
original = m
}
if m.ID != original.ID || m.Text != original.Text || !m.CreatedAt.Equal(original.CreatedAt) {
t.Fatal("retry returned a different result")
}
}
messages, err := s.Messages(t.Context(), chat.ID, dto.PositionDTO{}, 100)
if err != nil || len(messages) != 1 {
t.Fatalf("messages=%d error=%v", len(messages), err)
}
}
// TestMessageRetryConflict rejects a different body without publishing a second message.
func TestMessageRetryConflict(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
chat := fixtureChat(t, s, user)
message := dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: user.ID, Text: "first", IdempotencyKey: "retry"}
if _, err := s.CreateMessage(t.Context(), message); err != nil {
t.Fatal(err)
}
message.ID = uuid.New()
message.Text = "different"
if _, err := s.CreateMessage(t.Context(), message); !errors.Is(err, store.ErrConflict) {
t.Fatalf("expected conflict: %v", err)
}
}
// TestMessageRetryExpiry permits reuse after the original retention window ends.
func TestMessageRetryExpiry(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
chat := fixtureChat(t, s, user)
message := dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: user.ID, Text: "first", IdempotencyKey: "retry"}
if _, err := s.CreateMessage(t.Context(), message); err != nil {
t.Fatal(err)
}
if _, err := s.pool.Exec(t.Context(), "UPDATE message_idempotency SET expires_at=clock_timestamp()-interval '1 second'"); err != nil {
t.Fatal(err)
}
message.ID = uuid.New()
message.Text = "new"
if result, err := s.CreateMessage(t.Context(), message); err != nil || result.ID != message.ID {
t.Fatalf("expired result reused: %v", err)
}
}
// TestMessageRetryRollback proves failed inserts leave no poisoned idempotency result.
func TestMessageRetryRollback(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
chat := fixtureChat(t, s, user)
message := dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: uuid.New(), Text: "first", IdempotencyKey: "retry"}
if _, err := s.CreateMessage(t.Context(), message); err == nil {
t.Fatal("missing sender accepted")
}
var count int
if err := s.pool.QueryRow(t.Context(), "SELECT count(*) FROM message_idempotency").Scan(&count); err != nil || count != 0 {
t.Fatalf("failed write stored a result: %d %v", count, err)
}
message.SenderID = user.ID
if _, err := s.CreateMessage(t.Context(), message); err != nil {
t.Fatal(err)
}
}
// TestSchemaCheck verifies API schema checks neither create nor upgrade tables.
func TestSchemaCheck(t *testing.T) {
s := testStore(t)
if err := s.CheckSchema(t.Context()); err != nil {
t.Fatal(err)
}
if _, err := s.pool.Exec(t.Context(), "DELETE FROM schema_migrations WHERE version=5"); err != nil {
t.Fatal(err)
}
if err := s.CheckSchema(t.Context()); err == nil {
t.Fatal("outdated schema accepted")
}
s.Close()
if err := s.CheckSchema(t.Context()); err == nil {
t.Fatal("closed connection accepted")
}
}
// TestIdempotencyMigrationFailureRollsBackVersion keeps an unsuccessful DDL change out of migration history.
func TestIdempotencyMigrationFailureRollsBackVersion(t *testing.T) {
s := testStore(t)
if _, err := s.pool.Exec(t.Context(), "DELETE FROM schema_migrations WHERE version=2"); err != nil {
t.Fatal(err)
}
// The existing table deliberately conflicts with the pending migration.
if err := s.Start(t.Context()); err == nil {
t.Fatal("conflicting DDL reported success")
}
var applied bool
if err := s.pool.QueryRow(t.Context(), "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=2)").Scan(&applied); err != nil || applied {
t.Fatalf("failed migration marked applied: %v", err)
}
}
+190
View File
@@ -0,0 +1,190 @@
package postgres
import (
"context"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"go.opentelemetry.io/otel/propagation"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/pipeline"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
)
// QueueAttachment atomically exposes queued metadata and durable outbox intent.
func (s *Store) QueueAttachment(ctx context.Context, id uuid.UUID) (dto.Attachment, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
carrier := propagation.MapCarrier{}
propagation.TraceContext{}.Inject(ctx, carrier)
var result dto.Attachment
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
var err error
result, err = scanAttachment(tx.QueryRow(ctx, `UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=@id AND status='uploading' RETURNING `+attachmentColumns, pgx.StrictNamedArgs{"id": id}))
if err != nil {
return err
}
_, err = tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,pipeline_version,staging_key,traceparent,tracestate) VALUES(@job,@attachment,@version,@key,@parent,@state)`, pgx.StrictNamedArgs{"job": uuid.New(), "attachment": id, "version": result.PipelineVersion, "key": result.ObjectKey, "parent": carrier["traceparent"], "state": carrier["tracestate"]})
return err
})
return result, normalize(err)
}
// Due scans a bounded outbox page, including expired processing leases.
func (s *Store) Due(ctx context.Context, limit int) ([]pipeline.Job, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rows, err := s.pool.Query(ctx, `SELECT j.id,j.attachment_id,j.pipeline_version,j.attempt+1,j.created_at,j.traceparent,j.tracestate FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version WHERE j.status IN ('queued','processing') AND j.next_attempt_at<=clock_timestamp() AND (j.lease_until IS NULL OR j.lease_until<clock_timestamp()) AND (j.last_published_at IS NULL OR j.last_published_at<clock_timestamp()-interval '30 seconds') ORDER BY j.next_attempt_at,j.id LIMIT @limit`, pgx.StrictNamedArgs{"limit": limit})
if err != nil {
return nil, normalize(err)
}
defer rows.Close()
jobs := make([]pipeline.Job, 0)
for rows.Next() {
j := pipeline.Job{SchemaVersion: 1, Type: "attachment.process.v1"}
if err := rows.Scan(&j.ID, &j.AttachmentID, &j.Version, &j.Attempt, &j.CreatedAt, &j.Traceparent, &j.Tracestate); err != nil {
return nil, err
}
jobs = append(jobs, j)
}
return jobs, normalize(rows.Err())
}
// Published records broker acceptance without suppressing future crash recovery.
func (s *Store) Published(ctx context.Context, j pipeline.Job) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
_, err := s.pool.Exec(ctx, `UPDATE attachment_jobs SET last_published_at=clock_timestamp() WHERE id=@id AND attempt<@attempt`, pgx.StrictNamedArgs{"id": j.ID, "attempt": j.Attempt})
return normalize(err)
}
// Claim serializes version checks and attempt leases with the attachment row.
func (s *Store) Claim(ctx context.Context, j pipeline.Job, duration time.Duration, maxAttempts int) (*pipeline.Lease, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var result *pipeline.Lease
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
a, err := scanAttachment(tx.QueryRow(ctx, `SELECT `+attachmentColumns+` FROM attachments WHERE id=@id FOR UPDATE`, pgx.StrictNamedArgs{"id": j.AttachmentID}))
if err != nil {
return err
}
if a.PipelineVersion != j.Version || (a.Status != "queued" && a.Status != "processing") {
return nil
}
lease := pipeline.Lease{Job: j, Token: uuid.New(), Attachment: a}
err = tx.QueryRow(ctx, `UPDATE attachment_jobs SET status='processing',attempt=attempt+1,lease_id=@token,lease_until=clock_timestamp()+@seconds*interval '1 second',updated_at=clock_timestamp() WHERE id=@id AND attachment_id=@attachment AND pipeline_version=@version AND status IN ('queued','processing') AND next_attempt_at<=clock_timestamp() AND (lease_until IS NULL OR lease_until<clock_timestamp()) RETURNING attempt,staging_key`, pgx.StrictNamedArgs{"token": lease.Token, "seconds": duration.Seconds(), "id": j.ID, "attachment": j.AttachmentID, "version": j.Version}).Scan(&lease.Job.Attempt, &lease.StagingKey)
if err == pgx.ErrNoRows {
return nil
}
if err != nil {
return err
}
if lease.Job.Attempt > maxAttempts {
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET status='failed',error_code='retry_exhausted',lease_until=NULL WHERE id=@id`, pgx.StrictNamedArgs{"id": j.ID})
if err != nil {
return err
}
_, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=@id`, pgx.StrictNamedArgs{"id": j.AttachmentID})
return err
}
_, err = tx.Exec(ctx, `UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=@id`, pgx.StrictNamedArgs{"id": j.AttachmentID})
result = &lease
return err
})
return result, normalize(err)
}
// Complete publishes only the current, unexpired fenced attempt.
func (s *Store) Complete(ctx context.Context, l pipeline.Lease, key string, variants []dto.Variant) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
if variants == nil {
variants = []dto.Variant{}
}
published := false
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
var version int
if err := tx.QueryRow(ctx, `SELECT pipeline_version FROM attachments WHERE id=@id FOR UPDATE`, pgx.StrictNamedArgs{"id": l.Job.AttachmentID}).Scan(&version); err != nil {
return err
}
if version != l.Job.Version {
return nil
}
tag, err := tx.Exec(ctx, `UPDATE attachment_jobs SET status='ready',lease_until=NULL,error_code=NULL,updated_at=clock_timestamp() WHERE id=@id AND lease_id=@token AND status='processing' AND lease_until>clock_timestamp()`, pgx.StrictNamedArgs{"id": l.Job.ID, "token": l.Token})
if err != nil || tag.RowsAffected() == 0 {
return err
}
_, err = tx.Exec(ctx, `UPDATE attachments SET status='ready',object_key=@key,variants=@variants,error_code=NULL,updated_at=clock_timestamp() WHERE id=@id`, pgx.StrictNamedArgs{"key": key, "variants": variants, "id": l.Job.AttachmentID})
published = err == nil
return err
})
return published, normalize(err)
}
// Fail persists a retry deadline or terminal result before broker acknowledgement.
func (s *Store) Fail(ctx context.Context, l pipeline.Lease, code string, delay time.Duration, maxAttempts int) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
state := "queued"
if code == "invalid_image" || l.Job.Attempt >= maxAttempts {
state = "failed"
}
if state == "failed" && code != "invalid_image" {
code = "retry_exhausted"
}
return normalize(pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
var version int
if err := tx.QueryRow(ctx, `SELECT pipeline_version FROM attachments WHERE id=@id FOR UPDATE`, pgx.StrictNamedArgs{"id": l.Job.AttachmentID}).Scan(&version); err != nil {
return err
}
if version != l.Job.Version {
return nil
}
tag, err := tx.Exec(ctx, `UPDATE attachment_jobs SET status=@state,error_code=@code,lease_until=NULL,next_attempt_at=clock_timestamp()+@delay*interval '1 second',last_published_at=NULL,updated_at=clock_timestamp() WHERE id=@id AND lease_id=@token AND status='processing'`, pgx.StrictNamedArgs{"state": state, "code": code, "delay": delay.Seconds(), "id": l.Job.ID, "token": l.Token})
if err != nil || tag.RowsAffected() == 0 {
return err
}
_, err = tx.Exec(ctx, `UPDATE attachments SET status=@state,error_code=CASE WHEN @state='failed' THEN @code ELSE NULL END,updated_at=clock_timestamp() WHERE id=@id`, pgx.StrictNamedArgs{"state": state, "code": code, "id": l.Job.AttachmentID})
return err
}))
}
// Replay retries a failed logical job or explicitly creates a newer pipeline version.
func (s *Store) Replay(ctx context.Context, id uuid.UUID, version int) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return normalize(pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
a, err := scanAttachment(tx.QueryRow(ctx, `SELECT `+attachmentColumns+` FROM attachments WHERE id=@id FOR UPDATE`, pgx.StrictNamedArgs{"id": id}))
if err != nil {
return err
}
var expired bool
if err := tx.QueryRow(ctx, `SELECT staging_expired FROM attachment_jobs WHERE attachment_id=@id AND pipeline_version=@version`, pgx.StrictNamedArgs{"id": id, "version": a.PipelineVersion}).Scan(&expired); err != nil {
return err
}
if expired {
return store.ErrConflict
}
if version < a.PipelineVersion || version < 1 || (version == a.PipelineVersion && a.Status != "failed") {
return store.ErrConflict
}
var job uuid.UUID
if version == a.PipelineVersion {
err = tx.QueryRow(ctx, `UPDATE attachment_jobs SET status='queued',attempt=0,error_code=NULL,lease_until=NULL,last_published_at=NULL,next_attempt_at=clock_timestamp() WHERE attachment_id=@id AND pipeline_version=@version RETURNING id`, pgx.StrictNamedArgs{"id": id, "version": version}).Scan(&job)
} else {
job = uuid.New()
_, err = tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,pipeline_version,staging_key) SELECT @job,attachment_id,@version,staging_key FROM attachment_jobs WHERE attachment_id=@id AND pipeline_version=@previous`, pgx.StrictNamedArgs{"job": job, "version": version, "id": id, "previous": a.PipelineVersion})
}
if err != nil {
return err
}
_, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',pipeline_version=@version,error_code=NULL,updated_at=clock_timestamp() WHERE id=@id`, pgx.StrictNamedArgs{"version": version, "id": id})
if err != nil {
return err
}
_, err = tx.Exec(ctx, `INSERT INTO attachment_job_audit(job_id,action) VALUES(@job,'operator_replay')`, pgx.StrictNamedArgs{"job": job})
return err
}))
}
+281
View File
@@ -0,0 +1,281 @@
package postgres
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/pipeline"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
)
// queuedJob prepares independent durable intent without publishing a broker notification.
func queuedJob(t *testing.T, s *Store) (dto.Attachment, pipeline.Job) {
t.Helper()
a := fixtureAttachment(t, s)
queued, err := s.QueueAttachment(t.Context(), a.ID)
if err != nil || queued.Status != "queued" {
t.Fatalf("queue: %v", err)
}
jobs, err := s.Due(t.Context(), 100)
if err != nil || len(jobs) != 1 {
t.Fatalf("outbox: %d %v", len(jobs), err)
}
return queued, jobs[0]
}
// TestOutboxSurvivesMissingPublication verifies the COMMIT-before-publish window is recoverable.
func TestOutboxSurvivesMissingPublication(t *testing.T) {
s := testStore(t)
a, job := queuedJob(t, s)
jobs, err := s.Due(t.Context(), 100)
if err != nil || len(jobs) != 1 || jobs[0].ID != job.ID {
t.Fatalf("lost intent: %v", err)
}
if _, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: a.ChatID, SenderID: a.OwnerID, AttachmentIDs: []string{a.ID.String()}, IdempotencyKey: "queued"}); err != nil {
t.Fatal(err)
}
if err := s.Published(t.Context(), job); err != nil {
t.Fatal(err)
}
jobs, err = s.Due(t.Context(), 100)
if err != nil || len(jobs) != 0 {
t.Fatal("publication was not throttled")
}
}
// TestPipelineDuplicateAfterCommit verifies a lost acknowledgement cannot repeat a ready effect.
func TestPipelineDuplicateAfterCommit(t *testing.T) {
s := testStore(t)
a, job := queuedJob(t, s)
lease, err := s.Claim(t.Context(), job, time.Minute, 5)
if err != nil || lease == nil {
t.Fatalf("claim: %v", err)
}
duplicate, err := s.Claim(t.Context(), job, time.Minute, 5)
if err != nil || duplicate != nil {
t.Fatal("concurrent lease acquired")
}
variants := []dto.Variant{{Name: "thumbnail", ObjectKey: "result/new/thumb"}}
done, err := s.Complete(t.Context(), *lease, "result/new/original", variants)
if err != nil || !done {
t.Fatalf("complete: %v", err)
}
duplicate, err = s.Claim(t.Context(), job, time.Minute, 5)
if err != nil || duplicate != nil {
t.Fatal("ready regressed")
}
done, err = s.Complete(t.Context(), *lease, "result/old/original", nil)
if err != nil || done {
t.Fatal("duplicate commit accepted")
}
got, err := s.Attachment(t.Context(), a.ID)
if err != nil || got.ObjectKey != "result/new/original" || len(got.Variants) != 1 {
t.Fatal("published result changed")
}
}
// TestExpiredLeaseFencesLateSideEffect models a worker crash after S3 write but before COMMIT.
func TestExpiredLeaseFencesLateSideEffect(t *testing.T) {
s := testStore(t)
_, job := queuedJob(t, s)
old, err := s.Claim(t.Context(), job, time.Minute, 5)
if err != nil || old == nil {
t.Fatal(err)
}
_, err = s.pool.Exec(t.Context(), `UPDATE attachment_jobs SET lease_until=clock_timestamp()-interval '1 second' WHERE id=@id`, pgx.StrictNamedArgs{"id": job.ID})
if err != nil {
t.Fatal(err)
}
fresh, err := s.Claim(t.Context(), job, time.Minute, 5)
if err != nil || fresh == nil || fresh.Token == old.Token || fresh.Job.Attempt != 2 {
t.Fatalf("lease recovery: %v", err)
}
if ok, err := s.Complete(t.Context(), *old, "old-side-effect", nil); err != nil || ok {
t.Fatal("stale lease published")
}
if ok, err := s.Complete(t.Context(), *fresh, "new-side-effect", nil); err != nil || !ok {
t.Fatal("current lease rejected")
}
}
// TestPipelineVersionReordering verifies old delivery and late completion cannot overwrite version two.
func TestPipelineVersionReordering(t *testing.T) {
s := testStore(t)
a, job := queuedJob(t, s)
old, err := s.Claim(t.Context(), job, time.Minute, 5)
if err != nil || old == nil {
t.Fatal(err)
}
if err := s.Replay(t.Context(), a.ID, 2); err != nil {
t.Fatal(err)
}
jobs, err := s.Due(t.Context(), 100)
if err != nil || len(jobs) != 1 || jobs[0].Version != 2 {
t.Fatalf("new version: %v", err)
}
newer, err := s.Claim(t.Context(), jobs[0], time.Minute, 5)
if err != nil || newer == nil {
t.Fatal(err)
}
if ok, err := s.Complete(t.Context(), *newer, "version-two", nil); err != nil || !ok {
t.Fatal("new publication failed")
}
if ok, err := s.Complete(t.Context(), *old, "version-one", nil); err != nil || ok {
t.Fatal("old version overwrote current")
}
if err := s.Fail(t.Context(), *old, "processing_failed", 0, 5); err != nil {
t.Fatal(err)
}
if lease, err := s.Claim(t.Context(), job, time.Minute, 5); err != nil || lease != nil {
t.Fatal("old delivery claimed")
}
got, err := s.Attachment(t.Context(), a.ID)
if err != nil || got.ObjectKey != "version-two" || got.Status != "ready" {
t.Fatal("version fence broken")
}
}
// TestPipelineRetryAndReplay verifies bounded attempts and explicit recovery of terminal jobs.
func TestPipelineRetryAndReplay(t *testing.T) {
s := testStore(t)
a, job := queuedJob(t, s)
for attempt := 1; attempt <= 5; attempt++ {
lease, err := s.Claim(t.Context(), job, time.Minute, 5)
if err != nil || lease == nil || lease.Job.Attempt != attempt {
t.Fatalf("attempt %d: %v", attempt, err)
}
if err := s.Fail(t.Context(), *lease, "processing_failed", 0, 5); err != nil {
t.Fatal(err)
}
}
got, err := s.Attachment(t.Context(), a.ID)
if err != nil || got.Status != "failed" || got.ErrorCode == nil || *got.ErrorCode != "retry_exhausted" {
t.Fatal("retry not terminal")
}
if err := s.Replay(t.Context(), a.ID, 1); err != nil {
t.Fatal(err)
}
jobs, err := s.Due(t.Context(), 100)
if err != nil || len(jobs) != 1 || jobs[0].ID != job.ID || jobs[0].Attempt != 1 {
t.Fatal("replay changed logical job")
}
if err := s.Replay(t.Context(), a.ID, 1); !errors.Is(err, store.ErrConflict) {
t.Fatal("non-failed replay accepted")
}
}
// TestPipelinePermanentFailure verifies malformed sources do not consume all retries.
func TestPipelinePermanentFailure(t *testing.T) {
s := testStore(t)
a, job := queuedJob(t, s)
lease, err := s.Claim(t.Context(), job, time.Minute, 5)
if err != nil || lease == nil {
t.Fatal(err)
}
if err := s.Fail(t.Context(), *lease, "invalid_image", time.Minute, 5); err != nil {
t.Fatal(err)
}
got, err := s.Attachment(t.Context(), a.ID)
if err != nil || got.Status != "failed" || *got.ErrorCode != "invalid_image" {
t.Fatal("permanent failure retried")
}
}
// TestPipelineCanceledDatabase checks bounded failures do not masquerade as successful transitions.
func TestPipelineCanceledDatabase(t *testing.T) {
s := testStore(t)
a, job := queuedJob(t, s)
ctx, cancel := context.WithCancel(t.Context())
cancel()
if _, err := s.QueueAttachment(ctx, a.ID); err == nil {
t.Fatal("queue ignored cancellation")
}
if _, err := s.Due(ctx, 1); err == nil {
t.Fatal("outbox ignored cancellation")
}
if err := s.Published(ctx, job); err == nil {
t.Fatal("confirm ignored cancellation")
}
if _, err := s.Claim(ctx, job, time.Minute, 5); err == nil {
t.Fatal("claim ignored cancellation")
}
if _, err := s.Complete(ctx, pipeline.Lease{Job: job}, "key", nil); err == nil {
t.Fatal("complete ignored cancellation")
}
if err := s.Fail(ctx, pipeline.Lease{Job: job}, "processing_failed", 0, 5); err == nil {
t.Fatal("retry ignored cancellation")
}
if err := s.Replay(ctx, a.ID, 1); err == nil {
t.Fatal("replay ignored cancellation")
}
}
// TestRepeatedCrashesExhaustLeaseBudget prevents unlimited retries caused by process deaths.
func TestRepeatedCrashesExhaustLeaseBudget(t *testing.T) {
s := testStore(t)
a, job := queuedJob(t, s)
for attempt := 0; attempt < 2; attempt++ {
lease, err := s.Claim(t.Context(), job, -time.Second, 1)
if err != nil {
t.Fatal(err)
}
if attempt == 0 && lease == nil {
t.Fatal("first claim missing")
}
if attempt == 1 && lease != nil {
t.Fatal("crash budget not enforced")
}
}
got, err := s.Attachment(t.Context(), a.ID)
if err != nil || got.Status != "failed" {
t.Fatal("crash loop remains active")
}
}
// TestQueueUnknownReservation ensures an absent staging reservation cannot create durable work.
func TestQueueUnknownReservation(t *testing.T) {
s := testStore(t)
if _, err := s.QueueAttachment(t.Context(), uuid.New()); !errors.Is(err, store.ErrNotFound) {
t.Fatal(err)
}
}
// TestClaimUnknownAttachment leaves an untrusted notification without side effects.
func TestClaimUnknownAttachment(t *testing.T) {
s := testStore(t)
if _, err := s.Claim(t.Context(), pipeline.Job{ID: uuid.New(), AttachmentID: uuid.New(), Version: 1}, time.Minute, 5); !errors.Is(err, store.ErrNotFound) {
t.Fatal(err)
}
}
// TestCompleteUnknownAttachment cannot publish an arbitrary object key.
func TestCompleteUnknownAttachment(t *testing.T) {
s := testStore(t)
if _, err := s.Complete(t.Context(), pipeline.Lease{Job: pipeline.Job{AttachmentID: uuid.New()}}, "unknown", nil); !errors.Is(err, store.ErrNotFound) {
t.Fatal(err)
}
}
// TestFailUnknownAttachment cannot fabricate a retry record.
func TestFailUnknownAttachment(t *testing.T) {
s := testStore(t)
if err := s.Fail(t.Context(), pipeline.Lease{Job: pipeline.Job{AttachmentID: uuid.New()}}, "processing_failed", 0, 5); !errors.Is(err, store.ErrNotFound) {
t.Fatal(err)
}
}
// TestExpireStagingDatabaseFailure cannot authorize object deletion without SQL confirmation.
func TestExpireStagingDatabaseFailure(t *testing.T) {
s := testStore(t)
ctx, cancel := context.WithCancel(t.Context())
cancel()
if keys, err := s.ExpireStaging(ctx); err == nil || len(keys) != 0 {
t.Fatal("uncertain retention claim accepted")
}
}
+64
View File
@@ -0,0 +1,64 @@
package postgres
import (
"context"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
)
// CreateMessage serializes timestamps on the owning chat and atomically appends a message.
func (s *Store) CreateMessage(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
original, found, err := replayMessage(ctx, tx, message)
if err != nil {
return err
}
if found {
message = original
return nil
}
if err := validateAttachments(ctx, tx, message); err != nil {
return err
}
if err := tx.QueryRow(ctx, `UPDATE chats SET last_message_at=GREATEST(clock_timestamp(),last_message_at+interval '1 microsecond')
WHERE id=@chat RETURNING last_message_at`, pgx.StrictNamedArgs{"chat": message.ChatID}).Scan(&message.CreatedAt); err != nil {
return err
}
_, err = tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at,attachment_ids) VALUES(@id,@chat,@sender,@text,@time,@attachments)`, pgx.StrictNamedArgs{
"attachments": append([]string{}, message.AttachmentIDs...), "id": message.ID, "chat": message.ChatID, "sender": message.SenderID, "text": message.Text, "time": message.CreatedAt,
})
if err != nil {
return err
}
return rememberMessage(ctx, tx, message)
})
return message, normalize(err)
}
// Messages reads an indexed keyset page without scanning earlier history.
func (s *Store) Messages(ctx context.Context, chatID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rows, err := s.pool.Query(ctx, `SELECT id,chat_id,sender_id,text,created_at,attachment_ids FROM messages
WHERE chat_id=@chat AND (created_at,id)>(@time,@id) ORDER BY created_at,id LIMIT @limit`, pgx.StrictNamedArgs{
"chat": chatID, "time": position.CreatedAt, "id": position.ID, "limit": limit,
})
if err != nil {
return nil, normalize(err)
}
defer rows.Close()
messages := make([]dto.MessageDTO, 0)
for rows.Next() {
var message dto.MessageDTO
if err := rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt, &message.AttachmentIDs); err != nil {
return nil, normalize(err)
}
messages = append(messages, message)
}
return messages, normalize(rows.Err())
}
@@ -0,0 +1,34 @@
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL UNIQUE,
display_name text NOT NULL,
password_hash text NOT NULL DEFAULT '',
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
last_message_at timestamptz NOT NULL DEFAULT '-infinity'
);
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 chat_members_user ON chat_members(user_id,chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id),
sender_id uuid NOT NULL REFERENCES users(id),
text text NOT NULL,
created_at timestamptz NOT NULL,
FOREIGN KEY(chat_id,sender_id) REFERENCES chat_members(chat_id,user_id)
);
CREATE INDEX messages_history ON messages(chat_id,created_at,id);
CREATE TABLE sessions (
token_hash text PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id),
expires_at timestamptz NOT NULL
);
CREATE INDEX sessions_expiry ON sessions(expires_at);
@@ -0,0 +1,9 @@
CREATE TABLE message_idempotency (
user_id uuid NOT NULL REFERENCES users(id),
chat_id uuid NOT NULL REFERENCES chats(id),
key text NOT NULL,
message_id uuid NOT NULL REFERENCES messages(id),
expires_at timestamptz NOT NULL,
PRIMARY KEY (user_id,chat_id,key)
);
CREATE INDEX message_idempotency_expiry ON message_idempotency(expires_at);
@@ -0,0 +1,15 @@
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id),
owner_id uuid NOT NULL REFERENCES users(id),
filename text NOT NULL,
content_type text NOT NULL,
size_bytes bigint NOT NULL CHECK(size_bytes BETWEEN 1 AND 10485760),
sha256 text NOT NULL,
status text NOT NULL CHECK(status IN ('uploading','ready','missing','deleting')),
object_key text NOT NULL UNIQUE,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL
);
CREATE INDEX attachments_scan ON attachments(created_at,id);
ALTER TABLE messages ADD COLUMN attachment_ids text[] NOT NULL DEFAULT '{}';
@@ -0,0 +1,29 @@
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK(status IN ('uploading','queued','processing','ready','failed','missing','deleting'));
ALTER TABLE attachments ADD COLUMN variants jsonb NOT NULL DEFAULT '[]';
ALTER TABLE attachments ADD COLUMN error_code text;
ALTER TABLE attachments ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1 CHECK(pipeline_version>0);
CREATE TABLE attachment_jobs (
id uuid PRIMARY KEY,
attachment_id uuid NOT NULL REFERENCES attachments(id),
pipeline_version integer NOT NULL CHECK(pipeline_version>0),
attempt integer NOT NULL DEFAULT 0,
status text NOT NULL DEFAULT 'queued' CHECK(status IN ('queued','processing','ready','failed')),
staging_key text NOT NULL,
lease_id uuid,
lease_until timestamptz,
next_attempt_at timestamptz NOT NULL DEFAULT clock_timestamp(),
last_published_at timestamptz,
error_code text,
traceparent text NOT NULL DEFAULT '',
tracestate text NOT NULL DEFAULT '',
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
UNIQUE(attachment_id,pipeline_version)
);
CREATE INDEX attachment_jobs_due ON attachment_jobs(next_attempt_at) WHERE status IN ('queued','processing');
CREATE TABLE attachment_job_audit (
job_id uuid NOT NULL REFERENCES attachment_jobs(id),
action text NOT NULL,
at timestamptz NOT NULL DEFAULT clock_timestamp()
);
@@ -0,0 +1,2 @@
ALTER TABLE attachment_jobs ADD COLUMN staging_expired boolean NOT NULL DEFAULT false;
ALTER TABLE attachment_jobs ADD COLUMN staging_removed boolean NOT NULL DEFAULT false;
+17
View File
@@ -0,0 +1,17 @@
package postgres
import (
"context"
"time"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/observation"
)
// Snapshot observes current-version backlog and local pool occupancy under a short deadline.
func (s *Store) Snapshot(ctx context.Context) (observation.Snapshot, error) {
ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
defer cancel()
result := observation.Snapshot{PoolUsed: int64(s.pool.Stat().AcquiredConns())}
err := s.pool.QueryRow(ctx, `SELECT count(*),COALESCE(EXTRACT(EPOCH FROM clock_timestamp()-min(j.created_at)),0)::double precision FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version WHERE j.status IN ('queued','processing')`).Scan(&result.QueueDepth, &result.OldestSeconds)
return result, normalize(err)
}
@@ -0,0 +1,64 @@
package postgres
import (
"context"
"testing"
"time"
"github.com/jackc/pgx/v5"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)
// TestOutboxPreservesTraceContext verifies the durable handoff retains the incoming trace parent.
func TestOutboxPreservesTraceContext(t *testing.T) {
s := testStore(t)
a := fixtureAttachment(t, s)
parent := "00-11111111111111111111111111111111-2222222222222222-01"
ctx := propagation.TraceContext{}.Extract(t.Context(), propagation.MapCarrier{"traceparent": parent})
if !trace.SpanContextFromContext(ctx).IsValid() {
t.Fatal("invalid fixture context")
}
if _, err := s.QueueAttachment(ctx, a.ID); err != nil {
t.Fatal(err)
}
jobs, err := s.Due(ctx, 1)
if err != nil || len(jobs) != 1 || jobs[0].Traceparent != parent {
t.Fatal("durable trace carrier missing")
}
}
// TestSnapshotObservesCurrentBacklog checks unfinished accepted work rather than delivery count.
func TestSnapshotObservesCurrentBacklog(t *testing.T) {
s := testStore(t)
_, job := queuedJob(t, s)
_, err := s.pool.Exec(t.Context(), `UPDATE attachment_jobs SET created_at=clock_timestamp()-interval '10 seconds' WHERE id=@id`, pgx.StrictNamedArgs{"id": job.ID})
if err != nil {
t.Fatal(err)
}
snapshot, err := s.Snapshot(t.Context())
if err != nil || snapshot.QueueDepth != 1 || snapshot.OldestSeconds < 10 {
t.Fatal("incorrect accepted backlog")
}
lease, err := s.Claim(t.Context(), job, time.Minute, 5)
if err != nil || lease == nil {
t.Fatal(err)
}
if ok, err := s.Complete(t.Context(), *lease, "original", nil); err != nil || !ok {
t.Fatal(err)
}
snapshot, err = s.Snapshot(t.Context())
if err != nil || snapshot.QueueDepth != 0 || snapshot.OldestSeconds != 0 {
t.Fatal("completed work remains in backlog")
}
}
// TestSnapshotCancellationBoundsObservation prevents metrics collection from blocking on unavailable SQL.
func TestSnapshotCancellationBoundsObservation(t *testing.T) {
s := testStore(t)
ctx, cancel := context.WithCancel(t.Context())
cancel()
if _, err := s.Snapshot(ctx); err == nil {
t.Fatal("canceled snapshot succeeded")
}
}
@@ -0,0 +1,187 @@
package postgres
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"os"
"testing"
"time"
"github.com/jackc/pgx/v5"
"go.uber.org/zap"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/imageprocessor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/objectstore"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/pipeline"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/streamqueue"
)
type faultStore struct {
*Store
before bool
after bool
}
// Complete injects a lost connection before or after the actual SQL commit.
func (s *faultStore) Complete(ctx context.Context, l pipeline.Lease, key string, variants []dto.Variant) (bool, error) {
if s.before {
s.before = false
return false, errors.New("injected connection loss before commit")
}
done, err := s.Store.Complete(ctx, l, key, variants)
if err == nil && s.after {
s.after = false
return done, errors.New("injected lost commit acknowledgement")
}
return done, err
}
// TestRealPipelineFaultWindows verifies real objects and SQL remain correct across uncertain commits.
func TestRealPipelineFaultWindows(t *testing.T) {
for _, fault := range []struct {
name string
before bool
after bool
}{{"after_S3_before_commit", true, false}, {"after_commit_before_ack", false, true}} {
t.Run(fault.name, func(t *testing.T) {
if os.Getenv("S3_ENDPOINT") == "" || os.Getenv("BROKER_ADDRESS") == "" {
t.Skip("isolated S3 and broker required")
}
s := testStore(t)
a := fixtureAttachment(t, s)
data, err := os.ReadFile("../../../tests/fixtures/sample.png")
if err != nil {
t.Fatal(err)
}
sum := sha256.Sum256(data)
a.SHA256 = hex.EncodeToString(sum[:])
a.SizeBytes = int64(len(data))
_, err = s.pool.Exec(t.Context(), `UPDATE attachments SET size_bytes=@size,sha256=@sha WHERE id=@id`, pgx.StrictNamedArgs{"size": a.SizeBytes, "sha": a.SHA256, "id": a.ID})
if err != nil {
t.Fatal(err)
}
cfg, err := config.NewObjectStore()
if err != nil {
t.Fatal(err)
}
objects, err := objectstore.New(cfg)
if err != nil {
t.Fatal(err)
}
if err := objects.Put(t.Context(), a.ObjectKey, a.ContentType, bytes.NewReader(data), int64(len(data))); err != nil {
t.Fatal(err)
}
if _, err := s.QueueAttachment(t.Context(), a.ID); err != nil {
t.Fatal(err)
}
jobs, err := s.Due(t.Context(), 1)
if err != nil || len(jobs) != 1 {
t.Fatal("missing durable intent")
}
queue, err := streamqueue.NewScoped(os.Getenv("BROKER_ADDRESS"), a.ID.String(), "test-"+a.ID.String())
if err != nil {
t.Fatal(err)
}
defer func() {
if err := queue.Close(); err != nil {
t.Error(err)
}
}()
processor, err := imageprocessor.New()
if err != nil {
t.Fatal(err)
}
faulty := &faultStore{Store: s, before: fault.before, after: fault.after}
worker, err := pipeline.New(faulty, queue, objects, processor, zap.NewNop())
if err != nil {
t.Fatal(err)
}
// The real broker is exercised, while the exact delivery is controlled to avoid sharing consumer state.
if err := queue.Publish(t.Context(), jobs[0]); err != nil {
t.Fatal(err)
}
received, err := queue.Receive(t.Context())
if err != nil || received == nil {
t.Fatalf("delivery: %v", err)
}
delivery := *received
if err := worker.Handle(t.Context(), delivery); err != nil {
t.Fatal(err)
}
_, err = s.pool.Exec(t.Context(), `UPDATE attachment_jobs SET next_attempt_at=clock_timestamp()-interval '1 second' WHERE id=@id`, pgx.StrictNamedArgs{"id": jobs[0].ID})
if err != nil {
t.Fatal(err)
}
if err := worker.Handle(t.Context(), delivery); err != nil {
t.Fatal(err)
}
ready, err := s.Attachment(t.Context(), a.ID)
if err != nil || ready.Status != "ready" || len(ready.Variants) != 3 {
t.Fatalf("not ready: %v", err)
}
firstKey := ready.ObjectKey
if err := worker.Handle(t.Context(), delivery); err != nil {
t.Fatal(err)
}
again, err := s.Attachment(t.Context(), a.ID)
if err != nil || again.ObjectKey != firstKey {
t.Fatal("duplicate changed published effect")
}
reader, err := objects.Get(t.Context(), ready.ObjectKey)
if err != nil {
t.Fatal(err)
}
actual, err := io.ReadAll(reader)
closeErr := reader.Close()
if err != nil || closeErr != nil || !bytes.Equal(actual, data) {
t.Fatal("original changed")
}
t.Logf("fault=%s accepted=1 ready=1 variants=%d duplicate_effects=0", fault.name, len(ready.Variants))
})
}
}
// TestRetentionFencesReplay protects active work and makes interrupted cleanup repeatable.
func TestRetentionFencesReplay(t *testing.T) {
s := testStore(t)
a, job := queuedJob(t, s)
keys, err := s.ExpireStaging(t.Context())
if err != nil || len(keys) != 0 {
t.Fatal("active staging expired")
}
lease, err := s.Claim(t.Context(), job, time.Minute, 5)
if err != nil || lease == nil {
t.Fatal(err)
}
if ok, err := s.Complete(t.Context(), *lease, "result/original", nil); err != nil || !ok {
t.Fatal(err)
}
_, err = s.pool.Exec(t.Context(), `UPDATE attachments SET updated_at=clock_timestamp()-interval '8 days' WHERE id=@id`, pgx.StrictNamedArgs{"id": a.ID})
if err != nil {
t.Fatal(err)
}
keys, err = s.ExpireStaging(t.Context())
if err != nil || len(keys) != 1 || keys[0] != a.ObjectKey {
t.Fatal("terminal staging not claimed")
}
if err := s.Replay(t.Context(), a.ID, 2); err == nil {
t.Fatal("expired source replay accepted")
}
again, err := s.ExpireStaging(t.Context())
if err != nil || len(again) != 1 {
t.Fatal("unacknowledged cleanup lost")
}
if err := s.StagingRemoved(t.Context(), a.ObjectKey); err != nil {
t.Fatal(err)
}
keys, err = s.ExpireStaging(t.Context())
if err != nil || len(keys) != 0 {
t.Fatal("confirmed deletion repeated")
}
}
+64
View File
@@ -0,0 +1,64 @@
package postgres
import (
"context"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
)
// Scan returns a bounded metadata page ordered by the stable primary key.
func (s *Store) Scan(ctx context.Context, after uuid.UUID, limit int) ([]dto.Attachment, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rows, err := s.pool.Query(ctx, `SELECT `+attachmentColumns+` FROM attachments WHERE id>@after ORDER BY id LIMIT @limit`, pgx.StrictNamedArgs{"after": after, "limit": limit})
if err != nil {
return nil, normalize(err)
}
defer rows.Close()
result := make([]dto.Attachment, 0)
for rows.Next() {
a, err := scanAttachment(rows)
if err != nil {
return nil, err
}
result = append(result, a)
}
return result, normalize(rows.Err())
}
// Reclaim uses a durable deleting state to exclude publication during object cleanup.
func (s *Store) Reclaim(ctx context.Context, id uuid.UUID, cutoff time.Time, finish bool) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
query := `UPDATE attachments SET status='deleting' WHERE id=@id AND created_at<@cutoff AND status IN ('uploading','deleting') AND NOT EXISTS(SELECT 1 FROM messages WHERE @textid=ANY(attachment_ids))`
if finish {
query = `DELETE FROM attachments WHERE id=@id AND created_at<@cutoff AND status='deleting' AND NOT EXISTS(SELECT 1 FROM messages WHERE @textid=ANY(attachment_ids))`
}
tag, err := s.pool.Exec(ctx, query, pgx.StrictNamedArgs{"id": id, "textid": id.String(), "cutoff": cutoff})
return tag.RowsAffected() == 1, normalize(err)
}
// MarkMissing preserves referenced metadata while recording or clearing an availability incident.
func (s *Store) MarkMissing(ctx context.Context, id uuid.UUID, missing bool) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
status := "ready"
if missing {
status = "missing"
}
_, err := s.pool.Exec(ctx, `UPDATE attachments SET status=@status,updated_at=clock_timestamp() WHERE id=@id AND status IN ('ready','missing')`, pgx.StrictNamedArgs{"id": id, "status": status})
return normalize(err)
}
// HasObject protects even unfinished durable reservations from orphan cleanup.
func (s *Store) HasObject(ctx context.Context, key string) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var exists bool
err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=@key OR EXISTS(SELECT 1 FROM jsonb_array_elements(variants) v WHERE v->>'object_key'=@key) UNION ALL SELECT 1 FROM attachment_jobs WHERE staging_key=@key AND NOT staging_removed)`, pgx.StrictNamedArgs{"key": key}).Scan(&exists)
return exists, normalize(err)
}
@@ -0,0 +1,18 @@
package postgres
import "context"
type reconcileObjects struct {
exists bool
}
// Exists supplies a deterministic object-side fault while exercising real SQL transitions.
func (r *reconcileObjects) Exists(context.Context, string) (bool, error) {
return r.exists, nil
}
// Remove models an idempotent object removal for SQL cleanup tests.
func (r *reconcileObjects) Remove(context.Context, string) error {
r.exists = false
return nil
}
+52
View File
@@ -0,0 +1,52 @@
package postgres
import (
"os"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/media"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/objectstore"
)
// TestMeasuredMissingInventory measures bounded real PostgreSQL/S3 scans with injected missing originals.
func TestMeasuredMissingInventory(t *testing.T) {
if os.Getenv("S3_ENDPOINT") == "" {
t.Skip("isolated S3 required for measured reconciliation")
}
for _, size := range []struct {
name string
count int
}{{"100 records", 100}, {"1000 records", 1000}} {
t.Run(size.name, func(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
chat := fixtureChat(t, s, user)
_, err := s.pool.Exec(t.Context(), `WITH ids AS (SELECT gen_random_uuid() AS id FROM generate_series(1,@count::int))
INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status,object_key,created_at,updated_at)
SELECT id,@chat,@owner,'synthetic.png','image/png',32,'synthetic','ready','original/'||id::text,clock_timestamp()-interval '2 hours',clock_timestamp() FROM ids`, pgx.StrictNamedArgs{"count": size.count, "chat": chat.ID, "owner": user.ID})
if err != nil {
t.Fatal(err)
}
cfg, err := config.NewObjectStore()
if err != nil {
t.Fatal(err)
}
objects, err := objectstore.New(cfg)
if err != nil {
t.Fatal(err)
}
started := time.Now()
result, err := media.Reconcile(t.Context(), s, objects, uuid.Nil, time.Hour, false)
elapsed := time.Since(started)
if err != nil || result.Scanned != size.count || result.Missing != size.count || result.Changed != 0 {
t.Fatalf("inventory=%+v err=%v", result, err)
}
t.Logf("records=%d missing=%d elapsed_ms=%.3f apply=false", result.Scanned, result.Missing, float64(elapsed.Microseconds())/1000)
})
}
}
+35
View File
@@ -0,0 +1,35 @@
package postgres
import (
"context"
"github.com/jackc/pgx/v5"
)
// ExpireStaging atomically fences replay and returns old terminal sources in bounded batches.
func (s *Store) ExpireStaging(ctx context.Context) ([]string, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
rows, err := s.pool.Query(ctx, `WITH candidates AS (
SELECT a.id FROM attachments a
WHERE a.status IN ('ready','failed') AND a.updated_at<clock_timestamp()-interval '7 days'
AND EXISTS(SELECT 1 FROM attachment_jobs j WHERE j.attachment_id=a.id AND NOT j.staging_removed)
ORDER BY a.id LIMIT 100 FOR UPDATE OF a SKIP LOCKED
), expired AS (
UPDATE attachment_jobs SET staging_expired=true WHERE attachment_id IN (SELECT id FROM candidates)
RETURNING staging_key
) SELECT DISTINCT staging_key FROM expired`)
if err != nil {
return nil, normalize(err)
}
keys, err := pgx.CollectRows(rows, pgx.RowTo[string])
return keys, normalize(err)
}
// StagingRemoved records confirmed deletion; a failed acknowledgement is safe to repeat.
func (s *Store) StagingRemoved(ctx context.Context, key string) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
_, err := s.pool.Exec(ctx, `UPDATE attachment_jobs SET staging_removed=true WHERE staging_key=@key AND staging_expired`, pgx.StrictNamedArgs{"key": key})
return normalize(err)
}
+36
View File
@@ -0,0 +1,36 @@
package postgres
import (
"context"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// SaveSession persists an absolute expiry and a token digest in PostgreSQL.
func (s *Store) SaveSession(ctx context.Context, hash string, userID uuid.UUID, expiry time.Time) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
_, err := s.pool.Exec(ctx, `INSERT INTO sessions(token_hash,user_id,expires_at) VALUES(@hash,@user,@expiry)`, pgx.StrictNamedArgs{
"hash": hash, "user": userID, "expiry": expiry,
})
return normalize(err)
}
// SessionUser rejects absent, revoked and expired sessions using database time.
func (s *Store) SessionUser(ctx context.Context, hash string) (uuid.UUID, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var id uuid.UUID
err := s.pool.QueryRow(ctx, `SELECT user_id FROM sessions WHERE token_hash=@hash AND expires_at>clock_timestamp()`, pgx.StrictNamedArgs{"hash": hash}).Scan(&id)
return id, normalize(err)
}
// RevokeSession deletes the authoritative session before logout succeeds.
func (s *Store) RevokeSession(ctx context.Context, hash string) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
_, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash=@hash`, pgx.StrictNamedArgs{"hash": hash})
return normalize(err)
}
+161
View File
@@ -0,0 +1,161 @@
// Package postgres persists messenger records in PostgreSQL.
package postgres
import (
"context"
_ "embed"
"errors"
"fmt"
"io"
"net"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
)
//go:embed migrations/001_initial.sql
var initialMigration string
//go:embed migrations/002_idempotency.sql
var idempotencyMigration string
//go:embed migrations/003_attachments.sql
var attachmentsMigration string
//go:embed migrations/004_pipeline.sql
var pipelineMigration string
//go:embed migrations/005_retention.sql
var retentionMigration string
const migrationLockID = 202602
// Options bounds database resource use.
type Options struct {
// Tracer optionally observes queries and pool acquisitions without SQL payloads.
Tracer pgx.QueryTracer
// URL identifies the isolated application database.
URL string
// MaxConnections bounds concurrent database connections.
MaxConnections int32
// Timeout bounds each persistence operation.
Timeout time.Duration
}
// Store owns the PostgreSQL pool; Start and Close belong to application lifecycle.
type Store struct {
pool *pgxpool.Pool
timeout time.Duration
}
var _ store.Interface = (*Store)(nil)
// New validates options and builds a lazy pool without opening connections.
func New(options Options) (*Store, error) {
if options.URL == "" || options.MaxConnections < 1 || options.Timeout <= 0 {
return nil, fmt.Errorf("database URL, pool bound and timeout are required")
}
cfg, err := pgxpool.ParseConfig(options.URL)
if err != nil {
return nil, fmt.Errorf("invalid database configuration")
}
cfg.AfterConnect = func(_ context.Context, conn *pgx.Conn) error {
conn.TypeMap().RegisterType(&pgtype.Type{Name: "timestamptz", OID: pgtype.TimestamptzOID, Codec: &pgtype.TimestamptzCodec{ScanLocation: time.UTC}})
return nil
}
cfg.ConnConfig.Tracer = options.Tracer
cfg.MaxConns = options.MaxConnections
cfg.ConnConfig.ConnectTimeout = options.Timeout
pool, err := pgxpool.NewWithConfig(context.Background(), cfg)
if err != nil {
return nil, err
}
return &Store{pool: pool, timeout: options.Timeout}, nil
}
// Start verifies connectivity and applies versioned migrations under a transaction lock.
func (s *Store) Start(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock(@id)", pgx.StrictNamedArgs{"id": migrationLockID}); err != nil {
return err
}
if _, err := tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY)"); err != nil {
return err
}
for index, source := range []string{initialMigration, idempotencyMigration, attachmentsMigration, pipelineMigration, retentionMigration} {
version := index + 1
var exists bool
if err := tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=@version)", pgx.StrictNamedArgs{"version": version}).Scan(&exists); err != nil {
return err
}
if exists {
continue
}
if _, err := tx.Exec(ctx, source); err != nil {
return err
}
if _, err := tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES(@version)", pgx.StrictNamedArgs{"version": version}); err != nil {
return err
}
}
return nil
})
}
// Close releases owned pool resources after serving has stopped.
func (s *Store) Close() {
s.pool.Close()
}
// Ping checks whether mandatory persistence can serve requests.
func (s *Store) Ping(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return s.pool.Ping(ctx)
}
// normalize translates expected database errors without exposing SQL to higher layers.
func normalize(err error) error {
if errors.Is(err, pgx.ErrNoRows) {
return store.ErrNotFound
}
if databaseError, ok := errors.AsType[*pgconn.PgError](err); ok {
if databaseError.Code == "23505" {
return store.ErrConflict
}
if strings.HasPrefix(databaseError.Code, "08") || strings.HasPrefix(databaseError.Code, "53") ||
databaseError.Code == "57P01" || databaseError.Code == "57P02" || databaseError.Code == "57P03" {
return fmt.Errorf("%w: %w", store.ErrUnavailable, err)
}
}
var networkError net.Error
var connectError *pgconn.ConnectError
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) ||
errors.As(err, &networkError) || errors.As(err, &connectError) || pgconn.SafeToRetry(err) {
return fmt.Errorf("%w: %w", store.ErrUnavailable, err)
}
return err
}
// CheckSchema verifies readiness without allowing API replicas to run DDL.
func (s *Store) CheckSchema(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var version int
if err := s.pool.QueryRow(ctx, "SELECT COALESCE(max(version),0) FROM schema_migrations").Scan(&version); err != nil {
return err
}
if version != 5 {
return fmt.Errorf("database schema version %d; run server migrate", version)
}
return nil
}
+336
View File
@@ -0,0 +1,336 @@
package postgres
import (
"context"
"errors"
"os"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
)
// testStore creates an isolated schema inside the explicitly configured test database.
func testStore(t *testing.T) *Store {
t.Helper()
url := os.Getenv("TEST_DATABASE_URL")
if url == "" {
t.Skip("TEST_DATABASE_URL is required for PostgreSQL integration tests")
}
admin, err := pgx.Connect(t.Context(), url)
if err != nil {
t.Fatal(err)
}
schema := "test_" + uuid.New().String()[:8]
identifier := pgx.Identifier{schema}.Sanitize()
if _, err := admin.Exec(t.Context(), "CREATE SCHEMA "+identifier); err != nil {
t.Fatal(err)
}
separator := "?"
if containsQuery(url) {
separator = "&"
}
s, err := New(Options{URL: url + separator + "search_path=" + schema, MaxConnections: 4, Timeout: 3 * time.Second})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
s.Close()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if _, err := admin.Exec(ctx, "DROP SCHEMA "+identifier+" CASCADE"); err != nil {
t.Error(err)
}
if err := admin.Close(ctx); err != nil {
t.Error(err)
}
})
if err := s.Start(t.Context()); err != nil {
t.Fatal(err)
}
return s
}
// containsQuery identifies URL parameters without exposing credentials in test logs.
func containsQuery(value string) bool {
for _, char := range value {
if char == '?' {
return true
}
}
return false
}
// fixtureUser creates an independent profile for a persistence scenario.
func fixtureUser(t *testing.T, s *Store) dto.UserDTO {
t.Helper()
user, err := s.Register(t.Context(), dto.UserDTO{ID: uuid.New(), Username: "u_" + uuid.NewString()[:8], DisplayName: "Test"}, "test-hash")
if err != nil {
t.Fatal(err)
}
return user
}
// fixtureChat creates a chat containing an existing user.
func fixtureChat(t *testing.T, s *Store, user dto.UserDTO) dto.ChatDTO {
t.Helper()
chat, err := s.CreateChat(t.Context(), dto.ChatDTO{ID: uuid.New(), Title: "Test", MemberIDs: []uuid.UUID{user.ID}})
if err != nil {
t.Fatal(err)
}
return chat
}
// TestMigrationsRepeat verifies idempotent schema initialization.
func TestMigrationsRepeat(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
if err := s.Start(t.Context()); err != nil {
t.Fatal(err)
}
read, err := s.User(t.Context(), user.ID)
if err != nil || read.ID != user.ID || read.CreatedAt.Location() != time.UTC {
t.Fatalf("migration changed data or UTC: %v", err)
}
if err := s.Ping(t.Context()); err != nil {
t.Fatal(err)
}
}
// TestRegistrationRace verifies database uniqueness under concurrent registration.
func TestRegistrationRace(t *testing.T) {
s := testStore(t)
outcomes := make(chan error, 12)
var wg sync.WaitGroup
for range 12 {
wg.Go(func() {
_, err := s.Register(t.Context(), dto.UserDTO{ID: uuid.New(), Username: "same", DisplayName: "Test"}, "hash")
outcomes <- err
})
}
wg.Wait()
close(outcomes)
successes := 0
for err := range outcomes {
if err == nil {
successes++
} else if !errors.Is(err, store.ErrConflict) {
t.Fatal(err)
}
}
if successes != 1 {
t.Fatalf("got %d successful registrations", successes)
}
}
// TestCreateChatRollsBack verifies failure of membership insertion leaves no chat.
func TestCreateChatRollsBack(t *testing.T) {
s := testStore(t)
id := uuid.New()
_, err := s.CreateChat(t.Context(), dto.ChatDTO{ID: id, Title: "Rollback", MemberIDs: []uuid.UUID{uuid.New()}})
if err == nil {
t.Fatal("foreign key failure absent")
}
if _, err := s.Chat(t.Context(), id); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("chat survived rollback: %v", err)
}
}
// TestChatPageUsesMembershipAndCursor verifies one compound visibility/page invariant.
func TestChatPageUsesMembershipAndCursor(t *testing.T) {
s := testStore(t)
owner := fixtureUser(t, s)
outsider := fixtureUser(t, s)
first := fixtureChat(t, s, owner)
second := fixtureChat(t, s, owner)
fixtureChat(t, s, outsider)
page, err := s.Chats(t.Context(), owner.ID, dto.PositionDTO{CreatedAt: first.CreatedAt, ID: first.ID}, 10)
if err != nil || len(page) != 1 || page[0].ID != second.ID || len(page[0].MemberIDs) != 1 {
t.Fatalf("invalid membership page: %+v %v", page, err)
}
}
// TestMessagePageOrdersConcurrentWrites verifies monotonic durable ordering and continuation.
func TestMessagePageOrdersConcurrentWrites(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
chat := fixtureChat(t, s, user)
var wg sync.WaitGroup
failures := make(chan error, 20)
for range 20 {
wg.Go(func() {
_, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: user.ID, Text: "synthetic"})
failures <- err
})
}
wg.Wait()
close(failures)
for err := range failures {
if err != nil {
t.Fatal(err)
}
}
page, err := s.Messages(t.Context(), chat.ID, dto.PositionDTO{}, 10)
if err != nil || len(page) != 10 {
t.Fatalf("first page: %d %v", len(page), err)
}
for index := 1; index < len(page); index++ {
if !page[index].CreatedAt.After(page[index-1].CreatedAt) {
t.Fatal("timestamps are not monotonic")
}
}
last := page[len(page)-1]
next, err := s.Messages(t.Context(), chat.ID, dto.PositionDTO{CreatedAt: last.CreatedAt, ID: last.ID}, 20)
if err != nil || len(next) != 10 || !next[0].CreatedAt.After(last.CreatedAt) {
t.Fatalf("continuation: %d %v", len(next), err)
}
}
// TestCredentialsReadsStoredHash checks credential lookup independently of public profiles.
func TestCredentialsReadsStoredHash(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
got, hash, err := s.Credentials(t.Context(), user.Username)
if err != nil || got.ID != user.ID || hash != "test-hash" {
t.Fatalf("credentials mismatch: %v", err)
}
}
// TestUsersExistChecksAllIDs verifies the set membership contract.
func TestUsersExistChecksAllIDs(t *testing.T) {
for _, missing := range []bool{false, true} {
t.Run(map[bool]string{false: "all exist", true: "missing member"}[missing], func(t *testing.T) {
s := testStore(t)
ids := []uuid.UUID{fixtureUser(t, s).ID}
if missing {
ids = append(ids, uuid.New())
}
exists, err := s.UsersExist(t.Context(), ids)
if err != nil || exists == missing {
t.Fatalf("exists=%v error=%v", exists, err)
}
})
}
}
// TestSessionExpiry rejects persisted sessions whose absolute deadline has passed.
func TestSessionExpiry(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
if err := s.SaveSession(t.Context(), "expired", user.ID, time.Now().Add(-time.Second)); err != nil {
t.Fatal(err)
}
if _, err := s.SessionUser(t.Context(), "expired"); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("expired session accepted: %v", err)
}
}
// TestSessionRevocation removes a still-valid session from the source of truth.
func TestSessionRevocation(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
if err := s.SaveSession(t.Context(), "live", user.ID, time.Now().Add(time.Hour)); err != nil {
t.Fatal(err)
}
if err := s.RevokeSession(t.Context(), "live"); err != nil {
t.Fatal(err)
}
if _, err := s.SessionUser(t.Context(), "live"); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("revoked session accepted: %v", err)
}
}
// TestSessionResolvesOwner verifies a live session's immutable identity.
func TestSessionResolvesOwner(t *testing.T) {
s := testStore(t)
user := fixtureUser(t, s)
if err := s.SaveSession(t.Context(), "live", user.ID, time.Now().Add(time.Hour)); err != nil {
t.Fatal(err)
}
id, err := s.SessionUser(t.Context(), "live")
if err != nil || id != user.ID {
t.Fatalf("invalid owner: %v", err)
}
}
// TestNewRejectsInvalidOptions verifies pool construction errors without connecting.
func TestNewRejectsInvalidOptions(t *testing.T) {
for _, options := range []Options{{}, {URL: "://invalid", MaxConnections: 1, Timeout: time.Second}} {
if _, err := New(options); err == nil {
t.Fatal("invalid options accepted")
}
}
}
// TestCreateMessageMissingChat reports a typed missing-record error.
func TestCreateMessageMissingChat(t *testing.T) {
s := testStore(t)
_, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: uuid.New(), SenderID: uuid.New(), Text: "test"})
if !errors.Is(err, store.ErrNotFound) {
t.Fatal(err)
}
}
// TestMessagesCanceledReturnsError verifies bounded cancellation before query execution.
func TestMessagesCanceledReturnsError(t *testing.T) {
s := testStore(t)
ctx, cancel := context.WithCancel(t.Context())
cancel()
if _, err := s.Messages(ctx, uuid.New(), dto.PositionDTO{}, 10); err == nil {
t.Fatal("canceled query succeeded")
}
}
// TestChatsCanceledReturnsError verifies bounded cancellation of membership pages.
func TestChatsCanceledReturnsError(t *testing.T) {
s := testStore(t)
ctx, cancel := context.WithCancel(t.Context())
cancel()
if _, err := s.Chats(ctx, uuid.New(), dto.PositionDTO{}, 10); err == nil {
t.Fatal("canceled query succeeded")
}
}
// TestMigrationCancellationReturnsError checks startup cancellation before migration work.
func TestMigrationCancellationReturnsError(t *testing.T) {
s := testStore(t)
ctx, cancel := context.WithCancel(t.Context())
cancel()
if err := s.Start(ctx); err == nil {
t.Fatal("canceled migration succeeded")
}
}
// TestMigrationFailureRollsBackVersion verifies a failed migration is never marked applied.
func TestMigrationFailureRollsBackVersion(t *testing.T) {
s := testStore(t)
if _, err := s.pool.Exec(t.Context(), "DELETE FROM schema_migrations"); err != nil {
t.Fatal(err)
}
if err := s.Start(t.Context()); err == nil {
t.Fatal("conflicting unversioned schema accepted")
}
var count int
if err := s.pool.QueryRow(t.Context(), "SELECT count(*) FROM schema_migrations").Scan(&count); err != nil {
t.Fatal(err)
}
if count != 0 {
t.Fatal("failed migration version committed")
}
}
// TestMigrationRejectsBrokenVersionLedger verifies corrupt migration metadata stops startup safely.
func TestMigrationRejectsBrokenVersionLedger(t *testing.T) {
s := testStore(t)
if _, err := s.pool.Exec(t.Context(), "ALTER TABLE schema_migrations RENAME COLUMN version TO broken_version"); err != nil {
t.Fatal(err)
}
if err := s.Start(t.Context()); err == nil {
t.Fatal("broken version ledger accepted")
}
}
+58
View File
@@ -0,0 +1,58 @@
package postgres
import (
"context"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
)
// CreateUser inserts a profile and enforces uniqueness inside PostgreSQL.
func (s *Store) CreateUser(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error) {
return s.Register(ctx, user, "")
}
// Register atomically stores a profile and its password hash.
func (s *Store) Register(ctx context.Context, user dto.UserDTO, passwordHash string) (dto.UserDTO, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
err := s.pool.QueryRow(ctx, `INSERT INTO users(id,username,display_name,password_hash)
VALUES(@id,@username,@display_name,@password_hash) RETURNING created_at`, pgx.StrictNamedArgs{
"id": user.ID,
"username": user.Username,
"display_name": user.DisplayName,
"password_hash": passwordHash,
}).Scan(&user.CreatedAt)
return user, normalize(err)
}
// User reads a profile without credentials.
func (s *Store) User(ctx context.Context, id uuid.UUID) (dto.UserDTO, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var user dto.UserDTO
err := s.pool.QueryRow(ctx, `SELECT id,username,display_name,created_at FROM users WHERE id=@id`, pgx.StrictNamedArgs{"id": id}).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
return user, normalize(err)
}
// Credentials reads the account needed for password verification.
func (s *Store) Credentials(ctx context.Context, username string) (dto.UserDTO, string, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var user dto.UserDTO
var hash string
err := s.pool.QueryRow(ctx, `SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=@username`, pgx.StrictNamedArgs{"username": username}).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
return user, hash, normalize(err)
}
// UsersExist checks all distinct requested identifiers in one bounded query.
func (s *Store) UsersExist(ctx context.Context, ids []uuid.UUID) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var exists bool
err := s.pool.QueryRow(ctx, `SELECT NOT EXISTS (SELECT id FROM unnest(@ids::uuid[]) AS requested(id)
WHERE NOT EXISTS (SELECT 1 FROM users WHERE users.id=requested.id))`, pgx.StrictNamedArgs{"ids": ids}).Scan(&exists)
return exists, normalize(err)
}