carlos / platform Public

media: handler download with resume and the grant window

internal/mediahandler: Config, Run, jobError, errGrantExpired and
download. The source streams to <scratch>/in/source with the signed
If-Match exactly, Accept-Encoding: identity (F20) and no redirect,
counted against the byte cap; a broken connection resumes with Range
after min(2^n s, 10 s), at most 20 times, and must answer 206 from the
bytes written. 404, 412 and 403 map to their codes; a 403 at or after
the expiry, or any attempt that would begin then, is errGrantExpired and
Run exits 75 with no result. Errors and logs never carry a URL, query,
header or payload (F6). Retry waits are a ctx timer (F22).

cmd/carlos-media: codec reads and unsets CARLOS_MEDIA_JOB and exits
Run's answer; until Tasks 3-6 a downloaded source still exits 1.

s3test_test.go is an httptest S3 for Tasks 2 and 6. Copy deck: the
engine.codec.* and engine.download.* log lines, pending Luna pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ced769697c409b25a2919488c0ac71b306ce9d2e parent 9b9e95f
7 files changed, +1,812 −8
  • cmd/carlos-media/codec_test.go +48 −0
  • cmd/carlos-media/main.go +31 −6
  • docs/superpowers/notes/media-conversion-copy-deck.md +18 −2
  • internal/mediahandler/download.go +287 −0
  • internal/mediahandler/download_test.go +810 −0
  • internal/mediahandler/handler.go +210 −0
  • internal/mediahandler/s3test_test.go +408 −0
