| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | jitter "math/rand/v2" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 12 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 13 | ) |
| 14 | |
| 15 | type AssignmentSource interface { |
| 16 | Poll(context.Context) ([]runnerproto.Assignment, error) |
| 17 | Claim(context.Context, runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) |
| 18 | } |
| 19 | type Service struct { |
| 20 | Coordinator *CoordinatorService |
| 21 | Supervisor *Supervisor |
| 22 | Source AssignmentSource |
| 23 | BeforeRun func(RunClaim) |
| 24 | Report func(string) |
| 25 | } |
| 26 | |
| 27 | func (s *Service) Run(ctx context.Context) error { |
| 28 | if s.Supervisor == nil || s.Source == nil { |
| 29 | return provider.ErrContract |
| 30 | } |
| 31 | needsRecovery := true |
| 32 | claimRefusals := 0 |
| 33 | for { |
| 34 | if ctx.Err() != nil { |
| 35 | return ctx.Err() |
| 36 | } |
| 37 | if needsRecovery { |
| 38 | err := errors.Join(s.recoverClaims(ctx), s.Supervisor.Recover(ctx)) |
| 39 | if err != nil { |
| 40 | s.Supervisor.ready = false |
| 41 | if fatalServiceError(err) || errors.Is(err, context.Canceled) { |
| 42 | return err |
| 43 | } |
| 44 | s.report("runner.recovery_retry") |
| 45 | if err := serviceBackoff(ctx); err != nil { |
| 46 | return err |
| 47 | } |
| 48 | continue |
| 49 | } |
| 50 | needsRecovery = false |
| 51 | } |
| 52 | var coordinatorErr error |
| 53 | if s.Coordinator != nil { |
| 54 | coordinatorErr = s.Coordinator.Recover(ctx) |
| 55 | if fatalServiceError(coordinatorErr) || errors.Is(coordinatorErr, context.Canceled) { |
| 56 | return coordinatorErr |
| 57 | } |
| 58 | if coordinatorErr != nil { |
| 59 | s.report("runner.recovery_retry") |
| 60 | } |
| 61 | } |
| 62 | assignments, err := s.Source.Poll(ctx) |
| 63 | if err != nil { |
| 64 | if fatalServiceError(err) || errors.Is(err, context.Canceled) { |
| 65 | return err |
| 66 | } |
| 67 | s.report("runner.poll_retry") |
| 68 | assignments = nil |
| 69 | } |
| 70 | pollErr := err |
| 71 | if s.Coordinator != nil && coordinatorErr == nil { |
| 72 | coordinatorErr = s.Coordinator.Poll(ctx) |
| 73 | if coordinatorErr != nil { |
| 74 | s.report("runner.poll_retry") |
| 75 | } |
| 76 | } |
| 77 | if errors.Is(coordinatorErr, ErrJournal) || ctx.Err() != nil { |
| 78 | return errors.Join(coordinatorErr, ctx.Err()) |
| 79 | } |
| 80 | for _, a := range assignments { |
| 81 | if err := s.Supervisor.journal.AdmissionAllowed(ctx); err != nil { |
| 82 | needsRecovery = true |
| 83 | if ctx.Err() != nil { |
| 84 | return ctx.Err() |
| 85 | } |
| 86 | if err := serviceBackoff(ctx); err != nil { |
| 87 | return err |
| 88 | } |
| 89 | break |
| 90 | } |
| 91 | if err = s.Supervisor.journal.saveState(ctx, "assignment", a.ID, a); err != nil { |
| 92 | return err |
| 93 | } |
| 94 | request := runnerproto.ClaimRequest{Version: 2, AssignmentID: a.ID, Revision: a.Revision, RequestID: rand.Text()} |
| 95 | if err = s.Supervisor.journal.saveState(ctx, "claim", a.ID, request); err != nil { |
| 96 | return err |
| 97 | } |
| 98 | var claim runnerproto.ClaimResponse |
| 99 | err = retryAuthority(ctx, func() error { var e error; claim, e = s.Source.Claim(ctx, request); return e }) |
| 100 | if errors.Is(err, ErrClaimRefused) || errors.Is(err, provider.ErrIdentity) { |
| 101 | if err = s.clearClaim(ctx, request); err != nil { |
| 102 | return err |
| 103 | } |
| 104 | claimRefusals++ |
| 105 | if err := waitService(ctx, claimBackoffDelay(claimRefusals)); err != nil { |
| 106 | return err |
| 107 | } |
| 108 | continue |
| 109 | } |
| 110 | if err != nil { |
| 111 | return err |
| 112 | } |
| 113 | claimRefusals = 0 |
| 114 | if s.BeforeRun != nil { |
| 115 | s.BeforeRun(RunClaim{Assignment: a, ClaimResponse: claim}) |
| 116 | } |
| 117 | if err = s.withCoordinatorWaiting(ctx, func() error { return s.Supervisor.Run(ctx, RunClaim{Assignment: a, ClaimResponse: claim}) }); err != nil { |
| 118 | if errors.Is(err, ErrJournal) { |
| 119 | return err |
| 120 | } |
| 121 | needsRecovery = true |
| 122 | s.report("runner.attempt_retry") |
| 123 | if err := serviceBackoff(ctx); err != nil { |
| 124 | return err |
| 125 | } |
| 126 | break |
| 127 | } |
| 128 | } |
| 129 | if pollErr != nil || coordinatorErr != nil { |
| 130 | if err := serviceBackoff(ctx); err != nil { |
| 131 | return err |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | // Observe the shared home at claim/release and at the lease cadence so messages |
| 138 | // queued during specialist work acquire waiting status. This never dispatches. |
| 139 | func (s *Service) withCoordinatorWaiting(ctx context.Context, run func() error) error { |
| 140 | if s.Coordinator == nil { |
| 141 | return run() |
| 142 | } |
| 143 | observe := func(ctx context.Context) { |
| 144 | var turns []runnerproto.CoordinatorTurn |
| 145 | // A failed poll supplies no status and must not invent availability. |
| 146 | _ = s.Coordinator.call(ctx, "poll", runnerproto.CoordinatorRequest{}, &turns) |
| 147 | } |
| 148 | observe(ctx) |
| 149 | watch, cancel := context.WithCancel(ctx) |
| 150 | done := make(chan struct{}) |
| 151 | go func() { |
| 152 | defer close(done) |
| 153 | tick := time.NewTicker(leaseRenewInterval) |
| 154 | defer tick.Stop() |
| 155 | for { |
| 156 | select { |
| 157 | case <-watch.Done(): |
| 158 | return |
| 159 | case <-tick.C: |
| 160 | observe(watch) |
| 161 | } |
| 162 | } |
| 163 | }() |
| 164 | defer func() { |
| 165 | cancel() |
| 166 | <-done |
| 167 | cleanup, stop := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) |
| 168 | defer stop() |
| 169 | observe(cleanup) |
| 170 | }() |
| 171 | return run() |
| 172 | } |
| 173 | |
| 174 | func (s *Service) recoverClaims(ctx context.Context) error { |
| 175 | var claims []runnerproto.ClaimRequest |
| 176 | var attempts []attemptState |
| 177 | if err := s.Supervisor.journal.readStates(ctx, "claim", &claims); err != nil { |
| 178 | return err |
| 179 | } |
| 180 | if err := s.Supervisor.journal.readStates(ctx, "attempt", &attempts); err != nil { |
| 181 | return err |
| 182 | } |
| 183 | saved := map[string]bool{} |
| 184 | for _, a := range attempts { |
| 185 | saved[a.Claim.Assignment.ID] = true |
| 186 | } |
| 187 | for _, q := range claims { |
| 188 | if saved[q.AssignmentID] { |
| 189 | continue |
| 190 | } |
| 191 | source, ok := s.Source.(interface { |
| 192 | RecoverClaim(context.Context, runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) |
| 193 | }) |
| 194 | if !ok || s.Supervisor.workflow == nil { |
| 195 | return provider.ErrUncertain |
| 196 | } |
| 197 | var reply runnerproto.ClaimResponse |
| 198 | err := retryAuthority(ctx, func() error { var e error; reply, e = source.RecoverClaim(ctx, q); return e }) |
| 199 | if errors.Is(err, ErrNotClaimed) || errors.Is(err, ErrCleanupExpired) { |
| 200 | if err = s.clearClaim(ctx, q); err != nil { |
| 201 | return err |
| 202 | } |
| 203 | continue |
| 204 | } |
| 205 | if err != nil { |
| 206 | return err |
| 207 | } |
| 208 | if !reply.LeaseDeadline.IsZero() || !reply.AttemptDeadline.IsZero() { |
| 209 | return provider.ErrIdentity |
| 210 | } |
| 211 | var assignment runnerproto.Assignment |
| 212 | var raw []byte |
| 213 | 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 { |
| 214 | return err |
| 215 | } |
| 216 | if json.Unmarshal(raw, &assignment) != nil { |
| 217 | return provider.ErrIdentity |
| 218 | } |
| 219 | 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()}}} |
| 220 | if assignment.Kind != "prepare" { |
| 221 | record.Owner.Marker = attemptKey(reply.Scope, reply.Handle) |
| 222 | } |
| 223 | if err = s.Supervisor.save(ctx, record); err != nil { |
| 224 | return err |
| 225 | } |
| 226 | |
| 227 | } |
| 228 | return nil |
| 229 | } |
| 230 | |
| 231 | func (s *Service) clearClaim(ctx context.Context, q runnerproto.ClaimRequest) error { |
| 232 | _, err := s.Supervisor.journal.db.ExecContext(ctx, "DELETE FROM journal_supervisor WHERE kind='claim' AND state_key=?", q.AssignmentID) |
| 233 | return err |
| 234 | } |
| 235 | |
| 236 | func claimBackoffDelay(failures int) time.Duration { |
| 237 | base := time.Second * time.Duration(1<<min(max(failures-1, 0), 5)) |
| 238 | return min(30*time.Second, base+time.Duration(jitter.Int64N(int64(base/4)+1))) |
| 239 | } |
| 240 | func serviceBackoff(ctx context.Context) error { return waitService(ctx, 500*time.Millisecond) } |
| 241 | func waitService(ctx context.Context, delay time.Duration) error { |
| 242 | timer := time.NewTimer(delay) |
| 243 | defer timer.Stop() |
| 244 | select { |
| 245 | case <-ctx.Done(): |
| 246 | return ctx.Err() |
| 247 | case <-timer.C: |
| 248 | return nil |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | func fatalServiceError(err error) bool { |
| 253 | return errors.Is(err, ErrJournal) || errors.Is(err, provider.ErrContract) || errors.Is(err, provider.ErrIdentity) |
| 254 | } |
| 255 | func (s *Service) report(code string) { |
| 256 | if s.Report != nil { |
| 257 | s.Report(code) |
| 258 | } |
| 259 | } |
| 260 | |