Lab3 baseline: HAProxy, replicated stateless API, shared PostgreSQL/Valkey, idempotent messages
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
// Command migrate applies the embedded, checksummed PostgreSQL migrations and
|
||||
// exits. It is a separate one-shot compose service: API replicas never race to
|
||||
// migrate the shared schema. The advisory lock inside store.Migrate serialises
|
||||
// concurrent invocations of this command as well.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab3/internal/config"
|
||||
"mtusi.ru/messenger-lab3/internal/store"
|
||||
)
|
||||
|
||||
var revision = "unknown"
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})).
|
||||
With("service", "messenger-lab3-migrate", "revision", revision)
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
logger.Error("configuration error", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
|
||||
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
|
||||
MaxConns: cfg.DBMaxConns,
|
||||
MinConns: 0,
|
||||
ConnectTimeout: cfg.DBConnectTimeout,
|
||||
StatementTimeout: cfg.DBStatementTimeout,
|
||||
QueryTimeout: cfg.QueryTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("database configuration failed", "error", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
defer repository.Close()
|
||||
|
||||
for {
|
||||
pingCtx, pingCancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
err = repository.Ping(pingCtx)
|
||||
pingCancel()
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
logger.Error("postgres did not become ready", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
logger.Info("waiting for postgres", "error", err)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
|
||||
started := time.Now()
|
||||
if err := repository.Migrate(ctx); err != nil {
|
||||
logger.Error("migrations failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
logger.Info("migrations complete", "elapsed_ms", float64(time.Since(started).Microseconds())/1000.0)
|
||||
fmt.Println("migrations: up-to-date")
|
||||
}
|
||||
Reference in New Issue
Block a user