diff --git a/cmd/carlos-media/codec_test.go b/cmd/carlos-media/codec_test.go
new file mode 100644
index 000000000..4dd02b652
--- /dev/null
+++ b/cmd/carlos-media/codec_test.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "bytes"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/mediahandler"
+)
+
+// TestCodecDispatch: "codec" reads media.PayloadEnv, removes it from the
+// environment (so no child inherits the transfers), logs to stderr and
+// answers the handler's exit; with an argument it is refused before it
+// reads anything.
+func TestCodecDispatch(t *testing.T) {
+ scratch := t.TempDir()
+ t.Setenv(mediahandler.ScratchEnv, scratch)
+
+ t.Setenv(media.PayloadEnv, `{"v":2}`)
+ var stdout, stderr bytes.Buffer
+ if code := dispatch([]string{media.CodecCommand}, &stdout, &stderr); code != media.ExitFailed {
+ t.Fatalf("codec with a bad payload = %d, want %d", code, media.ExitFailed)
+ }
+ if _, ok := os.LookupEnv(media.PayloadEnv); ok {
+ t.Error("codec left the payload in its environment")
+ }
+ if stdout.Len() != 0 || !strings.HasPrefix(stderr.String(), "codec: payload refused: ") || strings.Count(stderr.String(), "\n") != 1 {
+ t.Errorf("codec printed %q / %q, want one refusal line on stderr", stdout.String(), stderr.String())
+ }
+ if ents, _ := os.ReadDir(scratch); len(ents) != 0 {
+ t.Errorf("a refused payload touched the scratch: %v", ents)
+ }
+
+ t.Setenv(media.PayloadEnv, `{"v":2}`)
+ stdout.Reset()
+ stderr.Reset()
+ if code := dispatch([]string{media.CodecCommand, "x"}, &stdout, &stderr); code != media.ExitFailed {
+ t.Fatalf("codec with an argument = %d, want %d", code, media.ExitFailed)
+ }
+ if stdout.Len() != 0 || stderr.Len() != 0 {
+ t.Errorf("codec with an argument printed %q / %q", stdout.String(), stderr.String())
+ }
+ if _, ok := os.LookupEnv(media.PayloadEnv); !ok {
+ t.Error("codec with an argument read the payload")
+ }
+}
diff --git a/cmd/carlos-media/main.go b/cmd/carlos-media/main.go
index 3070f6bbf..6312f10ea 100644
--- a/cmd/carlos-media/main.go
+++ b/cmd/carlos-media/main.go
@@ -5,8 +5,8 @@
// - deadline: the task's timer (deadline.go). It reads its two values
// from the environment, media.DeadlineEnv and media.ExpiryEnv, and
// takes no argument.
-// - codec: the conversion handler (plan 3 Task 2), reading
-// media.PayloadEnv.
+// - codec: the conversion handler (internal/mediahandler), reading
+// media.PayloadEnv and taking no argument.
// - selftest, drill: rollout checks (plan 3 Task 7).
// - version: prints the build.
//
@@ -17,6 +17,7 @@
package main
import (
+ "context"
"fmt"
"io"
"os"
@@ -25,6 +26,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/mediahandler"
"github.com/carlosframework/platform/internal/version"
)
@@ -47,10 +49,10 @@ func dispatch(args []string, stdout, stderr io.Writer) int {
switch args[0] {
case media.DeadlineCommand:
return deadlineCommand(args[1:])
- case media.CodecCommand, "selftest", "drill":
- // Filled by plan 3 Task 2 (codec) and Task 7 (selftest, drill).
- // Until then each fails, so no image built from this commit
- // can report a conversion done.
+ case media.CodecCommand:
+ return codecCommand(args[1:], stderr)
+ case "selftest", "drill":
+ // Filled by plan 3 Task 7. Until then each fails.
return media.ExitFailed
case "version":
fmt.Fprintln(stdout, version.Build)
@@ -74,6 +76,29 @@ func deadlineCommand(rest []string) int {
return runDeadline(os.Getenv, time.Now, stop)
}
+// codecCommand is the codec container's entry. It takes no argument
+// (the gate compares the command whole), reads the payload and removes
+// it from the environment, so no child the handler starts inherits the
+// transfers, and answers mediahandler.Run's exit. Log lines go to stderr,
+// the task's log.
+//
+// SIGTERM keeps its default action for now: the process dies and writes
+// no result, which is what ECS stopping the task asks for. Plan 3 Task 6
+// catches it to end the handler's children first.
+func codecCommand(rest []string, stderr io.Writer) int {
+ if len(rest) != 0 {
+ return media.ExitFailed
+ }
+ payload := os.Getenv(media.PayloadEnv)
+ os.Unsetenv(media.PayloadEnv)
+ cfg := mediahandler.Config{Logf: func(format string, args ...any) {
+ fmt.Fprintf(stderr, format+"\n", args...)
+ }}
+ // Background: the task's own end (the deadline container, or ECS
+ // stopping it) is what bounds the run; nothing above this cancels.
+ return mediahandler.Run(context.Background(), cfg, payload)
+}
+
// signalsReady runs once SIGTERM is caught. It does nothing in the
// binary; TestDeadlineSIGTERMProcess's child sets it to tell the parent
// when a SIGTERM will reach runDeadline rather than kill the process.
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index 0f5878428..c79bc9bfb 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -525,9 +525,25 @@ carries them yet (plan 3 writes it); the pack's price is left out.
## The engine binary (plan 3)
Operator-facing text from `cmd/carlos-media`, the engine image's one
-binary; it reaches a task's log only when the binary is started wrongly.
-The `deadline` command prints nothing.
+binary. The usage line reaches a task's log only when the binary is
+started wrongly; the `codec` lines are the task's log, and never carry a
+URL, a header, a credential or the payload. The `deadline` command
+prints nothing.
| Key | Text |
|---|---|
| `engine.usage` | `usage: carlos-media <deadline\|codec\|selftest\|drill\|version>` (pending Luna pass; plan 3 Task 1) |
+| `engine.codec.payload_refused` | `codec: payload refused: %s` (pending Luna pass; plan 3 Task 2). `%s` is one of `engine.codec.payload.*` or the payload's own shape check (`internal/media` `Payload.Validate`), never a value from the payload |
+| `engine.codec.payload.none` | `no payload` (pending Luna pass; plan 3 Task 2) |
+| `engine.codec.payload.too_long` | `payload is over the override limit` (pending Luna pass; plan 3 Task 2) |
+| `engine.codec.payload.undecodable` | `payload does not decode as a payload` (pending Luna pass; plan 3 Task 2) |
+| `engine.codec.payload.trailing` | `payload has data after the object` (pending Luna pass; plan 3 Task 2) |
+| `engine.codec.payload.no_cap` | `payload has no source byte cap` (pending Luna pass; plan 3 Task 2) |
+| `engine.codec.payload.no_expiry` | `payload has no grant expiry` (pending Luna pass; plan 3 Task 2) |
+| `engine.codec.scratch` | `codec: scratch directory unusable: %s` (pending Luna pass; plan 3 Task 2). `%s` is the system's error for a path under the scratch directory |
+| `engine.codec.grant_expired` | `codec: the grant has expired; no result is written` (pending Luna pass; plan 3 Task 2) |
+| `engine.codec.failed` | `codec: failed: %s` (pending Luna pass; plan 3 Task 2). `%s` is the job error code |
+| `engine.codec.not_built` | `codec: source downloaded; conversion is not built in this image` (pending Luna pass; plan 3 Task 2; removed when Task 6 lands) |
+| `engine.codec.stopped` | `codec: stopped: %s` (pending Luna pass; plan 3 Task 2). `%s` is Go's context error |
+| `engine.download.resume` | `source download: broke after %d bytes; resume %d of %d` (pending Luna pass; plan 3 Task 2) |
+| `engine.download.gave_up` | `source download: broke %d times; giving up` (pending Luna pass; plan 3 Task 2) |
diff --git a/internal/mediahandler/download.go b/internal/mediahandler/download.go
new file mode 100644
index 000000000..39c764b93
--- /dev/null
+++ b/internal/mediahandler/download.go
@@ -0,0 +1,287 @@
+package mediahandler
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// maxResumes is how many times one download may resume (spec §6 and plan
+// 3's Global Constraints: at most 20).
+const maxResumes = 20
+
+// maxResumeDelay caps the wait before a resume.
+const maxResumeDelay = 10 * time.Second
+
+// readChunk is the size of one read from the body.
+const readChunk = 256 << 10
+
+// The default client's bounds (AGENTS.md: network calls carry a
+// deadline). There is no whole-request timeout: a source is up to the
+// preset's byte cap, and the deadline container bounds the run.
+const (
+ dialTimeout = 30 * time.Second
+ tlsHandshakeTimeout = 15 * time.Second
+ responseHeaderTimeout = time.Minute
+)
+
+// defaultHTTPClient is the client a Config gets when it names none. It
+// never asks for compression (preflight F20: Go's transport would ask for
+// gzip and inflate a gzip-encoded object, so the bytes on disk would not
+// be the stored bytes the cap and Range offsets count), takes no proxy
+// from the environment (a proxy would see every signed URL), and follows
+// no redirect.
+func defaultHTTPClient() *http.Client {
+ return &http.Client{
+ Transport: &http.Transport{
+ Proxy: nil,
+ DialContext: (&net.Dialer{Timeout: dialTimeout, KeepAlive: 30 * time.Second}).DialContext,
+ TLSHandshakeTimeout: tlsHandshakeTimeout,
+ ResponseHeaderTimeout: responseHeaderTimeout,
+ ExpectContinueTimeout: time.Second,
+ IdleConnTimeout: 90 * time.Second,
+ ForceAttemptHTTP2: true,
+ DisableCompression: true,
+ },
+ CheckRedirect: noRedirect,
+ }
+}
+
+// noRedirect makes the client answer a 3xx as it is.
+func noRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+
+// resumeDelay is the wait before resume n (0 for the first):
+// min(2^n s, 10 s).
+func resumeDelay(n int) time.Duration {
+ if n >= 4 {
+ return maxResumeDelay
+ }
+ return min(time.Duration(1<<n)*time.Second, maxResumeDelay)
+}
+
+// waitCtx waits d, or until ctx ends.
+func waitCtx(ctx context.Context, d time.Duration) error {
+ t := time.NewTimer(d)
+ defer t.Stop()
+ select {
+ case <-t.C:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+// download streams the source to dst (which must not exist) with the
+// source transfer: its signed headers exactly, plus Accept-Encoding:
+// identity, and on a resume Range: bytes=<written>-. Rules:
+//
+// - before every attempt, now at or after the expiry is errGrantExpired;
+// no transfer begins after the grant (spec §5.4);
+// - 200 with a Content-Length over the cap is source_too_large before
+// any byte is read; every byte is counted as it streams, and one past
+// the cap is source_too_large;
+// - 404 source_not_found, 412 source_changed; 403 at or after the
+// expiry errGrantExpired, before it source_unreadable; 500, 502, 503
+// and 504 are retried as a broken connection; any other status is
+// source_unreadable;
+// - a broken connection or body resumes after resumeDelay, under the
+// same If-Match; a resume must answer 206 from the byte asked for,
+// else unreadable; past maxResumes resumes, unreadable.
+//
+// On any failure dst is removed. ctx's error is returned as it is.
+func download(ctx context.Context, cfg Config, p media.Payload, dst string) (err error) {
+ f, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if err != nil {
+ return jobError{media.CodeEngineFailed}
+ }
+ defer func() {
+ cerr := f.Close()
+ if err == nil && cerr != nil {
+ err = jobError{media.CodeEngineFailed}
+ }
+ if err != nil {
+ os.Remove(dst)
+ }
+ }()
+ d := &fetch{cfg: cfg, p: p, f: f, expiry: time.Unix(p.Expiry, 0), total: -1}
+ for resumes := 0; ; resumes++ {
+ if !cfg.Now().Before(d.expiry) {
+ return errGrantExpired
+ }
+ broken, err := d.attempt(ctx)
+ if err != nil || !broken {
+ return err
+ }
+ if resumes == maxResumes {
+ // engine.download.gave_up (pending Luna pass).
+ cfg.Logf("source download: broke %d times; giving up", maxResumes+1)
+ return jobError{media.CodeUnreadable}
+ }
+ // engine.download.resume (pending Luna pass).
+ cfg.Logf("source download: broke after %d bytes; resume %d of %d", d.written, resumes+1, maxResumes)
+ if err := cfg.wait(ctx, resumeDelay(resumes)); err != nil {
+ return err
+ }
+ }
+}
+
+// fetch is one download's state across its attempts.
+type fetch struct {
+ cfg Config
+ p media.Payload
+ f *os.File
+ expiry time.Time
+ written int64
+ total int64 // the object's size once a response has said it; -1 before
+}
+
+// attempt makes one GET from d.written. broken reports a connection or
+// body that failed in a way a resume may cure; err is a final answer.
+// Neither ever carries the request's URL.
+func (d *fetch) attempt(ctx context.Context) (broken bool, err error) {
+ src := d.p.Transfers.Source
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, d.p.Transfers.URL(src), nil)
+ if err != nil {
+ // url.Parse's error quotes the URL: drop it.
+ return false, jobError{media.CodeEngineFailed}
+ }
+ for k, v := range src.Header {
+ req.Header.Set(k, v)
+ }
+ req.Header.Set("Accept-Encoding", "identity")
+ if d.written > 0 {
+ req.Header.Set("Range", "bytes="+strconv.FormatInt(d.written, 10)+"-")
+ }
+ client := *d.cfg.HTTP
+ client.CheckRedirect = noRedirect
+ resp, err := client.Do(req)
+ if err != nil {
+ // *url.Error quotes the URL; only ctx's own error is passed on.
+ if ctx.Err() != nil {
+ return false, ctx.Err()
+ }
+ return true, nil
+ }
+ defer resp.Body.Close()
+ if err := d.check(resp); err != nil {
+ if errors.Is(err, errRetry) {
+ return true, nil
+ }
+ return false, err
+ }
+ return d.stream(ctx, resp.Body)
+}
+
+// check decides what a response's status and size headers allow.
+func (d *fetch) check(resp *http.Response) error {
+ limit := d.p.Limits.SourceBytes
+ switch resp.StatusCode {
+ case http.StatusOK:
+ if d.written > 0 {
+ // The store ignored the Range: the body would start again.
+ return jobError{media.CodeUnreadable}
+ }
+ if resp.ContentLength > limit {
+ return jobError{media.CodeSourceTooLarge}
+ }
+ d.total = resp.ContentLength
+ return nil
+ case http.StatusPartialContent:
+ // Content-Range must continue from the bytes written, at the size
+ // the store gave before; a 206 to the first GET must start at 0.
+ start, total, ok := contentRange(resp.Header.Get("Content-Range"))
+ if !ok || start != d.written || (d.total >= 0 && total >= 0 && total != d.total) {
+ return jobError{media.CodeUnreadable}
+ }
+ if total > limit {
+ return jobError{media.CodeSourceTooLarge}
+ }
+ if total >= 0 {
+ d.total = total
+ }
+ return nil
+ case http.StatusNotFound:
+ return jobError{media.CodeSourceNotFound}
+ case http.StatusPreconditionFailed:
+ return jobError{media.CodeSourceChanged}
+ case http.StatusForbidden:
+ if !d.cfg.Now().Before(d.expiry) {
+ return errGrantExpired
+ }
+ return jobError{media.CodeSourceUnreadable}
+ case http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
+ return errRetry
+ }
+ return jobError{media.CodeSourceUnreadable}
+}
+
+// errRetry is a status the store answers when it may do better on a
+// retry; attempt turns it into a broken connection.
+var errRetry = errors.New("retry")
+
+// stream copies body to the file, counting every byte against the cap.
+func (d *fetch) stream(ctx context.Context, body io.Reader) (broken bool, err error) {
+ limit := d.p.Limits.SourceBytes
+ buf := make([]byte, readChunk)
+ for {
+ n, rerr := body.Read(buf)
+ if n > 0 {
+ if d.written+int64(n) > limit {
+ return false, jobError{media.CodeSourceTooLarge}
+ }
+ if _, werr := d.f.Write(buf[:n]); werr != nil {
+ return false, jobError{media.CodeEngineFailed}
+ }
+ d.written += int64(n)
+ }
+ switch {
+ case rerr == nil:
+ continue
+ case rerr == io.EOF:
+ if d.total >= 0 && d.written != d.total {
+ return false, jobError{media.CodeUnreadable}
+ }
+ return false, nil
+ case ctx.Err() != nil:
+ return false, ctx.Err()
+ }
+ return true, nil
+ }
+}
+
+// contentRange reads "bytes <start>-<end>/<total>" (total "*" is -1).
+func contentRange(h string) (start, total int64, ok bool) {
+ rest, found := strings.CutPrefix(h, "bytes ")
+ if !found {
+ return 0, 0, false
+ }
+ span, size, found := strings.Cut(rest, "/")
+ if !found {
+ return 0, 0, false
+ }
+ first, last, found := strings.Cut(span, "-")
+ if !found {
+ return 0, 0, false
+ }
+ start, err1 := strconv.ParseInt(first, 10, 64)
+ end, err2 := strconv.ParseInt(last, 10, 64)
+ if err1 != nil || err2 != nil || start < 0 || end < start {
+ return 0, 0, false
+ }
+ if size == "*" {
+ return start, -1, true
+ }
+ total, err := strconv.ParseInt(size, 10, 64)
+ if err != nil || total <= end {
+ return 0, 0, false
+ }
+ return start, total, true
+}
diff --git a/internal/mediahandler/download_test.go b/internal/mediahandler/download_test.go
new file mode 100644
index 000000000..d266719dc
--- /dev/null
+++ b/internal/mediahandler/download_test.go
@@ -0,0 +1,810 @@
+package mediahandler
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/rand"
+ "errors"
+ "fmt"
+ "io/fs"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+const mib = 1 << 20
+
+// harness is a handler Config wired to an s3Server on a shared clock.
+// Its wait records each resume delay and returns at once; onWait, when
+// set, runs inside it.
+type harness struct {
+ s *s3Server
+ clock *testClock
+ cfg Config
+ mu sync.Mutex
+ logs []string
+ delays []time.Duration
+ onWait func()
+}
+
+func newHarness(t *testing.T) *harness {
+ t.Helper()
+ h := &harness{clock: newClock()}
+ h.s = newS3(t, h.clock)
+ h.cfg = Config{
+ Scratch: t.TempDir(),
+ HTTP: h.s.srv.Client(), // compression on: the request must still ask for identity
+ Now: h.clock.Now,
+ Logf: func(format string, args ...any) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ h.logs = append(h.logs, fmt.Sprintf(format, args...))
+ },
+ wait: func(ctx context.Context, d time.Duration) error {
+ h.mu.Lock()
+ h.delays = append(h.delays, d)
+ fn := h.onWait
+ h.mu.Unlock()
+ if fn != nil {
+ fn()
+ }
+ return ctx.Err()
+ },
+ }
+ if err := prepareScratch(h.cfg.Scratch); err != nil {
+ t.Fatal(err)
+ }
+ return h
+}
+
+func (h *harness) Logs() []string {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return append([]string(nil), h.logs...)
+}
+
+func (h *harness) Delays() []time.Duration {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return append([]time.Duration(nil), h.delays...)
+}
+
+// download runs download into <scratch>/in/source with a 20 s limit.
+func (h *harness) download(t *testing.T, p media.Payload) error {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ return download(ctx, h.cfg.withDefaults(), p, sourcePath(h.cfg))
+}
+
+func randomBytes(t *testing.T, n int) []byte {
+ t.Helper()
+ b := make([]byte, n)
+ if _, err := rand.Read(b); err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+func codeOf(err error) string {
+ var je jobError
+ if errors.As(err, &je) {
+ return je.code
+ }
+ if errors.Is(err, errGrantExpired) {
+ return "errGrantExpired"
+ }
+ if err == nil {
+ return "nil"
+ }
+ return "other: " + err.Error()
+}
+
+// wantNoSource fails t if the scratch source file exists.
+func (h *harness) wantNoSource(t *testing.T) {
+ t.Helper()
+ if _, err := os.Lstat(sourcePath(h.cfg)); !errors.Is(err, fs.ErrNotExist) {
+ t.Errorf("scratch source still there after a failed download (%v)", err)
+ }
+}
+
+func (h *harness) wantSource(t *testing.T, data []byte) {
+ t.Helper()
+ got, err := os.ReadFile(sourcePath(h.cfg))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(got, data) {
+ t.Fatalf("source on disk is %d bytes and differs from the %d stored", len(got), len(data))
+ }
+}
+
+func gets(rs []s3Request) []s3Request {
+ var out []s3Request
+ for _, r := range rs {
+ if r.Method == "GET" {
+ out = append(out, r)
+ }
+ }
+ return out
+}
+
+// TestDownloadSendsTheSignedHeaders: the store sees the signed If-Match
+// exactly, Accept-Encoding: identity, Range on a resume, Go's User-Agent
+// and nothing else; no header carries anything from the payload. The
+// query is the presigned one (the server refuses any other).
+func TestDownloadSendsTheSignedHeaders(t *testing.T) {
+ h := newHarness(t)
+ data := randomBytes(t, 3*mib)
+ p := h.s.payload(t, media.PresetVideo720p, data, 8*mib)
+ h.s.Cuts = []int64{mib}
+ if err := h.download(t, p); err != nil {
+ t.Fatalf("download: %s", codeOf(err))
+ }
+ h.wantSource(t, data)
+ h.s.CheckClean(t)
+ rs := h.s.Requests()
+ if len(rs) != 2 {
+ t.Fatalf("%d requests, want 2 (one cut, one resume)", len(rs))
+ }
+ allowed := map[string]bool{"If-Match": true, "Accept-Encoding": true, "User-Agent": true, "Range": true}
+ payloadBits := []string{testExec, media.PresetVideo720p, "uploads", "derived", "media-results", testToken, "X-Amz", "ASIA"}
+ for i, r := range rs {
+ for k, vs := range r.Header {
+ if !allowed[k] {
+ t.Errorf("request %d sent header %s", i, k)
+ }
+ for _, v := range vs {
+ for _, bit := range payloadBits {
+ if strings.Contains(v, bit) {
+ t.Errorf("request %d header %s carries %q from the payload", i, k, bit)
+ }
+ }
+ }
+ }
+ if got := r.Header.Get("If-Match"); got != `"`+testETag+`"` {
+ t.Errorf("request %d If-Match = %q, want the signed value", i, got)
+ }
+ if got := r.Header.Values("Accept-Encoding"); len(got) != 1 || got[0] != "identity" {
+ t.Errorf("request %d Accept-Encoding = %q, want identity (F20)", i, got)
+ }
+ }
+ if rs[0].Header.Get("Range") != "" || rs[1].Header.Get("Range") != fmt.Sprintf("bytes=%d-", mib) {
+ t.Errorf("Range = %q then %q, want none then bytes=%d-", rs[0].Header.Get("Range"), rs[1].Header.Get("Range"), mib)
+ }
+
+ // F20: a gzip-encoded object arrives as the stored bytes, not
+ // inflated, even through a client with compression on.
+ t.Run("gzip object", func(t *testing.T) {
+ h := newHarness(t)
+ var z bytes.Buffer
+ zw := gzip.NewWriter(&z)
+ zw.Write(bytes.Repeat([]byte("carlos media "), 200000))
+ zw.Close()
+ stored := z.Bytes()
+ p := h.s.payload(t, media.PresetVideo720p, nil, int64(len(stored)))
+ h.s.SetSource(stored, testETag, "gzip")
+ if err := h.download(t, p); err != nil {
+ t.Fatalf("download: %s", codeOf(err))
+ }
+ h.wantSource(t, stored)
+ })
+
+ // The handler's own client asks for no compression, takes no proxy
+ // and follows no redirect.
+ t.Run("default client", func(t *testing.T) {
+ c := defaultHTTPClient()
+ tr, ok := c.Transport.(*http.Transport)
+ if !ok || !tr.DisableCompression || tr.Proxy != nil || tr.ResponseHeaderTimeout == 0 || tr.DialContext == nil || tr.TLSHandshakeTimeout == 0 {
+ t.Fatalf("default transport %+v: want DisableCompression, no proxy, header, dial and TLS timeouts", tr)
+ }
+ if c.CheckRedirect == nil || c.CheckRedirect(nil, nil) != http.ErrUseLastResponse {
+ t.Fatal("default client follows redirects")
+ }
+ if (Config{}).withDefaults().HTTP.Transport.(*http.Transport).DisableCompression != true {
+ t.Fatal("Config's default HTTP is not defaultHTTPClient")
+ }
+ })
+
+ // A 3xx is answered as it is, whatever the given client would do.
+ t.Run("no redirect", func(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 1024), mib)
+ h.s.OnGet = func(n int) int { return http.StatusTemporaryRedirect }
+ if err := h.download(t, p); codeOf(err) != media.CodeSourceUnreadable {
+ t.Fatalf("download after a 307 = %s, want source_unreadable", codeOf(err))
+ }
+ if rs := h.s.Requests(); len(rs) != 1 {
+ t.Fatalf("%d requests, want 1: the redirect was followed", len(rs))
+ }
+ h.s.CheckClean(t)
+ h.wantNoSource(t)
+ })
+}
+
+// TestDownloadResumesUnderIfMatch: an 8 MiB source cut at 1 MiB and 5
+// MiB arrives whole; each resume carries If-Match and the Range from the
+// bytes written, after 1 s and then 2 s.
+func TestDownloadResumesUnderIfMatch(t *testing.T) {
+ h := newHarness(t)
+ data := randomBytes(t, 8*mib)
+ p := h.s.payload(t, media.PresetVideo720p, data, 8*mib)
+ h.s.Cuts = []int64{mib, 5 * mib}
+ if err := h.download(t, p); err != nil {
+ t.Fatalf("download: %s", codeOf(err))
+ }
+ h.wantSource(t, data)
+ h.s.CheckClean(t)
+ rs := h.s.Requests()
+ wantRange := []string{"", fmt.Sprintf("bytes=%d-", mib), fmt.Sprintf("bytes=%d-", 5*mib)}
+ wantStatus := []int{200, 206, 206}
+ if len(rs) != len(wantRange) {
+ t.Fatalf("%d requests, want %d", len(rs), len(wantRange))
+ }
+ for i, r := range rs {
+ if r.Header.Get("Range") != wantRange[i] || r.Status != wantStatus[i] {
+ t.Errorf("request %d: Range %q status %d, want %q %d", i, r.Header.Get("Range"), r.Status, wantRange[i], wantStatus[i])
+ }
+ if r.Header.Get("If-Match") != `"`+testETag+`"` {
+ t.Errorf("request %d: no signed If-Match", i)
+ }
+ }
+ if d := h.Delays(); len(d) != 2 || d[0] != time.Second || d[1] != 2*time.Second {
+ t.Errorf("resume delays %v, want [1s 2s]", d)
+ }
+}
+
+// TestDownloadSourceChanged: the object changes between the cut and the
+// resume, so the resume's If-Match answers 412: source_changed, and the
+// partial file is removed.
+func TestDownloadSourceChanged(t *testing.T) {
+ h := newHarness(t)
+ data := randomBytes(t, 2*mib)
+ p := h.s.payload(t, media.PresetVideo720p, data, 8*mib)
+ h.s.Cuts = []int64{mib}
+ h.s.OnGet = func(n int) int {
+ if n == 2 {
+ h.s.SetSource(data, "a-new-etag", "")
+ }
+ return 0
+ }
+ if err := h.download(t, p); codeOf(err) != media.CodeSourceChanged {
+ t.Fatalf("download = %s, want source_changed", codeOf(err))
+ }
+ if rs := h.s.Requests(); len(rs) != 2 || rs[1].Status != http.StatusPreconditionFailed {
+ t.Fatalf("requests %+v, want a cut GET then a 412", rs)
+ }
+ h.wantNoSource(t)
+}
+
+// TestDownloadCapWhileStreaming: with no Content-Length, a body one byte
+// past the cap is source_too_large and the scratch file is removed; a
+// body exactly at the cap downloads.
+func TestDownloadCapWhileStreaming(t *testing.T) {
+ for _, c := range []struct {
+ size int
+ want string
+ }{{mib + 1, media.CodeSourceTooLarge}, {mib, "nil"}} {
+ t.Run(fmt.Sprint(c.size), func(t *testing.T) {
+ h := newHarness(t)
+ data := randomBytes(t, c.size)
+ p := h.s.payload(t, media.PresetVideo720p, data, mib)
+ h.s.Chunked = true
+ if err := h.download(t, p); codeOf(err) != c.want {
+ t.Fatalf("download of %d bytes under a %d cap = %s, want %s", c.size, mib, codeOf(err), c.want)
+ }
+ if c.want == "nil" {
+ h.wantSource(t, data)
+ } else {
+ h.wantNoSource(t)
+ }
+ })
+ }
+}
+
+// TestDownloadContentLengthOverCap: a 200 whose Content-Length is over
+// the cap is source_too_large before any byte is read. The server sends
+// the headers and then nothing, so a handler that read the body would
+// wait until its context ended instead.
+func TestDownloadContentLengthOverCap(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, mib+1), mib)
+ h.s.HoldBody = true
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ if err := download(ctx, h.cfg.withDefaults(), p, sourcePath(h.cfg)); codeOf(err) != media.CodeSourceTooLarge {
+ t.Fatalf("download = %s, want source_too_large", codeOf(err))
+ }
+ h.wantNoSource(t)
+}
+
+// TestDownloadAfterExpiryExits75: a resume the store refuses because
+// the grant has expired makes Run exit 75 and write no result; nor does
+// any transfer begin once the clock reads the expiry.
+func TestDownloadAfterExpiryExits75(t *testing.T) {
+ run := func(t *testing.T, h *harness, p media.Payload) int {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ return Run(ctx, h.cfg, marshal(t, p))
+ }
+ noPUT := func(t *testing.T, h *harness) {
+ t.Helper()
+ for _, r := range h.s.Requests() {
+ if r.Method != "GET" {
+ t.Errorf("the server saw a %s of %s after the grant expired", r.Method, r.Path)
+ }
+ }
+ if _, ok := h.s.Object(resultPath); ok {
+ t.Error("a result object was written")
+ }
+ }
+
+ t.Run("resume refused after the expiry", func(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 2*mib), 8*mib)
+ h.s.Cuts = []int64{mib}
+ h.s.OnGet = func(n int) int {
+ if n == 2 {
+ h.clock.Set(h.s.expiry)
+ }
+ return 0
+ }
+ if code := run(t, h, p); code != media.ExitGrantExpired {
+ t.Fatalf("Run = %d, want %d", code, media.ExitGrantExpired)
+ }
+ if rs := h.s.Requests(); len(rs) != 2 || rs[1].Status != http.StatusForbidden {
+ t.Fatalf("requests %+v, want a cut GET then a 403", rs)
+ }
+ noPUT(t, h)
+ h.wantNoSource(t)
+ })
+
+ t.Run("no resume begins at the expiry", func(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 2*mib), 8*mib)
+ h.s.Cuts = []int64{mib}
+ h.onWait = func() { h.clock.Set(h.s.expiry) }
+ if code := run(t, h, p); code != media.ExitGrantExpired {
+ t.Fatalf("Run = %d, want %d", code, media.ExitGrantExpired)
+ }
+ if rs := h.s.Requests(); len(rs) != 1 {
+ t.Fatalf("%d requests, want 1: a resume began at the expiry", len(rs))
+ }
+ noPUT(t, h)
+ })
+
+ t.Run("no download begins at the expiry", func(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 1024), 8*mib)
+ h.clock.Set(h.s.expiry)
+ if code := run(t, h, p); code != media.ExitGrantExpired {
+ t.Fatalf("Run = %d, want %d", code, media.ExitGrantExpired)
+ }
+ if rs := h.s.Requests(); len(rs) != 0 {
+ t.Fatalf("%d requests, want none", len(rs))
+ }
+ })
+}
+
+// TestDownload403BeforeExpiryIsUnreadable: a 403 while the grant is
+// live (an infected object, a policy) is source_unreadable, on the first
+// GET or on a resume, and never resumed.
+func TestDownload403BeforeExpiryIsUnreadable(t *testing.T) {
+ for _, at := range []int{1, 2} {
+ t.Run(fmt.Sprint("GET ", at), func(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 2*mib), 8*mib)
+ h.s.Cuts = []int64{mib}
+ h.s.OnGet = func(n int) int {
+ if n == at {
+ return http.StatusForbidden
+ }
+ return 0
+ }
+ if err := h.download(t, p); codeOf(err) != media.CodeSourceUnreadable {
+ t.Fatalf("download = %s, want source_unreadable", codeOf(err))
+ }
+ if rs := h.s.Requests(); len(rs) != at {
+ t.Fatalf("%d requests, want %d", len(rs), at)
+ }
+ h.wantNoSource(t)
+ })
+ }
+}
+
+// TestDownloadStatuses: 404 is source_not_found; another 4xx is
+// source_unreadable at once; a 5xx is retried as a broken connection,
+// from the start when nothing was written.
+func TestDownloadStatuses(t *testing.T) {
+ for _, c := range []struct {
+ status int
+ want string
+ reqs int
+ }{
+ {http.StatusNotFound, media.CodeSourceNotFound, 1},
+ {http.StatusBadRequest, media.CodeSourceUnreadable, 1},
+ {http.StatusRequestedRangeNotSatisfiable, media.CodeSourceUnreadable, 1},
+ {http.StatusInternalServerError, "nil", 2},
+ {http.StatusBadGateway, "nil", 2},
+ {http.StatusServiceUnavailable, "nil", 2},
+ {http.StatusGatewayTimeout, "nil", 2},
+ {dropConnection, "nil", 2},
+ } {
+ t.Run(fmt.Sprint(c.status), func(t *testing.T) {
+ h := newHarness(t)
+ data := randomBytes(t, 4096)
+ p := h.s.payload(t, media.PresetVideo720p, data, mib)
+ h.s.OnGet = func(n int) int {
+ if n == 1 {
+ return c.status
+ }
+ return 0
+ }
+ if err := h.download(t, p); codeOf(err) != c.want {
+ t.Fatalf("download = %s, want %s", codeOf(err), c.want)
+ }
+ rs := h.s.Requests()
+ if len(rs) != c.reqs {
+ t.Fatalf("%d requests, want %d", len(rs), c.reqs)
+ }
+ if c.want == "nil" {
+ h.wantSource(t, data)
+ if rs[1].Header.Get("Range") != "" {
+ t.Errorf("a retry with nothing written sent Range %q", rs[1].Header.Get("Range"))
+ }
+ if d := h.Delays(); len(d) != 1 || d[0] != time.Second {
+ t.Errorf("delays %v, want [1s]", d)
+ }
+ }
+ })
+ }
+ t.Run("missing object", func(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, nil, mib)
+ h.s.mu.Lock()
+ delete(h.s.objects, srcPath)
+ h.s.mu.Unlock()
+ if err := h.download(t, p); codeOf(err) != media.CodeSourceNotFound {
+ t.Fatalf("download = %s, want source_not_found", codeOf(err))
+ }
+ })
+}
+
+// TestDownloadResumeMustContinue: a resume answered with a 200 (the
+// Range ignored) or a 206 from another offset is unreadable.
+func TestDownloadResumeMustContinue(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ fault func(*s3Server)
+ }{
+ {"range ignored", func(s *s3Server) { s.IgnoreRange = true }},
+ {"another offset", func(s *s3Server) { s.SkewRange = 1 }},
+ // With no size known (a chunked first answer, a "*" total) only
+ // the offset check can see the gap.
+ {"another offset, no size", func(s *s3Server) { s.SkewRange, s.NoTotal = 1, true }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ h := newHarness(t)
+ // The cap is the source's size, so a resume that started the
+ // body again would also pass it.
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 2*mib), 2*mib)
+ h.s.Cuts = []int64{mib}
+ h.s.Chunked = true
+ h.s.OnGet = func(n int) int {
+ if n == 2 {
+ h.s.mu.Lock()
+ c.fault(h.s)
+ h.s.mu.Unlock()
+ }
+ return 0
+ }
+ if err := h.download(t, p); codeOf(err) != media.CodeUnreadable {
+ t.Fatalf("download = %s, want unreadable", codeOf(err))
+ }
+ if rs := h.s.Requests(); len(rs) != 2 {
+ t.Fatalf("%d requests, want 2", len(rs))
+ }
+ h.wantNoSource(t)
+ })
+ }
+}
+
+// TestDownloadGivesUpAfter20Resumes: a body that breaks 21 times is
+// unreadable after exactly 20 resumes, each from the bytes written, with
+// the delays 1, 2, 4, 8 s and then 10 s.
+func TestDownloadGivesUpAfter20Resumes(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 64*1024), mib)
+ for i := 1; i <= 21; i++ {
+ h.s.Cuts = append(h.s.Cuts, int64(i*1000))
+ }
+ if err := h.download(t, p); codeOf(err) != media.CodeUnreadable {
+ t.Fatalf("download = %s, want unreadable", codeOf(err))
+ }
+ rs := h.s.Requests()
+ if len(rs) != 21 {
+ t.Fatalf("%d requests, want 21 (one GET and 20 resumes)", len(rs))
+ }
+ for i := 1; i < len(rs); i++ {
+ if want := fmt.Sprintf("bytes=%d-", i*1000); rs[i].Header.Get("Range") != want {
+ t.Errorf("resume %d Range %q, want %q", i, rs[i].Header.Get("Range"), want)
+ }
+ }
+ want := []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second}
+ for len(want) < 20 {
+ want = append(want, 10*time.Second)
+ }
+ if got := h.Delays(); fmt.Sprint(got) != fmt.Sprint(want) {
+ t.Errorf("delays %v, want %v", got, want)
+ }
+ h.wantNoSource(t)
+}
+
+// TestDownloadNeverReplacesAFile: the source path is created, never
+// opened through something already there.
+func TestDownloadNeverReplacesAFile(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 1024), mib)
+ outside := filepath.Join(t.TempDir(), "outside")
+ if err := os.WriteFile(outside, []byte("keep"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(outside, sourcePath(h.cfg)); err != nil {
+ t.Fatal(err)
+ }
+ if err := h.download(t, p); codeOf(err) != media.CodeEngineFailed {
+ t.Fatalf("download over a link = %s, want engine_failed", codeOf(err))
+ }
+ if b, _ := os.ReadFile(outside); string(b) != "keep" {
+ t.Fatalf("the link's target was written: %q", b)
+ }
+ if len(h.s.Requests()) != 0 {
+ t.Fatal("a request was made")
+ }
+}
+
+func TestResumeDelay(t *testing.T) {
+ for n, want := range map[int]time.Duration{0: time.Second, 1: 2 * time.Second, 2: 4 * time.Second, 3: 8 * time.Second, 4: 10 * time.Second, 19: 10 * time.Second, 63: 10 * time.Second, 64: 10 * time.Second} {
+ if got := resumeDelay(n); got != want {
+ t.Errorf("resumeDelay(%d) = %v, want %v", n, got, want)
+ }
+ }
+}
+
+// TestWaitCtxEndsWithTheContext: the real wait returns when ctx ends,
+// not after its delay.
+func TestWaitCtxEndsWithTheContext(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ done := make(chan error, 1)
+ go func() { done <- waitCtx(ctx, time.Hour) }()
+ select {
+ case err := <-done:
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("waitCtx = %v, want context.Canceled", err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("waitCtx ignored its context")
+ }
+ if err := waitCtx(context.Background(), time.Millisecond); err != nil {
+ t.Fatalf("waitCtx(1ms) = %v", err)
+ }
+}
+
+// TestRunRejectsABadPayload: a payload that is not exactly the payload
+// exits 1 before any request and before the scratch is touched.
+func TestRunRejectsABadPayload(t *testing.T) {
+ h := newHarness(t)
+ scratch := t.TempDir() // a fresh one, so prepareScratch's dirs show
+ good := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 1024), mib)
+ goodJSON := marshal(t, good)
+ mutate := func(f func(*media.Payload)) string {
+ p := good
+ p.Transfers.Outputs = append([]media.Transfer(nil), good.Transfers.Outputs...)
+ f(&p)
+ return marshal(t, p)
+ }
+ cases := map[string]string{
+ "empty": "",
+ "bad JSON": "{\"v\":1,",
+ "not JSON": "CARLOS_MEDIA_JOB",
+ "version 2": mutate(func(p *media.Payload) { p.V = 2 }),
+ "31-hex execution": mutate(func(p *media.Payload) { p.Execution = testExec[:31] }),
+ "upper-case hex": mutate(func(p *media.Payload) { p.Execution = strings.ToUpper(testExec) }),
+ "unknown preset": mutate(func(p *media.Payload) { p.Preset = "video-4k" }),
+ "two outputs": mutate(func(p *media.Payload) { p.Transfers.Outputs = p.Transfers.Outputs[:2] }),
+ "no byte cap": mutate(func(p *media.Payload) { p.Limits.SourceBytes = 0 }),
+ "no expiry": mutate(func(p *media.Payload) { p.Expiry = 0 }),
+ "unknown field": strings.Replace(goodJSON, `{"v":1,`, `{"v":1,"zz":1,`, 1),
+ "trailing data": goodJSON + ` {}`,
+ "over the limit": goodJSON + strings.Repeat(" ", media.MaxOverrideBytes),
+ }
+ cfg := h.cfg
+ cfg.Scratch = scratch
+ for name, payload := range cases {
+ if code := Run(context.Background(), cfg, payload); code != media.ExitFailed {
+ t.Errorf("%s: Run = %d, want %d", name, code, media.ExitFailed)
+ }
+ }
+ if n := len(h.s.Requests()); n != 0 {
+ t.Fatalf("bad payloads made %d requests", n)
+ }
+ if ents, _ := os.ReadDir(scratch); len(ents) != 0 {
+ t.Fatalf("a bad payload touched the scratch: %v", ents)
+ }
+ // The good payload is accepted (a control for the cases above).
+ if _, err := parsePayload(goodJSON); err != nil {
+ t.Fatalf("the good payload is refused: %v", err)
+ }
+}
+
+// TestRunPreparesScratchAndDownloads: a good payload makes in, out and
+// tmp at 0700 and downloads the source to in/source. Until the
+// conversion is built the run exits 1.
+func TestRunPreparesScratchAndDownloads(t *testing.T) {
+ h := newHarness(t)
+ data := randomBytes(t, 4096)
+ p := h.s.payload(t, media.PresetAudioAAC, data, mib)
+ cfg := h.cfg
+ cfg.Scratch = t.TempDir()
+ if code := Run(context.Background(), cfg, marshal(t, p)); code != media.ExitFailed {
+ t.Fatalf("Run = %d, want %d until the conversion is built", code, media.ExitFailed)
+ }
+ for _, d := range []string{"in", "out", "tmp"} {
+ fi, err := os.Lstat(filepath.Join(cfg.Scratch, d))
+ if err != nil || !fi.IsDir() || fi.Mode().Perm() != 0o700 {
+ t.Errorf("%s: %v %v, want a 0700 directory", d, fi, err)
+ }
+ }
+ got, err := os.ReadFile(filepath.Join(cfg.Scratch, "in", "source"))
+ if err != nil || !bytes.Equal(got, data) {
+ t.Fatalf("in/source: %d bytes, %v", len(got), err)
+ }
+ // A scratch whose "in" is a link is refused before any request.
+ cfg.Scratch = t.TempDir()
+ if err := os.Symlink(t.TempDir(), filepath.Join(cfg.Scratch, "in")); err != nil {
+ t.Fatal(err)
+ }
+ before := len(h.s.Requests())
+ if code := Run(context.Background(), cfg, marshal(t, p)); code != media.ExitFailed || len(h.s.Requests()) != before {
+ t.Fatalf("Run over a linked in/ = %d with %d requests", code, len(h.s.Requests())-before)
+ }
+}
+
+// TestHandlerNeverLogsTransfers: across a run of failures and resumes,
+// no log line (and no error download returns) carries a signature, the
+// token, an X-Amz parameter, the store's address or the source key.
+func TestHandlerNeverLogsTransfers(t *testing.T) {
+ type scenario struct {
+ name string
+ setup func(h *harness, data []byte)
+ }
+ var all []string
+ check := func(name string, h *harness, lines []string) {
+ for _, line := range lines {
+ for _, secret := range h.s.secrets() {
+ if strings.Contains(line, secret) {
+ t.Errorf("%s: %q contains %q", name, line, secret)
+ }
+ }
+ }
+ all = append(all, lines...)
+ }
+ for _, sc := range []scenario{
+ {"resumes", func(h *harness, data []byte) { h.s.Cuts = []int64{1000, 2000, 3000} }},
+ {"changed", func(h *harness, data []byte) {
+ h.s.Cuts = []int64{1000}
+ h.s.OnGet = func(n int) int {
+ if n == 2 {
+ h.s.SetSource(data, "x", "")
+ }
+ return 0
+ }
+ }},
+ {"denied", func(h *harness, data []byte) { h.s.OnGet = func(int) int { return 403 } }},
+ {"expired", func(h *harness, data []byte) {
+ h.s.Cuts = []int64{1000}
+ h.s.OnGet = func(n int) int {
+ if n == 2 {
+ h.clock.Set(h.s.expiry)
+ }
+ return 0
+ }
+ }},
+ {"gives up", func(h *harness, data []byte) {
+ for i := 1; i <= 21; i++ {
+ h.s.Cuts = append(h.s.Cuts, int64(i*100))
+ }
+ }},
+ {"redirect", func(h *harness, data []byte) { h.s.OnGet = func(int) int { return 307 } }},
+ {"unreachable", func(h *harness, data []byte) { h.s.srv.Close() }},
+ } {
+ h := newHarness(t)
+ data := randomBytes(t, 8192)
+ p := h.s.payload(t, media.PresetVideo720p, data, mib)
+ sc.setup(h, data)
+ cfg := h.cfg
+ cfg.Scratch = t.TempDir()
+ Run(context.Background(), cfg, marshal(t, p))
+ check(sc.name, h, h.Logs())
+ // download's own error, as a caller might print it.
+ h2 := newHarness(t)
+ p2 := h2.s.payload(t, media.PresetVideo720p, data, mib)
+ sc.setup(h2, data)
+ if err := h2.download(t, p2); err != nil {
+ check(sc.name+" error", h2, []string{err.Error(), fmt.Sprintf("%+v", err)})
+ }
+ }
+ // A refused payload is not quoted either.
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, nil, mib)
+ p.V = 2
+ Run(context.Background(), h.cfg, marshal(t, p))
+ bad := marshal(t, h.s.payload(t, media.PresetVideo720p, nil, mib))
+ Run(context.Background(), h.cfg, bad[:len(bad)-40])
+ // json's unknown-field error quotes the field's name.
+ Run(context.Background(), h.cfg, strings.Replace(bad, `{"v":1,`, `{"v":1,"X-Amz-Signature=`+testToken+`":1,`, 1))
+ check("bad payload", h, h.Logs())
+ if len(all) == 0 {
+ t.Fatal("no log lines were checked")
+ }
+}
+
+// TestConfigDefaults: the paths default to Debian's ffmpeg and
+// CARLOS_MEDIA_SCRATCH, else /scratch; a set field is kept.
+func TestConfigDefaults(t *testing.T) {
+ t.Setenv(ScratchEnv, "")
+ c := Config{}.withDefaults()
+ if c.FFmpeg != "/usr/bin/ffmpeg" || c.FFprobe != "/usr/bin/ffprobe" || c.Scratch != "/scratch" || c.Now == nil || c.Logf == nil || c.wait == nil || c.HTTP == nil {
+ t.Fatalf("defaults %+v", c)
+ }
+ t.Setenv(ScratchEnv, "/var/media/x1")
+ if got := (Config{}).withDefaults().Scratch; got != "/var/media/x1" {
+ t.Fatalf("Scratch = %q, want the environment's", got)
+ }
+ if got := (Config{Scratch: "/s", FFmpeg: "/f"}).withDefaults(); got.Scratch != "/s" || got.FFmpeg != "/f" {
+ t.Fatalf("set fields replaced: %+v", got)
+ }
+}
+
+// TestDownloadResumeSizeMustAgree: a resume whose Content-Range total
+// differs from the size the first answer gave is unreadable; with no
+// size before (a chunked first answer), a body that ends short of the
+// total it claimed is unreadable, and a claimed total over the cap is
+// source_too_large.
+func TestDownloadResumeSizeMustAgree(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ chunked bool
+ lie int64
+ want string
+ }{
+ {"total grew", false, 1, media.CodeUnreadable},
+ {"total shrank", false, -1000, media.CodeUnreadable},
+ {"ends short of its total", true, 1, media.CodeUnreadable},
+ {"total over the cap", true, 8 * mib, media.CodeSourceTooLarge},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ h := newHarness(t)
+ p := h.s.payload(t, media.PresetVideo720p, randomBytes(t, 2*mib), 8*mib)
+ h.s.Cuts = []int64{mib}
+ h.s.Chunked = c.chunked
+ h.s.TotalLie = c.lie
+ if err := h.download(t, p); codeOf(err) != c.want {
+ t.Fatalf("download = %s, want %s", codeOf(err), c.want)
+ }
+ if rs := h.s.Requests(); len(rs) != 2 {
+ t.Fatalf("%d requests, want 2", len(rs))
+ }
+ h.wantNoSource(t)
+ })
+ }
+}
diff --git a/internal/mediahandler/handler.go b/internal/mediahandler/handler.go
new file mode 100644
index 000000000..54e7dc190
--- /dev/null
+++ b/internal/mediahandler/handler.go
@@ -0,0 +1,210 @@
+// Package mediahandler is the codec container's handler (spec §5.5, §6):
+// it reads the payload, downloads the source with the signed transfer,
+// and (later tasks of plan 3) sniffs, probes, converts, collects the
+// outputs, uploads them and writes the result object.
+//
+// It never logs a transfer, a URL, a query, a header or the payload, and
+// no error it makes carries one (preflight F6): the presigned URLs hold
+// the session token and signatures for the whole execution.
+//
+// It imports no cloud SDK (provider boundary, plan 3 Task 13).
+package mediahandler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "net/http"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// ScratchEnv names the handler's scratch directory; unset, it is
+// DefaultScratch. The local runner (plan 3 Task 13) sets it per
+// execution.
+const ScratchEnv = "CARLOS_MEDIA_SCRATCH"
+
+// Defaults for Config's paths.
+const (
+ DefaultFFmpeg = "/usr/bin/ffmpeg"
+ DefaultFFprobe = "/usr/bin/ffprobe"
+ DefaultScratch = "/scratch"
+)
+
+// Config is what the handler runs with. Every path it uses is under
+// Scratch: <Scratch>/in/source, <Scratch>/out/<name>, <Scratch>/tmp.
+type Config struct {
+ FFmpeg, FFprobe, Scratch string
+ // HTTP makes every transfer. Whatever client is given, each request
+ // asks for identity encoding and follows no redirect (download.go).
+ HTTP *http.Client
+ // Now is the clock the grant expiry is compared with.
+ Now func() time.Time
+ // Logf writes one line to the task's log.
+ Logf func(string, ...any)
+
+ // wait sleeps before a resume; nil is a timer that honours ctx.
+ // Tests replace it to record the delays without waiting.
+ wait func(ctx context.Context, d time.Duration) error
+}
+
+// withDefaults fills every unset field.
+func (c Config) withDefaults() Config {
+ if c.FFmpeg == "" {
+ c.FFmpeg = DefaultFFmpeg
+ }
+ if c.FFprobe == "" {
+ c.FFprobe = DefaultFFprobe
+ }
+ if c.Scratch == "" {
+ c.Scratch = os.Getenv(ScratchEnv)
+ }
+ if c.Scratch == "" {
+ c.Scratch = DefaultScratch
+ }
+ if c.HTTP == nil {
+ c.HTTP = defaultHTTPClient()
+ }
+ if c.Now == nil {
+ c.Now = time.Now
+ }
+ if c.Logf == nil {
+ c.Logf = func(format string, args ...any) {
+ fmt.Fprintf(os.Stderr, format+"\n", args...)
+ }
+ }
+ if c.wait == nil {
+ c.wait = waitCtx
+ }
+ return c
+}
+
+// jobError is a named failure: its code is one of media.HandlerCodes,
+// and the result object will carry it (plan 3 Task 6).
+type jobError struct{ code string }
+
+func (e jobError) Error() string { return e.code }
+
+// errGrantExpired is a transfer refused, or not begun, at or after the
+// grant's expiry. The result PUT has expired with the same grant, so the
+// handler writes no result and exits media.ExitGrantExpired (spec §6,
+// astra R7-2).
+var errGrantExpired = errors.New("grant expired")
+
+// errNotBuilt ends a run that downloaded its source: the conversion
+// itself arrives in plan 3 Tasks 3 to 6, and until then no run may
+// report a conversion done.
+var errNotBuilt = errors.New("conversion not built")
+
+// Run is the codec's whole program: payload is media.PayloadEnv's value.
+// It answers the process's exit code.
+func Run(ctx context.Context, cfg Config, payload string) int {
+ cfg = cfg.withDefaults()
+ p, err := parsePayload(payload)
+ if err != nil {
+ // engine.codec.payload_refused (pending Luna pass). The reason
+ // names a field or a shape, never a value from the payload.
+ cfg.Logf("codec: payload refused: %v", err)
+ return media.ExitFailed
+ }
+ if err := prepareScratch(cfg.Scratch); err != nil {
+ // engine.codec.scratch (pending Luna pass).
+ cfg.Logf("codec: scratch directory unusable: %v", err)
+ return media.ExitFailed
+ }
+ err = download(ctx, cfg, p, sourcePath(cfg))
+ if err == nil {
+ err = errNotBuilt
+ }
+ return exitFor(cfg, err)
+}
+
+// exitFor logs err's outcome and answers the exit code for it.
+func exitFor(cfg Config, err error) int {
+ var je jobError
+ switch {
+ case errors.Is(err, errGrantExpired):
+ // engine.codec.grant_expired (pending Luna pass).
+ cfg.Logf("codec: the grant has expired; no result is written")
+ return media.ExitGrantExpired
+ case errors.As(err, &je):
+ // engine.codec.failed (pending Luna pass).
+ cfg.Logf("codec: failed: %s", je.code)
+ return media.ExitFailed
+ case errors.Is(err, errNotBuilt):
+ // engine.codec.not_built (pending Luna pass).
+ cfg.Logf("codec: source downloaded; conversion is not built in this image")
+ return media.ExitFailed
+ }
+ // engine.codec.stopped (pending Luna pass). Only ctx errors reach
+ // here, and they carry no URL.
+ cfg.Logf("codec: stopped: %v", err)
+ return media.ExitFailed
+}
+
+// sourcePath is <scratch>/in/source.
+func sourcePath(cfg Config) string { return filepath.Join(cfg.Scratch, "in", "source") }
+
+// parsePayload decodes the payload strictly (no unknown field, nothing
+// after the object, at most media.MaxOverrideBytes) and checks it:
+// Validate's shape, a positive byte cap and a positive expiry. Its errors
+// never quote the payload.
+func parsePayload(s string) (media.Payload, error) {
+ if s == "" {
+ return media.Payload{}, errors.New("no payload")
+ }
+ if len(s) > media.MaxOverrideBytes {
+ return media.Payload{}, errors.New("payload is over the override limit")
+ }
+ dec := json.NewDecoder(bytes.NewReader([]byte(s)))
+ dec.DisallowUnknownFields()
+ var p media.Payload
+ if err := dec.Decode(&p); err != nil {
+ // A json error can quote a fragment of the input: never pass it on.
+ return media.Payload{}, errors.New("payload does not decode as a payload")
+ }
+ if _, err := dec.Token(); err != io.EOF {
+ return media.Payload{}, errors.New("payload has data after the object")
+ }
+ if err := p.Validate(); err != nil {
+ return media.Payload{}, err
+ }
+ if p.Limits.SourceBytes <= 0 {
+ return media.Payload{}, errors.New("payload has no source byte cap")
+ }
+ if p.Expiry <= 0 {
+ return media.Payload{}, errors.New("payload has no grant expiry")
+ }
+ return p, nil
+}
+
+// prepareScratch makes <scratch>/in, out and tmp, each 0700. The scratch
+// directory itself must exist (the image holds it, 65534:65534 0700). A
+// name already there must be a real directory, not a link.
+func prepareScratch(scratch string) error {
+ for _, d := range []string{"in", "out", "tmp"} {
+ path := filepath.Join(scratch, d)
+ err := os.Mkdir(path, 0o700)
+ if err == nil {
+ continue
+ }
+ if !errors.Is(err, fs.ErrExist) {
+ return err
+ }
+ fi, lerr := os.Lstat(path)
+ if lerr != nil {
+ return lerr
+ }
+ if !fi.IsDir() {
+ return fmt.Errorf("%s is not a directory", path)
+ }
+ }
+ return nil
+}
diff --git a/internal/mediahandler/s3test_test.go b/internal/mediahandler/s3test_test.go
new file mode 100644
index 000000000..fa4cfced0
--- /dev/null
+++ b/internal/mediahandler/s3test_test.go
@@ -0,0 +1,408 @@
+package mediahandler
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// dropConnection, answered by OnGet, closes the connection unanswered.
+const dropConnection = -1
+
+// testToken is the session token every transfer of s3Server carries, as
+// the SDK encodes it in a query.
+const testToken = "IQoJb3JpZ2luX2VjTESTtoken%2Bwith%2Fslash%3D%3D"
+
+// testClock is a settable clock shared by the handler and s3Server.
+type testClock struct {
+ mu sync.Mutex
+ t time.Time
+}
+
+func newClock() *testClock { return &testClock{t: time.Date(2026, 11, 17, 12, 0, 0, 0, time.UTC)} }
+
+func (c *testClock) Now() time.Time {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.t
+}
+
+func (c *testClock) Set(t time.Time) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.t = t
+}
+
+// s3Object is one object the server holds.
+type s3Object struct {
+ data []byte
+ etag string // unquoted
+ encoding string // Content-Encoding to answer with, if any
+}
+
+// s3Transfer is what the server presigned on one path.
+type s3Transfer struct {
+ method string
+ query string // the whole raw query, as issued
+ signed []string // the signed header names besides host
+ signature string
+}
+
+// s3Request is one request the server saw.
+type s3Request struct {
+ Method, Path string
+ Header http.Header
+ Status int
+}
+
+// s3Server is an httptest S3 for one execution. It answers only the
+// transfers it presigned: the exact query (as decoded multisets), an
+// unexpired grant (403 at or after the expiry on its clock), and every
+// signed header present with its signed value. GET honours If-Match
+// (412) and Range (206 from "bytes=N-", 416 past the end); PUT honours
+// If-None-Match: * (412 when the key exists). Knobs, set before the
+// requests they affect:
+//
+// - Cuts: absolute offsets of the source; each GET whose body would
+// pass the first remaining cut sends up to it and drops the
+// connection, and the cut is used up.
+// - Chunked: GETs send no Content-Length.
+// - HoldBody: a 200 GET sends its headers, then sends nothing until the
+// client goes away.
+// - IgnoreRange, SkewRange, NoTotal, TotalLie: a store that answers a resume
+// wrongly.
+// - OnGet(n): runs before GET number n (from 1) is served; a non-zero
+// answer is sent as the status, with no body (a 3xx with a Location
+// on this server), and dropConnection closes the connection before
+// any response.
+type s3Server struct {
+ t *testing.T
+ srv *httptest.Server
+ clock *testClock
+ expiry time.Time
+
+ mu sync.Mutex
+ objects map[string]*s3Object
+ transfers map[string]s3Transfer
+ requests []s3Request
+ problems []string
+ gets int
+
+ Cuts []int64
+ Chunked bool
+ HoldBody bool
+ IgnoreRange bool // answer a ranged GET with the whole object, 200
+ SkewRange int64 // answer a ranged GET from this many bytes later
+ NoTotal bool // a 206's Content-Range total is "*"
+ TotalLie int64 // add this to a 206's Content-Range total; below 0, the 206 is of an object that much shorter
+ OnGet func(n int) int
+}
+
+// newS3 starts a server whose grant expires an hour after clock's now.
+func newS3(t *testing.T, clock *testClock) *s3Server {
+ s := &s3Server{t: t, clock: clock, expiry: clock.Now().Add(time.Hour), objects: map[string]*s3Object{}, transfers: map[string]s3Transfer{}}
+ s.srv = httptest.NewServer(http.HandlerFunc(s.serve))
+ t.Cleanup(s.srv.Close)
+ return s
+}
+
+const (
+ srcPath = "/src/uploads/clip%20one.mov"
+ outPrefix = "/out/derived/clip/"
+ resultPath = "/results/media-results/0123456789abcdef0123456789abcdef.json"
+ testETag = "9b2cf535f27731c974343645a3985328"
+ testExec = "0123456789abcdef0123456789abcdef"
+)
+
+// payload puts data at the source and presigns the execution's five
+// transfers; the byte cap is limit.
+func (s *s3Server) payload(t *testing.T, preset string, data []byte, limit int64) media.Payload {
+ t.Helper()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.objects[srcPath] = &s3Object{data: data, etag: testETag}
+ tr := media.Transfers{OutPrefix: s.srv.URL + outPrefix}
+ presign := func(method, path, xid string, signed []string) (base, rest string) {
+ sig := make([]byte, 32)
+ if _, err := rand.Read(sig); err != nil {
+ t.Fatal(err)
+ }
+ sigHex := hex.EncodeToString(sig)
+ date := s.clock.Now().UTC().Format("20060102T150405Z")
+ names := append([]string{"host"}, signed...)
+ sort.Strings(names)
+ q := "X-Amz-Algorithm=AWS4-HMAC-SHA256" +
+ "&X-Amz-Credential=ASIATESTTESTTESTTEST%2F" + date[:8] + "%2Fus-east-1%2Fs3%2Faws4_request" +
+ "&X-Amz-Date=" + date +
+ "&X-Amz-Expires=3600" +
+ "&X-Amz-Security-Token=" + testToken +
+ "&X-Amz-SignedHeaders=" + strings.Join(names, "%3B") +
+ "&x-id=" + xid +
+ "&X-Amz-Signature=" + sigHex
+ b, shared, rest, err := media.SplitPresigned(s.srv.URL + path + "?" + q)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tr.Shared == "" {
+ tr.Shared = shared
+ }
+ s.transfers[path] = s3Transfer{method: method, query: q, signed: signed, signature: sigHex}
+ return b, rest
+ }
+ base, rest := presign("GET", srcPath, "GetObject", []string{"if-match"})
+ tr.Source = media.Transfer{URL: base, Method: "GET", Query: rest, Header: map[string]string{"If-Match": `"` + testETag + `"`}}
+ for _, name := range media.OutputNames(preset) {
+ _, rest := presign("PUT", outPrefix+name, "PutObject", []string{"content-type", "if-none-match"})
+ tr.Outputs = append(tr.Outputs, media.Transfer{Name: name, Method: "PUT", Query: rest, Header: map[string]string{"Content-Type": media.ContentType(name), "If-None-Match": "*"}})
+ }
+ base, rest = presign("PUT", resultPath, "PutObject", []string{"content-type", "if-none-match"})
+ tr.Result = media.Transfer{URL: base, Method: "PUT", Query: rest, Header: map[string]string{"Content-Type": "application/json", "If-None-Match": "*"}}
+ return media.Payload{
+ V: media.PayloadVersion, Execution: testExec, Preset: preset,
+ Limits: media.JobLimits{SourceBytes: limit, GrantedMS: 600000, GrantedBy: "class", MaxMS: 3600000, OutputBytes: 1 << 30},
+ Expiry: s.expiry.Unix(),
+ Transfers: tr,
+ }
+}
+
+// secrets are the strings no log line or error may contain.
+func (s *s3Server) secrets() []string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ out := []string{testToken, "X-Amz", "x-amz", "X-Amz-Signature", s.srv.URL, "uploads/clip"}
+ if tok, err := url.QueryUnescape(testToken); err == nil {
+ out = append(out, tok)
+ }
+ for _, tr := range s.transfers {
+ out = append(out, tr.signature)
+ }
+ return out
+}
+
+// Requests is every request so far.
+func (s *s3Server) Requests() []s3Request {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return append([]s3Request(nil), s.requests...)
+}
+
+// CheckClean fails t if any request broke the presigned contract.
+func (s *s3Server) CheckClean(t *testing.T) {
+ t.Helper()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for _, p := range s.problems {
+ t.Errorf("s3 server: %s", p)
+ }
+}
+
+func (s *s3Server) serve(w http.ResponseWriter, r *http.Request) {
+ s.mu.Lock()
+ n := 0
+ if r.Method == "GET" {
+ s.gets++
+ n = s.gets
+ }
+ hook := s.OnGet
+ s.mu.Unlock()
+ forced := 0
+ if hook != nil && n > 0 {
+ forced = hook(n)
+ }
+ s.mu.Lock()
+ rec := s3Request{Method: r.Method, Path: r.URL.EscapedPath(), Header: r.Header.Clone()}
+ status, deferred := s.decide(r, forced)
+ rec.Status = status
+ s.requests = append(s.requests, rec)
+ s.mu.Unlock()
+ if deferred != nil {
+ deferred(w)
+ return
+ }
+ if status == dropConnection {
+ panic(http.ErrAbortHandler)
+ }
+ if status >= 300 && status < 400 {
+ w.Header().Set("Location", s.srv.URL+"/elsewhere")
+ }
+ w.WriteHeader(status)
+}
+
+// decide checks a request under s.mu and answers its status, or a
+// function that writes the whole response (outside the lock).
+func (s *s3Server) decide(r *http.Request, forced int) (int, func(http.ResponseWriter)) {
+ path := r.URL.EscapedPath()
+ tr, ok := s.transfers[path]
+ if !ok || tr.method != r.Method {
+ s.problems = append(s.problems, r.Method+" of a path never presigned")
+ return http.StatusForbidden, nil
+ }
+ if !sameQuery(r.URL.RawQuery, tr.query) {
+ s.problems = append(s.problems, r.Method+" with a query other than the presigned one")
+ return http.StatusForbidden, nil
+ }
+ for _, name := range tr.signed {
+ if r.Header.Get(name) == "" {
+ s.problems = append(s.problems, r.Method+" without its signed "+name)
+ return http.StatusForbidden, nil
+ }
+ }
+ if !s.clock.Now().Before(s.expiry) {
+ return http.StatusForbidden, nil
+ }
+ if forced != 0 {
+ return forced, nil
+ }
+ if r.Method == "PUT" {
+ return s.put(r)
+ }
+ return s.get(r)
+}
+
+func (s *s3Server) get(r *http.Request) (int, func(http.ResponseWriter)) {
+ obj, ok := s.objects[r.URL.EscapedPath()]
+ if !ok {
+ return http.StatusNotFound, nil
+ }
+ if r.Header.Get("If-Match") != `"`+obj.etag+`"` {
+ return http.StatusPreconditionFailed, nil
+ }
+ size := int64(len(obj.data))
+ start, status := int64(0), http.StatusOK
+ if rg := r.Header.Get("Range"); rg != "" && !s.IgnoreRange {
+ v, ok := strings.CutPrefix(rg, "bytes=")
+ v, ok2 := strings.CutSuffix(v, "-")
+ n, err := strconv.ParseInt(v, 10, 64)
+ if !ok || !ok2 || err != nil || n < 0 {
+ s.problems = append(s.problems, "a Range other than bytes=N-")
+ return http.StatusBadRequest, nil
+ }
+ if n >= size {
+ return http.StatusRequestedRangeNotSatisfiable, nil
+ }
+ start, status = min(n+s.SkewRange, size-1), http.StatusPartialContent
+ }
+ if status == http.StatusPartialContent && s.TotalLie < 0 {
+ size += s.TotalLie // a consistent answer for a smaller object
+ }
+ end := size
+ cut := false
+ if len(s.Cuts) > 0 && s.Cuts[0] > start && s.Cuts[0] < size {
+ end, cut = s.Cuts[0], true
+ s.Cuts = s.Cuts[1:]
+ }
+ body := obj.data[start:end]
+ total := strconv.FormatInt(size+max(s.TotalLie, 0), 10)
+ if s.NoTotal {
+ total = "*"
+ }
+ chunked, hold, enc, etag := s.Chunked, s.HoldBody && status == http.StatusOK, obj.encoding, obj.etag
+ return status, func(w http.ResponseWriter) {
+ h := w.Header()
+ h.Set("ETag", `"`+etag+`"`)
+ if enc != "" {
+ h.Set("Content-Encoding", enc)
+ }
+ if !chunked {
+ h.Set("Content-Length", strconv.FormatInt(size-start, 10))
+ }
+ if status == http.StatusPartialContent {
+ h.Set("Content-Range", "bytes "+strconv.FormatInt(start, 10)+"-"+strconv.FormatInt(size-1, 10)+"/"+total)
+ }
+ w.WriteHeader(status)
+ if hold {
+ w.(http.Flusher).Flush()
+ select {
+ case <-r.Context().Done():
+ case <-time.After(10 * time.Second):
+ }
+ panic(http.ErrAbortHandler)
+ }
+ w.Write(body)
+ if cut {
+ w.(http.Flusher).Flush()
+ panic(http.ErrAbortHandler)
+ }
+ }
+}
+
+func (s *s3Server) put(r *http.Request) (int, func(http.ResponseWriter)) {
+ path := r.URL.EscapedPath()
+ if _, exists := s.objects[path]; exists && r.Header.Get("If-None-Match") == "*" {
+ return http.StatusPreconditionFailed, nil
+ }
+ data, err := io.ReadAll(r.Body)
+ if err != nil {
+ return http.StatusBadRequest, nil
+ }
+ obj := &s3Object{data: data, etag: strconv.Itoa(len(s.objects) + 1)}
+ s.objects[path] = obj
+ return http.StatusOK, func(w http.ResponseWriter) {
+ w.Header().Set("ETag", `"`+obj.etag+`"`)
+ w.WriteHeader(http.StatusOK)
+ }
+}
+
+// Object answers what the server holds at path.
+func (s *s3Server) Object(path string) ([]byte, bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ o, ok := s.objects[path]
+ if !ok {
+ return nil, false
+ }
+ return append([]byte(nil), o.data...), true
+}
+
+// SetSource replaces the source's bytes, ETag and Content-Encoding.
+func (s *s3Server) SetSource(data []byte, etag, encoding string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.objects[srcPath] = &s3Object{data: data, etag: etag, encoding: encoding}
+}
+
+// sameQuery compares two raw queries as multisets of decoded pairs.
+func sameQuery(a, b string) bool {
+ qa, err1 := url.ParseQuery(a)
+ qb, err2 := url.ParseQuery(b)
+ if err1 != nil || err2 != nil || len(qa) != len(qb) {
+ return false
+ }
+ for k, va := range qa {
+ vb := qb[k]
+ if len(va) != len(vb) {
+ return false
+ }
+ va, vb = append([]string(nil), va...), append([]string(nil), vb...)
+ sort.Strings(va)
+ sort.Strings(vb)
+ for i := range va {
+ if va[i] != vb[i] {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// marshal is p as the payload's JSON.
+func marshal(t *testing.T, p media.Payload) string {
+ t.Helper()
+ b, err := json.Marshal(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}