| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "time" |
| 8 | ) |
| 9 | |
| 10 | type coordinatorRetry struct { |
| 11 | failures int |
| 12 | after time.Time |
| 13 | } |
| 14 | |
| 15 | func (s *CoordinatorService) clock() time.Time { |
| 16 | if s.now != nil { |
| 17 | return s.now() |
| 18 | } |
| 19 | return time.Now() |
| 20 | } |
| 21 | func (s *CoordinatorService) retryDue(id string) bool { return !s.clock().Before(s.retry[id].after) } |
| 22 | func (s *CoordinatorService) deferRetry(id string) { |
| 23 | if s.retry == nil { |
| 24 | s.retry = map[string]coordinatorRetry{} |
| 25 | } |
| 26 | r := s.retry[id] |
| 27 | r.failures = min(r.failures+1, 6) |
| 28 | r.after = s.clock().Add(min(leaseRenewInterval, time.Second*time.Duration(1<<(r.failures-1)))) |
| 29 | s.retry[id] = r |
| 30 | } |
| 31 | func (s *CoordinatorService) refusedCall(ctx context.Context, r *coordinatorState, op string, err error) error { |
| 32 | var refusal *RefusalError |
| 33 | if errors.As(err, &refusal) && refusal.CoordinatorDefinitive() { |
| 34 | return s.recordRefusal(ctx, r, op, refusal) |
| 35 | } |
| 36 | if ctx.Err() != nil { |
| 37 | return ctx.Err() |
| 38 | } |
| 39 | s.deferRetry(r.Claim.Turn.ID) |
| 40 | return nil |
| 41 | } |
| 42 | |
| 43 | // Older journals treated uncoded refusals as final. Restore their report work; |
| 44 | // no record with a saved claim can return to provider dispatch. |
| 45 | func (s *CoordinatorService) reopenUncodedRefusals(ctx context.Context) error { |
| 46 | var states []coordinatorState |
| 47 | if err := s.Journal.readStates(ctx, "coordinator", &states); err != nil { |
| 48 | return err |
| 49 | } |
| 50 | for _, r := range states { |
| 51 | if !r.Refused || (&RefusalError{Status: r.RefusalStatus, Reason: r.RefusalCode}).CoordinatorDefinitive() { |
| 52 | continue |
| 53 | } |
| 54 | id := r.Claim.Turn.ID |
| 55 | if r.Claim.Handle.Attempt == 0 { |
| 56 | q := runnerproto.CoordinatorRequest{TurnID: id, Revision: r.Claim.Turn.Revision} |
| 57 | if err := s.Journal.saveState(ctx, "coordinator-claim", id, q); err != nil { |
| 58 | return err |
| 59 | } |
| 60 | if _, err := s.Journal.db.ExecContext(ctx, "DELETE FROM journal_supervisor WHERE kind='coordinator' AND state_key=?", id); err != nil { |
| 61 | return err |
| 62 | } |
| 63 | } else { |
| 64 | r.Finished, r.Refused = false, false |
| 65 | if err := s.Journal.saveState(ctx, "coordinator", id, r); err != nil { |
| 66 | return err |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | return nil |
| 71 | } |
| 72 | |