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>
356 lines
11 KiB
Go
356 lines
11 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/noderunners/dlbot/internal/db"
|
|
"github.com/noderunners/dlbot/internal/probe"
|
|
"github.com/noderunners/dlbot/internal/sched"
|
|
"github.com/noderunners/dlbot/internal/storage"
|
|
"github.com/noderunners/dlbot/internal/workerproto"
|
|
)
|
|
|
|
// WorkerAPI is the pull protocol for remote workers. Workers call in; the
|
|
// core never connects out to a worker, so workers need no inbound ports.
|
|
//
|
|
// POST /worker/v1/claim take a job or a probe task (long poll)
|
|
// POST /worker/v1/heartbeat extend the lease, report progress
|
|
// POST /worker/v1/complete report a stored result
|
|
// POST /worker/v1/fail report a failure
|
|
// PUT /worker/v1/upload/{job} send the result file (local storage)
|
|
// GET /worker/v1/source/{job} fetch a derive job's source file
|
|
// POST /worker/v1/probe answer a probe task
|
|
//
|
|
// Every call carries "Authorization: Bearer <token>". A token belongs to
|
|
// one worker, is stored as a hash, and can be revoked. It grants exactly
|
|
// these calls and only for the worker's own jobs.
|
|
type WorkerAPI struct {
|
|
Store *db.Store
|
|
Sched *sched.Scheduler
|
|
Storage storage.Storage
|
|
Broker *probe.Broker
|
|
Log *slog.Logger
|
|
// PresignTTL is how long presigned upload and source URLs are valid.
|
|
PresignTTL time.Duration
|
|
// MaxWait caps how long a claim is held open.
|
|
MaxWait time.Duration
|
|
}
|
|
|
|
// NewWorkerToken returns a random bearer token and the hash to store.
|
|
func NewWorkerToken() (token, hash string) {
|
|
var raw [32]byte
|
|
if _, err := rand.Read(raw[:]); err != nil {
|
|
panic("api: no entropy: " + err.Error())
|
|
}
|
|
token = "dlw_" + hex.EncodeToString(raw[:])
|
|
return token, HashWorkerToken(token)
|
|
}
|
|
|
|
// HashWorkerToken returns the stored form of a token.
|
|
func HashWorkerToken(token string) string {
|
|
sum := sha256.Sum256([]byte(token))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
// RegisterWorkerAPI adds the worker routes to the server.
|
|
func (s *Server) RegisterWorkerAPI(w *WorkerAPI) {
|
|
if w.Log == nil {
|
|
w.Log = s.log
|
|
}
|
|
if w.MaxWait <= 0 {
|
|
w.MaxWait = 25 * time.Second
|
|
}
|
|
if w.PresignTTL <= 0 {
|
|
w.PresignTTL = time.Hour
|
|
}
|
|
s.mux.HandleFunc("POST /worker/v1/claim", w.auth(w.claim))
|
|
s.mux.HandleFunc("POST /worker/v1/heartbeat", w.auth(w.heartbeat))
|
|
s.mux.HandleFunc("POST /worker/v1/complete", w.auth(w.complete))
|
|
s.mux.HandleFunc("POST /worker/v1/fail", w.auth(w.fail))
|
|
s.mux.HandleFunc("PUT /worker/v1/upload/{job}", w.auth(w.upload))
|
|
s.mux.HandleFunc("GET /worker/v1/source/{job}", w.auth(w.source))
|
|
s.mux.HandleFunc("POST /worker/v1/probe", w.auth(w.probeResult))
|
|
}
|
|
|
|
type workerHandler func(rw http.ResponseWriter, r *http.Request, wk *db.Worker)
|
|
|
|
// auth resolves the bearer token to a worker. Unknown and revoked tokens
|
|
// get the same 401, so a revoked worker learns nothing more than "no".
|
|
func (a *WorkerAPI) auth(next workerHandler) http.HandlerFunc {
|
|
return func(rw http.ResponseWriter, r *http.Request) {
|
|
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
|
if !ok || token == "" {
|
|
writeError(rw, http.StatusUnauthorized, "missing bearer token")
|
|
return
|
|
}
|
|
hash := HashWorkerToken(strings.TrimSpace(token))
|
|
wk, err := a.Store.WorkerByToken(r.Context(), hash)
|
|
if err != nil || wk.Revoked || subtle.ConstantTimeCompare([]byte(wk.TokenHash), []byte(hash)) != 1 {
|
|
writeError(rw, http.StatusUnauthorized, "invalid token")
|
|
return
|
|
}
|
|
next(rw, r, wk)
|
|
}
|
|
}
|
|
|
|
func writeError(rw http.ResponseWriter, code int, msg string) {
|
|
rw.Header().Set("Content-Type", "application/json")
|
|
rw.WriteHeader(code)
|
|
_ = json.NewEncoder(rw).Encode(map[string]string{"error": msg})
|
|
}
|
|
|
|
func writeJSON(rw http.ResponseWriter, v any) {
|
|
rw.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(rw).Encode(v)
|
|
}
|
|
|
|
func readJSON(r *http.Request, v any) error {
|
|
return json.NewDecoder(io.LimitReader(r.Body, 8<<20)).Decode(v)
|
|
}
|
|
|
|
// normalizeTags lower-cases, de-duplicates and sorts tags.
|
|
func normalizeTags(tags []string) []string {
|
|
seen := map[string]bool{}
|
|
var out []string
|
|
for _, t := range tags {
|
|
t = strings.ToLower(strings.TrimSpace(t))
|
|
if t != "" && !seen[t] && !strings.Contains(t, ",") {
|
|
seen[t] = true
|
|
out = append(out, t)
|
|
}
|
|
}
|
|
sort.Strings(out)
|
|
return out
|
|
}
|
|
|
|
func (a *WorkerAPI) claim(rw http.ResponseWriter, r *http.Request, wk *db.Worker) {
|
|
var req workerproto.ClaimRequest
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeError(rw, http.StatusBadRequest, "bad json")
|
|
return
|
|
}
|
|
// The identity comes from the token, never from the body.
|
|
req.WorkerID = wk.ID
|
|
req.Tags = normalizeTags(req.Tags)
|
|
ctx := r.Context()
|
|
if err := a.Store.TouchWorker(ctx, wk.ID, strings.Join(req.Tags, ","), req.Capacity, req.Version, db.NowMilli()); err != nil {
|
|
a.Log.Error("touch worker", "worker_id", wk.ID, "err", err)
|
|
}
|
|
a.Sched.Seen(wk.ID, req.Capacity)
|
|
resp := workerproto.ClaimResponse{Commands: a.Sched.TakeCommands(wk.ID)}
|
|
|
|
// A draining worker finishes what it has and is given nothing new.
|
|
if wk.Draining {
|
|
writeJSON(rw, resp)
|
|
return
|
|
}
|
|
wait := time.Duration(req.WaitSeconds) * time.Second
|
|
if wait > a.MaxWait {
|
|
wait = a.MaxWait
|
|
}
|
|
deadline := time.Now().Add(wait)
|
|
for {
|
|
if req.ProbeOnly {
|
|
if a.Broker != nil {
|
|
resp.Probe = a.Broker.Take(req.Tags)
|
|
}
|
|
} else {
|
|
job, err := a.Sched.Claim(ctx, req)
|
|
if err != nil {
|
|
a.Log.Error("claim", "worker_id", wk.ID, "err", err)
|
|
writeError(rw, http.StatusInternalServerError, "claim failed")
|
|
return
|
|
}
|
|
if job != nil {
|
|
a.presign(ctx, job)
|
|
resp.Job = job
|
|
}
|
|
}
|
|
left := time.Until(deadline)
|
|
if resp.Job != nil || resp.Probe != nil || len(resp.Commands) > 0 || left <= 0 || ctx.Err() != nil {
|
|
writeJSON(rw, resp)
|
|
return
|
|
}
|
|
a.Sched.WaitWork(ctx, left)
|
|
}
|
|
}
|
|
|
|
// presign adds direct storage URLs to a job when the backend can make
|
|
// them, so the file bytes go straight to storage and not through the core.
|
|
func (a *WorkerAPI) presign(ctx context.Context, job *workerproto.Job) {
|
|
ps, ok := a.Storage.(storage.Presigner)
|
|
if !ok {
|
|
return
|
|
}
|
|
if sw, ok := a.Storage.(interface{ Presigning() bool }); ok && !sw.Presigning() {
|
|
return
|
|
}
|
|
if u, err := ps.PresignPut(ctx, job.UploadKey, a.PresignTTL); err == nil {
|
|
job.UploadURL = u
|
|
} else {
|
|
a.Log.Warn("presign upload", "job_id", job.ID, "err", err)
|
|
}
|
|
if job.SourceKey != "" {
|
|
if u, err := ps.PresignGet(ctx, job.SourceKey, a.PresignTTL); err == nil {
|
|
job.SourceURL = u
|
|
} else {
|
|
a.Log.Warn("presign source", "job_id", job.ID, "err", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// leaseStatus maps scheduler errors to HTTP: 409 tells a worker that the
|
|
// job is no longer its own and must be dropped.
|
|
func leaseStatus(rw http.ResponseWriter, err error) bool {
|
|
switch {
|
|
case err == nil:
|
|
return true
|
|
case errors.Is(err, sched.ErrLeaseLost), errors.Is(err, db.ErrNotFound):
|
|
writeError(rw, http.StatusConflict, "lease lost")
|
|
default:
|
|
writeError(rw, http.StatusInternalServerError, "internal error")
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (a *WorkerAPI) heartbeat(rw http.ResponseWriter, r *http.Request, wk *db.Worker) {
|
|
var req workerproto.HeartbeatRequest
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeError(rw, http.StatusBadRequest, "bad json")
|
|
return
|
|
}
|
|
req.WorkerID = wk.ID
|
|
resp, err := a.Sched.Heartbeat(r.Context(), req)
|
|
if leaseStatus(rw, err) {
|
|
writeJSON(rw, resp)
|
|
}
|
|
}
|
|
|
|
func (a *WorkerAPI) complete(rw http.ResponseWriter, r *http.Request, wk *db.Worker) {
|
|
var req workerproto.CompleteRequest
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeError(rw, http.StatusBadRequest, "bad json")
|
|
return
|
|
}
|
|
req.WorkerID = wk.ID
|
|
// The storage key is fixed by the core. A worker cannot point a job at
|
|
// somebody else's file.
|
|
req.StorageKey = sched.UploadKey(req.JobID)
|
|
if _, err := a.Storage.Stat(r.Context(), req.StorageKey); err != nil {
|
|
writeError(rw, http.StatusUnprocessableEntity, "the result was not uploaded")
|
|
return
|
|
}
|
|
if leaseStatus(rw, a.Sched.Complete(r.Context(), req)) {
|
|
writeJSON(rw, map[string]bool{"ok": true})
|
|
}
|
|
}
|
|
|
|
func (a *WorkerAPI) fail(rw http.ResponseWriter, r *http.Request, wk *db.Worker) {
|
|
var req workerproto.FailRequest
|
|
if err := readJSON(r, &req); err != nil {
|
|
writeError(rw, http.StatusBadRequest, "bad json")
|
|
return
|
|
}
|
|
req.WorkerID = wk.ID
|
|
if len(req.Detail) > 2000 {
|
|
req.Detail = req.Detail[:2000]
|
|
}
|
|
if leaseStatus(rw, a.Sched.Fail(r.Context(), req)) {
|
|
writeJSON(rw, map[string]bool{"ok": true})
|
|
}
|
|
}
|
|
|
|
// ownsJob checks that a job is running and leased to this worker.
|
|
func (a *WorkerAPI) ownsJob(ctx context.Context, jobID string, wk *db.Worker) (*db.Job, bool) {
|
|
job, err := a.Store.GetJob(ctx, jobID)
|
|
if err != nil || job.Status != db.JobRunning || job.WorkerID != wk.ID {
|
|
return nil, false
|
|
}
|
|
return job, true
|
|
}
|
|
|
|
// upload streams the result of a job into storage. It is used when the
|
|
// storage backend cannot hand out presigned URLs (local disk).
|
|
func (a *WorkerAPI) upload(rw http.ResponseWriter, r *http.Request, wk *db.Worker) {
|
|
job, ok := a.ownsJob(r.Context(), r.PathValue("job"), wk)
|
|
if !ok {
|
|
writeError(rw, http.StatusConflict, "lease lost")
|
|
return
|
|
}
|
|
body := io.Reader(r.Body)
|
|
if job.MaxSize > 0 {
|
|
// One byte over the cap is enough to know the file is too large.
|
|
body = io.LimitReader(r.Body, job.MaxSize+1)
|
|
}
|
|
counted := &countingReader{r: body}
|
|
if err := a.Storage.Put(r.Context(), sched.UploadKey(job.ID), counted, r.ContentLength); err != nil {
|
|
a.Log.Error("store upload", "job_id", job.ID, "worker_id", wk.ID, "err", err)
|
|
writeError(rw, http.StatusInternalServerError, "upload failed")
|
|
return
|
|
}
|
|
if job.MaxSize > 0 && counted.n > job.MaxSize {
|
|
_ = a.Storage.Delete(context.WithoutCancel(r.Context()), sched.UploadKey(job.ID))
|
|
writeError(rw, http.StatusRequestEntityTooLarge, "file is over the job's size cap")
|
|
return
|
|
}
|
|
writeJSON(rw, map[string]int64{"size": counted.n})
|
|
}
|
|
|
|
// source streams the stored file a derive job transcodes from.
|
|
func (a *WorkerAPI) source(rw http.ResponseWriter, r *http.Request, wk *db.Worker) {
|
|
job, ok := a.ownsJob(r.Context(), r.PathValue("job"), wk)
|
|
if !ok || job.SourceKey == "" {
|
|
writeError(rw, http.StatusConflict, "lease lost")
|
|
return
|
|
}
|
|
rc, size, err := a.Storage.Open(r.Context(), job.SourceKey)
|
|
if err != nil {
|
|
writeError(rw, http.StatusNotFound, "source is gone")
|
|
return
|
|
}
|
|
defer rc.Close()
|
|
rw.Header().Set("Content-Type", "application/octet-stream")
|
|
if size > 0 {
|
|
rw.Header().Set("Content-Length", strconv.FormatInt(size, 10))
|
|
}
|
|
_, _ = io.Copy(rw, rc)
|
|
}
|
|
|
|
func (a *WorkerAPI) probeResult(rw http.ResponseWriter, r *http.Request, wk *db.Worker) {
|
|
var res workerproto.ProbeResult
|
|
if err := readJSON(r, &res); err != nil {
|
|
writeError(rw, http.StatusBadRequest, "bad json")
|
|
return
|
|
}
|
|
res.WorkerID = wk.ID
|
|
if a.Broker == nil || a.Broker.Resolve(&res) != nil {
|
|
writeError(rw, http.StatusGone, "nobody waits for this probe anymore")
|
|
return
|
|
}
|
|
writeJSON(rw, map[string]bool{"ok": true})
|
|
}
|
|
|
|
type countingReader struct {
|
|
r io.Reader
|
|
n int64
|
|
}
|
|
|
|
func (c *countingReader) Read(p []byte) (int, error) {
|
|
n, err := c.r.Read(p)
|
|
c.n += int64(n)
|
|
return n, err
|
|
}
|