Files
Media-download-telegram-bot/internal/storage/local_test.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

222 lines
6.5 KiB
Go

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"
)
// 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()
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)
}
rc, size, err := st.Open(ctx, key)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(rc)
rc.Close()
if string(b) != "hello" || size != 5 {
t.Fatalf("got %q size %d", b, size)
}
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)
}
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, key); err != nil {
t.Fatal(err)
}
if _, _, err := st.Open(ctx, key); !errors.Is(err, ErrNotFound) {
t.Fatalf("Open after delete: %v", err)
}
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 TestLocalConformance(t *testing.T) {
st, err := NewLocal(t.TempDir())
if err != nil {
t.Fatal(err)
}
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")
}
}