package bootstrap import ( "context" "errors" "fmt" "log/slog" "time" "lincodex/backend/config" v1 "lincodex/backend/internal/adapter/primary/http/v1" "lincodex/backend/internal/adapter/secondary/postgres" redisadapter "lincodex/backend/internal/adapter/secondary/redis" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/identity" "lincodex/backend/internal/usecase/practice" "lincodex/backend/internal/worker/practicequeue" "lincodex/backend/internal/worker/retry" ) const ( // practicePoolMaxConns covers concurrent debug run requests; each holds // one short transaction. practicePoolMaxConns = 4 // practiceQueuePoolMaxConns covers the one job in progress and its // claim: every store call is one short transaction. practiceQueuePoolMaxConns = 2 // practiceRunTimeout bounds how long a run may stay unfinished on the // runner. The runner bounds one run by its CPU budget of 300 s plus the // compile phase and the queue of its own slots, so this is far above a // healthy run. practiceRunTimeout = 10 * time.Minute // A failed try waits 2 s, doubling up to a minute, so a short runner // outage costs few attempts. practiceBackoffInitial = 2 * time.Second practiceBackoffMax = time.Minute // practiceStoreTimeout bounds one write of the job state; each is one // short transaction. practiceStoreTimeout = 5 * time.Second ) // newPracticeHandler builds the debug run operations of code practice and the // PostgreSQL pool they own. Nothing connects here. It returns no handler when // DATABASE_URL is unset, and the operations then answer 501. Without a code // runner (CODE_RUNNER_URL unset) the operations answer 503 and store nothing. // The rate limit of debug runs uses the Redis limiter. The application clock // is time.Now. func newPracticeHandler( ctx context.Context, settings config.Config, logger *slog.Logger, keyring *identity.Keyring, cache *redisadapter.Cache, ) (*v1.PracticeHandler, func(), error) { if settings.DatabaseURL == "" { logger.Warn("code practice operations are not served because DATABASE_URL is not set") return nil, func() {}, nil } if keyring == nil || cache == nil { return nil, nil, errors.New("bootstrap.newPracticeHandler - identity keyring and Redis cache must be set") } pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, practicePoolMaxConns) if err != nil { return nil, nil, fmt.Errorf("bootstrap.newPracticeHandler - create pool: %w", err) } service, err := practice.NewService(postgres.NewTransactor(pool), keyring, time.Now, settings.CodeRunner.Enabled()) if err != nil { pool.Close() return nil, nil, fmt.Errorf("bootstrap.newPracticeHandler - create service: %w", err) } service.WithRunRateLimit(cache, outbound.RateLimitRule{Window: time.Minute, Limit: settings.Practice.RunsPerMinute}, outbound.RateLimitRule{Window: time.Hour, Limit: settings.Practice.RunsPerHour}, ) return v1.NewPracticeHandler(service), pool.Close, nil } // newPracticeQueueWorker builds the worker that runs practice jobs on the code // runner and the PostgreSQL pool it owns. Nothing connects here, so an // unavailable database or runner never blocks startup. It returns no worker // without a code runner or without DATABASE_URL: queued jobs then wait in the // database. The application clock is time.Now. func newPracticeQueueWorker( ctx context.Context, settings config.Config, logger *slog.Logger, runner outbound.CodeRunner, ) (*practicequeue.Worker, func(), error) { switch { case !settings.CodeRunner.Enabled(): logger.Info("practice queue worker is off because the code runner is disabled") return nil, func() {}, nil case settings.DatabaseURL == "": logger.Warn("practice queue worker skipped because DATABASE_URL is not set") return nil, func() {}, nil } pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, practiceQueuePoolMaxConns) if err != nil { return nil, nil, fmt.Errorf("bootstrap.newPracticeQueueWorker - create pool: %w", err) } store := postgres.NewPracticeJobStore(pool) workerLogger := logger.With(slog.String("component", "practice_queue")) executor, err := practice.NewExecutor(runner, store, time.Now, practice.ExecutionSettings{ PollInterval: settings.Practice.PollInterval, Lease: settings.Practice.JobLease, RunTimeout: practiceRunTimeout, MaxAttempts: settings.Practice.JobMaxAttempts, BackoffInitial: practiceBackoffInitial, BackoffMax: practiceBackoffMax, StoreTimeout: practiceStoreTimeout, }, workerLogger) if err != nil { pool.Close() return nil, nil, fmt.Errorf("bootstrap.newPracticeQueueWorker - create executor: %w", err) } worker, err := practicequeue.New(store, executor, workerLogger, practicequeue.Settings{ PollInterval: settings.Practice.PollInterval, Lease: settings.Practice.JobLease, StoreTimeout: practiceStoreTimeout, Backoff: retry.Backoff{Initial: practiceBackoffInitial, Max: practiceBackoffMax}, }, time.Now) if err != nil { pool.Close() return nil, nil, fmt.Errorf("bootstrap.newPracticeQueueWorker - create worker: %w", err) } // The application stops the worker before this cleanup runs, so no job // uses the pool while it closes. return worker, pool.Close, nil }