Files
lincodex/backend/internal/bootstrap/policy.go
T

58 lines
2.1 KiB
Go

package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/policy"
)
// startupPolicySeedTimeout bounds the demo policy seed, which reads one row
// and inserts at most one.
const startupPolicySeedTimeout = 30 * time.Second
// seedDemoPolicy publishes the demo product policy as version 1 when the
// product family has no version yet, so a fresh database has an effective
// policy as soon as the service starts. It runs right after the startup
// migrations and under the same switch: it is skipped when
// DATABASE_MIGRATE_ON_START is false or DATABASE_URL is unset, and then a
// developer who migrates by hand also starts without a seeded policy. It
// checks presence only, so an existing version, even one this build cannot
// decode, is left alone and does not block startup. A database error stops
// startup, like a failed migration.
func seedDemoPolicy(ctx context.Context, settings config.Config, logger *slog.Logger) error {
if !settings.DatabaseMigrateOnStart || settings.DatabaseURL == "" {
return nil
}
pool, err := postgres.NewPool(ctx, settings.DatabaseURL)
if err != nil {
return fmt.Errorf("bootstrap.seedDemoPolicy - create pool: %w", err)
}
defer pool.Close()
ctx, cancel := context.WithTimeout(ctx, startupPolicySeedTimeout)
defer cancel()
publisher := policy.NewPublisher(postgres.NewPolicyStore(pool).Policies(), time.Now)
result, err := publisher.EnsureDemoProductPolicy(ctx)
if err != nil {
return fmt.Errorf("bootstrap.seedDemoPolicy - ensure demo product policy: %w", err)
}
if !result.Created {
logger.Info("product policy already present; demo seed skipped",
slog.String("policy_key", string(domain.ProductPolicyKey)),
)
return nil
}
logger.Info("demo product policy published",
slog.String("policy_key", string(result.Version.Key())),
slog.Int("policy_version", int(result.Version.Version())),
slog.String("policy_kind", string(result.Version.Kind())),
slog.String("policy_version_id", result.Version.ID().String()),
)
return nil
}