| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "net/url" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/runner/heartbeat" |
| 16 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 17 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 18 | ) |
| 19 | |
| 20 | type HTTPInstance struct { |
| 21 | repositories func() ([]string, error) |
| 22 | origin string |
| 23 | client *http.Client |
| 24 | journal *Journal |
| 25 | mu sync.Mutex |
| 26 | bearer runnerproto.RunnerCredential |
| 27 | cleanup map[string]string |
| 28 | } |
| 29 | |
| 30 | func NewHTTPInstance(origin string, j *Journal, credential runnerproto.RunnerCredential) (*HTTPInstance, error) { |
| 31 | u, err := url.Parse(origin) |
| 32 | if err != nil || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Host == "" || u.Scheme != "https" && (u.Scheme != "http" || u.Hostname() != "127.0.0.1") || j == nil || credential.Token == "" { |
| 33 | return nil, provider.ErrContract |
| 34 | } |
| 35 | return &HTTPInstance{origin: strings.TrimRight(origin, "/"), journal: j, bearer: credential, cleanup: map[string]string{}, client: outboundClient()}, nil |
| 36 | } |
| 37 | func (c *HTTPInstance) post(ctx context.Context, op string, body any, token string, out any) error { |
| 38 | raw, err := runnerproto.Marshal(body) |
| 39 | if err != nil { |
| 40 | return err |
| 41 | } |
| 42 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.origin+"/"+op, bytes.NewReader(raw)) |
| 43 | if err != nil { |
| 44 | return err |
| 45 | } |
| 46 | req.Header.Set("Authorization", token) |
| 47 | req.Header.Set("Content-Type", "application/json") |
| 48 | response, err := c.client.Do(req) |
| 49 | if err != nil { |
| 50 | return ErrTransient |
| 51 | } |
| 52 | defer response.Body.Close() |
| 53 | if response.StatusCode != http.StatusOK { |
| 54 | check := fmt.Sprintf("http.response.status_%d", response.StatusCode) |
| 55 | if response.StatusCode == 403 || response.StatusCode == 401 || response.StatusCode == 409 || response.StatusCode == 422 || (strings.HasPrefix(op, "coordinator/") || op == "account-setups") && response.StatusCode >= 400 && response.StatusCode < 500 { |
| 56 | var body runnerproto.ErrorResponse |
| 57 | _ = runnerproto.DecodeLimit(io.LimitReader(response.Body, 4096), &body, 4096) |
| 58 | refusal := &RefusalError{Reason: refusalReason(body.Error), Status: response.StatusCode, Claim: op == "claim"} |
| 59 | return diagnosticAt(refusal, check+"."+refusal.Reason) |
| 60 | } |
| 61 | if op == "claim" && response.StatusCode == http.StatusServiceUnavailable { |
| 62 | return ErrClaimRefused |
| 63 | } |
| 64 | |
| 65 | if response.StatusCode >= 500 || response.StatusCode == http.StatusTooManyRequests { |
| 66 | return ErrTransient |
| 67 | } |
| 68 | return diagnosticAt(provider.ErrContract, check) |
| 69 | } |
| 70 | var envelope struct { |
| 71 | Version int `json:"version"` |
| 72 | Result json.RawMessage `json:"result"` |
| 73 | } |
| 74 | if err = runnerproto.DecodeLimit(io.LimitReader(response.Body, 3<<20), &envelope, 3<<20); err != nil { |
| 75 | return diagnosticAt(provider.ErrContract, "http.response.envelope") |
| 76 | } |
| 77 | if envelope.Version != 2 { |
| 78 | return diagnosticAt(provider.ErrContract, "http.response.version") |
| 79 | } |
| 80 | if out == nil || bytes.Equal(envelope.Result, []byte("null")) { |
| 81 | return nil |
| 82 | } |
| 83 | if err = runnerproto.DecodeLimit(bytes.NewReader(envelope.Result), out, 3<<20); err != nil { |
| 84 | return diagnosticAt(provider.ErrContract, "http.response.result") |
| 85 | } |
| 86 | return nil |
| 87 | } |
| 88 | func (c *HTTPInstance) token(assignment string, cleanup bool) (string, error) { |
| 89 | c.mu.Lock() |
| 90 | defer c.mu.Unlock() |
| 91 | if cleanup { |
| 92 | v := c.cleanup[assignment] |
| 93 | if v == "" { |
| 94 | return "", provider.ErrIdentity |
| 95 | } |
| 96 | return "Cleanup " + v, nil |
| 97 | } |
| 98 | if c.bearer.Token == "" || !time.Now().Before(c.bearer.ExpiresAt) { |
| 99 | return "", provider.ErrIdentity |
| 100 | } |
| 101 | return "Bearer " + c.bearer.Token, nil |
| 102 | } |
| 103 | func (c *HTTPInstance) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error { |
| 104 | token, err := c.token(q.AssignmentID, op == "contained") |
| 105 | if err != nil { |
| 106 | return err |
| 107 | } |
| 108 | call := func() error { return c.post(ctx, op, q, token, out) } |
| 109 | switch op { |
| 110 | case "evidence", "artifacts", "freeze", "freeze_feature", "complete", "questions", "prepare", "publication_ready", "publication_authorize", "receipts", "lost", "release", "stop", "contained", "events", "question_resolved", "conclude": |
| 111 | return retryAuthority(ctx, call) |
| 112 | default: |
| 113 | return call() |
| 114 | } |
| 115 | } |
| 116 | func (c *HTTPInstance) Poll(ctx context.Context) ([]runnerproto.Assignment, error) { |
| 117 | token, err := c.token("", false) |
| 118 | if err != nil { |
| 119 | return nil, err |
| 120 | } |
| 121 | var assignments []runnerproto.Assignment |
| 122 | err = c.post(ctx, "poll", runnerproto.PollRequest{Version: 2}, token, &assignments) |
| 123 | return assignments, err |
| 124 | } |
| 125 | func (c *HTTPInstance) Claim(ctx context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { |
| 126 | return c.claim(ctx, "claim", q) |
| 127 | } |
| 128 | func (c *HTTPInstance) RecoverClaim(ctx context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { |
| 129 | return c.claim(ctx, "recover_claim", q) |
| 130 | } |
| 131 | func (c *HTTPInstance) claim(ctx context.Context, op string, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { |
| 132 | token, err := c.token("", false) |
| 133 | if err != nil { |
| 134 | return runnerproto.ClaimResponse{}, err |
| 135 | } |
| 136 | var claim runnerproto.ClaimResponse |
| 137 | if err = c.post(ctx, op, q, token, &claim); err != nil { |
| 138 | return claim, err |
| 139 | } |
| 140 | if op == "recover_claim" && claim.CleanupExpired { |
| 141 | return claim, ErrCleanupExpired |
| 142 | } |
| 143 | if claim.NotClaimed { |
| 144 | return claim, ErrNotClaimed |
| 145 | } |
| 146 | if claim.CleanupToken == "" || claim.Handle.Runner == "" { |
| 147 | return runnerproto.ClaimResponse{}, provider.ErrIdentity |
| 148 | } |
| 149 | if err = c.journal.saveState(ctx, "cleanup", q.AssignmentID, claim.CleanupToken); err != nil { |
| 150 | return runnerproto.ClaimResponse{}, err |
| 151 | } |
| 152 | c.mu.Lock() |
| 153 | c.cleanup[q.AssignmentID] = claim.CleanupToken |
| 154 | c.mu.Unlock() |
| 155 | return claim, nil |
| 156 | } |
| 157 | func (c *HTTPInstance) InstallCredentials(ctx context.Context, rotation runnerproto.CredentialRotation, requestID string) error { |
| 158 | if rotation.Bearer.Token == "" || requestID == "" { |
| 159 | return provider.ErrIdentity |
| 160 | } |
| 161 | for id, token := range rotation.CleanupTokens { |
| 162 | if err := c.journal.saveState(ctx, "cleanup", id, token); err != nil { |
| 163 | return err |
| 164 | } |
| 165 | } |
| 166 | c.mu.Lock() |
| 167 | c.bearer = rotation.Bearer |
| 168 | for id, token := range rotation.CleanupTokens { |
| 169 | c.cleanup[id] = token |
| 170 | } |
| 171 | c.mu.Unlock() |
| 172 | token, err := c.token("", false) |
| 173 | if err != nil { |
| 174 | return err |
| 175 | } |
| 176 | return c.post(ctx, "heartbeat", runnerproto.HeartbeatRequest{Version: 2, RequestID: requestID + "/ack", RotationRequestID: requestID}, token, nil) |
| 177 | } |
| 178 | |
| 179 | func (c *HTTPInstance) RestoreClaim(claim RunClaim) error { |
| 180 | c.mu.Lock() |
| 181 | defer c.mu.Unlock() |
| 182 | var raw []byte |
| 183 | err := c.journal.db.QueryRow("SELECT body FROM journal_supervisor WHERE kind='cleanup' AND state_key=?", claim.Assignment.ID).Scan(&raw) |
| 184 | if err != nil { |
| 185 | return provider.ErrUncertain |
| 186 | } |
| 187 | var token string |
| 188 | if json.Unmarshal(raw, &token) != nil || token == "" { |
| 189 | return provider.ErrIdentity |
| 190 | } |
| 191 | c.cleanup[claim.Assignment.ID] = token |
| 192 | return nil |
| 193 | } |
| 194 | |
| 195 | func (c *HTTPInstance) Heartbeat(ctx context.Context, reports []runnerproto.ConnectionReport) error { |
| 196 | token, err := c.token("", false) |
| 197 | if err != nil { |
| 198 | return err |
| 199 | } |
| 200 | q, err := heartbeat.Request(reports, c.repositories) |
| 201 | if err != nil { |
| 202 | return err |
| 203 | } |
| 204 | return c.post(ctx, "heartbeat", q, token, nil) |
| 205 | } |
| 206 | |