feat(practice): queue practice runs with one running and ten waiting

This commit is contained in:
shira committed 2026-10-11 15:01:07 +03:00
1 parent 51770eea6c
commit 754c745fba
40 files changed
+3040 -70

No files matched your search

+21 -8
View File
@@ -22,6 +22,7 @@ import (
"lincodex/backend/internal/worker/jobrunner"
"lincodex/backend/internal/worker/mailsender"
"lincodex/backend/internal/worker/outboxrelay"
"lincodex/backend/internal/worker/practicequeue"
)
const (
@@ -37,9 +38,9 @@ type Application struct {
// mailSender is the transport selected by EMAIL_PROVIDER. Only the mail
// sending worker calls it.
mailSender outbound.MailSender
// codeRunner is the runner selected by CODE_RUNNER_URL: the disabled one
// when unset. Practice usecases receive it from here once they exist.
codeRunner outbound.CodeRunner
// practiceQueue runs practice jobs on the code runner while the servers
// run. It is nil without a configured code runner or database.
practiceQueue *practicequeue.Worker
// relay publishes outbox events while the servers run. It is nil when
// the relay is disabled or the database is not configured.
relay *outboxrelay.Relay
@@ -156,10 +157,18 @@ func start(ctx context.Context, config config.Config, logger *slog.Logger) (*App
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - initialize application: %w", err)
}
// No dependency needs the runner yet, so it is attached here rather than
// injected; the practice usecases will take it from the injector.
application.codeRunner = codeRunner
return application, cleanup, nil
// The worker is the only consumer of the runner, so it is built here
// with the runner rather than through the injector.
practiceQueue, closeQueue, err := newPracticeQueueWorker(ctx, config, logger, codeRunner)
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("bootstrap.start - create practice queue worker: %w", err)
}
application.practiceQueue = practiceQueue
return application, func() {
closeQueue()
cleanup()
}, nil
}
func logLevel(value string) logkit.Level {
@@ -223,7 +232,8 @@ func (application *Application) run(ctx context.Context) error {
}
// startWorkers runs the relay, every consumer, the scheduled job worker, the
// mail sending worker, and the delivery metrics sampler until ctx ends and returns a channel that
// mail sending worker, the delivery metrics sampler, and the practice queue
// worker until ctx ends and returns a channel that
// closes when all of them have stopped. The workers stop together with the
// servers; none of them depends on another.
func (application *Application) startWorkers(ctx context.Context) <-chan struct{} {
@@ -246,6 +256,9 @@ func (application *Application) startWorkers(ctx context.Context) <-chan struct{
if application.deliveryMetrics != nil {
workers.Go(func() { application.deliveryMetrics.Run(ctx) })
}
if application.practiceQueue != nil {
workers.Go(func() { application.practiceQueue.Run(ctx) })
}
stopped := make(chan struct{})
go func() {
defer close(stopped)
+86 -6
View File
@@ -10,31 +10,54 @@ import (
"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"
)
// practicePoolMaxConns covers concurrent debug run requests; each holds one
// short transaction.
const practicePoolMaxConns = 4
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 application clock is time.Now.
// 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 {
return nil, nil, errors.New("bootstrap.newPracticeHandler - identity keyring must be set")
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 {
@@ -45,5 +68,62 @@ func newPracticeHandler(
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
}
+1 -1
View File
@@ -184,7 +184,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
practiceHandler, cleanup15, err := newPracticeHandler(ctx, config2, logger, keyring)
practiceHandler, cleanup15, err := newPracticeHandler(ctx, config2, logger, keyring, cache)
if err != nil {
cleanup14()
cleanup13()