Files
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

248 lines
6.7 KiB
Go

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
}