feat(app) lab 3 implemented

This commit is contained in:
imadev
2026-10-30 18:11:30 +03:00
parent f731f9b460
commit 48a616e910
57 changed files with 1390 additions and 303 deletions
-2
View File
@@ -27,8 +27,6 @@ func Connect(ctx context.Context, url string, maxConns int32, wait time.Duration
return nil, fmt.Errorf("create pool: %w", err)
}
// AGENT: Compose may start the API while PostgreSQL is still booting. A bounded
// retry keeps the container from crash-looping without hiding a permanent error.
deadline := time.Now().Add(wait)
for {
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
+6 -13
View File
@@ -1,6 +1,3 @@
// AGENT: golang-migrate now runs the embedded SQL files instead of the previous
// hand-written runner. The legacy table upgrade below keeps existing lab 2
// volumes usable, so switching engines does not require deleting data.
package database
import (
@@ -22,16 +19,10 @@ import (
var migrationFiles embed.FS
const (
// The old in-house runner used this advisory lock. We keep the same key for
// the one-time table upgrade so an upgrade cannot race a still-running old
// instance that is applying the baseline migration.
legacyMigrationLockID int64 = 728_2026
migrationsTable = "schema_migrations"
)
// Migrate applies the embedded golang-migrate migrations. golang-migrate takes
// its own PostgreSQL advisory lock, records the current version and dirty flag
// in schema_migrations, and wraps each migration file in one transaction.
func Migrate(ctx context.Context, pool *pgxpool.Pool, databaseURL string) error {
if err := upgradeLegacyMigrationsTable(ctx, pool); err != nil {
return err
@@ -47,8 +38,6 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool, databaseURL string) error
_ = source.Close()
return fmt.Errorf("parse DATABASE_URL for migrations: %w", err)
}
// golang-migrate acquires its lock with context.Background(). A PostgreSQL
// lock timeout keeps startup bounded if another instance never releases it.
if connConfig.RuntimeParams == nil {
connConfig.RuntimeParams = make(map[string]string)
}
@@ -89,7 +78,7 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool, databaseURL string) error
// upgradeLegacyMigrationsTable replaces the table written by the previous
// in-house runner (version text, applied_at) with the golang-migrate schema
// (version bigint, dirty boolean). The schema itself is left untouched and the
// (version bigint, dirty boolean). The data schema itself is left untouched and the
// highest applied version is carried over, so a preserved volume does not need
// to be recreated. The migration DDL is idempotent, but preserving the version
// keeps the migration history truthful.
@@ -132,7 +121,11 @@ func upgradeLegacyMigrationsTable(ctx context.Context, pool *pgxpool.Pool) error
if err != nil {
return fmt.Errorf("begin migration table upgrade: %w", err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
defer func() {
rollbackCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = tx.Rollback(rollbackCtx)
}()
const upgrade = `
DROP TABLE IF EXISTS schema_migrations_migrate_tmp;
@@ -1,5 +1,3 @@
-- AGENT: Local rollback for the baseline schema. The application only runs Up
-- migrations; this file exists so golang-migrate can also step down in tests.
DROP TABLE IF EXISTS messages;
DROP TABLE IF EXISTS chat_members;
DROP TABLE IF EXISTS chats;
@@ -1,8 +1,3 @@
-- AGENT: Single versioned baseline migration for lab 2. The application records
-- applied versions in schema_migrations, so rerunning it never duplicates rows.
-- The unique username constraint is the authoritative defence against the
-- concurrent-registration race, not a SELECT followed by an INSERT.
CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY,
username text NOT NULL,
@@ -39,8 +34,5 @@ CREATE TABLE IF NOT EXISTS messages (
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000)
);
-- AGENT: This composite index matches the only history predicate and sort order:
-- (chat_id, created_at, id). It lets each keyset page seek directly to the cursor
-- instead of scanning the chat history from the beginning.
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx
ON messages (chat_id, created_at, id);
@@ -0,0 +1 @@
DROP TABLE IF EXISTS message_idempotency;
@@ -0,0 +1,14 @@
CREATE TABLE IF NOT EXISTS message_idempotency (
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
idempotency_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,
expires_at timestamptz NOT NULL,
PRIMARY KEY (sender_id, chat_id, idempotency_key),
CONSTRAINT message_idempotency_key_len CHECK (char_length(idempotency_key) BETWEEN 1 AND 128)
);
CREATE INDEX IF NOT EXISTS message_idempotency_expires_at_idx
ON message_idempotency (expires_at);
+12 -2
View File
@@ -18,7 +18,10 @@ func TestEmbeddedMigrationsParse(t *testing.T) {
for _, entry := range entries {
names[entry.Name()] = true
}
for _, want := range []string{"0001_init.up.sql", "0001_init.down.sql"} {
for _, want := range []string{
"0001_init.up.sql", "0001_init.down.sql",
"0002_message_idempotency.up.sql", "0002_message_idempotency.down.sql",
} {
if !names[want] {
t.Fatalf("migration %q is missing from the embedded filesystem", want)
}
@@ -37,7 +40,14 @@ func TestEmbeddedMigrationsParse(t *testing.T) {
if version != 1 {
t.Fatalf("first migration version = %d, want 1", version)
}
version, err = source.Next(version)
if err != nil {
t.Fatalf("read second migration: %v", err)
}
if version != 2 {
t.Fatalf("second migration version = %d, want 2", version)
}
if _, err := source.Next(version); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("expected the baseline to be the last migration, got %v", err)
t.Fatalf("expected 0002 to be the last migration, got %v", err)
}
}