media: collect outputs by descriptor, upload, report
Plan 3 Task 6: Run is wired end to end. Download, sniff, probe, check, then video (video, poster, playlist) or audio (loudness, encode under the ceiling, playlist, peaks with the final gain over min(duration, grant)), ffmpeg's version, every child dead, collect, three create-only PUTs in order, then the result object. collect opens the three names through a held os.Root: the output directory must not be a link and must be the one checked; each name is Lstat'ed (regular, not a link), opened O_RDONLY|O_NOFOLLOW|O_NONBLOCK and Fstat'ed (regular, one link, same device and inode, 1..bound). Refusals are engine_failed, or output_too_large for an oversized video.mp4/audio.mp4; uploads read from the open descriptors. upload/writeResult: signed headers, Content-Length, no redirects; 412 on the first attempt is engine_failed, a broken attempt is retried at most twice and a later 412 is accepted with ETag ""; expiry before an attempt or a 403 is errGrantExpired. No URL, query or header in any error or log line (F6). Run catches SIGTERM (children killed, exit 143, no result); every ffmpeg/ffprobe pass runs under the grant's deadline (exit 75); a named error writes a best-effort result and exits 1. The result reports the converted duration clamped to the grant (F15) and video.mp4/poster.jpg dimensions from outputSize (F16). A poster run that exits 0 with no file is unreadable; an ffmpeg failure with the scratch full is engine_failed (operator sizing, like the OOM ruling). 17 new engine log rows in the copy deck, pending Luna pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
21 files changed,
+2,391
−81
cmd/carlos-media/main.go+2 −3docs/superpowers/notes/media-conversion-copy-deck.md+18 −2internal/mediahandler/collect.go+86 −0internal/mediahandler/collect_linux.go+188 −0internal/mediahandler/collect_other.go+15 −0internal/mediahandler/collect_test.go+391 −0internal/mediahandler/download_test.go+9 −7internal/mediahandler/ffmpeg.go+9 −0internal/mediahandler/handler.go+9 −60internal/mediahandler/probe_test.go+6 −1internal/mediahandler/procs_linux.go+17 −0internal/mediahandler/procs_other.go+3 −0internal/mediahandler/result.go+75 −0internal/mediahandler/run.go+278 −0internal/mediahandler/run_test.go+588 −0internal/mediahandler/s3test_test.go+37 −8internal/mediahandler/testdata/probe/ok-audio.json+25 −0internal/mediahandler/testdata/probe/ok-av.json+39 −0internal/mediahandler/testdata/probe/provenance.txt+11 −0internal/mediahandler/upload.go+153 −0internal/mediahandler/upload_test.go+432 −0
diff --git a/cmd/carlos-media/main.go b/cmd/carlos-media/main.go| index 02ab89035..519212e34 100644 |
| --- a/cmd/carlos-media/main.go |
| +++ b/cmd/carlos-media/main.go |
| @@ -82,9 +82,8 @@ func deadlineCommand(rest []string) int { |
| // the handler starts, 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. |
| +// mediahandler.Run catches SIGTERM (ECS stopping the task): it kills |
| +// ffmpeg and every descendant, writes no result and exits 143. |
| func codecCommand(rest []string, stderr io.Writer) int { |
| if len(rest) != 0 { |
| return media.ExitFailed |
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md| index e033b2f05..ab4abbadc 100644 |
| --- a/docs/superpowers/notes/media-conversion-copy-deck.md |
| +++ b/docs/superpowers/notes/media-conversion-copy-deck.md |
| @@ -544,8 +544,7 @@ prints nothing. |
| | `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.codec.stopped` | `codec: stopped: %s` (pending Luna pass; plan 3 Task 2). `%s` is Go's context error. Since Task 6, the line of a SIGTERM (ECS stopping the task): the codec exits 143 and writes no result | |
| | `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) | |
| | `engine.codec.source_unopenable` | `codec: the downloaded source cannot be read: %s` (pending Luna pass; plan 3 Task 3). `%s` is the system's error for the scratch source path | |
| @@ -575,3 +574,20 @@ prints nothing. |
| | `engine.loudness.gain` | `codec: loudness %.1f LUFS, true peak %.1f dBTP, measurable %t; gain %.2f dB` (pending Luna pass; plan 3 Task 5, fix 1: one decimal, the meter's). Numbers only: the measurement and the gain the first encode uses | |
| | `engine.loudness.over_ceiling` | `codec: audio.mp4 peaks %.2f dB over the %.1f dBTP ceiling; encoding again at %.2f dB` (pending Luna pass; plan 3 Task 5, fix 1). The excess (true peak plus 0.05 over -1.5), the ceiling, and the second encode's gain | |
| | `engine.loudness.still_over` | `codec: audio.mp4 still peaks %.2f dB over the ceiling after the second encode; kept` (pending Luna pass; plan 3 Task 5, fix 1). Never a third encode | |
| +| `engine.encode.scratch_full` | `codec: ffmpeg (%s) failed with the scratch disk full` (pending Luna pass; plan 3 Task 6). `%s` as `engine.encode.failed`; the job fails `engine_failed`, not `unreadable` | |
| +| `engine.encode.no_frame` | `codec: ffmpeg wrote no frame to %s` (pending Luna pass; plan 3 Task 6). `%s` is `poster.jpg` | |
| +| `engine.version.unknown` | `codec: ffmpeg's version cannot be read; the result names none` (pending Luna pass; plan 3 Task 6) | |
| +| `engine.collect.refused` | `codec: output %s refused: %s` (pending Luna pass; plan 3 Task 6). The first `%s` is an output's name or `the output directory`; the second one of `a symlink`, `not a regular file`, `not a regular file when opened`, `not a directory`, `not the file checked before the open`, `not the directory checked before the open`, `has %d links`, `empty`, `over its %d-byte bound`, `not an output name`, `no file status`, `cannot be read: %s`, `cannot be opened: %s` (the system's error number's text), `collecting outputs needs Linux` | |
| +| `engine.upload.retry` | `codec: the upload of %s broke; retry %d of %d` (pending Luna pass; plan 3 Task 6). `%s` is an output's name or `the result` | |
| +| `engine.upload.gave_up` | `codec: the upload of %s broke %d times; giving up` (pending Luna pass; plan 3 Task 6) | |
| +| `engine.upload.exists` | `codec: the store already holds %s` (pending Luna pass; plan 3 Task 6). A 412 on the first attempt | |
| +| `engine.upload.exists_after_retry` | `codec: the store holds %s after a broken attempt; taken as this upload` (pending Luna pass; plan 3 Task 6) | |
| +| `engine.upload.denied` | `codec: the store refused %s (403); the grant is taken as expired` (pending Luna pass; plan 3 Task 6) | |
| +| `engine.upload.status` | `codec: the store answered %d to %s` (pending Luna pass; plan 3 Task 6). The HTTP status and an output's name or `the result` | |
| +| `engine.upload.mismatch` | `codec: the upload of %s does not match its transfer` (pending Luna pass; plan 3 Task 6) | |
| +| `engine.upload.unbuildable` | `codec: a request for the store cannot be built` (pending Luna pass; plan 3 Task 6) | |
| +| `engine.result.unmarshalable` | `codec: the result cannot be written as at most %d bytes of JSON` (pending Luna pass; plan 3 Task 6). `%d` is 65536 | |
| +| `engine.codec.done` | `codec: done; outputs and result written` (pending Luna pass; plan 3 Task 6) | |
| +| `engine.codec.result_unwritten` | `codec: converted, but the result could not be written` (pending Luna pass; plan 3 Task 6) | |
| +| `engine.codec.error_unwritten` | `codec: the result naming %s could not be written` (pending Luna pass; plan 3 Task 6). `%s` is the job error code | |
| +| `engine.codec.unexpected` | `codec: an unexpected %T ends the job` (pending Luna pass; plan 3 Task 6). `%T` is a Go error type, never its text | |
diff --git a/internal/mediahandler/collect.go b/internal/mediahandler/collect.go| new file mode 100644 |
| index 000000000..66a59aad0 |
| --- /dev/null |
| +++ b/internal/mediahandler/collect.go |
| @@ -0,0 +1,86 @@ |
| +package mediahandler |
| + |
| +import ( |
| + "os" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// The output bounds (spec §5.1, plan 3's Global Constraints): the media |
| +// file is at most the job's output limit and never more than one PUT |
| +// carries (outputBounds); the rest have fixed bounds. |
| +const ( |
| + playlistBound = 4 << 20 |
| + posterBound = 16 << 20 |
| + peaksBound = 64 << 10 |
| +) |
| + |
| +// collected is one output, opened by collect: its name, the open file |
| +// every byte of its upload is read from, and its size at the open. |
| +type collected struct { |
| + Name string |
| + File *os.File |
| + Size int64 |
| +} |
| + |
| +// outputBounds are each output's size bound for p: video.mp4 and |
| +// audio.mp4 at most min(p's output limit, media.MaxPutBytes) (a limit of |
| +// 0 or less is media.MaxPutBytes: preflight F37), the playlists 4 MiB, |
| +// the poster 16 MiB, peaks.json 64 KiB. |
| +func outputBounds(p media.Payload) map[string]int64 { |
| + big := int64(media.MaxPutBytes) |
| + if p.Limits.OutputBytes > 0 { |
| + big = min(big, p.Limits.OutputBytes) |
| + } |
| + return map[string]int64{ |
| + "video.mp4": big, "audio.mp4": big, |
| + "video.m3u8": playlistBound, "audio.m3u8": playlistBound, |
| + "poster.jpg": posterBound, |
| + "peaks.json": peaksBound, |
| + } |
| +} |
| + |
| +// mediaOutput reports whether name is a preset's media file, the one |
| +// output a source can make too large (output_too_large); any other |
| +// output over its bound is the engine's failure. |
| +func mediaOutput(name string) bool { return name == "video.mp4" || name == "audio.mp4" } |
| + |
| +// outputRefused is collect's refusal of one output: the output's name |
| +// (or "the output directory"), a fixed reason, and the job error it |
| +// is (engine_failed, or output_too_large for an oversized media file). |
| +// Its text holds only those and the system's error number: no path |
| +// outside the scratch, nothing of the file. |
| +type outputRefused struct{ name, why, code string } |
| + |
| +func (e outputRefused) Error() string { return "output " + e.name + " refused: " + e.why } |
| + |
| +func (e outputRefused) Unwrap() error { return jobError{e.code} } |
| + |
| +// closeCollected closes every file of cs. |
| +func closeCollected(cs []collected) { |
| + for _, c := range cs { |
| + if c.File != nil { |
| + _ = c.File.Close() |
| + } |
| + } |
| +} |
| + |
| +// The scratch is full when what its user may still write is under |
| +// scratchFullBytes, or its free inodes under scratchFullInodes (spec |
| +// §5.5: the task's ephemeral storage bounds a job's bytes and files). |
| +// A writer meets ENOSPC with a few blocks left at most, so a margin of |
| +// 16 MiB holds whatever block size and delayed allocation leave over. |
| +const ( |
| + scratchFullBytes = 16 << 20 |
| + scratchFullInodes = 64 |
| +) |
| + |
| +// diskIsFull is scratchFull's rule over statfs's numbers: available |
| +// blocks of bsize bytes, and total and free inodes (a file system that |
| +// reports no inodes, files 0, has no inode limit). |
| +func diskIsFull(bavail, bsize, files, ffree uint64) bool { |
| + if bsize > 0 && bavail < (scratchFullBytes+bsize-1)/bsize { |
| + return true |
| + } |
| + return files > 0 && ffree < scratchFullInodes |
| +} |
diff --git a/internal/mediahandler/collect_linux.go b/internal/mediahandler/collect_linux.go| new file mode 100644 |
| index 000000000..1a3aa8282 |
| --- /dev/null |
| +++ b/internal/mediahandler/collect_linux.go |
| @@ -0,0 +1,188 @@ |
| +//go:build linux |
| + |
| +package mediahandler |
| + |
| +import ( |
| + "errors" |
| + "io/fs" |
| + "os" |
| + "strconv" |
| + "syscall" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// collectBetween, when set, runs between an output's Lstat and its |
| +// open, and with "." between the output directory's Lstat and its |
| +// open. Tests use it to swap the file in that window; nil in |
| +// production. |
| +var collectBetween func(name string) |
| + |
| +// collect opens the outputs names, in order, inside dir, through one |
| +// directory descriptor it holds (os.OpenRoot; dir must be a directory, |
| +// not a link: openOutputDir), for upload (spec §6 "Collecting |
| +// outputs"). It runs only once ffmpeg and every descendant |
| +// are dead (childrenDead), so nothing changes the directory under it; |
| +// the checks below hold even if something could. For each name: |
| +// |
| +// - Lstat inside the root: a symlink, or anything but a regular file, |
| +// is refused without being opened (a FIFO would block an open, a |
| +// device would read anything); |
| +// - open inside the root with O_RDONLY|O_NOFOLLOW|O_NONBLOCK: a FIFO |
| +// swapped in after the Lstat cannot block the handler. os.Root |
| +// follows a final symlink that stays inside the root even with |
| +// O_NOFOLLOW, so the inode check below, not the flag, is what |
| +// refuses a link swapped in; |
| +// - Fstat of the open file: a regular file, exactly one link (a hard |
| +// link could name a file outside the output directory, or one the |
| +// upload would race), the same device and inode as the Lstat (the |
| +// open is of the file checked), and a size of 1 to bounds[name]. |
| +// |
| +// Every refusal is an outputRefused: engine_failed, but for video.mp4 |
| +// or audio.mp4 over its bound, which is output_too_large. On a refusal |
| +// every file collect opened is closed and no later name is opened. The |
| +// files answered stay open until the caller closes them |
| +// (closeCollected); each upload reads from its file, never the path |
| +// again. |
| +func collect(dir string, names []string, bounds map[string]int64) (out []collected, err error) { |
| + root, err := openOutputDir(dir) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer root.Close() |
| + defer func() { |
| + if err != nil { |
| + closeCollected(out) |
| + out = nil |
| + } |
| + }() |
| + for _, name := range names { |
| + c, err := collectOne(root, name, bounds[name]) |
| + if err != nil { |
| + return out, err |
| + } |
| + out = append(out, c) |
| + } |
| + return out, nil |
| +} |
| + |
| +// openOutputDir opens dir as collect's root. dir itself must be a |
| +// directory, not a symlink to one (the child runs as the user that owns |
| +// the scratch, so it could have put a link where the directory was), |
| +// and the root opened must be the directory checked. |
| +func openOutputDir(dir string) (*os.Root, error) { |
| + refuse := func(why string) (*os.Root, error) { |
| + return nil, outputRefused{"the output directory", why, media.CodeEngineFailed} |
| + } |
| + lfi, err := os.Lstat(dir) |
| + if err != nil { |
| + return refuse("cannot be read: " + sysReason(err)) |
| + } |
| + if !lfi.IsDir() { |
| + return refuse("not a directory") |
| + } |
| + if collectBetween != nil { |
| + collectBetween(".") |
| + } |
| + root, err := os.OpenRoot(dir) |
| + if err != nil { |
| + return refuse("cannot be opened: " + sysReason(err)) |
| + } |
| + rfi, err := root.Stat(".") |
| + if err != nil || !os.SameFile(lfi, rfi) { |
| + root.Close() |
| + return refuse("not the directory checked before the open") |
| + } |
| + return root, nil |
| +} |
| + |
| +// collectOne opens and checks one output; see collect. |
| +func collectOne(root *os.Root, name string, bound int64) (collected, error) { |
| + refuse := func(why string) (collected, error) { |
| + return collected{}, outputRefused{name, why, media.CodeEngineFailed} |
| + } |
| + if !plainName(name) || bound <= 0 { |
| + return refuse("not an output name") |
| + } |
| + lfi, err := root.Lstat(name) |
| + if err != nil { |
| + return refuse("cannot be read: " + sysReason(err)) |
| + } |
| + switch { |
| + case lfi.Mode()&fs.ModeSymlink != 0: |
| + return refuse("a symlink") |
| + case !lfi.Mode().IsRegular(): |
| + return refuse("not a regular file") |
| + } |
| + lst, ok := lfi.Sys().(*syscall.Stat_t) |
| + if !ok { |
| + return refuse("no file status") |
| + } |
| + if collectBetween != nil { |
| + collectBetween(name) |
| + } |
| + f, err := root.OpenFile(name, os.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0) |
| + if err != nil { |
| + return refuse("cannot be opened: " + sysReason(err)) |
| + } |
| + c, err := checkOpened(f, name, bound, lst) |
| + if err != nil { |
| + f.Close() |
| + return collected{}, err |
| + } |
| + return c, nil |
| +} |
| + |
| +// checkOpened holds the open file f to the Lstat's lst; see collect. |
| +func checkOpened(f *os.File, name string, bound int64, lst *syscall.Stat_t) (collected, error) { |
| + refuse := func(why string) (collected, error) { |
| + return collected{}, outputRefused{name, why, media.CodeEngineFailed} |
| + } |
| + fi, err := f.Stat() |
| + if err != nil { |
| + return refuse("cannot be read: " + sysReason(err)) |
| + } |
| + st, ok := fi.Sys().(*syscall.Stat_t) |
| + switch { |
| + case !ok: |
| + return refuse("no file status") |
| + case !fi.Mode().IsRegular(): |
| + return refuse("not a regular file when opened") |
| + case st.Dev != lst.Dev || st.Ino != lst.Ino: |
| + return refuse("not the file checked before the open") |
| + case st.Nlink != 1: |
| + return refuse("has " + strconv.FormatUint(uint64(st.Nlink), 10) + " links") |
| + case fi.Size() < 1: |
| + return refuse("empty") |
| + case fi.Size() > bound: |
| + code := media.CodeEngineFailed |
| + if mediaOutput(name) { |
| + code = media.CodeOutputTooLarge |
| + } |
| + return collected{}, outputRefused{name, "over its " + strconv.FormatInt(bound, 10) + "-byte bound", code} |
| + } |
| + return collected{Name: name, File: f, Size: fi.Size()}, nil |
| +} |
| + |
| +// sysReason is err's system error text alone (a *PathError's path, |
| +// which is under the scratch, is dropped), or a fixed text. |
| +func sysReason(err error) string { |
| + var errno syscall.Errno |
| + if errors.As(err, &errno) { |
| + return errno.Error() |
| + } |
| + return "an error" |
| +} |
| + |
| +// scratchFull reports whether the file system holding dir is full by |
| +// diskIsFull's rule. A statfs that fails is not full: the failure |
| +// keeps the code it had. |
| +func scratchFull(dir string) bool { |
| + var st unix.Statfs_t |
| + if err := unix.Statfs(dir, &st); err != nil { |
| + return false |
| + } |
| + return diskIsFull(st.Bavail, uint64(st.Bsize), st.Files, st.Ffree) |
| +} |
diff --git a/internal/mediahandler/collect_other.go b/internal/mediahandler/collect_other.go| new file mode 100644 |
| index 000000000..2dcf0079b |
| --- /dev/null |
| +++ b/internal/mediahandler/collect_other.go |
| @@ -0,0 +1,15 @@ |
| +//go:build !linux |
| + |
| +package mediahandler |
| + |
| +import "github.com/carlosframework/platform/internal/media" |
| + |
| +// collect needs Linux (O_NONBLOCK opens, Stat_t's links, device and |
| +// inode, as collect_linux.go checks them): the handler runs only in the |
| +// engine's Linux image. Elsewhere it opens nothing and refuses. |
| +func collect(string, []string, map[string]int64) ([]collected, error) { |
| + return nil, outputRefused{"the output directory", "collecting outputs needs Linux", media.CodeEngineFailed} |
| +} |
| + |
| +// scratchFull is never true off Linux, where nothing is converted. |
| +func scratchFull(string) bool { return false } |
diff --git a/internal/mediahandler/collect_test.go b/internal/mediahandler/collect_test.go| new file mode 100644 |
| index 000000000..579d7e8e2 |
| --- /dev/null |
| +++ b/internal/mediahandler/collect_test.go |
| @@ -0,0 +1,391 @@ |
| +//go:build linux |
| + |
| +package mediahandler |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "io" |
| + "net" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// collectBound is the media file's bound in these tests (the payload's |
| +// output limit), so one byte over it is a small sparse file. |
| +const collectBound = 64 << 10 |
| + |
| +// writeGoodOutputs writes each of names, a regular file of random bytes |
| +// within its bound, under dir, and answers their contents. |
| +func writeGoodOutputs(t *testing.T, dir string, names []string) map[string][]byte { |
| + t.Helper() |
| + out := map[string][]byte{} |
| + for i, name := range names { |
| + data := randomBytes(t, 1000+i*100) |
| + if err := os.WriteFile(filepath.Join(dir, name), data, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + out[name] = data |
| + } |
| + return out |
| +} |
| + |
| +// openFDs is how many descriptors the process has open. |
| +func openFDs(t *testing.T) int { |
| + t.Helper() |
| + ents, err := os.ReadDir("/proc/self/fd") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return len(ents) |
| +} |
| + |
| +// hostile makes dir/name hostile in one way; bound is name's bound. |
| +// why is collect's reason for it: each kind is caught by its own check, |
| +// so removing that check changes the reason even where a later one |
| +// still refuses. |
| +type hostile struct { |
| + name, why string |
| + make func(t *testing.T, dir, name string, bound int64) |
| +} |
| + |
| +var hostiles = []hostile{ |
| + {"symlink to /etc/passwd", "a symlink", func(t *testing.T, dir, name string, _ int64) { |
| + replace(t, dir, name, func(path string) error { return os.Symlink("/etc/passwd", path) }) |
| + }}, |
| + {"symlink to a sibling", "a symlink", func(t *testing.T, dir, name string, _ int64) { |
| + if err := os.WriteFile(filepath.Join(dir, "sibling"), []byte("sibling"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + replace(t, dir, name, func(path string) error { return os.Symlink("sibling", path) }) |
| + }}, |
| + {"hard link", "has 2 links", func(t *testing.T, dir, name string, _ int64) { |
| + if err := os.Link(filepath.Join(dir, name), filepath.Join(dir, "second-name")); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + {"FIFO", "not a regular file", func(t *testing.T, dir, name string, _ int64) { |
| + replace(t, dir, name, func(path string) error { return unix.Mkfifo(path, 0o600) }) |
| + }}, |
| + {"directory", "not a regular file", func(t *testing.T, dir, name string, _ int64) { |
| + replace(t, dir, name, func(path string) error { return os.Mkdir(path, 0o700) }) |
| + }}, |
| + {"socket", "not a regular file", func(t *testing.T, dir, name string, _ int64) { |
| + // A relative name: a sandbox's TMPDIR can make the absolute path |
| + // longer than a socket address holds (preflight F34). |
| + t.Chdir(dir) |
| + replace(t, dir, name, func(string) error { |
| + l, err := net.Listen("unix", name) |
| + if err == nil { |
| + t.Cleanup(func() { l.Close() }) |
| + } |
| + return err |
| + }) |
| + }}, |
| + {"empty file", "empty", func(t *testing.T, dir, name string, _ int64) { |
| + replace(t, dir, name, func(path string) error { return os.WriteFile(path, nil, 0o600) }) |
| + }}, |
| + {"one byte over its bound", "over its ", func(t *testing.T, dir, name string, bound int64) { |
| + if err := os.Truncate(filepath.Join(dir, name), bound+1); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + {"missing", "cannot be read: no such file or directory", func(t *testing.T, dir, name string, _ int64) { |
| + if err := os.Remove(filepath.Join(dir, name)); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| +} |
| + |
| +// replace removes dir/name and makes something else there. |
| +func replace(t *testing.T, dir, name string, make func(path string) error) { |
| + t.Helper() |
| + path := filepath.Join(dir, name) |
| + if err := os.Remove(path); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := make(path); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// TestCollectRefusesHostileOutputs: under each expected name of each |
| +// preset in turn, a symlink (out of the scratch, or to a sibling), a |
| +// hard link, a FIFO, a directory, a socket, an empty file, a file one |
| +// byte over its bound, or nothing: collect refuses it, engine_failed |
| +// (output_too_large for an oversized video.mp4 or audio.mp4), naming |
| +// it; leaves no descriptor open; never opens a name after it; and, |
| +// through deliver, the store receives no request at all. |
| +func TestCollectRefusesHostileOutputs(t *testing.T) { |
| + h := newHarness(t) // one server for every case: none may reach it |
| + t.Cleanup(func() { collectBetween = nil }) |
| + for _, preset := range []string{media.PresetVideo720p, media.PresetAudioAAC} { |
| + p := h.s.payload(t, preset, nil, mib) |
| + p.Limits.OutputBytes = collectBound |
| + bounds := outputBounds(p) |
| + names := media.OutputNames(preset) |
| + for i, name := range names { |
| + for _, k := range hostiles { |
| + t.Run(preset+"/"+name+"/"+k.name, func(t *testing.T) { |
| + cfg := h.cfg.withDefaults() |
| + cfg.Scratch = t.TempDir() |
| + if err := prepareScratch(cfg.Scratch); err != nil { |
| + t.Fatal(err) |
| + } |
| + out := filepath.Join(cfg.Scratch, "out") |
| + writeGoodOutputs(t, out, names) |
| + k.make(t, out, name, bounds[name]) |
| + want := media.CodeEngineFailed |
| + if k.name == "one byte over its bound" && mediaOutput(name) { |
| + want = media.CodeOutputTooLarge |
| + } |
| + |
| + var opened []string |
| + collectBetween = func(n string) { opened = append(opened, n) } |
| + before := openFDs(t) |
| + cs, err := collect(out, names, bounds) |
| + after := openFDs(t) |
| + collectBetween = nil |
| + if cs != nil || codeOf(err) != want { |
| + t.Fatalf("collect = %d files, %s; want %s", len(cs), codeOf(err), want) |
| + } |
| + if !strings.HasPrefix(err.Error(), "output "+name+" refused: "+k.why) { |
| + t.Fatalf("collect's refusal %q, want %s refused: %s", err, name, k.why) |
| + } |
| + if after != before { |
| + t.Fatalf("%d descriptors open after the refusal, %d before", after, before) |
| + } |
| + for _, n := range opened { |
| + if slices.Index(names, n) > i { |
| + t.Fatalf("collect opened %s, after the refused %s", n, name) |
| + } |
| + } |
| + |
| + f, _ := parseProbe(fixture(t, "ok-av"), media.PresetVideo720p) |
| + if _, err := deliver(context.Background(), cfg, p, f); codeOf(err) != want { |
| + t.Fatalf("deliver = %s, want %s", codeOf(err), want) |
| + } |
| + if rs := h.s.Requests(); len(rs) != 0 { |
| + t.Fatalf("the store received %d requests", len(rs)) |
| + } |
| + }) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// TestCollectAcceptsRegularFiles: regular files of one link, 1 byte or |
| +// exactly their bound, are answered in order, open read-only, with |
| +// their sizes; each reads its own bytes from the descriptor, even after |
| +// its path is given to another file. |
| +func TestCollectAcceptsRegularFiles(t *testing.T) { |
| + dir := t.TempDir() |
| + names := media.OutputNames(media.PresetVideo720p) |
| + p := media.Payload{Limits: media.JobLimits{OutputBytes: collectBound}} |
| + want := writeGoodOutputs(t, dir, names) |
| + want["video.mp4"] = randomBytes(t, collectBound) // at its bound |
| + want["poster.jpg"] = []byte{0xff} // one byte |
| + for _, n := range []string{"video.mp4", "poster.jpg"} { |
| + if err := os.WriteFile(filepath.Join(dir, n), want[n], 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + cs, err := collect(dir, names, outputBounds(p)) |
| + if err != nil { |
| + t.Fatalf("collect: %v", err) |
| + } |
| + defer closeCollected(cs) |
| + if len(cs) != 3 { |
| + t.Fatalf("%d files, want 3", len(cs)) |
| + } |
| + // Every path now names other bytes. |
| + for _, n := range names { |
| + tmp := filepath.Join(dir, "new") |
| + if err := os.WriteFile(tmp, []byte("replaced"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Rename(tmp, filepath.Join(dir, n)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for i, c := range cs { |
| + if c.Name != names[i] || c.Size != int64(len(want[c.Name])) { |
| + t.Fatalf("file %d: %s of %d bytes", i, c.Name, c.Size) |
| + } |
| + got, err := io.ReadAll(io.NewSectionReader(c.File, 0, c.Size)) |
| + if err != nil || !bytes.Equal(got, want[c.Name]) { |
| + t.Fatalf("%s: read %d bytes, %v", c.Name, len(got), err) |
| + } |
| + if _, err := c.File.Write([]byte("x")); err == nil { |
| + t.Fatalf("%s is open for writing", c.Name) |
| + } |
| + } |
| +} |
| + |
| +// TestCollectRefusesASwapAfterTheLstat: what is opened must be what the |
| +// Lstat checked. Swapped in between (collectBetween): a symlink to a |
| +// regular sibling inside the directory (os.Root follows it even with |
| +// O_NOFOLLOW; the inode check refuses it), another regular file (the |
| +// inode check), or a FIFO (opened without blocking, O_NONBLOCK, then |
| +// refused as not regular). Each fails if its guard is removed; the FIFO |
| +// case by blocking, which the 10 s bound turns into a failure. |
| +func TestCollectRefusesASwapAfterTheLstat(t *testing.T) { |
| + t.Cleanup(func() { collectBetween = nil }) |
| + names := media.OutputNames(media.PresetAudioAAC) |
| + bounds := outputBounds(media.Payload{}) |
| + for _, c := range []struct { |
| + name string |
| + swap func(dir, path string) error |
| + why string |
| + }{ |
| + {"symlink to a sibling", func(dir, path string) error { |
| + if err := os.WriteFile(filepath.Join(dir, "sibling"), []byte("sibling"), 0o600); err != nil { |
| + return err |
| + } |
| + if err := os.Remove(path); err != nil { |
| + return err |
| + } |
| + return os.Symlink("sibling", path) |
| + }, "not the file checked before the open"}, |
| + {"another file", func(dir, path string) error { |
| + tmp := filepath.Join(dir, "other") |
| + if err := os.WriteFile(tmp, []byte("other"), 0o600); err != nil { |
| + return err |
| + } |
| + return os.Rename(tmp, path) |
| + }, "not the file checked before the open"}, |
| + {"FIFO", func(dir, path string) error { |
| + if err := os.Remove(path); err != nil { |
| + return err |
| + } |
| + return unix.Mkfifo(path, 0o600) |
| + }, "not a regular file when opened"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + dir := t.TempDir() |
| + writeGoodOutputs(t, dir, names) |
| + var swapErr error |
| + collectBetween = func(n string) { |
| + if n == "audio.m3u8" { |
| + swapErr = c.swap(dir, filepath.Join(dir, n)) |
| + } |
| + } |
| + done := make(chan error, 1) |
| + go func() { |
| + cs, err := collect(dir, names, bounds) |
| + closeCollected(cs) |
| + done <- err |
| + }() |
| + var err error |
| + select { |
| + case err = <-done: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("collect blocked") |
| + } |
| + collectBetween = nil |
| + if swapErr != nil { |
| + t.Fatal(swapErr) |
| + } |
| + if codeOf(err) != media.CodeEngineFailed || !strings.Contains(err.Error(), "audio.m3u8 refused: "+c.why) { |
| + t.Fatalf("collect = %v, want audio.m3u8 refused: %s", err, c.why) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestCollectNeedsItsDirectory: an output directory that is a symlink |
| +// (to a directory of good outputs), or absent, is refused before |
| +// anything in it is opened. |
| +func TestCollectNeedsItsDirectory(t *testing.T) { |
| + names := media.OutputNames(media.PresetVideo720p) |
| + bounds := outputBounds(media.Payload{}) |
| + if _, err := collect(filepath.Join(t.TempDir(), "absent"), names, bounds); codeOf(err) != media.CodeEngineFailed { |
| + t.Fatalf("absent directory: %s", codeOf(err)) |
| + } |
| + elsewhere := t.TempDir() |
| + writeGoodOutputs(t, elsewhere, names) |
| + link := filepath.Join(t.TempDir(), "out") |
| + if err := os.Symlink(elsewhere, link); err != nil { |
| + t.Fatal(err) |
| + } |
| + if cs, err := collect(link, names, bounds); cs != nil || codeOf(err) != media.CodeEngineFailed || !strings.Contains(err.Error(), "not a directory") { |
| + t.Fatalf("a linked directory: %d files, %v", len(cs), err) |
| + } |
| + // A name that is not a plain file name is never looked up. |
| + dir := t.TempDir() |
| + writeGoodOutputs(t, dir, names) |
| + if _, err := collect(dir, []string{"../" + filepath.Base(dir) + "/video.mp4"}, map[string]int64{"../" + filepath.Base(dir) + "/video.mp4": 1 << 20}); codeOf(err) != media.CodeEngineFailed { |
| + t.Fatalf("a path for a name: %s", codeOf(err)) |
| + } |
| +} |
| + |
| +// TestCollectRefusesADirectorySwap: the output directory swapped for a |
| +// link to another directory of good outputs, after its Lstat and |
| +// before its open, is refused: the root opened is not the directory |
| +// checked. |
| +func TestCollectRefusesADirectorySwap(t *testing.T) { |
| + t.Cleanup(func() { collectBetween = nil }) |
| + names := media.OutputNames(media.PresetVideo720p) |
| + parent := t.TempDir() |
| + out := filepath.Join(parent, "out") |
| + elsewhere := filepath.Join(parent, "elsewhere") |
| + for _, d := range []string{out, elsewhere} { |
| + if err := os.Mkdir(d, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + writeGoodOutputs(t, d, names) |
| + } |
| + var swapErr error |
| + collectBetween = func(n string) { |
| + if n == "." { |
| + swapErr = errors.Join(os.Rename(out, filepath.Join(parent, "moved")), os.Symlink("elsewhere", out)) |
| + } |
| + } |
| + cs, err := collect(out, names, outputBounds(media.Payload{})) |
| + collectBetween = nil |
| + if swapErr != nil { |
| + t.Fatal(swapErr) |
| + } |
| + if cs != nil || codeOf(err) != media.CodeEngineFailed || !strings.Contains(err.Error(), "not the directory checked") { |
| + t.Fatalf("collect = %d files, %v", len(cs), err) |
| + } |
| +} |
| + |
| +// TestChildrenDeadKillsStrays: a child of the handler still alive when |
| +// the outputs are to be read (none should be: runChild reaps each run's |
| +// tree) is killed and reaped by childrenDead. |
| +func TestChildrenDeadKillsStrays(t *testing.T) { |
| + needChildren(t) |
| + cmd := exec.Command(fakeBinary(t)) |
| + cmd.Env = []string{fakeEnv + "=block"} |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + pid := cmd.Process.Pid |
| + cfg, _ := fakeConfig(t, "block") |
| + if err := childrenDead(cfg); err != nil { |
| + t.Fatalf("childrenDead: %v", err) |
| + } |
| + wantGone(t, pid) |
| +} |
| + |
| +// TestScratchFullOnARealDirectory: a test's temporary directory is not |
| +// full, and statfs failing (no such directory) is not full either. |
| +func TestScratchFullOnARealDirectory(t *testing.T) { |
| + if scratchFull(t.TempDir()) { |
| + t.Fatal("a temporary directory reads as full") |
| + } |
| + if scratchFull(filepath.Join(t.TempDir(), "absent")) { |
| + t.Fatal("an absent directory reads as full") |
| + } |
| +} |
diff --git a/internal/mediahandler/download_test.go b/internal/mediahandler/download_test.go| index fab8cc0be..502a12c28 100644 |
| --- a/internal/mediahandler/download_test.go |
| +++ b/internal/mediahandler/download_test.go |
| @@ -1010,8 +1010,9 @@ func TestRunRejectsABadPayload(t *testing.T) { |
| } |
| // 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. |
| +// tmp at 0700 and downloads the source to in/source. Random bytes then |
| +// sniff as no container: the run exits 1 (Task 6's run_test.go drives |
| +// whole conversions). |
| func TestRunPreparesScratchAndDownloads(t *testing.T) { |
| h := newHarness(t) |
| data := randomBytes(t, 4096) |
| @@ -1019,7 +1020,7 @@ func TestRunPreparesScratchAndDownloads(t *testing.T) { |
| 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) |
| + t.Fatalf("Run = %d, want %d for bytes that are no container", code, media.ExitFailed) |
| } |
| for _, d := range []string{"in", "out", "tmp"} { |
| fi, err := os.Lstat(filepath.Join(cfg.Scratch, d)) |
| @@ -1031,14 +1032,15 @@ func TestRunPreparesScratchAndDownloads(t *testing.T) { |
| 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. |
| + // A scratch whose "in" is a link is refused before the source is |
| + // fetched (its result, engine_failed, is TestRunScratchUnusableWritesEngineFailed's). |
| 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) |
| + before := len(gets(h.s.Requests())) |
| + if code := Run(context.Background(), cfg, marshal(t, p)); code != media.ExitFailed || len(gets(h.s.Requests())) != before { |
| + t.Fatalf("Run over a linked in/ = %d with %d GETs", code, len(gets(h.s.Requests()))-before) |
| } |
| } |
diff --git a/internal/mediahandler/ffmpeg.go b/internal/mediahandler/ffmpeg.go| index 307589d54..fd71eea70 100644 |
| --- a/internal/mediahandler/ffmpeg.go |
| +++ b/internal/mediahandler/ffmpeg.go |
| @@ -286,6 +286,11 @@ func encode(ctx context.Context, cfg Config, what string, args []string) error { |
| // before the child has exited or ctx has ended, so it is the |
| // kernel's OOM killer (the task's memory, not the source, is what |
| // ran out), and the operator, not the tenant, has to act; |
| +// - any other failure with the scratch's file system full |
| +// (Config.diskFull): engine_failed. The task's storage is sized |
| +// from the source with headroom for the outputs (media.EphemeralGiB), |
| +// so running out is the engine's sizing, as the OOM killer is, and |
| +// the operator, not the tenant, has to act (plan 3 Task 6); |
| // - any other failure, a crash by another signal included: |
| // unreadable. With logTail, the log line carries the last |
| // encodeLogTail bytes of ffmpeg's stderr (quoted, so it stays one |
| @@ -305,6 +310,10 @@ func ffmpegOutcome(ctx context.Context, cfg Config, what string, err error, tail |
| // engine.encode.killed (pending Luna pass). |
| cfg.Logf("codec: ffmpeg (%s) was killed by SIGKILL, likely out of memory", what) |
| return jobError{media.CodeEngineFailed} |
| + case cfg.diskFull(cfg.Scratch): |
| + // engine.encode.scratch_full (pending Luna pass). |
| + cfg.Logf("codec: ffmpeg (%s) failed with the scratch disk full", what) |
| + return jobError{media.CodeEngineFailed} |
| case !logTail: |
| // engine.encode.failed_unlogged (pending Luna pass). |
| cfg.Logf("codec: ffmpeg (%s) failed; its output is not logged", what) |
diff --git a/internal/mediahandler/handler.go b/internal/mediahandler/handler.go| index 61c67add0..0ba1d81f6 100644 |
| --- a/internal/mediahandler/handler.go |
| +++ b/internal/mediahandler/handler.go |
| @@ -1,7 +1,7 @@ |
| // Package mediahandler is the codec container's handler (spec §5.5, §6): |
| // it reads the payload, downloads the source with the signed transfer, |
| -// sniffs, probes and checks it, and (later tasks of plan 3) converts, |
| -// collects the outputs, uploads them and writes the result object. |
| +// sniffs, probes and checks it, converts it, collects the outputs, |
| +// uploads them and writes the result object (run.go). |
| // |
| // 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 |
| @@ -62,6 +62,9 @@ type Config struct { |
| // extraEnv is appended to every child's environment (childEnv). |
| // Tests only: it names the fake ffmpeg's scenario. |
| extraEnv []string |
| + // diskFull reports whether the scratch's file system is full; nil |
| + // is scratchFull. Tests replace it. |
| + diskFull func(dir string) bool |
| } |
| // withDefaults fills every unset field. |
| @@ -95,11 +98,14 @@ func (c Config) withDefaults() Config { |
| if c.idle == nil { |
| c.idle = newIdleTimer |
| } |
| + if c.diskFull == nil { |
| + c.diskFull = scratchFull |
| + } |
| 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). |
| +// and the result object carries it (run.go's finish). |
| type jobError struct{ code string } |
| func (e jobError) Error() string { return e.code } |
| @@ -110,63 +116,6 @@ func (e jobError) Error() string { return e.code } |
| // 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 |
| - // is one of parsePayload's fixed strings, 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 { |
| - // Sniff, probe and check (spec §6). The encodes (plan 3 Tasks 4 |
| - // and 5) take the demuxer and the facts. |
| - _, _, err = inspectSource(ctx, cfg, p) |
| - } |
| - 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") } |
diff --git a/internal/mediahandler/probe_test.go b/internal/mediahandler/probe_test.go| index 7aa92d1cc..bcd9a5f3e 100644 |
| --- a/internal/mediahandler/probe_test.go |
| +++ b/internal/mediahandler/probe_test.go |
| @@ -52,6 +52,9 @@ func TestParseProbeFixtures(t *testing.T) { |
| "lying-10h": {v, probeFacts{VideoIndex: 0, AudioIndex: -1, Width: 1280, Height: 720, FPS: 30, VideoCodec: "h264", DurationMS: 36000000}}, |
| "wav-mono": {a, probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "pcm_s16le", Channels: 1, DurationMS: 2500}}, |
| "aac-6ch": {a, probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "aac", Channels: 6, DurationMS: 2000}}, |
| + // Hand-written for Run's ok-video and ok-audio (plan 3 Task 6). |
| + "ok-av": {v, probeFacts{VideoIndex: 0, AudioIndex: 1, Width: 160, Height: 90, SARNum: 1, SARDen: 1, FPS: 30, VideoCodec: "h264", AudioCodec: "aac", Channels: 2, DurationMS: 9000}}, |
| + "ok-audio": {a, probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "aac", Channels: 2, DurationMS: 9000}}, |
| } |
| entries, err := probeFixtures.ReadDir("testdata/probe") |
| if err != nil { |
| @@ -764,7 +767,8 @@ func TestRunInspectsTheSource(t *testing.T) { |
| {"an mp3 under video-720p", "probe-mp3-cover-art", headID3, "codec: failed: unsupported_container", 0}, |
| {"a bomb", "probe-bomb-30000", headMP4, "codec: failed: source_dimensions", 1}, |
| {"cover art only", "probe-m4a-cover-art", headM4A, "codec: failed: no_video", 1}, |
| - {"a good 4K60", "probe-h264-4k60", headMP4, "codec: source downloaded; conversion is not built in this image", 1}, |
| + // Inspection passes, so the encode begins (and cannot start). |
| + {"a good 4K60", "probe-h264-4k60", headMP4, "codec: child process: cannot start /nonexistent/ffmpeg: fork/exec /nonexistent/ffmpeg: no such file or directory", 1}, |
| } { |
| h := newHarness(t) |
| data := append(append([]byte(nil), c.head...), randomBytes(t, 1024)...) |
| @@ -774,6 +778,7 @@ func TestRunInspectsTheSource(t *testing.T) { |
| cfg := h.cfg |
| cfg.Scratch = t.TempDir() |
| cfg.FFprobe, cfg.extraEnv = fc.FFprobe, fc.extraEnv |
| + cfg.FFmpeg = "/nonexistent/ffmpeg" |
| if code := Run(context.Background(), cfg, marshal(t, p)); code != media.ExitFailed { |
| t.Errorf("%s: Run = %d", c.name, code) |
| } |
diff --git a/internal/mediahandler/procs_linux.go b/internal/mediahandler/procs_linux.go| index b7b44289c..603664c7a 100644 |
| --- a/internal/mediahandler/procs_linux.go |
| +++ b/internal/mediahandler/procs_linux.go |
| @@ -158,6 +158,23 @@ func runChildTo(ctx context.Context, cfg Config, name string, args []string, dir |
| return tail.Bytes(), childFailed(cfg, "wait failed", waitErr) |
| } |
| +// childrenDead makes sure the handler has no child left before it |
| +// reads the output directory (spec §6: only after the child and every |
| +// descendant are dead). runChild already reaps each run's whole tree, |
| +// so this finds none; it is the check, not the cleanup: any process it |
| +// finds is killed and reaped as runChild would, within reapBudget, else |
| +// engine_failed. |
| +func childrenDead(cfg Config) error { |
| + childMu.Lock() |
| + defer childMu.Unlock() |
| + budget := time.NewTimer(reapBudget) |
| + defer budget.Stop() |
| + if err := reapDescendants(budget.C); err != nil { |
| + return childFailed(cfg, "descendants outlived the cleanup", err) |
| + } |
| + return nil |
| +} |
| + |
| // childFailed logs why a child could not be run or cleaned up and |
| // answers engine_failed. |
| func childFailed(cfg Config, why string, err error) error { |
diff --git a/internal/mediahandler/procs_other.go b/internal/mediahandler/procs_other.go| index 201d9c1b9..9c4ecfa1c 100644 |
| --- a/internal/mediahandler/procs_other.go |
| +++ b/internal/mediahandler/procs_other.go |
| @@ -22,3 +22,6 @@ func runChildTo(_ context.Context, cfg Config, _ string, _ []string, _ string, _ |
| cfg.Logf("codec: child processes need Linux") |
| return nil, jobError{media.CodeEngineFailed} |
| } |
| + |
| +// childrenDead has nothing to check where no child can be started. |
| +func childrenDead(Config) error { return nil } |
diff --git a/internal/mediahandler/result.go b/internal/mediahandler/result.go| new file mode 100644 |
| index 000000000..9d5efe584 |
| --- /dev/null |
| +++ b/internal/mediahandler/result.go |
| @@ -0,0 +1,75 @@ |
| +package mediahandler |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "path/filepath" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// writeResult PUTs r, as JSON, to the payload's result transfer |
| +// (create-only, like the outputs: put's rules). A result over |
| +// media.MaxResultBytes, which the console would not read, is never |
| +// sent: engine_failed. |
| +func writeResult(ctx context.Context, cfg Config, p media.Payload, r media.Result) error { |
| + b, err := json.Marshal(r) |
| + if err != nil || len(b) > media.MaxResultBytes { |
| + // engine.result.unmarshalable (pending Luna pass). |
| + cfg.Logf("codec: the result cannot be written as at most %d bytes of JSON", media.MaxResultBytes) |
| + return jobError{media.CodeEngineFailed} |
| + } |
| + _, err = put(ctx, cfg, p, p.Transfers.Result, "the result", int64(len(b)), func() io.Reader { return bytes.NewReader(b) }) |
| + return err |
| +} |
| + |
| +// versionOutputBytes is the most of ffmpeg -version's output kept. |
| +const versionOutputBytes = 4 << 10 |
| + |
| +// ffmpegVersion is the version ffmpeg -version names on its first line, |
| +// "ffmpeg version <v> Copyright …", for the result (spec §5.2). The |
| +// binary is the image's own, run as every other ffmpeg is (runChild), |
| +// on no input. A run that fails, or a line that is not that shape, or a |
| +// version of anything but letters, digits and ".+~:_-" (at most 64), |
| +// gives "" (the result then names none), logged; only ctx ending is an |
| +// error. |
| +func ffmpegVersion(ctx context.Context, cfg Config) (string, error) { |
| + out := &capBuffer{max: versionOutputBytes} |
| + _, err := runChildTo(ctx, cfg, cfg.FFmpeg, []string{"-hide_banner", "-version"}, filepath.Join(cfg.Scratch, "tmp"), out) |
| + if ctx.Err() != nil { |
| + return "", ctx.Err() |
| + } |
| + v := "" |
| + if err == nil { |
| + v = parseVersion(out.buf.Bytes()) |
| + } |
| + if v == "" { |
| + // engine.version.unknown (pending Luna pass). |
| + cfg.Logf("codec: ffmpeg's version cannot be read; the result names none") |
| + } |
| + return v, nil |
| +} |
| + |
| +// parseVersion reads "ffmpeg version <v> …" from b's first line; "" if |
| +// it is not that, or v is not a plain version. |
| +func parseVersion(b []byte) string { |
| + line, _, _ := bytes.Cut(b, []byte{'\n'}) |
| + fields := strings.Fields(string(line)) |
| + if len(fields) < 3 || fields[0] != "ffmpeg" || fields[1] != "version" { |
| + return "" |
| + } |
| + v := fields[2] |
| + if len(v) > 64 { |
| + return "" |
| + } |
| + for i := 0; i < len(v); i++ { |
| + c := v[i] |
| + if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.IndexByte(".+~:_-", c) >= 0) { |
| + return "" |
| + } |
| + } |
| + return v |
| +} |
diff --git a/internal/mediahandler/run.go b/internal/mediahandler/run.go| new file mode 100644 |
| index 000000000..11dc8d935 |
| --- /dev/null |
| +++ b/internal/mediahandler/run.go |
| @@ -0,0 +1,278 @@ |
| +package mediahandler |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io/fs" |
| + "os" |
| + "os/signal" |
| + "path/filepath" |
| + "syscall" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// exitStopped is the codec's exit when it is stopped (SIGTERM, which |
| +// ECS sends when the deadline container or the console ends the task, |
| +// or its context ending) before it finished: 128 + SIGTERM, what a |
| +// process SIGTERM killed reports. No result is written: the console |
| +// classifies the stop from the deadline container's exit |
| +// (media.ClassifyStop). |
| +const exitStopped = 143 |
| + |
| +// Run is the codec's whole program: payload is media.PayloadEnv's value. |
| +// It answers the process's exit code. The flow (spec §6): |
| +// |
| +// download → sniff → probe → check → (audio-aac: measure, the gain) |
| +// → encode (video-720p: video, poster; audio-aac: audio under the |
| +// ceiling) → readFMP4 + the playlist → (audio-aac: peaks) → ffmpeg's |
| +// version → every child dead → collect → upload the three outputs in |
| +// order → the result object → exit 0. |
| +// |
| +// Exits (finish): |
| +// |
| +// - 0 once the result object is written; |
| +// - SIGTERM, or ctx ending: every child killed (runChild), exit |
| +// exitStopped, no result; |
| +// - errGrantExpired (a transfer refused, or not begun, at or after the |
| +// grant's expiry, or an ffmpeg pass still running at it): exit |
| +// media.ExitGrantExpired, no result (the result PUT has expired |
| +// with the same grant); |
| +// - a jobError anywhere (a refused payload aside): a best-effort result |
| +// object with its code, exit media.ExitFailed; |
| +// - the success result not written: exit media.ExitFailed, no second |
| +// attempt. |
| +// |
| +// Every ffmpeg and ffprobe pass runs under the grant's deadline |
| +// (grantContext): converting past it cannot be uploaded. The download |
| +// and the uploads do not: a transfer begun before the expiry completes |
| +// (spec §5.4), and each checks the expiry before it begins. |
| +func Run(ctx context.Context, cfg Config, payload string) int { |
| + cfg = cfg.withDefaults() |
| + ctx, stop := signal.NotifyContext(ctx, syscall.SIGTERM) |
| + defer stop() |
| + p, err := parsePayload(payload) |
| + if err != nil { |
| + // engine.codec.payload_refused (pending Luna pass). The reason |
| + // is one of parsePayload's fixed strings, never a value from the |
| + // payload. |
| + cfg.Logf("codec: payload refused: %v", err) |
| + return media.ExitFailed |
| + } |
| + return finish(ctx, cfg, p, runJob(ctx, cfg, p)) |
| +} |
| + |
| +// runJob is Run's flow from the scratch to the result object. |
| +func runJob(ctx context.Context, cfg Config, p media.Payload) error { |
| + if err := prepareScratch(cfg.Scratch); err != nil { |
| + // engine.codec.scratch (pending Luna pass). |
| + cfg.Logf("codec: scratch directory unusable: %v", err) |
| + return jobError{media.CodeEngineFailed} |
| + } |
| + if err := download(ctx, cfg, p, sourcePath(cfg)); err != nil { |
| + return err |
| + } |
| + gctx, cancel := grantContext(ctx, cfg, p) |
| + defer cancel() |
| + f, durationMS, version, err := convert(gctx, cfg, p) |
| + if err != nil { |
| + return grantEnded(ctx, gctx, err) |
| + } |
| + if err := childrenDead(cfg); err != nil { |
| + return err |
| + } |
| + outputs, err := deliver(ctx, cfg, p, f) |
| + if err != nil { |
| + return err |
| + } |
| + r := media.Result{ |
| + V: media.ResultVersion, |
| + Execution: p.Execution, |
| + Source: sourceFacts(f, p.Preset, durationMS), |
| + FFmpeg: version, |
| + Outputs: outputs, |
| + } |
| + if err := writeResult(ctx, cfg, p, r); err != nil { |
| + return resultUnwritten{err} |
| + } |
| + return nil |
| +} |
| + |
| +// grantContext is ctx ended at the grant's expiry. The expiry is read |
| +// against cfg.Now (the clock every transfer compares it with), and the |
| +// time left is put on Go's own clock, which a context's deadline uses. |
| +func grantContext(ctx context.Context, cfg Config, p media.Payload) (context.Context, context.CancelFunc) { |
| + left := time.Unix(p.Expiry, 0).Sub(cfg.Now()) |
| + return context.WithTimeout(ctx, left) |
| +} |
| + |
| +// grantEnded maps an error of a pass run under gctx: gctx's end while |
| +// ctx goes on is the grant's expiry; anything else is as it is. |
| +func grantEnded(ctx, gctx context.Context, err error) error { |
| + if ctx.Err() == nil && gctx.Err() != nil && errors.Is(err, gctx.Err()) { |
| + return errGrantExpired |
| + } |
| + return err |
| +} |
| + |
| +// convert sniffs, probes and checks the source, encodes it, packages |
| +// the media file and makes the preset's third output, and reads ffmpeg's |
| +// version, all under ctx (the grant's). durationMS is what was |
| +// converted: readFMP4's, never more than the granted duration |
| +// (packageOutput, spec A2). |
| +func convert(ctx context.Context, cfg Config, p media.Payload) (f probeFacts, durationMS int64, version string, err error) { |
| + demuxer, f, err := inspectSource(ctx, cfg, p) |
| + if err != nil { |
| + return f, 0, "", err |
| + } |
| + switch p.Preset { |
| + case media.PresetVideo720p: |
| + durationMS, err = convertVideo(ctx, cfg, p, demuxer, f) |
| + case media.PresetAudioAAC: |
| + durationMS, err = convertAudio(ctx, cfg, p, demuxer, f) |
| + default: |
| + err = jobError{media.CodeEngineFailed} // Validate knows only these two |
| + } |
| + if err != nil { |
| + return f, 0, "", err |
| + } |
| + version, err = ffmpegVersion(ctx, cfg) |
| + return f, durationMS, version, err |
| +} |
| + |
| +// convertVideo is video-720p's: the video and the poster |
| +// (encodeVideo), the poster required (a run that exits 0 with no file |
| +// decoded no frame: unreadable), then video.mp4's playlist. |
| +func convertVideo(ctx context.Context, cfg Config, p media.Payload, demuxer string, f probeFacts) (int64, error) { |
| + if err := encodeVideo(ctx, cfg, p, demuxer, f); err != nil { |
| + return 0, err |
| + } |
| + if _, err := os.Lstat(outPath(cfg, videoNames[2])); errors.Is(err, fs.ErrNotExist) { |
| + // engine.encode.no_frame (pending Luna pass). |
| + cfg.Logf("codec: ffmpeg wrote no frame to %s", videoNames[2]) |
| + return 0, jobError{media.CodeUnreadable} |
| + } |
| + return packageOutput(cfg, p, videoNames[0], videoNames[1]) |
| +} |
| + |
| +// convertAudio is audio-aac's, in the order Task 5 left: the loudness |
| +// pass, the encode under the ceiling, audio.mp4's playlist, then the |
| +// peaks with the gain audio.mp4 was finally encoded with, over the |
| +// converted duration. |
| +func convertAudio(ctx context.Context, cfg Config, p media.Payload, demuxer string, f probeFacts) (int64, error) { |
| + gain, err := measureLoudness(ctx, cfg, p, demuxer, f) |
| + if err != nil { |
| + return 0, err |
| + } |
| + final, err := encodeAudioUnderCeiling(ctx, cfg, p, demuxer, f, gain) |
| + if err != nil { |
| + return 0, err |
| + } |
| + durationMS, err := packageOutput(cfg, p, audioNames[0], audioNames[1]) |
| + if err != nil { |
| + return 0, err |
| + } |
| + durationMS = min(durationMS, p.Limits.GrantedMS) |
| + if err := makePeaks(ctx, cfg, p, demuxer, f, final, durationMS); err != nil { |
| + return 0, err |
| + } |
| + return durationMS, nil |
| +} |
| + |
| +// sourceFacts are the result's source facts: the converted duration |
| +// (spec A2: what the job is charged for, at most the grant), the |
| +// source's stored dimensions and video codec (video-720p), and its |
| +// audio codec when it has audio. |
| +func sourceFacts(f probeFacts, preset string, durationMS int64) *media.SourceFacts { |
| + s := &media.SourceFacts{DurationMS: durationMS} |
| + if preset == media.PresetVideo720p && f.VideoIndex >= 0 { |
| + s.Width, s.Height, s.VideoCodec = f.Width, f.Height, f.VideoCodec |
| + } |
| + if f.AudioIndex >= 0 { |
| + s.AudioCodec = f.AudioCodec |
| + } |
| + return s |
| +} |
| + |
| +// deliver collects the preset's three outputs from <scratch>/out and |
| +// uploads them in payload order, each from its open file. A refusal by |
| +// collect uploads nothing. video.mp4 and poster.jpg carry the output |
| +// size (outputSize, preflight F16). |
| +func deliver(ctx context.Context, cfg Config, p media.Payload, f probeFacts) ([]media.OutputFact, error) { |
| + names := media.OutputNames(p.Preset) |
| + cs, err := collect(filepath.Join(cfg.Scratch, "out"), names, outputBounds(p)) |
| + if err != nil { |
| + // engine.collect.refused (pending Luna pass). err is an |
| + // outputRefused: an output's name and a fixed reason. |
| + cfg.Logf("codec: %v", err) |
| + return nil, err |
| + } |
| + defer closeCollected(cs) |
| + w, h := outputSize(f) |
| + var outs []media.OutputFact |
| + for i, c := range cs { |
| + etag, err := upload(ctx, cfg, p, p.Transfers.Outputs[i], c) |
| + if err != nil { |
| + return nil, err |
| + } |
| + o := media.OutputFact{Name: c.Name, Bytes: c.Size, ETag: etag, ContentType: media.ContentType(c.Name)} |
| + if c.Name == "video.mp4" || c.Name == "poster.jpg" { |
| + o.Width, o.Height = w, h |
| + } |
| + outs = append(outs, o) |
| + } |
| + return outs, nil |
| +} |
| + |
| +// resultUnwritten is the success result's PUT failing: the job ends |
| +// without a second attempt (finish). |
| +type resultUnwritten struct{ err error } |
| + |
| +func (e resultUnwritten) Error() string { return "result not written: " + e.err.Error() } |
| + |
| +func (e resultUnwritten) Unwrap() error { return e.err } |
| + |
| +// finish logs err's outcome, writes the failure's result object when |
| +// there is one to write, and answers the exit code (see Run). |
| +func finish(ctx context.Context, cfg Config, p media.Payload, err error) int { |
| + var je jobError |
| + var unwritten resultUnwritten |
| + switch { |
| + case err == nil: |
| + // engine.codec.done (pending Luna pass). |
| + cfg.Logf("codec: done; outputs and result written") |
| + return media.ExitDone |
| + case ctx.Err() != nil: |
| + // engine.codec.stopped (pending Luna pass). Go's context error. |
| + cfg.Logf("codec: stopped: %v", ctx.Err()) |
| + return exitStopped |
| + 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, &unwritten): |
| + // engine.codec.result_unwritten (pending Luna pass). Why is |
| + // logged where the PUT failed. |
| + cfg.Logf("codec: converted, but the result could not be written") |
| + return media.ExitFailed |
| + case !errors.As(err, &je): |
| + // engine.codec.unexpected (pending Luna pass). The type alone: |
| + // an error's text could quote a URL (preflight F6). |
| + cfg.Logf("codec: an unexpected %T ends the job", err) |
| + je = jobError{media.CodeEngineFailed} |
| + } |
| + // engine.codec.failed (pending Luna pass). |
| + cfg.Logf("codec: failed: %s", je.code) |
| + werr := writeResult(ctx, cfg, p, media.Result{V: media.ResultVersion, Execution: p.Execution, Error: je.code}) |
| + switch { |
| + case werr == nil: |
| + case ctx.Err() != nil: |
| + cfg.Logf("codec: stopped: %v", ctx.Err()) |
| + return exitStopped |
| + default: |
| + // engine.codec.error_unwritten (pending Luna pass). |
| + cfg.Logf("codec: the result naming %s could not be written", je.code) |
| + } |
| + return media.ExitFailed |
| +} |
diff --git a/internal/mediahandler/run_test.go b/internal/mediahandler/run_test.go| new file mode 100644 |
| index 000000000..80b09e793 |
| --- /dev/null |
| +++ b/internal/mediahandler/run_test.go |
| @@ -0,0 +1,588 @@ |
| +//go:build linux |
| + |
| +package mediahandler |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "embed" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "os" |
| + "os/signal" |
| + "path/filepath" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// fmp4Files are the encodes the ok scenarios write (testdata/fmp4, |
| +// Task 4's fixtures). |
| +// |
| +//go:embed testdata/fmp4/video.mp4 testdata/fmp4/audio.mp4 |
| +var fmp4Files embed.FS |
| + |
| +// fakeVersion is what the fakes answer to -version. |
| +const ( |
| + fakeVersionLine = "ffmpeg version 7.1.5-0+deb13u1 Copyright (c) 2000-2025 the FFmpeg developers\nbuilt with gcc 14\n" |
| + fakeVersion = "7.1.5-0+deb13u1" |
| +) |
| + |
| +// fakeJPEG is the poster the ok fakes write: a JPEG's start and end |
| +// markers around a few bytes. |
| +var fakeJPEG = []byte{0xff, 0xd8, 0xff, 0xe0, 0, 0x10, 'J', 'F', 'I', 'F', 0, 0xff, 0xd9} |
| + |
| +// fakePIDFileEnv names the file a hang scenario writes its pid to. |
| +const fakePIDFileEnv = "MEDIA_FAKE_PIDFILE" |
| + |
| +func init() { |
| + // ok-video and ok-audio are ffprobe and ffmpeg for a whole run: the |
| + // probe answers testdata/probe/ok-av or ok-audio, -version answers |
| + // fakeVersionLine, and each encode writes Task 4's fixture (or a |
| + // JPEG, or peaks.raw's samples) to its last argument, which must not |
| + // exist (ffmpeg without -y). The loudness pass answers I -20, TP -6 |
| + // (gain +4); the output meter TP -3, under the ceiling. |
| + fakeScenarios["ok-video"] = func(args []string) int { return fakeOK("ok-av", args, nil) } |
| + fakeScenarios["ok-audio"] = func(args []string) int { return fakeOK("ok-audio", args, nil) } |
| + // ok-video-hang probes, then writes its pid and waits for the |
| + // SIGKILL it alone does not ignore, as its video encode. |
| + fakeScenarios["ok-video-hang"] = func(args []string) int { |
| + return fakeOK("ok-av", args, func(name string) (int, bool) { |
| + if name != "video.mp4" { |
| + return 0, false |
| + } |
| + if err := os.WriteFile(os.Getenv(fakePIDFileEnv), []byte(strconv.Itoa(os.Getpid())), 0o600); err != nil { |
| + return 1, true |
| + } |
| + return blockForever(), true |
| + }) |
| + } |
| + // ok-video-noposter exits 0 having written no poster (no frame). |
| + fakeScenarios["ok-video-noposter"] = func(args []string) int { |
| + return fakeOK("ok-av", args, func(name string) (int, bool) { return 0, name == "poster.jpg" }) |
| + } |
| + // ok-video-poster-link leaves the poster a symlink out of the |
| + // scratch. |
| + fakeScenarios["ok-video-poster-link"] = func(args []string) int { |
| + return fakeOK("ok-av", args, func(name string) (int, bool) { |
| + if name != "poster.jpg" { |
| + return 0, false |
| + } |
| + return fakeLink("/etc/passwd", args[len(args)-1]), true |
| + }) |
| + } |
| +} |
| + |
| +// fakeOK is the ok scenarios' fake: probe answers the fixture probe, |
| +// and each ffmpeg run is answered by override for its output's name, |
| +// when it answers true, else as ok-video and ok-audio do. |
| +func fakeOK(probe string, args []string, override func(name string) (int, bool)) int { |
| + switch { |
| + case slices.Contains(args, "-version"): |
| + fmt.Print(fakeVersionLine) |
| + return 0 |
| + case slices.Contains(args, "-of"): |
| + return fakeProbe(probe, args) |
| + case slices.Contains(args, "null"): |
| + if strings.HasSuffix(argAfter(args, "-i"), "/out/audio.mp4") { |
| + fmt.Fprint(os.Stderr, summary("-16.0", "-3.0")) |
| + } else { |
| + fmt.Fprint(os.Stderr, summary("-20.0", "-6.0")) |
| + } |
| + return 0 |
| + } |
| + out := args[len(args)-1] |
| + name := filepath.Base(out) |
| + if override != nil { |
| + if code, ok := override(name); ok { |
| + return code |
| + } |
| + } |
| + var data []byte |
| + switch name { |
| + case "video.mp4", "audio.mp4": |
| + b, err := fmp4Files.ReadFile("testdata/fmp4/" + name) |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "fake:", err) |
| + return 1 |
| + } |
| + data = b |
| + case "poster.jpg": |
| + data = fakeJPEG |
| + case peaksRaw: |
| + data = s16le(fakePeakSamples()) |
| + default: |
| + fmt.Fprintln(os.Stderr, "fake: an unexpected output") |
| + return 1 |
| + } |
| + f, err := os.OpenFile(out, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) |
| + if err == nil { |
| + _, err = f.Write(data) |
| + err = errors.Join(err, f.Close()) |
| + } |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "fake:", err) |
| + return 1 |
| + } |
| + return 0 |
| +} |
| + |
| +// runJobSetup is a harness, a payload for preset whose source is |
| +// Task 4's fixture (so it sniffs as ISO BMFF) and whose grant is the |
| +// 9 s those fixtures were encoded under, and a Config on the fake |
| +// running scenario, recording its runs. |
| +func runJobSetup(t *testing.T, preset, scenario string) (*harness, media.Payload, Config, string) { |
| + t.Helper() |
| + h := newHarness(t) |
| + src := "video.mp4" |
| + if preset == media.PresetAudioAAC { |
| + src = "audio.mp4" |
| + } |
| + data, err := fmp4Files.ReadFile("testdata/fmp4/" + src) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p := h.s.payload(t, preset, data, 8*mib) |
| + p.Limits.GrantedMS = 9000 |
| + fake, record := fakeConfig(t, scenario) |
| + cfg := h.cfg |
| + cfg.Scratch = t.TempDir() // Run prepares it |
| + cfg.FFmpeg, cfg.FFprobe, cfg.extraEnv = fake.FFmpeg, fake.FFprobe, fake.extraEnv |
| + return h, p, cfg, record |
| +} |
| + |
| +// runFor runs Run with a 30 s bound. |
| +func runFor(t *testing.T, cfg Config, p media.Payload) int { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| + defer cancel() |
| + return Run(ctx, cfg, marshal(t, p)) |
| +} |
| + |
| +// requestLine is "METHOD path". |
| +func requestLines(rs []s3Request) []string { |
| + var out []string |
| + for _, r := range rs { |
| + out = append(out, r.Method+" "+r.Path) |
| + } |
| + return out |
| +} |
| + |
| +// passKinds names each recorded run: probe, version, meter (the null |
| +// muxer, with its input's name), or the output it wrote. |
| +func passKinds(runs []fakeRun) []string { |
| + var out []string |
| + for _, r := range runs { |
| + switch { |
| + case slices.Contains(r.Args, "-version"): |
| + out = append(out, "version") |
| + case slices.Contains(r.Args, "-of"): |
| + out = append(out, "probe") |
| + case slices.Contains(r.Args, "null"): |
| + out = append(out, "meter "+filepath.Base(argAfter(r.Args, "-i"))) |
| + default: |
| + out = append(out, filepath.Base(r.Args[len(r.Args)-1])) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// TestRunSuccessWritesResultLast: a whole run of each preset on the |
| +// fakes: the store sees the source's GET, the three outputs' PUTs in |
| +// payload order, then the result's PUT, and nothing else; Run exits 0. |
| +// The result parses with media.ParseResult and says: the converted |
| +// duration clamped to the 9 s grant (the files run 66 ms and 21 ms past |
| +// it: spec A2, preflight F15), the source's facts, ffmpeg's version, |
| +// and each output's size, unquoted ETag and content type as the store |
| +// holds them, with video.mp4's and poster.jpg's dimensions from |
| +// outputSize (F16). The passes run in Task 5's order: for audio, the |
| +// loudness pass, the encode, its meter, then the peaks, whose |
| +// peaks.json gives the clamped duration too. |
| +func TestRunSuccessWritesResultLast(t *testing.T) { |
| + for _, c := range []struct { |
| + preset, scenario string |
| + passes []string |
| + source media.SourceFacts |
| + dims map[string][2]int |
| + }{ |
| + {media.PresetVideo720p, "ok-video", []string{"probe", "video.mp4", "poster.jpg", "version"}, |
| + media.SourceFacts{DurationMS: 9000, Width: 160, Height: 90, VideoCodec: "h264", AudioCodec: "aac"}, |
| + map[string][2]int{"video.mp4": {160, 90}, "poster.jpg": {160, 90}}}, |
| + {media.PresetAudioAAC, "ok-audio", []string{"probe", "meter source", "audio.mp4", "meter audio.mp4", peaksRaw, "version"}, |
| + media.SourceFacts{DurationMS: 9000, AudioCodec: "aac"}, nil}, |
| + } { |
| + t.Run(c.preset, func(t *testing.T) { |
| + h, p, cfg, record := runJobSetup(t, c.preset, c.scenario) |
| + if code := runFor(t, cfg, p); code != media.ExitDone { |
| + t.Fatalf("Run = %d, want 0; logs %q", code, h.Logs()) |
| + } |
| + h.s.CheckClean(t) |
| + names := media.OutputNames(c.preset) |
| + want := []string{"GET " + srcPath} |
| + for _, n := range names { |
| + want = append(want, "PUT "+outPrefix+n) |
| + } |
| + want = append(want, "PUT "+resultPath) |
| + if got := requestLines(h.s.Requests()); !slices.Equal(got, want) { |
| + t.Fatalf("requests\n got %q\nwant %q", got, want) |
| + } |
| + if got := passKinds(fakeRuns(t, record)); !slices.Equal(got, c.passes) { |
| + t.Fatalf("passes %q, want %q", got, c.passes) |
| + } |
| + b, _ := h.s.Object(resultPath) |
| + r, err := media.ParseResult(b, testExec, c.preset) |
| + if err != nil { |
| + t.Fatalf("ParseResult: %v\n%s", err, b) |
| + } |
| + if r.Error != "" || r.Source == nil || *r.Source != c.source || r.FFmpeg != fakeVersion { |
| + t.Fatalf("result %s", b) |
| + } |
| + for i, o := range r.Outputs { |
| + held, _ := h.s.Object(outPrefix + o.Name) |
| + h.s.mu.Lock() |
| + etag := h.s.objects[outPrefix+o.Name].etag |
| + h.s.mu.Unlock() |
| + d := c.dims[o.Name] |
| + if o.Name != names[i] || o.Bytes != int64(len(held)) || o.ETag != etag || o.ContentType != media.ContentType(o.Name) || o.Width != d[0] || o.Height != d[1] { |
| + t.Errorf("output %d: %+v; the store holds %d bytes, ETag %q", i, o, len(held), etag) |
| + } |
| + } |
| + media0, _ := fmp4Files.ReadFile("testdata/fmp4/" + names[0]) |
| + if got, _ := h.s.Object(outPrefix + names[0]); !bytes.Equal(got, media0) { |
| + t.Error("the media file uploaded is not the encode's") |
| + } |
| + if pl, _ := h.s.Object(outPrefix + names[1]); !bytes.HasPrefix(pl, []byte("#EXTM3U\n")) || !bytes.Contains(pl, []byte("\n"+names[0]+"\n")) { |
| + t.Errorf("playlist %q", pl) |
| + } |
| + if c.preset == media.PresetAudioAAC { |
| + pk, _ := h.s.Object(outPrefix + "peaks.json") |
| + var v struct { |
| + Version int `json:"version"` |
| + DurationMS int64 `json:"duration_ms"` |
| + Peaks []uint8 `json:"peaks"` |
| + } |
| + if err := json.Unmarshal(pk, &v); err != nil || v.Version != 1 || v.DurationMS != 9000 || len(v.Peaks) != peakCount { |
| + t.Errorf("peaks.json: version %d, %d ms, %d peaks, %v", v.Version, v.DurationMS, len(v.Peaks), err) |
| + } |
| + } |
| + for _, line := range h.Logs() { |
| + for _, s := range h.s.secrets() { |
| + if strings.Contains(line, s) { |
| + t.Errorf("log %q contains %q", line, s) |
| + } |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestRunNamedErrorWritesResultAndExits1: an M4A with cover art under |
| +// video-720p is no_video (preflight F17). Nothing is encoded, no output |
| +// is PUT, and the result names the code; Run exits 1. |
| +func TestRunNamedErrorWritesResultAndExits1(t *testing.T) { |
| + h, p, cfg, record := runJobSetup(t, media.PresetVideo720p, "probe-m4a-cover-art") |
| + if code := runFor(t, cfg, p); code != media.ExitFailed { |
| + t.Fatalf("Run = %d, want 1", code) |
| + } |
| + want := []string{"GET " + srcPath, "PUT " + resultPath} |
| + if got := requestLines(h.s.Requests()); !slices.Equal(got, want) { |
| + t.Fatalf("requests %q, want %q", got, want) |
| + } |
| + b, _ := h.s.Object(resultPath) |
| + r, err := media.ParseResult(b, testExec, media.PresetVideo720p) |
| + if err != nil || r.Error != media.CodeNoVideo || r.Source != nil || len(r.Outputs) != 0 { |
| + t.Fatalf("result %s, %v", b, err) |
| + } |
| + if got := passKinds(fakeRuns(t, record)); !slices.Equal(got, []string{"probe"}) { |
| + t.Fatalf("passes %q, want the probe alone", got) |
| + } |
| + h.s.CheckClean(t) |
| +} |
| + |
| +// TestRunExpiryBeforeLastUploadExits75: the clock reaches the grant's |
| +// expiry once the second output is stored: the third PUT never begins, |
| +// no result is written, and Run exits 75. |
| +func TestRunExpiryBeforeLastUploadExits75(t *testing.T) { |
| + h, p, cfg, _ := runJobSetup(t, media.PresetVideo720p, "ok-video") |
| + cfg.Now = func() time.Time { |
| + if len(puts(h.s.Requests())) >= 2 { |
| + return h.s.expiry |
| + } |
| + return h.clock.Now() |
| + } |
| + if code := runFor(t, cfg, p); code != media.ExitGrantExpired { |
| + t.Fatalf("Run = %d, want 75", code) |
| + } |
| + want := []string{"GET " + srcPath, "PUT " + outPrefix + "video.mp4", "PUT " + outPrefix + "video.m3u8"} |
| + if got := requestLines(h.s.Requests()); !slices.Equal(got, want) { |
| + t.Fatalf("requests %q, want %q", got, want) |
| + } |
| + if _, ok := h.s.Object(resultPath); ok { |
| + t.Fatal("a result was written") |
| + } |
| +} |
| + |
| +// waitForPID waits for the fake to write its pid to path. |
| +func waitForPID(t *testing.T, path string, done <-chan int) int { |
| + t.Helper() |
| + tick := time.NewTicker(10 * time.Millisecond) |
| + defer tick.Stop() |
| + limit := time.NewTimer(20 * time.Second) |
| + defer limit.Stop() |
| + for { |
| + if b, err := os.ReadFile(path); err == nil && len(b) > 0 { |
| + pid, err := strconv.Atoi(string(b)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return pid |
| + } |
| + select { |
| + case <-tick.C: |
| + case code := <-done: |
| + t.Fatalf("Run ended (%d) before the encode began", code) |
| + case <-limit.C: |
| + t.Fatal("the encode never began") |
| + } |
| + } |
| +} |
| + |
| +// wantGone fails t if pid still exists (runChild reaped it, so a |
| +// zombie would not do either). |
| +func wantGone(t *testing.T, pid int) { |
| + t.Helper() |
| + if err := unix.Kill(pid, 0); !errors.Is(err, unix.ESRCH) { |
| + t.Fatalf("the encode (pid %d) is still there: %v", pid, err) |
| + } |
| +} |
| + |
| +// hangSetup is runJobSetup on ok-video-hang, with its pid file. |
| +func hangSetup(t *testing.T) (*harness, media.Payload, Config, string) { |
| + t.Helper() |
| + h, p, cfg, _ := runJobSetup(t, media.PresetVideo720p, "ok-video-hang") |
| + pidFile := filepath.Join(t.TempDir(), "pid") |
| + cfg.extraEnv = append(append([]string(nil), cfg.extraEnv...), fakePIDFileEnv+"="+pidFile) |
| + return h, p, cfg, pidFile |
| +} |
| + |
| +// TestRunSIGTERMKillsChildren: SIGTERM to the process while an encode |
| +// that ignores SIGTERM runs: Run kills it (and reaps it), writes nothing |
| +// more, and exits 143. |
| +func TestRunSIGTERMKillsChildren(t *testing.T) { |
| + // The test's own handler keeps the test process alive whatever Run |
| + // has registered. |
| + safety := make(chan os.Signal, 1) |
| + signal.Notify(safety, syscall.SIGTERM) |
| + defer signal.Stop(safety) |
| + |
| + h, p, cfg, pidFile := hangSetup(t) |
| + done := make(chan int, 1) |
| + go func() { done <- runFor(t, cfg, p) }() |
| + pid := waitForPID(t, pidFile, done) |
| + if err := unix.Kill(os.Getpid(), unix.SIGTERM); err != nil { |
| + t.Fatal(err) |
| + } |
| + select { |
| + case code := <-done: |
| + if code != exitStopped { |
| + t.Fatalf("Run = %d, want %d", code, exitStopped) |
| + } |
| + case <-time.After(20 * time.Second): |
| + t.Fatal("Run did not end on SIGTERM") |
| + } |
| + wantGone(t, pid) |
| + if got := requestLines(h.s.Requests()); !slices.Equal(got, []string{"GET " + srcPath}) { |
| + t.Fatalf("requests %q, want the source's GET alone", got) |
| + } |
| +} |
| + |
| +// TestRunGrantDeadlineEndsFFmpeg: an encode still running at the grant's |
| +// expiry is killed then (every pass runs under the grant's deadline), |
| +// nothing is uploaded, no result is written, and Run exits 75. |
| +func TestRunGrantDeadlineEndsFFmpeg(t *testing.T) { |
| + h, p, cfg, pidFile := hangSetup(t) |
| + // 5 s of grant left: room for the download and the probe to finish |
| + // first, even under -race; the encode then hangs past it. |
| + h.clock.Set(h.s.expiry.Add(-5 * time.Second)) |
| + done := make(chan int, 1) |
| + go func() { done <- runFor(t, cfg, p) }() |
| + pid := waitForPID(t, pidFile, done) |
| + select { |
| + case code := <-done: |
| + if code != media.ExitGrantExpired { |
| + t.Fatalf("Run = %d, want 75", code) |
| + } |
| + case <-time.After(20 * time.Second): |
| + t.Fatal("the encode outlived the grant") |
| + } |
| + wantGone(t, pid) |
| + if got := requestLines(h.s.Requests()); !slices.Equal(got, []string{"GET " + srcPath}) { |
| + t.Fatalf("requests %q, want the source's GET alone", got) |
| + } |
| +} |
| + |
| +// TestRunPosterMissingIsUnreadable: a poster run that exits 0 and |
| +// writes nothing (no frame, from 1 s in and again from the first frame) |
| +// is unreadable: the result names it and no output is PUT. |
| +func TestRunPosterMissingIsUnreadable(t *testing.T) { |
| + h, p, cfg, _ := runJobSetup(t, media.PresetVideo720p, "ok-video-noposter") |
| + if code := runFor(t, cfg, p); code != media.ExitFailed { |
| + t.Fatalf("Run = %d, want 1", code) |
| + } |
| + wantOnlyResult(t, h, media.PresetVideo720p, media.CodeUnreadable) |
| +} |
| + |
| +// TestRunRefusedOutputUploadsNothing: a poster left as a symlink out of |
| +// the scratch is refused by collect: engine_failed, and none of the |
| +// three outputs is PUT. |
| +func TestRunRefusedOutputUploadsNothing(t *testing.T) { |
| + h, p, cfg, _ := runJobSetup(t, media.PresetVideo720p, "ok-video-poster-link") |
| + if code := runFor(t, cfg, p); code != media.ExitFailed { |
| + t.Fatalf("Run = %d, want 1", code) |
| + } |
| + wantOnlyResult(t, h, media.PresetVideo720p, media.CodeEngineFailed) |
| +} |
| + |
| +// wantOnlyResult fails t unless the store saw the source's GET and a |
| +// result naming code, and nothing else. |
| +func wantOnlyResult(t *testing.T, h *harness, preset, code string) { |
| + t.Helper() |
| + want := []string{"GET " + srcPath, "PUT " + resultPath} |
| + if got := requestLines(h.s.Requests()); !slices.Equal(got, want) { |
| + t.Fatalf("requests %q, want %q", got, want) |
| + } |
| + b, _ := h.s.Object(resultPath) |
| + if r, err := media.ParseResult(b, testExec, preset); err != nil || r.Error != code { |
| + t.Fatalf("result %s, %v; want %s", b, err, code) |
| + } |
| +} |
| + |
| +// TestRunResultRefusedIsNotRetried: when the store refuses the success |
| +// result (a 400), the job exits 1 with that one attempt: no error |
| +// result is written after it. |
| +func TestRunResultRefusedIsNotRetried(t *testing.T) { |
| + h, p, cfg, _ := runJobSetup(t, media.PresetVideo720p, "ok-video") |
| + h.s.OnPut = func(n int) int { |
| + if n == 4 { |
| + return http.StatusBadRequest |
| + } |
| + return 0 |
| + } |
| + if code := runFor(t, cfg, p); code != media.ExitFailed { |
| + t.Fatalf("Run = %d, want 1", code) |
| + } |
| + if got := puts(h.s.Requests()); len(got) != 4 || got[3].Path != resultPath { |
| + t.Fatalf("PUTs %q, want three outputs and one result", requestLines(got)) |
| + } |
| + if !slices.Contains(h.Logs(), "codec: converted, but the result could not be written") { |
| + t.Fatalf("logs %q", h.Logs()) |
| + } |
| +} |
| + |
| +// TestRunScratchFullIsEngineFailed: an encode that fails while the |
| +// scratch's file system is full is the engine's failure (its storage |
| +// was sized too small), not the source's: engine_failed; the same |
| +// failure with room left is unreadable. |
| +func TestRunScratchFullIsEngineFailed(t *testing.T) { |
| + for _, full := range []bool{true, false} { |
| + cfg, _ := fakeConfig(t, "fail") |
| + var lines []string |
| + cfg.Logf = func(f string, a ...any) { lines = append(lines, fmt.Sprintf(f, a...)) } |
| + cfg.diskFull = func(dir string) bool { |
| + if dir != cfg.Scratch { |
| + t.Errorf("diskFull asked of %s, not the scratch", dir) |
| + } |
| + return full |
| + } |
| + err := encode(context.Background(), cfg, "video", []string{"-i", "x", outPath(cfg, "video.mp4")}) |
| + want := map[bool]string{true: media.CodeEngineFailed, false: media.CodeUnreadable}[full] |
| + if codeOf(err) != want { |
| + t.Fatalf("full %t: encode = %s, want %s", full, codeOf(err), want) |
| + } |
| + if full && (len(lines) != 1 || lines[0] != "codec: ffmpeg (video) failed with the scratch disk full") { |
| + t.Fatalf("logged %q", lines) |
| + } |
| + } |
| +} |
| + |
| +// TestRunScratchUnusableWritesEngineFailed: a scratch whose in/ is a |
| +// link is refused before the source is fetched, and the result says |
| +// engine_failed. |
| +func TestRunScratchUnusableWritesEngineFailed(t *testing.T) { |
| + h, p, cfg, _ := runJobSetup(t, media.PresetVideo720p, "ok-video") |
| + if err := os.Symlink(t.TempDir(), filepath.Join(cfg.Scratch, "in")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if code := runFor(t, cfg, p); code != media.ExitFailed { |
| + t.Fatalf("Run = %d, want 1", code) |
| + } |
| + if got := requestLines(h.s.Requests()); !slices.Equal(got, []string{"PUT " + resultPath}) { |
| + t.Fatalf("requests %q, want the result alone", got) |
| + } |
| + b, _ := h.s.Object(resultPath) |
| + if r, err := media.ParseResult(b, testExec, media.PresetVideo720p); err != nil || r.Error != media.CodeEngineFailed { |
| + t.Fatalf("result %s, %v", b, err) |
| + } |
| +} |
| + |
| +// TestRealRun: Run end to end on the real ffmpeg (skipped without it, |
| +// realConfig): a 1080p clip with audio and a 10 s stereo WAV, each |
| +// converted, uploaded and reported, with the real version and sizes. |
| +func TestRealRun(t *testing.T) { |
| + for _, c := range []struct { |
| + recipe, preset string |
| + durationMS int64 |
| + w, h int |
| + }{ |
| + {"h264-1080p", media.PresetVideo720p, 2500, 1280, 720}, |
| + {"fixture-audio", media.PresetAudioAAC, 10000, 0, 0}, |
| + } { |
| + t.Run(c.recipe, func(t *testing.T) { |
| + real := realConfig(t) |
| + makeSource(t, real, c.recipe) |
| + data, err := os.ReadFile(sourcePath(real)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h := newHarness(t) |
| + p := h.s.payload(t, c.preset, data, 64*mib) |
| + cfg := h.cfg |
| + cfg.Scratch = t.TempDir() |
| + cfg.FFmpeg, cfg.FFprobe, cfg.extraEnv = real.FFmpeg, real.FFprobe, real.extraEnv |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) |
| + defer cancel() |
| + if code := Run(ctx, cfg, marshal(t, p)); code != media.ExitDone { |
| + t.Fatalf("Run = %d; logs %q", code, h.Logs()) |
| + } |
| + b, _ := h.s.Object(resultPath) |
| + r, err := media.ParseResult(b, testExec, c.preset) |
| + if err != nil { |
| + t.Fatalf("ParseResult: %v", err) |
| + } |
| + t.Logf("result %s; log %q", b, h.Logs()) |
| + if d := r.Source.DurationMS - c.durationMS; d < -100 || d > 100 || !strings.HasPrefix(r.FFmpeg, "7.") { |
| + t.Fatalf("result %s", b) |
| + } |
| + for _, o := range r.Outputs { |
| + if (o.Name == "video.mp4" || o.Name == "poster.jpg") && (o.Width != c.w || o.Height != c.h) { |
| + t.Errorf("%s is %dx%d, want %dx%d", o.Name, o.Width, o.Height, c.w, c.h) |
| + } |
| + } |
| + if c.preset == media.PresetVideo720p { |
| + if poster, _ := h.s.Object(outPrefix + "poster.jpg"); !bytes.HasPrefix(poster, []byte{0xff, 0xd8}) { |
| + t.Error("the poster is not a JPEG") |
| + } |
| + } |
| + h.s.CheckClean(t) |
| + }) |
| + } |
| +} |
diff --git a/internal/mediahandler/s3test_test.go b/internal/mediahandler/s3test_test.go| index 7d3e72b57..b2c012ca4 100644 |
| --- a/internal/mediahandler/s3test_test.go |
| +++ b/internal/mediahandler/s3test_test.go |
| @@ -18,8 +18,14 @@ import ( |
| "github.com/carlosframework/platform/internal/media" |
| ) |
| -// dropConnection, answered by OnGet, closes the connection unanswered. |
| -const dropConnection = -1 |
| +// dropConnection, answered by OnGet or OnPut, closes the connection |
| +// unanswered. dropAfterCommit, answered by OnPut, stores the object and |
| +// then closes the connection unanswered (a PUT cut after the store |
| +// committed it). |
| +const ( |
| + dropConnection = -1 |
| + dropAfterCommit = -2 |
| +) |
| // testToken is the session token every transfer of s3Server carries, as |
| // the SDK encodes it in a query. |
| @@ -63,9 +69,10 @@ type s3Transfer struct { |
| // s3Request is one request the server saw. |
| type s3Request struct { |
| - Method, Path string |
| - Header http.Header |
| - Status int |
| + Method, Path string |
| + Header http.Header |
| + ContentLength int64 |
| + Status int |
| } |
| // s3Server is an httptest S3 for one execution. It answers only the |
| @@ -100,6 +107,8 @@ type s3Request struct { |
| // 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. |
| +// - OnPut(n): the same for PUT number n (from 1), the result's |
| +// included; dropAfterCommit stores the object first. |
| type s3Server struct { |
| t *testing.T |
| srv *httptest.Server |
| @@ -112,6 +121,7 @@ type s3Server struct { |
| requests []s3Request |
| problems []string |
| gets int |
| + puts int |
| Cuts []int64 |
| StallAt int64 |
| @@ -130,6 +140,7 @@ type s3Server struct { |
| TrimBody int64 |
| LengthLie int64 |
| OnGet func(n int) int |
| + OnPut func(n int) int |
| } |
| // newS3 starts a server whose grant expires an hour after clock's now. |
| @@ -244,18 +255,23 @@ func (s *s3Server) CheckClean(t *testing.T) { |
| func (s *s3Server) serve(w http.ResponseWriter, r *http.Request) { |
| s.mu.Lock() |
| n := 0 |
| - if r.Method == "GET" { |
| + hook := s.OnGet |
| + switch r.Method { |
| + case "GET": |
| s.gets++ |
| n = s.gets |
| + case "PUT": |
| + s.puts++ |
| + n = s.puts |
| + hook = s.OnPut |
| } |
| - 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()} |
| + rec := s3Request{Method: r.Method, Path: r.URL.EscapedPath(), Header: r.Header.Clone(), ContentLength: r.ContentLength} |
| status, deferred := s.decide(r, forced) |
| rec.Status = status |
| s.requests = append(s.requests, rec) |
| @@ -295,6 +311,12 @@ func (s *s3Server) decide(r *http.Request, forced int) (int, func(http.ResponseW |
| if !s.clock.Now().Before(s.expiry) { |
| return http.StatusForbidden, nil |
| } |
| + if forced == dropAfterCommit && r.Method == "PUT" { |
| + if status, _ := s.put(r); status != http.StatusOK { |
| + return status, nil |
| + } |
| + return dropConnection, nil |
| + } |
| if forced != 0 { |
| return forced, nil |
| } |
| @@ -497,3 +519,10 @@ func marshal(t *testing.T, p media.Payload) string { |
| } |
| return string(b) |
| } |
| + |
| +// Hold stores data at path, as an object already there. |
| +func (s *s3Server) Hold(path string, data []byte) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + s.objects[path] = &s3Object{data: append([]byte(nil), data...), etag: "held"} |
| +} |
diff --git a/internal/mediahandler/testdata/probe/ok-audio.json b/internal/mediahandler/testdata/probe/ok-audio.json| new file mode 100644 |
| index 000000000..ebc0bbc3b |
| --- /dev/null |
| +++ b/internal/mediahandler/testdata/probe/ok-audio.json |
| @@ -0,0 +1,25 @@ |
| +{ |
| + "programs": [ |
| + |
| + ], |
| + "stream_groups": [ |
| + |
| + ], |
| + "streams": [ |
| + { |
| + "index": 0, |
| + "codec_name": "aac", |
| + "codec_type": "audio", |
| + "channels": 2, |
| + "r_frame_rate": "0/0", |
| + "avg_frame_rate": "0/0", |
| + "duration": "9.000000", |
| + "disposition": { |
| + "attached_pic": 0 |
| + } |
| + } |
| + ], |
| + "format": { |
| + "duration": "9.000000" |
| + } |
| +} |
diff --git a/internal/mediahandler/testdata/probe/ok-av.json b/internal/mediahandler/testdata/probe/ok-av.json| new file mode 100644 |
| index 000000000..3154632e4 |
| --- /dev/null |
| +++ b/internal/mediahandler/testdata/probe/ok-av.json |
| @@ -0,0 +1,39 @@ |
| +{ |
| + "programs": [ |
| + |
| + ], |
| + "stream_groups": [ |
| + |
| + ], |
| + "streams": [ |
| + { |
| + "index": 0, |
| + "codec_name": "h264", |
| + "codec_type": "video", |
| + "width": 160, |
| + "height": 90, |
| + "sample_aspect_ratio": "1:1", |
| + "r_frame_rate": "30/1", |
| + "avg_frame_rate": "30/1", |
| + "duration": "9.000000", |
| + "disposition": { |
| + "attached_pic": 0 |
| + } |
| + }, |
| + { |
| + "index": 1, |
| + "codec_name": "aac", |
| + "codec_type": "audio", |
| + "channels": 2, |
| + "r_frame_rate": "0/0", |
| + "avg_frame_rate": "0/0", |
| + "duration": "9.000000", |
| + "disposition": { |
| + "attached_pic": 0 |
| + } |
| + } |
| + ], |
| + "format": { |
| + "duration": "9.000000" |
| + } |
| +} |
diff --git a/internal/mediahandler/testdata/probe/provenance.txt b/internal/mediahandler/testdata/probe/provenance.txt| index 84ffe5dde..910cc5a68 100644 |
| --- a/internal/mediahandler/testdata/probe/provenance.txt |
| +++ b/internal/mediahandler/testdata/probe/provenance.txt |
| @@ -31,3 +31,14 @@ dolby-vision-8-4.json Dolby Vision 8.4 configuration record |
| dolby-vision-5.json Dolby Vision 5 configuration record |
| bomb-30000.json a 30000x30000 header |
| lying-10h.json a 10 h header over a 4 s stream |
| + |
| +Hand-written for Run's fake scenarios ok-video and ok-audio (plan 3 |
| +Task 6), in the same shape: the sources of testdata/fmp4's video.mp4 |
| +(fixture-av: H.264 160x90 30 fps, AAC stereo) and audio.mp4 |
| +(fixture-audio, answered as the AAC it was encoded to), each said to |
| +last exactly the 9 s grant those files were encoded under. The files |
| +themselves run past it (9.0667 s and 9.0213 s), which is what the |
| +handler's clamp to the grant (spec A2, preflight F15) is tested with: |
| + |
| +ok-av.json H.264 160x90 + AAC stereo, 9.000 s |
| +ok-audio.json AAC stereo, 9.000 s |
diff --git a/internal/mediahandler/upload.go b/internal/mediahandler/upload.go| new file mode 100644 |
| index 000000000..d71d89b19 |
| --- /dev/null |
| +++ b/internal/mediahandler/upload.go |
| @@ -0,0 +1,153 @@ |
| +package mediahandler |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "net/http" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// putRetries is how many times one PUT is made again after a broken |
| +// attempt: at most three attempts in all. |
| +const putRetries = 2 |
| + |
| +// putBodyDrain is the most of a PUT response's body read before it is |
| +// closed: S3's answers are small, and nothing in them is used. |
| +const putBodyDrain = 64 << 10 |
| + |
| +// upload PUTs one collected output with its transfer t (create-only: |
| +// t's signed If-None-Match: *), reading every byte from c's open file |
| +// through an io.SectionReader, with Content-Length c.Size. It answers |
| +// the store's ETag, unquoted. See put for the rules. |
| +func upload(ctx context.Context, cfg Config, p media.Payload, t media.Transfer, c collected) (etag string, err error) { |
| + if t.Method != http.MethodPut || t.Name != c.Name || c.File == nil || c.Size < 1 { |
| + // engine.upload.mismatch (pending Luna pass). |
| + cfg.Logf("codec: the upload of %s does not match its transfer", c.Name) |
| + return "", jobError{media.CodeEngineFailed} |
| + } |
| + return put(ctx, cfg, p, t, c.Name, c.Size, func() io.Reader { return io.NewSectionReader(c.File, 0, c.Size) }) |
| +} |
| + |
| +// put makes one create-only PUT of size bytes (body makes the reader |
| +// for each attempt) with transfer t; what names it in the log. Rules: |
| +// |
| +// - before every attempt, now at or after the grant's expiry is |
| +// errGrantExpired, and nothing is sent (spec §5.4); |
| +// - the request carries t's signed headers exactly, Content-Length, |
| +// and Accept-Encoding: identity, and follows no redirect; |
| +// - 200: done, with the response's ETag unquoted ("" when it has none |
| +// or an odd one: the console then takes HEAD's); |
| +// - 412 on the first attempt: the store already holds the key, which |
| +// no one but this execution may write (spec §9): engine_failed; |
| +// - a broken attempt (a transport error, or 500, 502, 503 or 504, |
| +// which may have stored the object) is made again, at most |
| +// putRetries times, after resumeDelay; a 412 after one is this |
| +// upload's own object, accepted with ETag ""; |
| +// - 403: errGrantExpired. The signature covers only this execution's |
| +// key, so the store refusing it is the grant's end (a clock behind |
| +// the store's), and the result PUT will meet the same refusal; |
| +// - any other status: engine_failed. |
| +// |
| +// No error and no log line carries the URL, the query or a header |
| +// (preflight F6); ctx's error is returned as it is. |
| +func put(ctx context.Context, cfg Config, p media.Payload, t media.Transfer, what string, size int64, body func() io.Reader) (etag string, err error) { |
| + expiry := time.Unix(p.Expiry, 0) |
| + broken := false |
| + for attempt := 0; ; attempt++ { |
| + if err := ctx.Err(); err != nil { |
| + return "", err |
| + } |
| + if !cfg.Now().Before(expiry) { |
| + return "", errGrantExpired |
| + } |
| + status, etag, err := putOnce(ctx, cfg, p, t, size, body()) |
| + if err != nil { |
| + return "", err |
| + } |
| + switch status { |
| + case http.StatusOK: |
| + return etag, nil |
| + case http.StatusPreconditionFailed: |
| + if broken { |
| + // engine.upload.exists_after_retry (pending Luna pass). |
| + cfg.Logf("codec: the store holds %s after a broken attempt; taken as this upload", what) |
| + return "", nil |
| + } |
| + // engine.upload.exists (pending Luna pass). |
| + cfg.Logf("codec: the store already holds %s", what) |
| + return "", jobError{media.CodeEngineFailed} |
| + case http.StatusForbidden: |
| + // engine.upload.denied (pending Luna pass). |
| + cfg.Logf("codec: the store refused %s (403); the grant is taken as expired", what) |
| + return "", errGrantExpired |
| + case statusBroken, http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: |
| + default: |
| + // engine.upload.status (pending Luna pass). |
| + cfg.Logf("codec: the store answered %d to %s", status, what) |
| + return "", jobError{media.CodeEngineFailed} |
| + } |
| + if attempt == putRetries { |
| + // engine.upload.gave_up (pending Luna pass). |
| + cfg.Logf("codec: the upload of %s broke %d times; giving up", what, putRetries+1) |
| + return "", jobError{media.CodeEngineFailed} |
| + } |
| + broken = true |
| + // engine.upload.retry (pending Luna pass). |
| + cfg.Logf("codec: the upload of %s broke; retry %d of %d", what, attempt+1, putRetries) |
| + if err := cfg.wait(ctx, resumeDelay(attempt)); err != nil { |
| + return "", err |
| + } |
| + } |
| +} |
| + |
| +// statusBroken is putOnce's status for an attempt that got no answer. |
| +const statusBroken = -1 |
| + |
| +// putOnce makes one attempt and answers its status (statusBroken for a |
| +// transport error) and ETag. err is final: ctx's own, or engine_failed |
| +// for a request that cannot be built. |
| +func putOnce(ctx context.Context, cfg Config, p media.Payload, t media.Transfer, size int64, body io.Reader) (status int, etag string, err error) { |
| + req, err := http.NewRequestWithContext(ctx, http.MethodPut, p.Transfers.URL(t), body) |
| + if err != nil { |
| + // url.Parse's error quotes the URL: drop it. |
| + // engine.upload.unbuildable (pending Luna pass). |
| + cfg.Logf("codec: a request for the store cannot be built") |
| + return 0, "", jobError{media.CodeEngineFailed} |
| + } |
| + req.ContentLength = size |
| + for k, v := range t.Header { |
| + req.Header.Set(k, v) |
| + } |
| + req.Header.Set("Accept-Encoding", "identity") |
| + client := *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 0, "", ctx.Err() |
| + } |
| + return statusBroken, "", nil |
| + } |
| + defer resp.Body.Close() |
| + _, _ = io.CopyN(io.Discard, resp.Body, putBodyDrain) |
| + return resp.StatusCode, unquoteETag(resp.Header.Get("ETag")), nil |
| +} |
| + |
| +// unquoteETag is a strong ETag's value without its quotes: "" for none, |
| +// a weak one, or one holding anything but printable ASCII, which the |
| +// result would otherwise carry to the console. |
| +func unquoteETag(h string) string { |
| + if len(h) < 3 || len(h) > 258 || h[0] != '"' || h[len(h)-1] != '"' { |
| + return "" |
| + } |
| + v := h[1 : len(h)-1] |
| + for i := 0; i < len(v); i++ { |
| + if v[i] < 0x21 || v[i] > 0x7e || v[i] == '"' { |
| + return "" |
| + } |
| + } |
| + return v |
| +} |
diff --git a/internal/mediahandler/upload_test.go b/internal/mediahandler/upload_test.go| new file mode 100644 |
| index 000000000..219be86f3 |
| --- /dev/null |
| +++ b/internal/mediahandler/upload_test.go |
| @@ -0,0 +1,432 @@ |
| +package mediahandler |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// collectedFile writes data to a new file named name and opens it, as |
| +// collect answers an output. |
| +func collectedFile(t *testing.T, name string, data []byte) collected { |
| + t.Helper() |
| + path := filepath.Join(t.TempDir(), name) |
| + if err := os.WriteFile(path, data, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + f, err := os.Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { f.Close() }) |
| + return collected{Name: name, File: f, Size: int64(len(data))} |
| +} |
| + |
| +// uploadVideo uploads data as video.mp4 with h's first output transfer. |
| +func (h *harness) uploadVideo(t *testing.T, p media.Payload, data []byte) (string, error) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + defer cancel() |
| + return upload(ctx, h.cfg.withDefaults(), p, p.Transfers.Outputs[0], collectedFile(t, "video.mp4", data)) |
| +} |
| + |
| +func puts(rs []s3Request) []s3Request { |
| + var out []s3Request |
| + for _, r := range rs { |
| + if r.Method == "PUT" { |
| + out = append(out, r) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// TestUploadSendsTheSignedHeaders: one PUT of the output's path with its |
| +// presigned query (the server refuses any other), its signed |
| +// Content-Type and If-None-Match exactly, the file's size as |
| +// Content-Length (never chunked), Accept-Encoding: identity, and the |
| +// bytes of the open file, even once its path names another file. The |
| +// answer is the store's ETag without quotes. |
| +func TestUploadSendsTheSignedHeaders(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + data := randomBytes(t, 300<<10) |
| + c := collectedFile(t, "video.mp4", data) |
| + // The path now names other bytes: the upload reads the descriptor. |
| + other := filepath.Join(filepath.Dir(c.File.Name()), "other") |
| + if err := os.WriteFile(other, []byte("other"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Rename(other, c.File.Name()); err != nil { |
| + t.Fatal(err) |
| + } |
| + etag, err := upload(context.Background(), h.cfg.withDefaults(), p, p.Transfers.Outputs[0], c) |
| + if err != nil { |
| + t.Fatalf("upload: %s", codeOf(err)) |
| + } |
| + h.s.CheckClean(t) |
| + rs := h.s.Requests() |
| + if len(rs) != 1 { |
| + t.Fatalf("%d requests, want 1", len(rs)) |
| + } |
| + r := rs[0] |
| + if r.Method != "PUT" || r.Path != outPrefix+"video.mp4" || r.ContentLength != int64(len(data)) { |
| + t.Fatalf("request %s %s length %d", r.Method, r.Path, r.ContentLength) |
| + } |
| + if r.Header.Get("Content-Type") != "video/mp4" || r.Header.Get("If-None-Match") != "*" || r.Header.Get("Accept-Encoding") != "identity" { |
| + t.Fatalf("headers %v", r.Header) |
| + } |
| + if len(r.Header.Values("Transfer-Encoding")) != 0 { |
| + t.Fatalf("a chunked PUT: %v", r.Header) |
| + } |
| + got, _ := h.s.Object(outPrefix + "video.mp4") |
| + if !bytes.Equal(got, data) { |
| + t.Fatalf("the store holds %d bytes, not the file's %d", len(got), len(data)) |
| + } |
| + h.s.mu.Lock() |
| + want := h.s.objects[outPrefix+"video.mp4"].etag |
| + h.s.mu.Unlock() |
| + if etag != want || strings.Contains(etag, `"`) { |
| + t.Fatalf("etag %q, want %q unquoted", etag, want) |
| + } |
| +} |
| + |
| +// TestUploadSecondPutRefused: spec §9, the store already holds the key |
| +// when the first attempt is made, so it answers 412: engine_failed, |
| +// with one PUT and the held object untouched. |
| +func TestUploadSecondPutRefused(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + h.s.Hold(outPrefix+"video.mp4", []byte("held")) |
| + _, err := h.uploadVideo(t, p, randomBytes(t, 4096)) |
| + if codeOf(err) != media.CodeEngineFailed { |
| + t.Fatalf("upload = %s, want engine_failed", codeOf(err)) |
| + } |
| + if n := len(puts(h.s.Requests())); n != 1 { |
| + t.Fatalf("%d PUTs, want 1", n) |
| + } |
| + if got, _ := h.s.Object(outPrefix + "video.mp4"); string(got) != "held" { |
| + t.Fatal("the held object was replaced") |
| + } |
| +} |
| + |
| +// TestUploadRetryAfterTransportError: a PUT the store committed and the |
| +// connection then lost is made again; that attempt's 412 is this |
| +// upload's own object, accepted with ETag "" (the console takes HEAD's). |
| +// A PUT cut before the commit, or a 503, is made again and its 200 |
| +// answers the ETag. Each retry waits resumeDelay. |
| +func TestUploadRetryAfterTransportError(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + first int |
| + wantETag bool |
| + }{ |
| + {"cut after the commit", dropAfterCommit, false}, |
| + {"cut before the commit", dropConnection, true}, |
| + {"503", http.StatusServiceUnavailable, true}, |
| + {"500", http.StatusInternalServerError, true}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + h.s.OnPut = func(n int) int { |
| + if n == 1 { |
| + return c.first |
| + } |
| + return 0 |
| + } |
| + data := randomBytes(t, 64<<10) |
| + etag, err := h.uploadVideo(t, p, data) |
| + if err != nil { |
| + t.Fatalf("upload: %s", codeOf(err)) |
| + } |
| + if (etag != "") != c.wantETag { |
| + t.Fatalf("etag %q, want one: %t", etag, c.wantETag) |
| + } |
| + rs := puts(h.s.Requests()) |
| + if len(rs) != 2 { |
| + t.Fatalf("%d PUTs, want 2", len(rs)) |
| + } |
| + if !c.wantETag && rs[1].Status != http.StatusPreconditionFailed { |
| + t.Fatalf("the retry got %d, want 412", rs[1].Status) |
| + } |
| + if got, _ := h.s.Object(outPrefix + "video.mp4"); !bytes.Equal(got, data) { |
| + t.Fatal("the store does not hold the file") |
| + } |
| + if d := h.Delays(); len(d) != 1 || d[0] != time.Second { |
| + t.Fatalf("delays %v, want [1s]", d) |
| + } |
| + h.s.CheckClean(t) |
| + }) |
| + } |
| +} |
| + |
| +// TestUploadGivesUpAfterTwoRetries: three broken attempts, then |
| +// engine_failed, with no fourth. |
| +func TestUploadGivesUpAfterTwoRetries(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + h.s.OnPut = func(int) int { return dropConnection } |
| + if _, err := h.uploadVideo(t, p, randomBytes(t, 4096)); codeOf(err) != media.CodeEngineFailed { |
| + t.Fatalf("upload = %s, want engine_failed", codeOf(err)) |
| + } |
| + if n := len(puts(h.s.Requests())); n != 3 { |
| + t.Fatalf("%d PUTs, want 3", n) |
| + } |
| + if d := h.Delays(); len(d) != 2 || d[0] != time.Second || d[1] != 2*time.Second { |
| + t.Fatalf("delays %v, want [1s 2s]", d) |
| + } |
| +} |
| + |
| +// TestUploadExpiry: no attempt begins at or after the expiry (none at |
| +// all, or no retry once the wait crosses it), and a 403 is the grant's |
| +// end: errGrantExpired each time. |
| +func TestUploadExpiry(t *testing.T) { |
| + t.Run("at the expiry", func(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + h.clock.Set(h.s.expiry) |
| + if _, err := h.uploadVideo(t, p, randomBytes(t, 64)); codeOf(err) != "errGrantExpired" { |
| + t.Fatalf("upload = %s", codeOf(err)) |
| + } |
| + if n := len(h.s.Requests()); n != 0 { |
| + t.Fatalf("%d requests, want none", n) |
| + } |
| + }) |
| + t.Run("403", func(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + h.s.OnPut = func(int) int { return http.StatusForbidden } |
| + if _, err := h.uploadVideo(t, p, randomBytes(t, 64)); codeOf(err) != "errGrantExpired" { |
| + t.Fatalf("upload = %s", codeOf(err)) |
| + } |
| + if n := len(h.s.Requests()); n != 1 { |
| + t.Fatalf("%d requests, want 1", n) |
| + } |
| + }) |
| + t.Run("expired during the retry wait", func(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + h.s.OnPut = func(int) int { return dropConnection } |
| + h.onWait = func() { h.clock.Set(h.s.expiry) } |
| + if _, err := h.uploadVideo(t, p, randomBytes(t, 64)); codeOf(err) != "errGrantExpired" { |
| + t.Fatalf("upload = %s", codeOf(err)) |
| + } |
| + if n := len(h.s.Requests()); n != 1 { |
| + t.Fatalf("%d requests, want 1", n) |
| + } |
| + }) |
| +} |
| + |
| +// TestUploadOtherStatuses: any other answer is engine_failed at once, |
| +// a redirect included: never followed (Go's client would follow a |
| +// 301, 302 or 303 to a PUT as a GET of the Location). |
| +func TestUploadOtherStatuses(t *testing.T) { |
| + for _, status := range []int{http.StatusBadRequest, http.StatusNotFound, http.StatusNotImplemented, |
| + http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect} { |
| + t.Run(fmt.Sprint(status), func(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + h.s.OnPut = func(int) int { return status } |
| + if _, err := h.uploadVideo(t, p, randomBytes(t, 64)); codeOf(err) != media.CodeEngineFailed { |
| + t.Fatalf("upload = %s", codeOf(err)) |
| + } |
| + if n := len(h.s.Requests()); n != 1 { |
| + t.Fatalf("%d requests, want 1", n) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestUploadRefusesAMismatch: a file under another name than its |
| +// transfer's, or an empty one, is engine_failed before any request. |
| +func TestUploadRefusesAMismatch(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + cfg := h.cfg.withDefaults() |
| + if _, err := upload(context.Background(), cfg, p, p.Transfers.Outputs[1], collectedFile(t, "video.mp4", []byte("x"))); codeOf(err) != media.CodeEngineFailed { |
| + t.Fatalf("upload under another name = %s", codeOf(err)) |
| + } |
| + empty := collectedFile(t, "video.mp4", []byte("x")) |
| + empty.Size = 0 |
| + if _, err := upload(context.Background(), cfg, p, p.Transfers.Outputs[0], empty); codeOf(err) != media.CodeEngineFailed { |
| + t.Fatalf("upload of nothing = %s", codeOf(err)) |
| + } |
| + if n := len(h.s.Requests()); n != 0 { |
| + t.Fatalf("%d requests, want none", n) |
| + } |
| +} |
| + |
| +// TestWriteResult: the result is one create-only PUT of its JSON to the |
| +// result transfer, which media.ParseResult reads back; a second write |
| +// meets the first (412 on its first attempt): engine_failed. |
| +func TestWriteResult(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetAudioAAC, nil, mib) |
| + cfg := h.cfg.withDefaults() |
| + r := media.Result{V: media.ResultVersion, Execution: testExec, Error: media.CodeNoAudio} |
| + if err := writeResult(context.Background(), cfg, p, r); err != nil { |
| + t.Fatalf("writeResult: %s", codeOf(err)) |
| + } |
| + b, ok := h.s.Object(resultPath) |
| + if !ok { |
| + t.Fatal("no result object") |
| + } |
| + got, err := media.ParseResult(b, testExec, media.PresetAudioAAC) |
| + if err != nil || got.Error != media.CodeNoAudio { |
| + t.Fatalf("result %+v, %v", got, err) |
| + } |
| + rs := h.s.Requests() |
| + if len(rs) != 1 || rs[0].Header.Get("Content-Type") != "application/json" || rs[0].ContentLength != int64(len(b)) { |
| + t.Fatalf("requests %+v", rs) |
| + } |
| + if err := writeResult(context.Background(), cfg, p, r); codeOf(err) != media.CodeEngineFailed { |
| + t.Fatalf("second writeResult = %s, want engine_failed", codeOf(err)) |
| + } |
| + h.s.CheckClean(t) |
| + |
| + // A result the console would not read (over media.MaxResultBytes) |
| + // is never sent. |
| + big := media.Result{V: media.ResultVersion, Execution: testExec} |
| + for len(big.Outputs)*64 <= media.MaxResultBytes { |
| + big.Outputs = append(big.Outputs, media.OutputFact{Name: "video.mp4", Bytes: 1, ETag: strings.Repeat("e", 32)}) |
| + } |
| + before := len(h.s.Requests()) |
| + if err := writeResult(context.Background(), cfg, p, big); codeOf(err) != media.CodeEngineFailed { |
| + t.Fatalf("an oversized result: %s, want engine_failed", codeOf(err)) |
| + } |
| + if n := len(h.s.Requests()) - before; n != 0 { |
| + t.Fatalf("an oversized result made %d requests", n) |
| + } |
| +} |
| + |
| +// TestUploadNeverLogsTransfers: across every way an upload or the |
| +// result's PUT ends, no log line and no error carries a signature, the |
| +// token, an X-Amz parameter, the store's address or the source key |
| +// (preflight F6). |
| +func TestUploadNeverLogsTransfers(t *testing.T) { |
| + setups := map[string]func(h *harness){ |
| + "ok": func(h *harness) {}, |
| + "held": func(h *harness) { h.s.Hold(outPrefix+"video.mp4", []byte("x")) }, |
| + "cut": func(h *harness) { |
| + h.s.OnPut = func(n int) int { |
| + if n == 1 { |
| + return dropAfterCommit |
| + } |
| + return 0 |
| + } |
| + }, |
| + "broken": func(h *harness) { h.s.OnPut = func(int) int { return dropConnection } }, |
| + "denied": func(h *harness) { h.s.OnPut = func(int) int { return http.StatusForbidden } }, |
| + "redirect": func(h *harness) { h.s.OnPut = func(int) int { return http.StatusTemporaryRedirect } }, |
| + "unreachable": func(h *harness) { h.s.srv.Close() }, |
| + } |
| + checked := 0 |
| + for name, setup := range setups { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + secrets := h.s.secrets() |
| + setup(h) |
| + _, err := h.uploadVideo(t, p, randomBytes(t, 256)) |
| + werr := writeResult(context.Background(), h.cfg.withDefaults(), p, media.Result{V: 1, Execution: testExec, Error: media.CodeUnreadable}) |
| + lines := h.Logs() |
| + for _, e := range []error{err, werr} { |
| + if e != nil { |
| + lines = append(lines, e.Error(), fmt.Sprintf("%+v", e)) |
| + } |
| + } |
| + for _, line := range lines { |
| + for _, s := range secrets { |
| + if strings.Contains(line, s) { |
| + t.Errorf("%s: %q contains %q", name, line, s) |
| + } |
| + } |
| + checked++ |
| + } |
| + } |
| + if checked == 0 { |
| + t.Fatal("nothing was checked") |
| + } |
| +} |
| + |
| +// TestUnquoteETag: a strong ETag loses its quotes; anything else is "". |
| +func TestUnquoteETag(t *testing.T) { |
| + for in, want := range map[string]string{ |
| + `"9b2cf535f27731c974343645a3985328"`: "9b2cf535f27731c974343645a3985328", |
| + `"abc-2"`: "abc-2", |
| + ``: "", |
| + `""`: "", |
| + `abc`: "", |
| + `W/"abc"`: "", |
| + `"a"b"`: "", |
| + "\"a\nb\"": "", |
| + `"a b"`: "", |
| + `"` + strings.Repeat("a", 257) + `"`: "", |
| + } { |
| + if got := unquoteETag(in); got != want { |
| + t.Errorf("unquoteETag(%q) = %q, want %q", in, got, want) |
| + } |
| + } |
| +} |
| + |
| +// TestParseVersion: ffmpeg -version's first line names the version; |
| +// anything else, or a version with other characters, is "". |
| +func TestParseVersion(t *testing.T) { |
| + for in, want := range map[string]string{ |
| + "ffmpeg version 7.1.5-0+deb13u1 Copyright (c) 2000-2025 the FFmpeg developers\nbuilt with gcc\n": "7.1.5-0+deb13u1", |
| + "ffmpeg version n7.1 Copyright": "n7.1", |
| + "ffmpeg version 7.1": "7.1", |
| + "ffprobe version 7.1 Copyright": "", |
| + "ffmpeg version": "", |
| + "\nffmpeg version 7.1": "", |
| + "ffmpeg version 7.1<script> Copyright": "", |
| + "ffmpeg version " + strings.Repeat("7", 65): "", |
| + } { |
| + if got := parseVersion([]byte(in)); got != want { |
| + t.Errorf("parseVersion(%q) = %q, want %q", in, got, want) |
| + } |
| + } |
| +} |
| + |
| +// TestDiskIsFull: under 16 MiB available, or 64 free inodes, is full. |
| +func TestDiskIsFull(t *testing.T) { |
| + for _, c := range []struct { |
| + bavail, bsize, files, ffree uint64 |
| + want bool |
| + }{ |
| + {0, 4096, 1000, 1000, true}, |
| + {4095, 4096, 1000, 1000, true}, // 16 MiB less one block |
| + {4096, 4096, 1000, 1000, false}, // 16 MiB |
| + {1 << 30, 4096, 1000, 63, true}, |
| + {1 << 30, 4096, 1000, 64, false}, |
| + {1 << 30, 4096, 0, 0, false}, // no inode limit |
| + {0, 0, 0, 0, false}, // no block size: unknown |
| + } { |
| + if got := diskIsFull(c.bavail, c.bsize, c.files, c.ffree); got != c.want { |
| + t.Errorf("diskIsFull(%d, %d, %d, %d) = %t", c.bavail, c.bsize, c.files, c.ffree, got) |
| + } |
| + } |
| +} |
| + |
| +// TestOutputBounds: the media file is bounded by the job's limit and |
| +// never past media.MaxPutBytes; the rest by their fixed bounds. |
| +func TestOutputBounds(t *testing.T) { |
| + p := media.Payload{Limits: media.JobLimits{OutputBytes: 1 << 20}} |
| + b := outputBounds(p) |
| + if b["video.mp4"] != 1<<20 || b["audio.mp4"] != 1<<20 || b["video.m3u8"] != 4<<20 || b["audio.m3u8"] != 4<<20 || b["poster.jpg"] != 16<<20 || b["peaks.json"] != 64<<10 { |
| + t.Fatalf("bounds %v", b) |
| + } |
| + for _, o := range []int64{0, -1, media.MaxPutBytes + 1} { |
| + p.Limits.OutputBytes = o |
| + if got := outputBounds(p)["video.mp4"]; got != media.MaxPutBytes { |
| + t.Errorf("OutputBytes %d: video.mp4 bound %d, want MaxPutBytes", o, got) |
| + } |
| + } |
| +} |