package runner import ( "context" "crypto/rand" "encoding/json" "errors" jitter "math/rand/v2" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type AssignmentSource interface { Poll(context.Context) ([]runnerproto.Assignment, error) Claim(context.Context, runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) } type Service struct { Coordinator *CoordinatorService Supervisor *Supervisor Source AssignmentSource BeforeRun func(RunClaim) Report func(string) } func (s *Service) Run(ctx context.Context) error { if s.Supervisor == nil || s.Source == nil { return provider.ErrContract } needsRecovery := true claimRefusals := 0 for { if ctx.Err() != nil { return ctx.Err() } if needsRecovery { err := errors.Join(s.recoverClaims(ctx), s.Supervisor.Recover(ctx)) if err != nil { s.Supervisor.ready = false if fatalServiceError(err) || errors.Is(err, context.Canceled) { return err } s.report("runner.recovery_retry") if err := serviceBackoff(ctx); err != nil { return err } continue } needsRecovery = false } var coordinatorErr error if s.Coordinator != nil { coordinatorErr = s.Coordinator.Recover(ctx) if fatalServiceError(coordinatorErr) || errors.Is(coordinatorErr, context.Canceled) { return coordinatorErr } if coordinatorErr != nil { s.report("runner.recovery_retry") } } assignments, err := s.Source.Poll(ctx) if err != nil { if fatalServiceError(err) || errors.Is(err, context.Canceled) { return err } s.report("runner.poll_retry") assignments = nil } pollErr := err if s.Coordinator != nil && coordinatorErr == nil { coordinatorErr = s.Coordinator.Poll(ctx) if coordinatorErr != nil { s.report("runner.poll_retry") } } if errors.Is(coordinatorErr, ErrJournal) || ctx.Err() != nil { return errors.Join(coordinatorErr, ctx.Err()) } for _, a := range assignments { if err := s.Supervisor.journal.AdmissionAllowed(ctx); err != nil { needsRecovery = true if ctx.Err() != nil { return ctx.Err() } if err := serviceBackoff(ctx); err != nil { return err } break } if err = s.Supervisor.journal.saveState(ctx, "assignment", a.ID, a); err != nil { return err } request := runnerproto.ClaimRequest{Version: 2, AssignmentID: a.ID, Revision: a.Revision, RequestID: rand.Text()} if err = s.Supervisor.journal.saveState(ctx, "claim", a.ID, request); err != nil { return err } var claim runnerproto.ClaimResponse err = retryAuthority(ctx, func() error { var e error; claim, e = s.Source.Claim(ctx, request); return e }) if errors.Is(err, ErrClaimRefused) || errors.Is(err, provider.ErrIdentity) { if err = s.clearClaim(ctx, request); err != nil { return err } claimRefusals++ if err := waitService(ctx, claimBackoffDelay(claimRefusals)); err != nil { return err } continue } if err != nil { return err } claimRefusals = 0 if s.BeforeRun != nil { s.BeforeRun(RunClaim{Assignment: a, ClaimResponse: claim}) } if err = s.withCoordinatorWaiting(ctx, func() error { return s.Supervisor.Run(ctx, RunClaim{Assignment: a, ClaimResponse: claim}) }); err != nil { if errors.Is(err, ErrJournal) { return err } needsRecovery = true s.report("runner.attempt_retry") if err := serviceBackoff(ctx); err != nil { return err } break } } if pollErr != nil || coordinatorErr != nil { if err := serviceBackoff(ctx); err != nil { return err } } } } // Observe the shared home at claim/release and at the lease cadence so messages // queued during specialist work acquire waiting status. This never dispatches. func (s *Service) withCoordinatorWaiting(ctx context.Context, run func() error) error { if s.Coordinator == nil { return run() } observe := func(ctx context.Context) { var turns []runnerproto.CoordinatorTurn // A failed poll supplies no status and must not invent availability. _ = s.Coordinator.call(ctx, "poll", runnerproto.CoordinatorRequest{}, &turns) } observe(ctx) watch, cancel := context.WithCancel(ctx) done := make(chan struct{}) go func() { defer close(done) tick := time.NewTicker(leaseRenewInterval) defer tick.Stop() for { select { case <-watch.Done(): return case <-tick.C: observe(watch) } } }() defer func() { cancel() <-done cleanup, stop := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer stop() observe(cleanup) }() return run() } func (s *Service) recoverClaims(ctx context.Context) error { var claims []runnerproto.ClaimRequest var attempts []attemptState if err := s.Supervisor.journal.readStates(ctx, "claim", &claims); err != nil { return err } if err := s.Supervisor.journal.readStates(ctx, "attempt", &attempts); err != nil { return err } saved := map[string]bool{} for _, a := range attempts { saved[a.Claim.Assignment.ID] = true } for _, q := range claims { if saved[q.AssignmentID] { continue } source, ok := s.Source.(interface { RecoverClaim(context.Context, runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) }) if !ok || s.Supervisor.workflow == nil { return provider.ErrUncertain } var reply runnerproto.ClaimResponse err := retryAuthority(ctx, func() error { var e error; reply, e = source.RecoverClaim(ctx, q); return e }) if errors.Is(err, ErrNotClaimed) || errors.Is(err, ErrCleanupExpired) { if err = s.clearClaim(ctx, q); err != nil { return err } continue } if err != nil { return err } if !reply.LeaseDeadline.IsZero() || !reply.AttemptDeadline.IsZero() { return provider.ErrIdentity } var assignment runnerproto.Assignment var raw []byte if err = s.Supervisor.journal.db.QueryRowContext(ctx, "SELECT body FROM journal_supervisor WHERE kind='assignment' AND state_key=?", q.AssignmentID).Scan(&raw); err != nil { return err } if json.Unmarshal(raw, &assignment) != nil { return provider.ErrIdentity } record := &attemptState{Direct: s.Supervisor.namespaces != nil, Claim: RunClaim{Assignment: assignment, ClaimResponse: reply}, Phase: "recovering", Owner: ProcessOwner{LocalOnly: true, Attempt: reply.Handle.Attempt, Fence: reply.Handle.Fence, Marker: assignment.ID, Workspace: provider.Workspace{Path: s.Supervisor.workflow.cfg.Workspaces.PreparationDirectory()}}} if assignment.Kind != "prepare" { record.Owner.Marker = attemptKey(reply.Scope, reply.Handle) } if err = s.Supervisor.save(ctx, record); err != nil { return err } } return nil } func (s *Service) clearClaim(ctx context.Context, q runnerproto.ClaimRequest) error { _, err := s.Supervisor.journal.db.ExecContext(ctx, "DELETE FROM journal_supervisor WHERE kind='claim' AND state_key=?", q.AssignmentID) return err } func claimBackoffDelay(failures int) time.Duration { base := time.Second * time.Duration(1<