Перенесите реализацию lab3 и сохраните серии нагрузочных экспериментов
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
// Package postgres opens the connection pool and applies the schema.
|
||||
//
|
||||
// Server-side timeouts are constants rather than settings: they bound how
|
||||
// long one request can hold a connection, and the request deadline of the API
|
||||
// is chosen against them.
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/pressly/goose/v3/lock"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/migrations"
|
||||
)
|
||||
|
||||
const (
|
||||
connectTimeout = time.Second
|
||||
statementTimeout = 5 * time.Second
|
||||
idleInTxTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
const codeUniqueViolation = "23505"
|
||||
|
||||
func NewPool(ctx context.Context, dsn string, maxConns int32) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse database url: %w", err)
|
||||
}
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.ConnConfig.ConnectTimeout = connectTimeout
|
||||
// Unlike net.Dialer, pgx resolves the host before ConnectTimeout starts.
|
||||
// Docker DNS takes seconds to give up on a stopped container: unbounded,
|
||||
// every request would wait out its deadline and log only "context
|
||||
// deadline exceeded" instead of the failed lookup.
|
||||
cfg.ConnConfig.LookupFunc = func(ctx context.Context, host string) ([]string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, connectTimeout)
|
||||
defer cancel()
|
||||
return net.DefaultResolver.LookupHost(ctx, host)
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(statementTimeout.Milliseconds(), 10)
|
||||
cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = strconv.FormatInt(idleInTxTimeout.Milliseconds(), 10)
|
||||
// The application keeps every time in UTC; pgx would otherwise scan
|
||||
// timestamptz into time.Local.
|
||||
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
|
||||
}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// Migrate applies pending migrations and returns their versions; a session
|
||||
// advisory lock makes overlapping runs wait for each other.
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool) ([]int64, error) {
|
||||
locker, err := lock.NewPostgresSessionLocker()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("migration lock: %w", err)
|
||||
}
|
||||
db := stdlib.OpenDBFromPool(pool)
|
||||
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.FS, goose.WithSessionLocker(locker))
|
||||
if err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("load migrations: %w", err)
|
||||
}
|
||||
defer provider.Close()
|
||||
results, err := provider.Up(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("apply migrations: %w", err)
|
||||
}
|
||||
applied := make([]int64, 0, len(results))
|
||||
for _, r := range results {
|
||||
applied = append(applied, r.Source.Version)
|
||||
}
|
||||
return applied, nil
|
||||
}
|
||||
|
||||
// Classify marks a failure to reach the database as apperr.KindUnavailable,
|
||||
// which the API answers with 503 instead of 500; any other error is returned
|
||||
// unchanged. Unreachable means: the connection could not be made or broke,
|
||||
// the request deadline passed, or the server refused work (PostgreSQL error
|
||||
// classes 08 connection exception, 53 insufficient resources, 57 operator
|
||||
// intervention such as shutdown or statement timeout).
|
||||
func Classify(err error) error {
|
||||
if err == nil || !unreachable(err) {
|
||||
return err
|
||||
}
|
||||
return apperr.Wrap(apperr.KindUnavailable, "database unavailable", err)
|
||||
}
|
||||
|
||||
func unreachable(err error) bool {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
|
||||
switch class := pgErr.Code[:min(2, len(pgErr.Code))]; class {
|
||||
case "08", "53", "57":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
if _, ok := errors.AsType[*pgconn.ConnectError](err); ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := errors.AsType[net.Error](err); ok {
|
||||
return true
|
||||
}
|
||||
return errors.Is(err, context.DeadlineExceeded) ||
|
||||
errors.Is(err, context.Canceled) ||
|
||||
errors.Is(err, io.EOF) ||
|
||||
errors.Is(err, io.ErrUnexpectedEOF) ||
|
||||
errors.Is(err, net.ErrClosed) ||
|
||||
pgconn.Timeout(err) ||
|
||||
pgconn.SafeToRetry(err)
|
||||
}
|
||||
|
||||
// IsUniqueViolation reports whether err is a unique violation of the named
|
||||
// constraint.
|
||||
func IsUniqueViolation(err error, constraint string) bool {
|
||||
pgErr, ok := errors.AsType[*pgconn.PgError](err)
|
||||
return ok && pgErr.Code == codeUniqueViolation && pgErr.ConstraintName == constraint
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/postgres"
|
||||
"messenger/internal/testenv"
|
||||
"messenger/migrations"
|
||||
)
|
||||
|
||||
var db *testenv.DB
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
var err error
|
||||
db, err = testenv.StartPostgres(context.Background())
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
code := m.Run()
|
||||
db.Close()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func TestPoolScansTimestamptzInUTC(t *testing.T) {
|
||||
var got time.Time
|
||||
if err := db.Pool.QueryRow(context.Background(), `SELECT now()`).Scan(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Location() != time.UTC {
|
||||
t.Fatalf("timestamptz scanned in %v, want UTC", got.Location())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateIsRepeatable(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
applied, err := postgres.Migrate(ctx, db.Pool)
|
||||
if err != nil {
|
||||
t.Fatalf("second migrate: %v", err)
|
||||
}
|
||||
if len(applied) != 0 {
|
||||
t.Fatalf("second migrate applied %v, want nothing", applied)
|
||||
}
|
||||
var version int64
|
||||
if err := db.Pool.QueryRow(ctx, `SELECT max(version_id) FROM goose_db_version`).Scan(&version); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files, err := fs.Glob(migrations.FS, "*.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if version != int64(len(files)) {
|
||||
t.Fatalf("schema version = %d, want %d (one per migration file)", version, len(files))
|
||||
}
|
||||
for _, table := range []string{"users", "chats", "chat_members", "messages", "message_idempotency_keys"} {
|
||||
var exists bool
|
||||
if err := db.Pool.QueryRow(ctx, `SELECT to_regclass('public.' || $1) IS NOT NULL`, table).Scan(&exists); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !exists {
|
||||
t.Fatalf("table %s is missing", table)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolAppliesLimitsAndTimeouts(t *testing.T) {
|
||||
if got := db.Pool.Config().MaxConns; got != 10 {
|
||||
t.Fatalf("MaxConns = %d, want 10", got)
|
||||
}
|
||||
if got := db.Pool.Config().ConnConfig.ConnectTimeout; got != time.Second {
|
||||
t.Fatalf("ConnectTimeout = %v, want 1s", got)
|
||||
}
|
||||
ctx := context.Background()
|
||||
for setting, want := range map[string]string{
|
||||
"statement_timeout": "5s",
|
||||
"idle_in_transaction_session_timeout": "10s",
|
||||
} {
|
||||
var got string
|
||||
if err := db.Pool.QueryRow(ctx, "SHOW "+setting).Scan(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("%s = %q, want %q", setting, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetEmptiesEveryTableButKeepsSchemaVersion(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
_, err := db.Pool.Exec(ctx, `
|
||||
WITH u AS (
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ('0190f1d2-0000-7000-8000-000000000001', 'reset_check', 'Reset', 'x', now())
|
||||
RETURNING id
|
||||
), c AS (
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
VALUES ('0190f1d2-0000-7000-8000-000000000002', 'Reset', now())
|
||||
RETURNING id
|
||||
), m AS (
|
||||
INSERT INTO chat_members (chat_id, user_id) SELECT c.id, u.id FROM c, u
|
||||
)
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT '0190f1d2-0000-7000-8000-000000000003', c.id, u.id, 'hi', now() FROM c, u`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
db.Reset(t)
|
||||
|
||||
for _, table := range []string{"users", "chats", "chat_members", "messages"} {
|
||||
var n int
|
||||
if err := db.Pool.QueryRow(ctx, "SELECT count(*) FROM "+table).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 0 {
|
||||
t.Fatalf("%s has %d rows after Reset", table, n)
|
||||
}
|
||||
}
|
||||
var versions int
|
||||
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM goose_db_version`).Scan(&versions); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if versions == 0 {
|
||||
t.Fatal("Reset wiped the schema version table")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsUniqueViolation(t *testing.T) {
|
||||
db.Reset(t)
|
||||
ctx := context.Background()
|
||||
insert := `INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, 'taken', 'Taken', 'x', now())`
|
||||
if _, err := db.Pool.Exec(ctx, insert, "0190f1d2-0000-7000-8000-000000000011"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, dup := db.Pool.Exec(ctx, insert, "0190f1d2-0000-7000-8000-000000000012")
|
||||
if dup == nil {
|
||||
t.Fatal("duplicate username was accepted")
|
||||
}
|
||||
|
||||
if !postgres.IsUniqueViolation(dup, "users_username_key") {
|
||||
t.Fatalf("not recognised as a username violation: %v", dup)
|
||||
}
|
||||
if postgres.IsUniqueViolation(dup, "some_other_key") {
|
||||
t.Fatal("matched a different constraint")
|
||||
}
|
||||
if postgres.IsUniqueViolation(fmt.Errorf("wrapped: %w", dup), "users_username_key") == false {
|
||||
t.Fatal("wrapped error not recognised")
|
||||
}
|
||||
if postgres.IsUniqueViolation(errors.New("plain"), "users_username_key") || postgres.IsUniqueViolation(nil, "users_username_key") {
|
||||
t.Fatal("non-database error recognised as a violation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyMarksUnreachableDatabaseAsUnavailable(t *testing.T) {
|
||||
unavailable := map[string]error{
|
||||
"admin shutdown": &pgconn.PgError{Code: "57P01"},
|
||||
"statement timeout": &pgconn.PgError{Code: "57014"},
|
||||
"connection failure": &pgconn.PgError{Code: "08006"},
|
||||
"too many connections": &pgconn.PgError{Code: "53300"},
|
||||
"deadline": fmt.Errorf("query: %w", context.DeadlineExceeded),
|
||||
"network": &net.OpError{Op: "read", Net: "tcp", Err: errors.New("connection reset")},
|
||||
"unexpected eof": fmt.Errorf("read: %w", io.ErrUnexpectedEOF),
|
||||
}
|
||||
for name, err := range unavailable {
|
||||
got := postgres.Classify(err)
|
||||
if apperr.KindOf(got) != apperr.KindUnavailable || !errors.Is(got, err) {
|
||||
t.Errorf("%s: Classify = %v (kind %v), want KindUnavailable keeping the cause", name, got, apperr.KindOf(got))
|
||||
}
|
||||
}
|
||||
for name, err := range map[string]error{
|
||||
"unique violation": &pgconn.PgError{Code: "23505"},
|
||||
"plain": errors.New("boom"),
|
||||
"nil": nil,
|
||||
} {
|
||||
if got := postgres.Classify(err); got != err {
|
||||
t.Errorf("%s: Classify = %v, want the error unchanged", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPoolUsesTheRequestedSize(t *testing.T) {
|
||||
pool, err := postgres.NewPool(context.Background(), db.DSN, 3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if got := pool.Config().MaxConns; got != 3 {
|
||||
t.Fatalf("MaxConns = %d, want 3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyRealConnectFailure(t *testing.T) {
|
||||
_, err := postgres.NewPool(context.Background(), "postgres://u:p@127.0.0.1:1/db?connect_timeout=1", 1)
|
||||
if err == nil {
|
||||
t.Fatal("NewPool to a closed port must fail")
|
||||
}
|
||||
if apperr.KindOf(postgres.Classify(err)) != apperr.KindUnavailable {
|
||||
t.Fatalf("connect failure classified as %v: %v", apperr.KindOf(postgres.Classify(err)), err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user