feat(backend): add transactional outbox and embedded goose migrations
This commit is contained in:
1 parent
653f3775f8
commit
15e2e50561
40 files changed
+2471
-67
No files matched your search
@@ -0,0 +1,57 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/db"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
)
|
||||
|
||||
// startupMigrationTimeout bounds lock waiting and migration work before the
|
||||
// servers start. It matches the migration lock retry window.
|
||||
const startupMigrationTimeout = 5 * time.Minute
|
||||
|
||||
// migrateDatabase applies embedded migrations before any listener opens, so the
|
||||
// service never serves requests against an older schema. Without DATABASE_URL
|
||||
// the service keeps its existing behavior: it starts and reports not ready.
|
||||
func migrateDatabase(ctx context.Context, settings config.Config, logger *slog.Logger) error {
|
||||
if !settings.DatabaseMigrateOnStart {
|
||||
logger.Info("startup database migrations are disabled")
|
||||
return nil
|
||||
}
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("startup database migrations skipped because DATABASE_URL is not set")
|
||||
return nil
|
||||
}
|
||||
migrations, err := db.Migrations()
|
||||
if err != nil {
|
||||
return fmt.Errorf("bootstrap.migrateDatabase - load migrations: %w", err)
|
||||
}
|
||||
migrator, err := postgres.NewMigrator(settings.DatabaseURL, migrations)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bootstrap.migrateDatabase - create migrator: %w", err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, startupMigrationTimeout)
|
||||
defer cancel()
|
||||
applied, err := migrator.Up(ctx)
|
||||
if closeErr := migrator.Close(); closeErr != nil {
|
||||
err = errors.Join(err, fmt.Errorf("bootstrap.migrateDatabase - close migrator: %w", closeErr))
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("bootstrap.migrateDatabase - apply migrations: %w", err)
|
||||
}
|
||||
for _, migration := range applied {
|
||||
logger.Info("database migration applied",
|
||||
slog.Int64("version", migration.Version),
|
||||
slog.String("name", migration.Name),
|
||||
slog.Duration("duration", migration.Duration),
|
||||
)
|
||||
}
|
||||
logger.Info("database schema is up to date", slog.Int("applied_migrations", len(applied)))
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user