Оставить одну обратимую миграцию и минимальные файлы стенда
This commit is contained in:
+26
-29
@@ -2,16 +2,19 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5"
|
||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
@@ -50,50 +53,44 @@ func openDatabase(ctx context.Context) (*pgxpool.Pool, error) {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err = applyMigrations(ctx, db); err != nil {
|
||||
if err = runMigrations(url, "up"); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func applyMigrations(ctx context.Context, db *pgxpool.Pool) error {
|
||||
files, err := migrationFiles.ReadDir("migrations")
|
||||
// runMigrations uses versioned up/down SQL embedded in the API binary.
|
||||
// "down" rolls back exactly one version and is an explicit operator command.
|
||||
func runMigrations(url, direction string) error {
|
||||
source, err := iofs.New(migrationFiles, "migrations")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sort.Slice(files, func(i, j int) bool { return files[i].Name() < files[j].Name() })
|
||||
tx, err := db.Begin(ctx)
|
||||
sqlDB, err := sql.Open("pgx", url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(20426002)"); err != nil {
|
||||
driver, err := pgxmigrate.WithInstance(sqlDB, &pgxmigrate.Config{})
|
||||
if err != nil {
|
||||
sqlDB.Close()
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)"); err != nil {
|
||||
m, err := migrate.NewWithInstance("iofs", source, "pgx5", driver)
|
||||
if err != nil {
|
||||
sqlDB.Close()
|
||||
return err
|
||||
}
|
||||
for _, file := range files {
|
||||
var exists bool
|
||||
if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=$1)", file.Name()).Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
continue
|
||||
}
|
||||
sql, readErr := migrationFiles.ReadFile("migrations/" + file.Name())
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
if _, err = tx.Exec(ctx, string(sql)); err != nil {
|
||||
return fmt.Errorf("migration %s: %w", file.Name(), err)
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES($1)", file.Name()); err != nil {
|
||||
return err
|
||||
}
|
||||
defer m.Close()
|
||||
if direction == "down" {
|
||||
err = m.Steps(-1)
|
||||
} else {
|
||||
err = m.Up()
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
if errors.Is(err, migrate.ErrNoChange) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func uniqueViolation(err error) bool {
|
||||
|
||||
+26
@@ -110,6 +110,32 @@ func serverAddress() string {
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) > 1 {
|
||||
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
|
||||
client := http.Client{Timeout: 2 * time.Second}
|
||||
response, err := client.Get("http://127.0.0.1:8080/health/ready")
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(os.Args) != 3 || os.Args[1] != "migrate" || (os.Args[2] != "up" && os.Args[2] != "down") {
|
||||
log.Fatal("usage: messenger migrate up|down")
|
||||
}
|
||||
url, err := databaseURL()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err = runMigrations(url, os.Args[2]); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Printf("migration %s complete", os.Args[2])
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
db, err := openDatabase(ctx)
|
||||
cancel()
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
DROP TABLE IF EXISTS sessions;
|
||||
DROP TABLE IF EXISTS messages;
|
||||
DROP TABLE IF EXISTS chat_members;
|
||||
DROP TABLE IF EXISTS chats;
|
||||
DROP TABLE IF EXISTS users;
|
||||
@@ -1,33 +1,32 @@
|
||||
CREATE TABLE users (
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id uuid PRIMARY KEY,
|
||||
username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash bytea NOT NULL,
|
||||
password_salt bytea NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE TABLE chats (
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE TABLE chat_members (
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
PRIMARY KEY (chat_id,user_id)
|
||||
);
|
||||
CREATE INDEX chat_members_user_idx ON chat_members(user_id,chat_id);
|
||||
CREATE TABLE messages (
|
||||
CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members(user_id,chat_id);
|
||||
CREATE TABLE IF NOT EXISTS 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 CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX messages_history_idx ON messages(chat_id,created_at,id);
|
||||
CREATE TABLE sessions (
|
||||
CREATE INDEX IF NOT EXISTS messages_history_idx ON messages(chat_id,created_at,id);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX sessions_expiry_idx ON sessions(expires_at);
|
||||
CREATE INDEX IF NOT EXISTS sessions_expiry_idx ON sessions(expires_at);
|
||||
+9
-5
@@ -41,6 +41,7 @@ func (s *userStore) create(ctx context.Context, username, displayName, password
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
packedHash := append(salt, hash...)
|
||||
user := User{
|
||||
ID: uuid.New().String(),
|
||||
Username: username,
|
||||
@@ -48,7 +49,7 @@ func (s *userStore) create(ctx context.Context, username, displayName, password
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
_, err = s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,password_salt,created_at) VALUES($1,$2,$3,$4,$5,$6)", user.ID, user.Username, user.DisplayName, hash, salt, user.CreatedAt)
|
||||
_, err = s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES($1,$2,$3,$4,$5)", user.ID, user.Username, user.DisplayName, packedHash, user.CreatedAt)
|
||||
return user, err
|
||||
}
|
||||
|
||||
@@ -60,17 +61,20 @@ func (s *userStore) getByID(ctx context.Context, id string) (User, error) {
|
||||
|
||||
func (s *userStore) verifyPassword(ctx context.Context, username, password string) (User, bool, error) {
|
||||
var user User
|
||||
var hash, salt []byte
|
||||
err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash,password_salt FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash, &salt)
|
||||
var packedHash []byte
|
||||
err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &packedHash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return User{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, false, err
|
||||
}
|
||||
actual, err := derivePassword(password, salt)
|
||||
if len(packedHash) != 64 {
|
||||
return User{}, false, errors.New("invalid password hash format")
|
||||
}
|
||||
actual, err := derivePassword(password, packedHash[:32])
|
||||
if err != nil {
|
||||
return User{}, false, err
|
||||
}
|
||||
return user, subtle.ConstantTimeCompare(hash, actual) == 1, nil
|
||||
return user, subtle.ConstantTimeCompare(packedHash[32:], actual) == 1, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user