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>
This commit is contained in:
Michilis
2026-11-18 09:27:11 +00:00
co-authored by Claude Fable 5.2
parent 9c9d641eda
commit 7d4893bc3f
51 changed files with 4732 additions and 108 deletions
+175 -22
View File
@@ -1,24 +1,43 @@
package storage
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"sort"
"strings"
"testing"
"time"
"github.com/johannesboyne/gofakes3"
"github.com/johannesboyne/gofakes3/backend/s3mem"
)
func TestLocalRoundTrip(t *testing.T) {
// conformance is the behavior every backend must show. It runs against
// the local disk and against S3.
func conformance(t *testing.T, st Storage) {
t.Helper()
ctx := context.Background()
st, err := NewLocal(t.TempDir())
if err != nil {
key := "jobs/a/media"
if _, _, err := st.Open(ctx, key); !errors.Is(err, ErrNotFound) {
t.Fatalf("Open of a missing key: %v, want ErrNotFound", err)
}
if _, err := st.Stat(ctx, key); !errors.Is(err, ErrNotFound) {
t.Fatalf("Stat of a missing key: %v, want ErrNotFound", err)
}
if err := st.Delete(ctx, key); err != nil {
t.Fatalf("Delete of a missing key must be a no-op: %v", err)
}
if err := st.Put(ctx, key, strings.NewReader("hello"), 5); err != nil {
t.Fatal(err)
}
if err := st.Put(ctx, "jobs/a/media.mp4", strings.NewReader("hello"), 5); err != nil {
t.Fatal(err)
}
rc, size, err := st.Open(ctx, "jobs/a/media.mp4")
rc, size, err := st.Open(ctx, key)
if err != nil {
t.Fatal(err)
}
@@ -27,42 +46,176 @@ func TestLocalRoundTrip(t *testing.T) {
if string(b) != "hello" || size != 5 {
t.Fatalf("got %q size %d", b, size)
}
obj, err := st.Stat(ctx, "jobs/a/media.mp4")
if err != nil || obj.Size != 5 {
obj, err := st.Stat(ctx, key)
if err != nil || obj.Size != 5 || obj.Key != key || time.Since(obj.ModTime) > time.Hour {
t.Fatalf("Stat = %+v, %v", obj, err)
}
// Put replaces, and works without a known size.
if err := st.Put(ctx, key, io.MultiReader(strings.NewReader("new "), strings.NewReader("content")), -1); err != nil {
t.Fatal(err)
}
rc, size, err = st.Open(ctx, key)
if err != nil {
t.Fatal(err)
}
b, _ = io.ReadAll(rc)
rc.Close()
if string(b) != "new content" || size != 11 {
t.Fatalf("after replace got %q size %d", b, size)
}
for _, k := range []string{"jobs/b/media", "cache/x"} {
if err := st.Put(ctx, k, strings.NewReader("x"), 1); err != nil {
t.Fatal(err)
}
}
var keys []string
if err := st.List(ctx, "jobs/", func(o Object) error { keys = append(keys, o.Key); return nil }); err != nil {
t.Fatal(err)
}
if len(keys) != 1 || keys[0] != "jobs/a/media.mp4" {
t.Fatalf("List = %v", keys)
sort.Strings(keys)
if strings.Join(keys, ",") != "jobs/a/media,jobs/b/media" {
t.Fatalf("List(jobs/) = %v", keys)
}
stop := errors.New("stop")
if err := st.List(ctx, "", func(Object) error { return stop }); !errors.Is(err, stop) {
t.Fatalf("List must pass the callback's error on: %v", err)
}
if err := st.Delete(ctx, "jobs/a/media.mp4"); err != nil {
if err := st.Delete(ctx, key); err != nil {
t.Fatal(err)
}
if _, _, err := st.Open(ctx, "jobs/a/media.mp4"); !errors.Is(err, ErrNotFound) {
if _, _, err := st.Open(ctx, key); !errors.Is(err, ErrNotFound) {
t.Fatalf("Open after delete: %v", err)
}
if err := st.Delete(ctx, "jobs/a/media.mp4"); err != nil {
t.Fatalf("second delete should be a no-op: %v", err)
}
if _, err := os.Stat(st.root + "/jobs"); !os.IsNotExist(err) {
t.Fatalf("empty parent directories should be removed")
for _, bad := range []string{"", "/abs", "../x", "a/../../x"} {
if err := st.Put(ctx, bad, strings.NewReader("x"), 1); err == nil {
t.Errorf("Put(%q) should fail", bad)
}
}
}
func TestLocalRejectsEscapingKeys(t *testing.T) {
ctx := context.Background()
func TestLocalConformance(t *testing.T) {
st, err := NewLocal(t.TempDir())
if err != nil {
t.Fatal(err)
}
for _, key := range []string{"", "/abs", "../x", "a/../../x", "a//b", "a/./b", `a\b`} {
if err := st.Put(ctx, key, strings.NewReader("x"), 1); err == nil {
conformance(t, st)
// Local specifics: empty parent directories are removed, and keys
// cannot be used to walk out of the root.
if _, err := os.Stat(st.root + "/jobs/a"); !os.IsNotExist(err) {
t.Fatal("empty parent directories should be removed")
}
for _, key := range []string{"a//b", "a/./b", `a\b`} {
if err := st.Put(context.Background(), key, strings.NewReader("x"), 1); err == nil {
t.Errorf("Put(%q) should fail", key)
}
}
if _, ok := Storage(st).(Presigner); ok {
t.Fatal("local storage has no presigned URLs")
}
}
// fakeS3 starts an in-memory S3 server with one bucket.
func fakeS3(t *testing.T, bucket string) string {
t.Helper()
backend := s3mem.New()
if err := backend.CreateBucket(bucket); err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(gofakes3.New(backend).Server())
t.Cleanup(srv.Close)
return srv.URL
}
func TestS3Conformance(t *testing.T) {
endpoint := fakeS3(t, "dlbot")
for _, prefix := range []string{"", "tenant-a"} {
st, err := NewS3(context.Background(), S3Config{
Endpoint: endpoint, Bucket: "dlbot", AccessKey: "k", SecretKey: "s", Region: "us-east-1",
PathStyle: true, Prefix: prefix, Presign: true,
})
if err != nil {
t.Fatal(err)
}
conformance(t, st)
}
}
func TestS3PresignedURLs(t *testing.T) {
endpoint := fakeS3(t, "dlbot")
ctx := context.Background()
st, err := NewS3(ctx, S3Config{
Endpoint: endpoint, Bucket: "dlbot", AccessKey: "k", SecretKey: "s", Region: "us-east-1",
PathStyle: true, Prefix: "p", Presign: true,
})
if err != nil {
t.Fatal(err)
}
putURL, err := st.PresignPut(ctx, "jobs/z/media", time.Minute)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(putURL, "/dlbot/p/jobs/z/media") || !strings.Contains(putURL, "X-Amz-Signature=") {
t.Fatalf("presigned PUT url = %s", putURL)
}
// A worker uploads with nothing but the URL: no keys, no bearer token.
req, _ := http.NewRequest(http.MethodPut, putURL, bytes.NewReader([]byte("from a worker")))
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("presigned PUT answered %d", resp.StatusCode)
}
obj, err := st.Stat(ctx, "jobs/z/media")
if err != nil || obj.Size != 13 {
t.Fatalf("object after presigned PUT = %+v, %v", obj, err)
}
getURL, err := st.PresignGet(ctx, "jobs/z/media", time.Minute)
if err != nil {
t.Fatal(err)
}
resp, err = http.Get(getURL)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if string(body) != "from a worker" {
t.Fatalf("presigned GET returned %q", body)
}
// Presigning can be off, and a separate endpoint can be used for it.
off, _ := NewS3(ctx, S3Config{Endpoint: endpoint, Bucket: "dlbot", AccessKey: "k", SecretKey: "s", PathStyle: true})
if _, err := off.PresignPut(ctx, "k", time.Minute); err == nil || off.Presigning() {
t.Fatal("presigning should be off by default")
}
pub, err := NewS3(ctx, S3Config{
Endpoint: endpoint, Bucket: "dlbot", AccessKey: "k", SecretKey: "s", Region: "us-east-1", PathStyle: true,
Presign: true, PresignEndpoint: "https://files.example.com",
})
if err != nil {
t.Fatal(err)
}
if u, _ := pub.PresignGet(ctx, "k", time.Minute); !strings.HasPrefix(u, "https://files.example.com/dlbot/k?") {
t.Fatalf("presign endpoint not used: %s", u)
}
}
func TestS3ReportsMissingBucketAndBadConfig(t *testing.T) {
endpoint := fakeS3(t, "dlbot")
ctx := context.Background()
if _, err := NewS3(ctx, S3Config{Endpoint: endpoint, Bucket: "nope", AccessKey: "k", SecretKey: "s", PathStyle: true}); err == nil ||
!strings.Contains(err.Error(), "does not exist") {
t.Fatalf("missing bucket: %v", err)
}
if _, err := NewS3(ctx, S3Config{Bucket: "dlbot"}); err == nil {
t.Fatal("an empty endpoint must be rejected")
}
if _, err := NewS3(ctx, S3Config{Endpoint: endpoint}); err == nil {
t.Fatal("an empty bucket must be rejected")
}
}
+247
View File
@@ -0,0 +1,247 @@
package storage
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
// S3Config describes an S3 compatible bucket (AWS S3, Garage, MinIO, ...).
type S3Config struct {
// Endpoint is host:port, or a URL whose scheme decides TLS.
Endpoint string
Region string
Bucket string
AccessKey string
SecretKey string
// UseSSL is used when Endpoint has no scheme.
UseSSL bool
// PathStyle addresses the bucket as /bucket/key instead of as a
// subdomain. Garage and MinIO need it.
PathStyle bool
// Prefix is put in front of every key, to share a bucket.
Prefix string
// Presign turns on presigned URLs, so workers send files straight to
// the bucket instead of through the core.
Presign bool
// PresignEndpoint is the endpoint workers reach the bucket at, when it
// differs from the one the core uses (for example a public hostname
// versus a private network address). Empty means Endpoint.
PresignEndpoint string
}
// S3 stores files in an S3 compatible bucket.
type S3 struct {
client *minio.Client
signer *minio.Client
bucket string
prefix string
presign bool
}
var _ Storage = (*S3)(nil)
func newS3Client(cfg S3Config, endpoint string) (*minio.Client, error) {
secure := cfg.UseSSL
if u, err := url.Parse(endpoint); err == nil && u.Scheme != "" && u.Host != "" {
secure = u.Scheme == "https"
endpoint = u.Host
}
lookup := minio.BucketLookupAuto
if cfg.PathStyle {
lookup = minio.BucketLookupPath
}
return minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
Secure: secure,
Region: cfg.Region,
BucketLookup: lookup,
})
}
// NewS3 connects to the bucket and checks that it is reachable.
func NewS3(ctx context.Context, cfg S3Config) (*S3, error) {
if cfg.Endpoint == "" || cfg.Bucket == "" {
return nil, errors.New("storage: s3 needs an endpoint and a bucket")
}
client, err := newS3Client(cfg, cfg.Endpoint)
if err != nil {
return nil, fmt.Errorf("storage: s3: %w", err)
}
s := &S3{
client: client, signer: client, bucket: cfg.Bucket, presign: cfg.Presign,
prefix: strings.Trim(cfg.Prefix, "/"),
}
if s.prefix != "" {
s.prefix += "/"
}
if cfg.PresignEndpoint != "" {
if s.signer, err = newS3Client(cfg, cfg.PresignEndpoint); err != nil {
return nil, fmt.Errorf("storage: s3 presign endpoint: %w", err)
}
}
cctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
ok, err := client.BucketExists(cctx, cfg.Bucket)
if err != nil {
return nil, fmt.Errorf("storage: s3 bucket %q: %w", cfg.Bucket, err)
}
if !ok {
return nil, fmt.Errorf("storage: s3 bucket %q does not exist", cfg.Bucket)
}
return s, nil
}
func (s *S3) key(key string) (string, error) {
if key == "" || strings.HasPrefix(key, "/") || strings.Contains(key, "..") || strings.ContainsRune(key, 0) {
return "", fmt.Errorf("storage: bad key %q", key)
}
return s.prefix + key, nil
}
func notFoundS3(err error) error {
if err == nil {
return nil
}
resp := minio.ToErrorResponse(err)
if resp.StatusCode == http.StatusNotFound || resp.Code == "NoSuchKey" || resp.Code == "NotFound" {
return ErrNotFound
}
return err
}
// Put implements Storage. The body is streamed; an unknown size (-1) makes
// the client upload in parts.
func (s *S3) Put(ctx context.Context, key string, r io.Reader, size int64) error {
k, err := s.key(key)
if err != nil {
return err
}
if size < 0 {
// Without a size the client would use a chunked streaming upload,
// which not every S3 compatible server understands. Spooling to a
// temp file first costs local disk and gives a plain upload that
// works everywhere. Callers normally know the size.
tmp, err := os.CreateTemp("", "dlbot-s3-*")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
defer tmp.Close()
if size, err = io.Copy(tmp, r); err != nil {
return err
}
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
return err
}
r = tmp
}
_, err = s.client.PutObject(ctx, s.bucket, k, r, size, minio.PutObjectOptions{ContentType: "application/octet-stream"})
return err
}
// Open implements Storage.
func (s *S3) Open(ctx context.Context, key string) (io.ReadCloser, int64, error) {
k, err := s.key(key)
if err != nil {
return nil, 0, err
}
obj, err := s.client.GetObject(ctx, s.bucket, k, minio.GetObjectOptions{})
if err != nil {
return nil, 0, notFoundS3(err)
}
st, err := obj.Stat()
if err != nil {
obj.Close()
return nil, 0, notFoundS3(err)
}
return obj, st.Size, nil
}
// Stat implements Storage.
func (s *S3) Stat(ctx context.Context, key string) (Object, error) {
k, err := s.key(key)
if err != nil {
return Object{}, err
}
st, err := s.client.StatObject(ctx, s.bucket, k, minio.StatObjectOptions{})
if err != nil {
return Object{}, notFoundS3(err)
}
return Object{Key: key, Size: st.Size, ModTime: st.LastModified}, nil
}
// Delete implements Storage.
func (s *S3) Delete(ctx context.Context, key string) error {
k, err := s.key(key)
if err != nil {
return err
}
if err := s.client.RemoveObject(ctx, s.bucket, k, minio.RemoveObjectOptions{}); err != nil {
if errors.Is(notFoundS3(err), ErrNotFound) {
return nil
}
return err
}
return nil
}
// List implements Storage.
func (s *S3) List(ctx context.Context, prefix string, fn func(Object) error) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
for info := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: s.prefix + prefix, Recursive: true}) {
if info.Err != nil {
return info.Err
}
if err := fn(Object{Key: strings.TrimPrefix(info.Key, s.prefix), Size: info.Size, ModTime: info.LastModified}); err != nil {
return err
}
}
return nil
}
// Presigning reports whether presigned URLs are turned on. The worker API
// asks before it hands URLs to workers.
func (s *S3) Presigning() bool { return s.presign }
// PresignPut implements Presigner.
func (s *S3) PresignPut(ctx context.Context, key string, ttl time.Duration) (string, error) {
if !s.presign {
return "", errors.New("storage: presigned urls are off")
}
k, err := s.key(key)
if err != nil {
return "", err
}
u, err := s.signer.PresignedPutObject(ctx, s.bucket, k, ttl)
if err != nil {
return "", err
}
return u.String(), nil
}
// PresignGet implements Presigner.
func (s *S3) PresignGet(ctx context.Context, key string, ttl time.Duration) (string, error) {
if !s.presign {
return "", errors.New("storage: presigned urls are off")
}
k, err := s.key(key)
if err != nil {
return "", err
}
u, err := s.signer.PresignedGetObject(ctx, s.bucket, k, ttl, nil)
if err != nil {
return "", err
}
return u.String(), nil
}
+10
View File
@@ -34,3 +34,13 @@ type Storage interface {
// List calls fn for every object whose key starts with prefix.
List(ctx context.Context, prefix string, fn func(Object) error) error
}
// Presigner is implemented by backends that can hand out time-limited
// URLs, so a worker or a browser can move file bytes directly to and from
// storage without passing through the core.
type Presigner interface {
// PresignPut returns a URL that accepts one HTTP PUT of the object.
PresignPut(ctx context.Context, key string, ttl time.Duration) (string, error)
// PresignGet returns a URL that serves the object to HTTP GET.
PresignGet(ctx context.Context, key string, ttl time.Duration) (string, error)
}