package worker import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "os" "strings" "time" "github.com/noderunners/dlbot/internal/workerproto" ) // HTTPCoordinator talks to the core's worker API. It is the Coordinator // of the standalone worker binary. type HTTPCoordinator struct { base string token string // api is for the small JSON calls, files for uploads and downloads, // which have no overall timeout and rely on the context instead. api *http.Client files *http.Client } var _ Coordinator = (*HTTPCoordinator)(nil) // NewHTTPCoordinator creates a client for the core at baseURL. func NewHTTPCoordinator(baseURL, token string) *HTTPCoordinator { return &HTTPCoordinator{ base: strings.TrimRight(baseURL, "/"), token: token, api: &http.Client{Timeout: 90 * time.Second}, files: &http.Client{}, } } // StatusError is a non-2xx answer from the core. type StatusError struct { Code int Msg string } func (e *StatusError) Error() string { return fmt.Sprintf("core answered %d: %s", e.Code, e.Msg) } // LeaseLost reports that the core no longer considers the job ours. func (e *StatusError) LeaseLost() bool { return e.Code == http.StatusConflict } // Unauthorized reports that the core rejected the worker's token. func (e *StatusError) Unauthorized() bool { return e.Code == http.StatusUnauthorized } // IsUnauthorized reports whether err means the token was rejected, which // no amount of retrying fixes. func IsUnauthorized(err error) bool { var se *StatusError return errors.As(err, &se) && se.Unauthorized() } func (c *HTTPCoordinator) call(ctx context.Context, path string, in, out any) error { body, err := json.Marshal(in) if err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.base+path, bytes.NewReader(body)) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+c.token) req.Header.Set("Content-Type", "application/json") resp, err := c.api.Do(req) if err != nil { return err } defer resp.Body.Close() return decode(resp, out) } func decode(resp *http.Response, out any) error { data, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20)) if err != nil { return err } if resp.StatusCode < 200 || resp.StatusCode > 299 { var e struct { Error string `json:"error"` } _ = json.Unmarshal(data, &e) if e.Error == "" { e.Error = http.StatusText(resp.StatusCode) } return &StatusError{Code: resp.StatusCode, Msg: e.Error} } if out == nil || len(data) == 0 { return nil } return json.Unmarshal(data, out) } // ClaimAny asks for work and returns the whole response: a job, a probe // task, and any commands for the worker. func (c *HTTPCoordinator) ClaimAny(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.ClaimResponse, error) { var resp workerproto.ClaimResponse if err := c.call(ctx, "/worker/v1/claim", req, &resp); err != nil { return nil, err } return &resp, nil } // Claim implements Coordinator. func (c *HTTPCoordinator) Claim(ctx context.Context, req workerproto.ClaimRequest) (*workerproto.Job, error) { resp, err := c.ClaimAny(ctx, req) if err != nil { return nil, err } return resp.Job, nil } // Heartbeat implements Coordinator. func (c *HTTPCoordinator) Heartbeat(ctx context.Context, req workerproto.HeartbeatRequest) (workerproto.HeartbeatResponse, error) { var resp workerproto.HeartbeatResponse err := c.call(ctx, "/worker/v1/heartbeat", req, &resp) return resp, err } // Complete implements Coordinator. func (c *HTTPCoordinator) Complete(ctx context.Context, req workerproto.CompleteRequest) error { return c.call(ctx, "/worker/v1/complete", req, nil) } // Fail implements Coordinator. func (c *HTTPCoordinator) Fail(ctx context.Context, req workerproto.FailRequest) error { return c.call(ctx, "/worker/v1/fail", req, nil) } // ProbeResult answers a probe task. func (c *HTTPCoordinator) ProbeResult(ctx context.Context, res workerproto.ProbeResult) error { return c.call(ctx, "/worker/v1/probe", res, nil) } // Upload implements Coordinator. With a presigned URL the file goes // straight to storage; otherwise it is streamed to the core. Either way // it is never read into memory. func (c *HTTPCoordinator) Upload(ctx context.Context, job *workerproto.Job, path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() st, err := f.Stat() if err != nil { return err } url, direct := job.UploadURL, job.UploadURL != "" if !direct { url = c.base + "/worker/v1/upload/" + job.ID } req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, f) if err != nil { return err } req.ContentLength = st.Size() req.Header.Set("Content-Type", "application/octet-stream") if !direct { // The bearer token is only ever sent to the core, never to storage. req.Header.Set("Authorization", "Bearer "+c.token) } resp, err := c.files.Do(req) if err != nil { return err } defer resp.Body.Close() return decode(resp, nil) } // Fetch implements Coordinator. func (c *HTTPCoordinator) Fetch(ctx context.Context, job *workerproto.Job, path string) error { url, direct := job.SourceURL, job.SourceURL != "" if !direct { url = c.base + "/worker/v1/source/" + job.ID } req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return err } if !direct { req.Header.Set("Authorization", "Bearer "+c.token) } resp, err := c.files.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { return decode(resp, nil) } out, err := os.Create(path) if err != nil { return err } if _, err := io.Copy(out, resp.Body); err != nil { out.Close() return err } return out.Close() }