Files
Media-download-telegram-bot/internal/worker/httpcoord.go
T
MichilisandClaude Fable 5.2 7d4893bc3f Phase 4: scale out
Remote workers, Postgres and S3, all chosen by configuration.

- Pull-based worker protocol over HTTP: claim (long poll), heartbeat,
  complete, fail, upload, source, probe. Workers need no inbound ports
- cmd/worker: standalone stateless worker with health endpoint and
  scheduled yt-dlp self-update
- Per-worker bearer tokens, stored hashed, revocable; identity always
  taken from the token; actions only on jobs the worker holds a lease for
- Tags: site_tags routes a site's jobs and lookups to workers that carry
  the required tags
- Drain, /workers, /ytdlp update, and "core worker add|revoke|list"
- Link lookups can run on remote workers (PROBE_MODE), so the core needs
  no yt-dlp and no residential address
- Postgres backend with pgx, same schema and queries; per-user advisory
  lock and job row lock where SQLite's serial writes were relied on
- The whole test suite runs on SQLite and on Postgres
- S3 storage backend with presigned worker uploads, sharing a conformance
  suite with the local backend
- Dockerfile with core, worker and faketelegram targets, docker-compose
  with optional Postgres and local Bot API server, systemd units
- deploy/acceptance/kill-worker.sh: kills a worker mid-job and checks
  that the other one delivers the file
- Fixes found on the way: /cancel could let the next playlist item start;
  a refund note could be missing when the sweep refunded first

Docker was not available on the build machine: the compose files were
validated with "docker compose config" only. The acceptance scenario was
run with real processes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 09:27:11 +00:00

209 lines
5.6 KiB
Go

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()
}