// 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 }