media: report output MD5s, check them exactly, bound results
Plan 3 Task 6 fix round 1 (Astra P1 + 3 P2, Fable Important + minors). P1: the handler hashes each output as it is sent and always reports that MD5 as its ETag; a 200 with another ETag is engine_failed, and a 412 after a broken attempt is reported with our MD5, never the store's. Track requires HEAD's ETag to equal it exactly (single-part, SSE-S3); the fill-from-HEAD path is gone, so bytes the app swaps in after a lost answer fail the job. ParseResult requires an MD5-form ETag. P2: a failure result meeting the expiry exits 75; a 403 is grant expiry only within 60 s of it, else engine_failed with the failure result written (success result too); PUT answer bodies are closed unread and uploads get the download's per-read idle timer; 409 is retried. ParseResult bounds the ffmpeg version, source codecs, content types (ContentType(name), which apimedia now answers) and dimensions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
18 files changed,
+769
−157
docs/superpowers/notes/media-conversion-copy-deck.md+5 −2internal/console/apimedia.go+3 −1internal/console/apimedia_test.go+3 −3internal/console/mediaretire_test.go+1 −1internal/media/media_test.go+46 −3internal/media/result.go+90 −2internal/mediahandler/collect.go+12 −0internal/mediahandler/collect_linux.go+0 −11internal/mediahandler/collect_test.go+9 −4internal/mediahandler/download_test.go+2 −0internal/mediahandler/run.go+19 −7internal/mediahandler/run_test.go+74 −0internal/mediahandler/s3test_test.go+81 −8internal/mediahandler/upload.go+144 −36internal/mediahandler/upload_test.go+227 −40internal/mediajobs/jobs_test.go+35 −21internal/mediajobs/track.go+16 −16internal/sim/mediajobs/witness_test.go+2 −2
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md| index ab4abbadc..dc54068a9 100644 |
| --- a/docs/superpowers/notes/media-conversion-copy-deck.md |
| +++ b/docs/superpowers/notes/media-conversion-copy-deck.md |
| @@ -581,8 +581,11 @@ prints nothing. |
| | `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.exists_after_retry` | `codec: the store holds %s after a broken attempt; reported with this upload's MD5` (pending Luna pass; plan 3 Task 6, fix 1). The console then requires the object's ETag to equal that MD5 | |
| +| `engine.upload.denied` | `codec: the store refused %s (403) before the grant's expiry` (pending Luna pass; plan 3 Task 6, fix 1). More than a minute before it: the job fails `engine_failed` and the failure result is still written | |
| +| `engine.upload.expired` | `codec: the store refused %s (403) at the grant's expiry` (pending Luna pass; plan 3 Task 6, fix 1). Within a minute of it: exit 75, no result | |
| +| `engine.upload.other_bytes` | `codec: the store's ETag for %s is not the MD5 of the bytes sent` (pending Luna pass; plan 3 Task 6, fix 1) | |
| +| `engine.upload.unhashable` | `codec: %s cannot be read to hash it: %s` (pending Luna pass; plan 3 Task 6, fix 1). An output's name or `the result`, and the system's error number's text | |
| | `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) | |
diff --git a/internal/console/apimedia.go b/internal/console/apimedia.go| index b5fdb74b4..48514d50e 100644 |
| --- a/internal/console/apimedia.go |
| +++ b/internal/console/apimedia.go |
| @@ -91,8 +91,10 @@ func (s *Server) mediaAnswer(j mediajobs.Job) mediaJobAnswer { |
| a.FFmpeg = r.FFmpeg |
| prefix := media.OutputPrefix(j.Key, j.ETag, j.Preset, j.Execution) |
| for _, o := range r.Outputs { |
| + // The content type is the platform's for the name, not |
| + // the result's (ParseResult also requires them equal). |
| a.Outputs = append(a.Outputs, mediaJobOutput{Key: prefix + o.Name, Bytes: o.Bytes, ETag: o.ETag, |
| - ContentType: o.ContentType, Width: o.Width, Height: o.Height}) |
| + ContentType: media.ContentType(o.Name), Width: o.Width, Height: o.Height}) |
| } |
| } |
| } |
diff --git a/internal/console/apimedia_test.go b/internal/console/apimedia_test.go| index 0f19e0fd4..2f558d4ab 100644 |
| --- a/internal/console/apimedia_test.go |
| +++ b/internal/console/apimedia_test.go |
| @@ -535,9 +535,9 @@ func TestGetDoneAnswerShape(t *testing.T) { |
| etag := "9b2cf535f27731c974343645a3985328" |
| prefix := media.OutputPrefix(mediaTestKey, etag, media.PresetVideo720p, x) |
| outs := []media.OutputFact{ |
| - {Name: "video.mp4", Bytes: 4000, ETag: "o1", ContentType: "video/mp4", Width: 1280, Height: 720}, |
| - {Name: "video.m3u8", Bytes: 300, ETag: "o2", ContentType: "application/vnd.apple.mpegurl"}, |
| - {Name: "poster.jpg", Bytes: 500, ETag: "o3", ContentType: "image/jpeg", Width: 1280, Height: 720}, |
| + {Name: "video.mp4", Bytes: 4000, ETag: "00000000000000000000000000000001", ContentType: "video/mp4", Width: 1280, Height: 720}, |
| + {Name: "video.m3u8", Bytes: 300, ETag: "00000000000000000000000000000002", ContentType: "application/vnd.apple.mpegurl"}, |
| + {Name: "poster.jpg", Bytes: 500, ETag: "00000000000000000000000000000003", ContentType: "image/jpeg", Width: 1280, Height: 720}, |
| } |
| for _, o := range outs { |
| f.grants.Objects[f.bucket+"/"+prefix+o.Name] = mediatest.Object{Size: o.Bytes, ETag: o.ETag} |
diff --git a/internal/console/mediaretire_test.go b/internal/console/mediaretire_test.go| index 8ad0e5cca..fb671814f 100644 |
| --- a/internal/console/mediaretire_test.go |
| +++ b/internal/console/mediaretire_test.go |
| @@ -565,7 +565,7 @@ func (f *mediaDoorFixture) done(key string) string { |
| prefix := media.OutputPrefix(key, head.ETag, media.PresetVideo720p, x) |
| var outs []media.OutputFact |
| for i, n := range media.OutputNames(media.PresetVideo720p) { |
| - o := media.OutputFact{Name: n, Bytes: int64(100 + i), ETag: "o" + n, ContentType: media.ContentType(n)} |
| + o := media.OutputFact{Name: n, Bytes: int64(100 + i), ETag: strings.Repeat("0", 31) + string(rune('1'+i)), ContentType: media.ContentType(n)} |
| f.grants.Objects[f.bucket+"/"+prefix+n] = mediatest.Object{Size: o.Bytes, ETag: o.ETag} |
| outs = append(outs, o) |
| } |
diff --git a/internal/media/media_test.go b/internal/media/media_test.go| index d75c2ac06..0862e98e2 100644 |
| --- a/internal/media/media_test.go |
| +++ b/internal/media/media_test.go |
| @@ -316,9 +316,9 @@ func TestParseResult(t *testing.T) { |
| Source: &SourceFacts{DurationMS: 120000, Width: 1920, Height: 1080, VideoCodec: "h264", AudioCodec: "aac"}, |
| FFmpeg: "7.1.1", |
| Outputs: []OutputFact{ |
| - {Name: "video.mp4", Bytes: 1000, ETag: "e1", ContentType: "video/mp4", Width: 1280, Height: 720}, |
| - {Name: "video.m3u8", Bytes: 200, ETag: "e2", ContentType: "application/vnd.apple.mpegurl"}, |
| - {Name: "poster.jpg", Bytes: 300, ETag: "", ContentType: "image/jpeg", Width: 1280, Height: 720}, |
| + {Name: "video.mp4", Bytes: 1000, ETag: "9b2cf535f27731c974343645a3985328", ContentType: "video/mp4", Width: 1280, Height: 720}, |
| + {Name: "video.m3u8", Bytes: 200, ETag: "0123456789abcdef0123456789abcdef", ContentType: "application/vnd.apple.mpegurl"}, |
| + {Name: "poster.jpg", Bytes: 300, ETag: "fedcba9876543210fedcba9876543210", ContentType: "image/jpeg", Width: 1280, Height: 720}, |
| }, |
| } |
| } |
| @@ -374,6 +374,34 @@ func TestParseResult(t *testing.T) { |
| r8 := good() |
| r8.Source = nil |
| bad["no source facts"] = enc(r8) |
| + // Plan 3 Task 6 fix 1: what the console answers is held to the |
| + // handler's shapes. |
| + shape := map[string]func(*Result){ |
| + "version with a space": func(r *Result) { r.FFmpeg = "7.1 beta" }, |
| + "version with markup": func(r *Result) { r.FFmpeg = "<b>7</b>" }, |
| + "version of 65 characters": func(r *Result) { r.FFmpeg = strings.Repeat("7", 65) }, |
| + "unknown video codec": func(r *Result) { r.Source.VideoCodec = "mjpeg" }, |
| + "unknown audio codec": func(r *Result) { r.Source.AudioCodec = "pcm_s16le_planar" }, |
| + "source width without height": func(r *Result) { r.Source.Height = 0 }, |
| + "source over MaxSide": func(r *Result) { r.Source.Width = MaxSide + 1 }, |
| + "negative source height": func(r *Result) { r.Source.Height = -1 }, |
| + "another content type": func(r *Result) { r.Outputs[0].ContentType = "text/html" }, |
| + "no content type": func(r *Result) { r.Outputs[1].ContentType = "" }, |
| + "empty ETag": func(r *Result) { r.Outputs[2].ETag = "" }, |
| + "upper-case ETag": func(r *Result) { r.Outputs[0].ETag = "9B2CF535F27731C974343645A3985328" }, |
| + "quoted ETag": func(r *Result) { r.Outputs[0].ETag = `"9b2cf535f27731c974343645a39853"` }, |
| + "31-character ETag": func(r *Result) { r.Outputs[0].ETag = "9b2cf535f27731c974343645a398532" }, |
| + "multipart ETag": func(r *Result) { r.Outputs[0].ETag = "9b2cf535f27731c974343645a3985328-2" }, |
| + "output height 0": func(r *Result) { r.Outputs[0].Height = 0 }, |
| + "output over MaxSide": func(r *Result) { r.Outputs[2].Width = MaxSide + 1 }, |
| + } |
| + for name, f := range shape { |
| + r := good() |
| + r.Source = &SourceFacts{} |
| + *r.Source = *good().Source |
| + f(&r) |
| + bad[name] = enc(r) |
| + } |
| bad["unknown field"] = []byte(`{"v":1,"execution":"` + x + `","error":"no_video","extra":1}`) |
| bad["trailing data"] = append(enc(good()), []byte(` {}`)...) |
| // Pad a valid result with trailing spaces to exactly MaxResultBytes+1: |
| @@ -386,6 +414,21 @@ func TestParseResult(t *testing.T) { |
| t.Errorf("%s: accepted", name) |
| } |
| } |
| + // The edges of each bound are accepted. |
| + edge := good() |
| + edge.FFmpeg = strings.Repeat("7", 64) |
| + edge.Source.Width, edge.Source.Height = MaxSide, 1 |
| + edge.Source.VideoCodec, edge.Source.AudioCodec = "av1", "pcm_mulaw" |
| + edge.Outputs[0].Width, edge.Outputs[0].Height = 1, MaxSide |
| + if _, err := ParseResult(enc(edge), x, PresetVideo720p); err != nil { |
| + t.Errorf("a result at the bounds: %v", err) |
| + } |
| + none := good() |
| + none.FFmpeg = "" |
| + *none.Source = SourceFacts{DurationMS: 1} |
| + if _, err := ParseResult(enc(none), x, PresetVideo720p); err != nil { |
| + t.Errorf("a result with no version, codecs or dimensions: %v", err) |
| + } |
| // Exactly MaxResultBytes with the same padding is accepted. |
| atLimit := enc(good()) |
| atLimit = append(atLimit, []byte(strings.Repeat(" ", MaxResultBytes-len(atLimit)))...) |
diff --git a/internal/media/result.go b/internal/media/result.go| index f94cdffc7..d1fd39283 100644 |
| --- a/internal/media/result.go |
| +++ b/internal/media/result.go |
| @@ -6,6 +6,7 @@ import ( |
| "errors" |
| "fmt" |
| "io" |
| + "strings" |
| ) |
| // ResultVersion is the result object's schema version. |
| @@ -24,7 +25,7 @@ type SourceFacts struct { |
| type OutputFact struct { |
| Name string `json:"name"` |
| Bytes int64 `json:"bytes"` |
| - ETag string `json:"etag"` // "" when an upload retry met 412 (plan 3 Task 6); the console takes HEAD's |
| + ETag string `json:"etag"` // the MD5 of the bytes uploaded, lower-case hex: S3's single-part ETag, which HEAD must match |
| ContentType string `json:"content_type"` |
| Width int `json:"width,omitempty"` |
| Height int `json:"height,omitempty"` |
| @@ -45,7 +46,14 @@ type Result struct { |
| // no unknown field and nothing after the object, version 1, the expected |
| // execution, and an error that is empty or a handler code. A success |
| // result must carry the source facts and exactly the preset's outputs, |
| -// each once, each of 1 to MaxPutBytes bytes. |
| +// each once, each of 1 to MaxPutBytes bytes. Everything the console |
| +// later answers is held to the shapes the handler writes (plan 3 Task 6 |
| +// fix 1), so a forged result cannot put free text in an API answer: the |
| +// ffmpeg version ("" or up to 64 of letters, digits and ".+~:_-"); the |
| +// source's codecs ("" or one the handler accepts); every dimension 0 |
| +// (absent) or 1 to MaxSide, a width and its height both or neither; |
| +// each output's content type exactly ContentType(name); each output's |
| +// ETag an MD5 in lower-case hex. |
| func ParseResult(b []byte, execution, preset string) (Result, error) { |
| if len(b) > MaxResultBytes { |
| return Result{}, fmt.Errorf("result is %d bytes, over %d", len(b), MaxResultBytes) |
| @@ -93,6 +101,86 @@ func ParseResult(b []byte, execution, preset string) (Result, error) { |
| if o.Bytes < 1 || o.Bytes > MaxPutBytes { |
| return Result{}, fmt.Errorf("result output %s is %d bytes", o.Name, o.Bytes) |
| } |
| + if o.ContentType != ContentType(o.Name) { |
| + return Result{}, fmt.Errorf("result output %s has another content type", o.Name) |
| + } |
| + if !md5Hex(o.ETag) { |
| + return Result{}, fmt.Errorf("result output %s has an ETag that is not an MD5", o.Name) |
| + } |
| + if !dimensions(o.Width, o.Height) { |
| + return Result{}, fmt.Errorf("result output %s has dimensions out of bounds", o.Name) |
| + } |
| + } |
| + if err := checkFacts(r); err != nil { |
| + return Result{}, err |
| } |
| return r, nil |
| } |
| + |
| +// resultVideoCodecs and resultAudioCodecs are the codec names the |
| +// handler's check accepts (internal/mediahandler's videoCodecs and |
| +// audioCodecs; its TestResultCodecsMatchTheChecks holds the two equal). |
| +var ( |
| + resultVideoCodecs = map[string]bool{"h264": true, "hevc": true, "vp8": true, "vp9": true, "av1": true} |
| + resultAudioCodecs = map[string]bool{"aac": true, "opus": true, "vorbis": true, "mp3": true, "flac": true, |
| + "pcm_u8": true, "pcm_s16le": true, "pcm_s16be": true, "pcm_s24le": true, "pcm_s24be": true, |
| + "pcm_s32le": true, "pcm_s32be": true, "pcm_f32le": true, "pcm_f32be": true, "pcm_f64le": true, |
| + "pcm_f64be": true, "pcm_alaw": true, "pcm_mulaw": true} |
| +) |
| + |
| +// checkFacts holds a success result's version and source facts to the |
| +// handler's shapes (see ParseResult). |
| +func checkFacts(r Result) error { |
| + if !versionString(r.FFmpeg) { |
| + return errors.New("result ffmpeg version is not a version") |
| + } |
| + s := r.Source |
| + if s.VideoCodec != "" && !resultVideoCodecs[s.VideoCodec] { |
| + return errors.New("result source video codec is not one the handler accepts") |
| + } |
| + if s.AudioCodec != "" && !resultAudioCodecs[s.AudioCodec] { |
| + return errors.New("result source audio codec is not one the handler accepts") |
| + } |
| + if !dimensions(s.Width, s.Height) { |
| + return errors.New("result source dimensions out of bounds") |
| + } |
| + return nil |
| +} |
| + |
| +// dimensions reports whether w x h is absent (both 0) or both in 1 to |
| +// MaxSide. |
| +func dimensions(w, h int) bool { |
| + if w == 0 && h == 0 { |
| + return true |
| + } |
| + return w >= 1 && w <= MaxSide && h >= 1 && h <= MaxSide |
| +} |
| + |
| +// versionString reports whether v is "" or 1 to 64 of letters, digits |
| +// and ".+~:_-" (what the handler reads from ffmpeg -version). |
| +func versionString(v string) bool { |
| + if len(v) > 64 { |
| + return false |
| + } |
| + 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 false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// md5Hex reports whether s is 32 lower-case hex characters. |
| +func md5Hex(s string) bool { |
| + if len(s) != 32 { |
| + return false |
| + } |
| + for i := 0; i < len(s); i++ { |
| + c := s[i] |
| + if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
diff --git a/internal/mediahandler/collect.go b/internal/mediahandler/collect.go| index 66a59aad0..c95f4770b 100644 |
| --- a/internal/mediahandler/collect.go |
| +++ b/internal/mediahandler/collect.go |
| @@ -1,7 +1,9 @@ |
| package mediahandler |
| import ( |
| + "errors" |
| "os" |
| + "syscall" |
| "github.com/carlosframework/platform/internal/media" |
| ) |
| @@ -84,3 +86,13 @@ func diskIsFull(bavail, bsize, files, ffree uint64) bool { |
| } |
| return files > 0 && ffree < scratchFullInodes |
| } |
| + |
| +// 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" |
| +} |
diff --git a/internal/mediahandler/collect_linux.go b/internal/mediahandler/collect_linux.go| index 1a3aa8282..709b03f9e 100644 |
| --- a/internal/mediahandler/collect_linux.go |
| +++ b/internal/mediahandler/collect_linux.go |
| @@ -3,7 +3,6 @@ |
| package mediahandler |
| import ( |
| - "errors" |
| "io/fs" |
| "os" |
| "strconv" |
| @@ -166,16 +165,6 @@ func checkOpened(f *os.File, name string, bound int64, lst *syscall.Stat_t) (col |
| 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. |
diff --git a/internal/mediahandler/collect_test.go b/internal/mediahandler/collect_test.go| index 579d7e8e2..893c68b2c 100644 |
| --- a/internal/mediahandler/collect_test.go |
| +++ b/internal/mediahandler/collect_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "bytes" |
| "context" |
| "errors" |
| + "fmt" |
| "io" |
| "net" |
| "os" |
| @@ -95,7 +96,7 @@ var hostiles = []hostile{ |
| {"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) { |
| + {"one byte over its bound", "", func(t *testing.T, dir, name string, bound int64) { |
| if err := os.Truncate(filepath.Join(dir, name), bound+1); err != nil { |
| t.Fatal(err) |
| } |
| @@ -159,8 +160,12 @@ func TestCollectRefusesHostileOutputs(t *testing.T) { |
| 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) |
| + why := k.why |
| + if k.name == "one byte over its bound" { |
| + why = fmt.Sprintf("over its %d-byte bound", bounds[name]) |
| + } |
| + if want := "output " + name + " refused: " + why; err.Error() != want { |
| + t.Fatalf("collect's refusal %q, want exactly %q", err, want) |
| } |
| if after != before { |
| t.Fatalf("%d descriptors open after the refusal, %d before", after, before) |
| @@ -296,7 +301,7 @@ func TestCollectRefusesASwapAfterTheLstat(t *testing.T) { |
| if swapErr != nil { |
| t.Fatal(swapErr) |
| } |
| - if codeOf(err) != media.CodeEngineFailed || !strings.Contains(err.Error(), "audio.m3u8 refused: "+c.why) { |
| + if codeOf(err) != media.CodeEngineFailed || err.Error() != "output audio.m3u8 refused: "+c.why { |
| t.Fatalf("collect = %v, want audio.m3u8 refused: %s", err, c.why) |
| } |
| }) |
diff --git a/internal/mediahandler/download_test.go b/internal/mediahandler/download_test.go| index 502a12c28..45d18042c 100644 |
| --- a/internal/mediahandler/download_test.go |
| +++ b/internal/mediahandler/download_test.go |
| @@ -637,6 +637,7 @@ type fakeIdle struct { |
| fire func() |
| stalled bool |
| durations []time.Duration |
| + resets int |
| } |
| type fakeIdleTimer struct { |
| @@ -655,6 +656,7 @@ func (t *fakeIdleTimer) Reset(time.Duration) bool { |
| t.fi.mu.Lock() |
| defer t.fi.mu.Unlock() |
| t.fi.armed, t.fi.fire = true, t.f |
| + t.fi.resets++ |
| if t.fi.stalled { |
| t.fi.stalled = false |
| t.f() |
diff --git a/internal/mediahandler/run.go b/internal/mediahandler/run.go| index 11dc8d935..59c30b35d 100644 |
| --- a/internal/mediahandler/run.go |
| +++ b/internal/mediahandler/run.go |
| @@ -35,14 +35,17 @@ const exitStopped = 143 |
| // - 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 |
| +// - errGrantExpired (a transfer not begun because the grant's expiry |
| +// has come, a 403 within a minute of it, or an ffmpeg pass still |
| +// running at it): exit media.ExitGrantExpired, no result (the result |
| +// PUT has expired with the same grant). The same when it is the |
| +// failure result's own PUT that meets the expiry; |
| +// - a jobError anywhere (a refused payload aside), a 403 well before |
| +// the expiry included (put's storeDenied): a best-effort result |
| // object with its code, exit media.ExitFailed; |
| -// - the success result not written: exit media.ExitFailed, no second |
| -// attempt. |
| +// - the success result not written for any other reason (a 412, a |
| +// store that kept breaking): exit media.ExitFailed, no second |
| +// attempt, since that result may be stored already. |
| // |
| // Every ffmpeg and ffprobe pass runs under the grant's deadline |
| // (grantContext): converting past it cannot be uploaded. The download |
| @@ -94,6 +97,10 @@ func runJob(ctx context.Context, cfg Config, p media.Payload) error { |
| Outputs: outputs, |
| } |
| if err := writeResult(ctx, cfg, p, r); err != nil { |
| + var denied storeDenied |
| + if errors.As(err, &denied) { |
| + return err // nothing was stored: finish writes the failure result |
| + } |
| return resultUnwritten{err} |
| } |
| return nil |
| @@ -270,6 +277,11 @@ func finish(ctx context.Context, cfg Config, p media.Payload, err error) int { |
| case ctx.Err() != nil: |
| cfg.Logf("codec: stopped: %v", ctx.Err()) |
| return exitStopped |
| + case errors.Is(werr, errGrantExpired): |
| + // The failure result itself met the grant's expiry: the console |
| + // reads exit 75 as grant_expired (Task 6 fix 1, Astra P2). |
| + cfg.Logf("codec: the grant has expired; no result is written") |
| + return media.ExitGrantExpired |
| default: |
| // engine.codec.error_unwritten (pending Luna pass). |
| cfg.Logf("codec: the result naming %s could not be written", je.code) |
diff --git a/internal/mediahandler/run_test.go b/internal/mediahandler/run_test.go| index 80b09e793..08b11fce7 100644 |
| --- a/internal/mediahandler/run_test.go |
| +++ b/internal/mediahandler/run_test.go |
| @@ -488,6 +488,80 @@ func TestRunResultRefusedIsNotRetried(t *testing.T) { |
| } |
| } |
| +// TestRunFailureResultMeetsTheExpiry (Astra P2): a named error whose |
| +// failure result cannot begin because the grant's expiry has come, |
| +// before its PUT or during its retry wait, exits 75 (grant_expired), |
| +// not 1, and no result is stored. |
| +func TestRunFailureResultMeetsTheExpiry(t *testing.T) { |
| + t.Run("before its PUT", func(t *testing.T) { |
| + h, p, cfg, record := runJobSetup(t, media.PresetVideo720p, "probe-m4a-cover-art") |
| + cfg.Now = func() time.Time { |
| + if _, err := os.Stat(record); err == nil { |
| + return h.s.expiry // once the probe has run |
| + } |
| + return h.clock.Now() |
| + } |
| + if code := runFor(t, cfg, p); code != media.ExitGrantExpired { |
| + t.Fatalf("Run = %d, want 75", code) |
| + } |
| + if got := requestLines(h.s.Requests()); !slices.Equal(got, []string{"GET " + srcPath}) { |
| + t.Fatalf("requests %q, want the source's GET alone", got) |
| + } |
| + }) |
| + t.Run("during its retry wait", func(t *testing.T) { |
| + h, p, cfg, _ := runJobSetup(t, media.PresetVideo720p, "probe-m4a-cover-art") |
| + h.s.OnPut = firstPut(dropConnection) |
| + h.onWait = func() { h.clock.Set(h.s.expiry) } |
| + if code := runFor(t, cfg, p); code != media.ExitGrantExpired { |
| + t.Fatalf("Run = %d, want 75", code) |
| + } |
| + if got := requestLines(h.s.Requests()); !slices.Equal(got, []string{"GET " + srcPath, "PUT " + resultPath}) { |
| + t.Fatalf("requests %q, want the GET and one broken result PUT", got) |
| + } |
| + if _, ok := h.s.Object(resultPath); ok { |
| + t.Fatal("a result was stored") |
| + } |
| + }) |
| +} |
| + |
| +// TestRunDeniedWritesTheFailureResult (Astra P2, Fable): a 403 well |
| +// before the expiry, on an output or on the success result, is |
| +// engine_failed, and the failure result is then written; Run exits 1. |
| +func TestRunDeniedWritesTheFailureResult(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + at int |
| + want []string |
| + }{ |
| + {"an output", 1, []string{"GET " + srcPath, "PUT " + outPrefix + "video.mp4", "PUT " + resultPath}}, |
| + {"the success result", 4, []string{"GET " + srcPath, "PUT " + outPrefix + "video.mp4", "PUT " + outPrefix + "video.m3u8", |
| + "PUT " + outPrefix + "poster.jpg", "PUT " + resultPath, "PUT " + resultPath}}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + h, p, cfg, _ := runJobSetup(t, media.PresetVideo720p, "ok-video") |
| + h.s.OnPut = func(n int) int { |
| + if n == c.at { |
| + return http.StatusForbidden |
| + } |
| + return 0 |
| + } |
| + 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, c.want) { |
| + t.Fatalf("requests\n got %q\nwant %q", got, c.want) |
| + } |
| + 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) |
| + } |
| + if !slices.Contains(h.Logs(), "codec: the store refused "+map[int]string{1: "video.mp4", 4: "the result"}[c.at]+" (403) before the grant's expiry") { |
| + 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 |
diff --git a/internal/mediahandler/s3test_test.go b/internal/mediahandler/s3test_test.go| index b2c012ca4..3588dc1f4 100644 |
| --- a/internal/mediahandler/s3test_test.go |
| +++ b/internal/mediahandler/s3test_test.go |
| @@ -1,6 +1,7 @@ |
| package mediahandler |
| import ( |
| + "crypto/md5" |
| "crypto/rand" |
| "encoding/hex" |
| "encoding/json" |
| @@ -22,9 +23,21 @@ import ( |
| // unanswered. dropAfterCommit, answered by OnPut, stores the object and |
| // then closes the connection unanswered (a PUT cut after the store |
| // committed it). |
| +// swapAfterCommit, answered by OnPut, stores the object, then replaces |
| +// it with other bytes of the same length (the app's own credentials |
| +// writing under derived/), then closes the connection unanswered. |
| +// stallBody stores the object and answers 200 with its headers, then |
| +// sends none of the body it announced until the client goes away. |
| +// holdPut reads the body and answers nothing until the client goes |
| +// away, closing Held first. wrongETag stores the object and answers 200 with |
| +// an ETag that is not its MD5. |
| const ( |
| dropConnection = -1 |
| dropAfterCommit = -2 |
| + swapAfterCommit = -3 |
| + stallBody = -4 |
| + holdPut = -5 |
| + wrongETag = -6 |
| ) |
| // testToken is the session token every transfer of s3Server carries, as |
| @@ -141,11 +154,12 @@ type s3Server struct { |
| LengthLie int64 |
| OnGet func(n int) int |
| OnPut func(n int) int |
| + Held chan struct{} |
| } |
| // newS3 starts a server whose grant expires an hour after clock's now. |
| func newS3(t *testing.T, clock *testClock) *s3Server { |
| - s := &s3Server{t: t, clock: clock, expiry: clock.Now().Add(time.Hour), objects: map[string]*s3Object{}, transfers: map[string]s3Transfer{}, Stalled: make(chan struct{})} |
| + s := &s3Server{t: t, clock: clock, expiry: clock.Now().Add(time.Hour), objects: map[string]*s3Object{}, transfers: map[string]s3Transfer{}, Stalled: make(chan struct{}), Held: make(chan struct{})} |
| s.srv = httptest.NewServer(http.HandlerFunc(s.serve)) |
| t.Cleanup(s.srv.Close) |
| return s |
| @@ -311,11 +325,8 @@ 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 r.Method == "PUT" && forced <= dropAfterCommit { |
| + return s.putForced(r, forced) |
| } |
| if forced != 0 { |
| return forced, nil |
| @@ -460,7 +471,7 @@ func (s *s3Server) put(r *http.Request) (int, func(http.ResponseWriter)) { |
| if err != nil { |
| return http.StatusBadRequest, nil |
| } |
| - obj := &s3Object{data: data, etag: strconv.Itoa(len(s.objects) + 1)} |
| + obj := &s3Object{data: data, etag: md5hex(data)} |
| s.objects[path] = obj |
| return http.StatusOK, func(w http.ResponseWriter) { |
| w.Header().Set("ETag", `"`+obj.etag+`"`) |
| @@ -524,5 +535,67 @@ func marshal(t *testing.T, p media.Payload) string { |
| 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"} |
| + s.objects[path] = &s3Object{data: append([]byte(nil), data...), etag: md5hex(data)} |
| +} |
| + |
| +// ETagOf is the ETag of the object at path ("" if none). |
| +func (s *s3Server) ETagOf(path string) string { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + if o, ok := s.objects[path]; ok { |
| + return o.etag |
| + } |
| + return "" |
| +} |
| + |
| +// md5hex is data's MD5 in lower-case hex: S3's ETag for a single-part |
| +// PUT. |
| +func md5hex(data []byte) string { |
| + sum := md5.Sum(data) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +// putForced is a PUT answered as OnPut's special values say (see their |
| +// constants), under s.mu. |
| +func (s *s3Server) putForced(r *http.Request, forced int) (int, func(http.ResponseWriter)) { |
| + if forced == holdPut { |
| + held := s.Held |
| + return http.StatusOK, func(http.ResponseWriter) { |
| + // Read the body first: Go's server notices a client gone |
| + // only once the body is read. |
| + _, _ = io.Copy(io.Discard, r.Body) |
| + close(held) |
| + waitGone(r) |
| + panic(http.ErrAbortHandler) |
| + } |
| + } |
| + status, _ := s.put(r) |
| + if status != http.StatusOK { |
| + return status, nil |
| + } |
| + obj := s.objects[r.URL.EscapedPath()] |
| + switch forced { |
| + case swapAfterCommit: |
| + other := make([]byte, len(obj.data)) |
| + for i, c := range obj.data { |
| + other[i] = c ^ 0xff |
| + } |
| + s.objects[r.URL.EscapedPath()] = &s3Object{data: other, etag: md5hex(other)} |
| + case stallBody: |
| + etag := obj.etag |
| + return http.StatusOK, func(w http.ResponseWriter) { |
| + w.Header().Set("ETag", `"`+etag+`"`) |
| + w.Header().Set("Content-Length", "1000") |
| + w.WriteHeader(http.StatusOK) |
| + w.(http.Flusher).Flush() |
| + waitGone(r) |
| + panic(http.ErrAbortHandler) |
| + } |
| + case wrongETag: |
| + return http.StatusOK, func(w http.ResponseWriter) { |
| + w.Header().Set("ETag", `"`+strings.Repeat("0", 32)+`"`) |
| + w.WriteHeader(http.StatusOK) |
| + } |
| + } |
| + return dropConnection, nil |
| } |
diff --git a/internal/mediahandler/upload.go b/internal/mediahandler/upload.go| index d71d89b19..fe6947030 100644 |
| --- a/internal/mediahandler/upload.go |
| +++ b/internal/mediahandler/upload.go |
| @@ -2,8 +2,12 @@ package mediahandler |
| import ( |
| "context" |
| + "crypto/md5" |
| + "encoding/hex" |
| + "hash" |
| "io" |
| "net/http" |
| + "sync" |
| "time" |
| "github.com/carlosframework/platform/internal/media" |
| @@ -13,14 +17,22 @@ import ( |
| // 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 |
| +// deniedMargin is how close to the grant's expiry a 403 may come and |
| +// still be taken as the grant's end (errGrantExpired). Earlier, a 403 is |
| +// the store refusing this writer: engine_failed (Task 6 fix 1). A |
| +// minute covers the task's clock running behind the store's. |
| +const deniedMargin = 60 * time.Second |
| + |
| +// bodyClosedWait bounds the wait for the transport to finish with a |
| +// request body once the response has come, before its hash is read. |
| +const bodyClosedWait = 5 * time.Second |
| // 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. |
| +// the MD5 of those bytes, lower-case hex: the ETag S3 gives a |
| +// single-part PUT under SSE-S3, which the console requires the object's |
| +// HEAD to match exactly (mediajobs Track). 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). |
| @@ -30,29 +42,48 @@ func upload(ctx context.Context, cfg Config, p media.Payload, t media.Transfer, |
| return put(ctx, cfg, p, t, c.Name, c.Size, func() io.Reader { return io.NewSectionReader(c.File, 0, c.Size) }) |
| } |
| +// storeDenied is a PUT the store refused (403) well before the grant's |
| +// expiry: engine_failed, and the failure result is still attempted. |
| +type storeDenied struct{} |
| + |
| +func (storeDenied) Error() string { return media.CodeEngineFailed } |
| + |
| +func (storeDenied) Unwrap() error { return jobError{media.CodeEngineFailed} } |
| + |
| // 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: |
| +// for each attempt) with transfer t; what names it in the log. It |
| +// answers the MD5 of the bytes, lower-case hex, never "". 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); |
| +// and Accept-Encoding: identity, and follows no redirect; each read |
| +// of its body must come within idleTimeout of the last (and the |
| +// answer within idleTimeout of the body's end), else the attempt is |
| +// broken; the response's body is closed unread, so a store that |
| +// stalls it cannot hold the handler; |
| +// - 200: done. The MD5 is the one hashed as the body was sent; an |
| +// ETag in the answer other than it means the store holds other |
| +// bytes than these: engine_failed; |
| // - 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; |
| +// no one but this execution should write (spec §9): engine_failed; |
| +// - a broken attempt (a transport error; or 409, 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 taken as |
| +// this upload's own object, and answered with this upload's MD5, |
| +// not the store's. That is safe only because the console requires |
| +// the object's HEAD ETag to equal the reported MD5 exactly: the |
| +// app's own store credentials can write under derived/, so after a |
| +// lost answer it could put other bytes of the same length there, and |
| +// that object's ETag then fails the job (Task 6 fix 1, Astra P1); |
| +// - 403 within deniedMargin of the expiry: errGrantExpired (a clock |
| +// behind the store's, and the result PUT will meet the same |
| +// refusal); earlier: storeDenied (engine_failed); |
| // - 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) { |
| +func put(ctx context.Context, cfg Config, p media.Payload, t media.Transfer, what string, size int64, body func() io.Reader) (sum string, err error) { |
| expiry := time.Unix(p.Expiry, 0) |
| broken := false |
| for attempt := 0; ; attempt++ { |
| @@ -62,27 +93,43 @@ func put(ctx context.Context, cfg Config, p media.Payload, t media.Transfer, wha |
| if !cfg.Now().Before(expiry) { |
| return "", errGrantExpired |
| } |
| - status, etag, err := putOnce(ctx, cfg, p, t, size, body()) |
| + status, storeETag, sent, err := putOnce(ctx, cfg, p, t, size, body()) |
| if err != nil { |
| return "", err |
| } |
| switch status { |
| case http.StatusOK: |
| - return etag, nil |
| + if sent == "" { |
| + if sent, err = hashAll(cfg, what, body()); err != nil { |
| + return "", err |
| + } |
| + } |
| + if storeETag != "" && storeETag != sent { |
| + // engine.upload.other_bytes (pending Luna pass). |
| + cfg.Logf("codec: the store's ETag for %s is not the MD5 of the bytes sent", what) |
| + return "", jobError{media.CodeEngineFailed} |
| + } |
| + return sent, 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 |
| + cfg.Logf("codec: the store holds %s after a broken attempt; reported with this upload's MD5", what) |
| + return hashAll(cfg, what, body()) |
| } |
| // engine.upload.exists (pending Luna pass). |
| cfg.Logf("codec: the store already holds %s", what) |
| return "", jobError{media.CodeEngineFailed} |
| case http.StatusForbidden: |
| + if !cfg.Now().Before(expiry.Add(-deniedMargin)) { |
| + // engine.upload.expired (pending Luna pass). |
| + cfg.Logf("codec: the store refused %s (403) at the grant's expiry", what) |
| + return "", errGrantExpired |
| + } |
| // 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: |
| + cfg.Logf("codec: the store refused %s (403) before the grant's expiry", what) |
| + return "", storeDenied{} |
| + case statusBroken, http.StatusConflict, 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) |
| @@ -106,15 +153,22 @@ func put(ctx context.Context, cfg Config, p media.Payload, t media.Transfer, wha |
| 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) |
| +// transport error or an idle body), the store's ETag, unquoted, and the |
| +// MD5 of the body sent ("" unless the transport read and released all |
| +// size bytes). 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, r io.Reader) (status int, etag, sum string, err error) { |
| + actx, cancel := context.WithCancel(ctx) |
| + defer cancel() |
| + idle := cfg.idle(idleTimeout, cancel) |
| + defer idle.Stop() |
| + b := &sentBody{r: r, h: md5.New(), idle: idle, closed: make(chan struct{})} |
| + req, err := http.NewRequestWithContext(actx, http.MethodPut, p.Transfers.URL(t), b) |
| 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} |
| + return 0, "", "", jobError{media.CodeEngineFailed} |
| } |
| req.ContentLength = size |
| for k, v := range t.Header { |
| @@ -123,22 +177,76 @@ func putOnce(ctx context.Context, cfg Config, p media.Payload, t media.Transfer, |
| req.Header.Set("Accept-Encoding", "identity") |
| client := *cfg.HTTP |
| client.CheckRedirect = noRedirect |
| + idle.Reset(idleTimeout) |
| resp, err := client.Do(req) |
| + idle.Stop() |
| 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 0, "", "", ctx.Err() |
| } |
| - return statusBroken, "", nil |
| + return statusBroken, "", "", nil |
| + } |
| + // Unread: the answer's body holds nothing used, and a store that |
| + // sent its headers and then stalls the body must not hold the |
| + // handler (Task 6 fix 1). |
| + resp.Body.Close() |
| + timer := time.NewTimer(bodyClosedWait) |
| + defer timer.Stop() |
| + select { |
| + case <-b.closed: |
| + // The transport is done with the body: its hash is final. |
| + if b.n == size { |
| + sum = hex.EncodeToString(b.h.Sum(nil)) |
| + } |
| + case <-timer.C: |
| + } |
| + return resp.StatusCode, unquoteETag(resp.Header.Get("ETag")), sum, nil |
| +} |
| + |
| +// sentBody is a PUT's body: it hashes and counts what the transport |
| +// reads, resets the idle timer on each read, and closes closed when the |
| +// transport closes it (after its last read). |
| +type sentBody struct { |
| + r io.Reader |
| + h hash.Hash |
| + n int64 |
| + idle idleTimer |
| + closed chan struct{} |
| + once sync.Once |
| +} |
| + |
| +func (b *sentBody) Read(p []byte) (int, error) { |
| + n, err := b.r.Read(p) |
| + if n > 0 { |
| + b.h.Write(p[:n]) |
| + b.n += int64(n) |
| + b.idle.Reset(idleTimeout) |
| + } |
| + return n, err |
| +} |
| + |
| +func (b *sentBody) Close() error { |
| + b.once.Do(func() { close(b.closed) }) |
| + return nil |
| +} |
| + |
| +// hashAll is the MD5 of everything r reads, lower-case hex. MD5 is the |
| +// store's ETag for a single-part PUT, compared with HEAD's; it is not a |
| +// secret's hash. A read failure of the handler's own file is |
| +// engine_failed. |
| +func hashAll(cfg Config, what string, r io.Reader) (string, error) { |
| + h := md5.New() |
| + if _, err := io.Copy(h, r); err != nil { |
| + // engine.upload.unhashable (pending Luna pass). |
| + cfg.Logf("codec: %s cannot be read to hash it: %s", what, sysReason(err)) |
| + return "", jobError{media.CodeEngineFailed} |
| } |
| - defer resp.Body.Close() |
| - _, _ = io.CopyN(io.Discard, resp.Body, putBodyDrain) |
| - return resp.StatusCode, unquoteETag(resp.Header.Get("ETag")), nil |
| + return hex.EncodeToString(h.Sum(nil)), 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. |
| +// a weak one, or one holding anything but printable ASCII. |
| func unquoteETag(h string) string { |
| if len(h) < 3 || len(h) > 258 || h[0] != '"' || h[len(h)-1] != '"' { |
| return "" |
diff --git a/internal/mediahandler/upload_test.go b/internal/mediahandler/upload_test.go| index 219be86f3..6f3ee1c41 100644 |
| --- a/internal/mediahandler/upload_test.go |
| +++ b/internal/mediahandler/upload_test.go |
| @@ -3,6 +3,8 @@ package mediahandler |
| import ( |
| "bytes" |
| "context" |
| + "encoding/json" |
| + "errors" |
| "fmt" |
| "net/http" |
| "os" |
| @@ -38,6 +40,16 @@ func (h *harness) uploadVideo(t *testing.T, p media.Payload, data []byte) (strin |
| return upload(ctx, h.cfg.withDefaults(), p, p.Transfers.Outputs[0], collectedFile(t, "video.mp4", data)) |
| } |
| +// firstPut answers v to the first PUT and nothing special after. |
| +func firstPut(v int) func(int) int { |
| + return func(n int) int { |
| + if n == 1 { |
| + return v |
| + } |
| + return 0 |
| + } |
| +} |
| + |
| func puts(rs []s3Request) []s3Request { |
| var out []s3Request |
| for _, r := range rs { |
| @@ -53,7 +65,7 @@ func puts(rs []s3Request) []s3Request { |
| // 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. |
| +// answer is the MD5 of the bytes sent, which is the store's ETag. |
| func TestUploadSendsTheSignedHeaders(t *testing.T) { |
| h := newHarness(t) |
| p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| @@ -90,11 +102,8 @@ func TestUploadSendsTheSignedHeaders(t *testing.T) { |
| 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) |
| + if etag != md5hex(data) || etag != h.s.ETagOf(outPrefix+"video.mp4") { |
| + t.Fatalf("etag %q, want the MD5 of the bytes sent, %q, which the store also answers", etag, md5hex(data)) |
| } |
| } |
| @@ -118,20 +127,23 @@ func TestUploadSecondPutRefused(t *testing.T) { |
| } |
| // 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. |
| +// connection then lost is made again; that attempt's 412 is taken as |
| +// this upload's own object, answered with the MD5 of the bytes sent |
| +// (the console checks it against the object: TestUploadRetryAcceptsOnlyItsOwnMD5). |
| +// A PUT cut before the commit, or a 409 (ConditionalRequestConflict), |
| +// 500 or 503, is made again and its 200 answers the same MD5. Each retry |
| +// waits resumeDelay. |
| func TestUploadRetryAfterTransportError(t *testing.T) { |
| for _, c := range []struct { |
| name string |
| first int |
| - wantETag bool |
| + retry412 bool |
| }{ |
| - {"cut after the commit", dropAfterCommit, false}, |
| - {"cut before the commit", dropConnection, true}, |
| - {"503", http.StatusServiceUnavailable, true}, |
| - {"500", http.StatusInternalServerError, true}, |
| + {"cut after the commit", dropAfterCommit, true}, |
| + {"cut before the commit", dropConnection, false}, |
| + {"409", http.StatusConflict, false}, |
| + {"503", http.StatusServiceUnavailable, false}, |
| + {"500", http.StatusInternalServerError, false}, |
| } { |
| t.Run(c.name, func(t *testing.T) { |
| h := newHarness(t) |
| @@ -147,15 +159,15 @@ func TestUploadRetryAfterTransportError(t *testing.T) { |
| if err != nil { |
| t.Fatalf("upload: %s", codeOf(err)) |
| } |
| - if (etag != "") != c.wantETag { |
| - t.Fatalf("etag %q, want one: %t", etag, c.wantETag) |
| + if etag != md5hex(data) { |
| + t.Fatalf("etag %q, want the MD5 of the bytes sent", etag) |
| } |
| 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 c.retry412 != (rs[1].Status == http.StatusPreconditionFailed) { |
| + t.Fatalf("the retry got %d", rs[1].Status) |
| } |
| if got, _ := h.s.Object(outPrefix + "video.mp4"); !bytes.Equal(got, data) { |
| t.Fatal("the store does not hold the file") |
| @@ -168,6 +180,127 @@ func TestUploadRetryAfterTransportError(t *testing.T) { |
| } |
| } |
| +// TestUploadRetryAcceptsOnlyItsOwnMD5 (Astra P1): the first PUT commits, |
| +// its answer is lost, and the app's own credentials put other bytes of |
| +// the same length at the key before the retry, which meets 412. The |
| +// upload still answers the MD5 of the bytes it sent, never the store's |
| +// ETag, so the result reports an ETag the object's HEAD does not have, |
| +// and the console fails the job (mediajobs TestOutputSwappedAfterALostAnswerFails). |
| +func TestUploadRetryAcceptsOnlyItsOwnMD5(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 swapAfterCommit |
| + } |
| + return 0 |
| + } |
| + data := randomBytes(t, 64<<10) |
| + etag, err := h.uploadVideo(t, p, data) |
| + if err != nil { |
| + t.Fatalf("upload: %s", codeOf(err)) |
| + } |
| + held, _ := h.s.Object(outPrefix + "video.mp4") |
| + if len(held) != len(data) || bytes.Equal(held, data) { |
| + t.Fatal("the store does not hold other bytes of the same length") |
| + } |
| + if etag != md5hex(data) || etag == h.s.ETagOf(outPrefix+"video.mp4") { |
| + t.Fatalf("reported %q; the bytes sent hash to %q and the store's object is %q", etag, md5hex(data), h.s.ETagOf(outPrefix+"video.mp4")) |
| + } |
| + if rs := puts(h.s.Requests()); len(rs) != 2 || rs[1].Status != http.StatusPreconditionFailed { |
| + t.Fatalf("PUTs %+v, want a cut one and a 412", rs) |
| + } |
| +} |
| + |
| +// TestUploadRefusesOtherBytes: a 200 whose ETag is not the MD5 of the |
| +// bytes sent means the store holds something else: engine_failed. |
| +func TestUploadRefusesOtherBytes(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + h.s.OnPut = func(int) int { return wrongETag } |
| + 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 != 1 { |
| + t.Fatalf("%d PUTs, want 1", n) |
| + } |
| +} |
| + |
| +// TestUploadStalledAnswerBody (Astra P2): a store that sends 200 and its |
| +// headers, announcing a body, then sends none of it does not hold the |
| +// upload: the body is closed unread. |
| +func TestUploadStalledAnswerBody(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + h.s.OnPut = func(int) int { return stallBody } |
| + data := randomBytes(t, 4096) |
| + start := time.Now() |
| + etag, err := h.uploadVideo(t, p, data) // 20 s bound |
| + if err != nil || etag != md5hex(data) { |
| + t.Fatalf("upload = %q, %s", etag, codeOf(err)) |
| + } |
| + if d := time.Since(start); d > bodyClosedWait { |
| + t.Fatalf("the upload took %v over a stalled answer", d) |
| + } |
| +} |
| + |
| +// TestUploadIdleAttemptIsBroken (Astra P2): an attempt the store does |
| +// not answer ends when the per-read idle timer (idleTimeout, as |
| +// the download's) fires, and is made again. |
| +func TestUploadIdleAttemptIsBroken(t *testing.T) { |
| + h := newHarness(t) |
| + fi := &fakeIdle{} |
| + h.cfg.idle = fi.new |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + h.s.OnPut = func(n int) int { |
| + if n == 1 { |
| + return holdPut |
| + } |
| + return 0 |
| + } |
| + go func() { |
| + <-h.s.Held |
| + fi.stall() |
| + }() |
| + data := randomBytes(t, 4096) |
| + etag, err := h.uploadVideo(t, p, data) |
| + if err != nil || etag != md5hex(data) { |
| + t.Fatalf("upload = %q, %s", etag, codeOf(err)) |
| + } |
| + if n := len(puts(h.s.Requests())); n != 2 { |
| + t.Fatalf("%d PUTs, want 2", n) |
| + } |
| + fi.mu.Lock() |
| + defer fi.mu.Unlock() |
| + if len(fi.durations) == 0 { |
| + t.Fatal("no idle timer") |
| + } |
| + for _, d := range fi.durations { |
| + if d != idleTimeout { |
| + t.Errorf("idle timer of %v, want %v", d, idleTimeout) |
| + } |
| + } |
| +} |
| + |
| +// TestUploadIdleTimerFollowsTheBody: the idle timer is armed for the |
| +// attempt and again on every read of the body, so a large upload that |
| +// keeps moving is never cut, however long it takes. |
| +func TestUploadIdleTimerFollowsTheBody(t *testing.T) { |
| + h := newHarness(t) |
| + fi := &fakeIdle{} |
| + h.cfg.idle = fi.new |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + if _, err := h.uploadVideo(t, p, randomBytes(t, 4*mib)); err != nil { |
| + t.Fatalf("upload: %s", codeOf(err)) |
| + } |
| + fi.mu.Lock() |
| + defer fi.mu.Unlock() |
| + // 4 MiB is read in many pieces (Go copies a body 32 KiB at a time). |
| + if fi.resets < 16 { |
| + t.Fatalf("the idle timer was armed %d times for a 4 MiB body", fi.resets) |
| + } |
| +} |
| + |
| // TestUploadGivesUpAfterTwoRetries: three broken attempts, then |
| // engine_failed, with no fourth. |
| func TestUploadGivesUpAfterTwoRetries(t *testing.T) { |
| @@ -200,17 +333,39 @@ func TestUploadExpiry(t *testing.T) { |
| 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) |
| - } |
| - }) |
| + // A 403 is the grant's end only within a minute of the expiry; |
| + // earlier it is the store refusing this writer: engine_failed |
| + // (storeDenied), so the failure result is still attempted. |
| + for _, c := range []struct { |
| + name string |
| + before time.Duration |
| + want string |
| + }{ |
| + {"403 an hour before the expiry", time.Hour, media.CodeEngineFailed}, |
| + {"403 61 s before the expiry", 61 * time.Second, media.CodeEngineFailed}, |
| + {"403 60 s before the expiry", 60 * time.Second, "errGrantExpired"}, |
| + {"403 1 s before the expiry", time.Second, "errGrantExpired"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, media.PresetVideo720p, nil, mib) |
| + h.s.OnPut = func(int) int { |
| + h.clock.Set(h.s.expiry.Add(-c.before)) |
| + return http.StatusForbidden |
| + } |
| + _, err := h.uploadVideo(t, p, randomBytes(t, 64)) |
| + if codeOf(err) != c.want { |
| + t.Fatalf("upload = %s, want %s", codeOf(err), c.want) |
| + } |
| + var denied storeDenied |
| + if c.want == media.CodeEngineFailed && !errors.As(err, &denied) { |
| + t.Fatalf("upload = %T, want storeDenied", 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) |
| @@ -313,18 +468,13 @@ func TestWriteResult(t *testing.T) { |
| // (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 |
| - } |
| - }, |
| + "ok": func(h *harness) {}, |
| + "held": func(h *harness) { h.s.Hold(outPrefix+"video.mp4", []byte("x")) }, |
| + "cut": func(h *harness) { h.s.OnPut = firstPut(dropAfterCommit) }, |
| "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 } }, |
| + "swapped": func(h *harness) { h.s.OnPut = firstPut(swapAfterCommit) }, |
| + "other bytes": func(h *harness) { h.s.OnPut = func(int) int { return wrongETag } }, |
| "redirect": func(h *harness) { h.s.OnPut = func(int) int { return http.StatusTemporaryRedirect } }, |
| "unreachable": func(h *harness) { h.s.srv.Close() }, |
| } |
| @@ -430,3 +580,40 @@ func TestOutputBounds(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// TestResultCodecsMatchTheChecks: every codec name check accepts passes |
| +// the console's ParseResult as a source codec, and one it refuses does |
| +// not (media's resultVideoCodecs and resultAudioCodecs, Task 6 fix 1). |
| +func TestResultCodecsMatchTheChecks(t *testing.T) { |
| + result := func(video, audio string) []byte { |
| + r := media.Result{V: media.ResultVersion, Execution: testExec, FFmpeg: "7.1.5-0+deb13u1", |
| + Source: &media.SourceFacts{DurationMS: 1000, Width: 1920, Height: 1080, VideoCodec: video, AudioCodec: audio}} |
| + for i, n := range media.OutputNames(media.PresetVideo720p) { |
| + o := media.OutputFact{Name: n, Bytes: 1, ETag: md5hex([]byte{byte(i)}), ContentType: media.ContentType(n)} |
| + if n != "video.m3u8" { |
| + o.Width, o.Height = 1280, 720 |
| + } |
| + r.Outputs = append(r.Outputs, o) |
| + } |
| + b, err := json.Marshal(r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b |
| + } |
| + for name := range videoCodecs { |
| + if _, err := media.ParseResult(result(name, "aac"), testExec, media.PresetVideo720p); err != nil { |
| + t.Errorf("video codec %s: %v", name, err) |
| + } |
| + } |
| + for name := range audioCodecs { |
| + if _, err := media.ParseResult(result("h264", name), testExec, media.PresetVideo720p); err != nil { |
| + t.Errorf("audio codec %s: %v", name, err) |
| + } |
| + } |
| + for _, c := range [][2]string{{"mjpeg", "aac"}, {"h264", "pcm_s16le_planar"}, {"h264", "<b>x</b>"}} { |
| + if _, err := media.ParseResult(result(c[0], c[1]), testExec, media.PresetVideo720p); err == nil { |
| + t.Errorf("codecs %q accepted", c) |
| + } |
| + } |
| +} |
diff --git a/internal/mediajobs/jobs_test.go b/internal/mediajobs/jobs_test.go| index 22f6ab475..f4f90ffc8 100644 |
| --- a/internal/mediajobs/jobs_test.go |
| +++ b/internal/mediajobs/jobs_test.go |
| @@ -920,7 +920,11 @@ func TestOutputSizeMismatchFails(t *testing.T) { |
| mutate func(h *harness, k string) |
| }{ |
| {"size", func(h *harness, k string) { o := h.gr.Objects[k]; o.Size++; h.gr.Objects[k] = o }}, |
| - {"etag", func(h *harness, k string) { o := h.gr.Objects[k]; o.ETag = "other"; h.gr.Objects[k] = o }}, |
| + {"etag", func(h *harness, k string) { |
| + o := h.gr.Objects[k] |
| + o.ETag = strings.Repeat("f", 32) |
| + h.gr.Objects[k] = o |
| + }}, |
| {"missing", func(h *harness, k string) { delete(h.gr.Objects, k) }}, |
| } { |
| t.Run(c.name, func(t *testing.T) { |
| @@ -1493,10 +1497,35 @@ func TestStopAfterThePassBeganWaits(t *testing.T) { |
| } |
| } |
| -// TestUploadRetryETagFilled (Astra P2): an output the handler reports with |
| -// an empty ETag (an upload retry met 412) validates against its HEAD, and |
| -// the stored result carries the HEAD's ETag, still after cleanup. |
| -func TestUploadRetryETagFilled(t *testing.T) { |
| +// TestOutputSwappedAfterALostAnswerFails (plan 3 Task 6 fix 1, Astra |
| +// P1): the codec's first PUT committed and its answer was lost; the |
| +// app's own credentials then put other bytes of the same length at the |
| +// key, and the codec's retry met 412. The codec reports the MD5 of what |
| +// it sent; the object's HEAD answers the replacement's ETag; Track takes |
| +// nothing from HEAD and fails the job engine_failed. |
| +func TestOutputSwappedAfterALostAnswerFails(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + r, task := h.run(a) |
| + h.now = h.now.Add(2 * time.Minute) |
| + h.codecSucceeds(r, 60000) |
| + k := r.Bucket + "/" + media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) + "video.mp4" |
| + o := h.gr.Objects[k] |
| + o.ETag = fmt.Sprintf("%032x", 0xbad) // same size, other bytes |
| + h.gr.Objects[k] = o |
| + h.finish(task, media.ExitDone) |
| + h.track() |
| + got := h.row(a) |
| + wantState(t, got, stateFailed, media.CodeEngineFailed, (2 * time.Minute).Milliseconds()) |
| + if got.Result != nil { |
| + t.Fatalf("a failed row stored a result: %+v", got.Result) |
| + } |
| +} |
| + |
| +// TestOutputWithNoETagFails: a result reporting an output with no ETag, |
| +// which the console used to fill from HEAD, is invalid output: |
| +// ParseResult refuses it and the job fails engine_failed. |
| +func TestOutputWithNoETagFails(t *testing.T) { |
| h := newHarness(t, "", nil) |
| a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| r, task := h.run(a) |
| @@ -1510,22 +1539,7 @@ func TestUploadRetryETagFilled(t *testing.T) { |
| h.gr.Results[r.Execution], _ = json.Marshal(res) |
| h.finish(task, media.ExitDone) |
| h.track() |
| - h.cleanup() |
| - got := h.row(a) |
| - wantState(t, got, stateDone, "", (2 * time.Minute).Milliseconds()) |
| - if got.Result == nil || len(got.Result.Outputs) != 3 { |
| - t.Fatalf("stored result %+v", got.Result) |
| - } |
| - prefix := media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) |
| - for _, o := range got.Result.Outputs { |
| - obj, ok := h.gr.Objects[r.Bucket+"/"+prefix+o.Name] |
| - if !ok || o.ETag == "" || o.ETag != obj.ETag { |
| - t.Fatalf("output %s stored with ETag %q, the object has %q", o.Name, o.ETag, obj.ETag) |
| - } |
| - } |
| - if !got.CleanupDue.IsZero() { |
| - t.Fatal("not cleaned") |
| - } |
| + wantState(t, h.row(a), stateFailed, media.CodeEngineFailed, (2 * time.Minute).Milliseconds()) |
| } |
| // TestOutputHeadDeniedWaits (controller ruling): a HEAD answering |
diff --git a/internal/mediajobs/track.go b/internal/mediajobs/track.go| index aa98b99cb..1b8a5ef5a 100644 |
| --- a/internal/mediajobs/track.go |
| +++ b/internal/mediajobs/track.go |
| @@ -153,16 +153,15 @@ func (j *Jobs) trackOne(ctx context.Context, r Job, t media.Task, now time.Time) |
| code = media.CodeEngineFailed |
| default: |
| var transient bool |
| - if code, transient = j.checkOutputs(ctx, r, &res); transient { |
| + if code, transient = j.checkOutputs(ctx, r, res); transient { |
| return nil |
| } |
| } |
| if code != "" { |
| return j.failStop(ctx, k, code, ran, "", ended, now) |
| } |
| - // The stored result is the validated one, every output ETag the |
| - // object's own (checkOutputs fills the ones an upload retry left |
| - // empty), not the bytes as read. |
| + // The stored result is the validated one, re-encoded, not the |
| + // bytes as read. |
| validated, err := json.Marshal(res) |
| if err != nil { |
| return err |
| @@ -180,15 +179,19 @@ func (j *Jobs) trackOne(ctx context.Context, r Job, t media.Task, now time.Time) |
| } |
| // checkOutputs HEADs each output the result reports: absent, a size other |
| -// than the reported one, or a reported ETag other than the object's is |
| -// engine_failed. An output the result reports with no ETag (an upload |
| -// retry that met 412) gets the HEAD's. transient is a HEAD that failed |
| -// otherwise, ErrDenied included (a console that lost its HEAD permission |
| -// must not fail and clean every finishing job): the row is left for the |
| -// next pass. |
| -func (j *Jobs) checkOutputs(ctx context.Context, r Job, res *media.Result) (code string, transient bool) { |
| +// than the reported one, or an ETag other than the reported one is |
| +// engine_failed. The reported ETag is the MD5 of the bytes the codec |
| +// sent (ParseResult requires one), which S3 answers as the ETag of a |
| +// single-part PUT under SSE-S3 (and MinIO likewise), so the comparison |
| +// is exact and nothing is taken from HEAD: the app's own credentials can |
| +// write under derived/, and an object it swapped in after a lost upload |
| +// answer, even of the same length, fails here (plan 3 Task 6 fix 1, |
| +// Astra P1). transient is a HEAD that failed otherwise, ErrDenied |
| +// included (a console that lost its HEAD permission must not fail and |
| +// clean every finishing job): the row is left for the next pass. |
| +func (j *Jobs) checkOutputs(ctx context.Context, r Job, res media.Result) (code string, transient bool) { |
| prefix := media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) |
| - for i, o := range res.Outputs { |
| + for _, o := range res.Outputs { |
| h, err := j.d.Grants.Head(ctx, r.Bucket, prefix+o.Name) |
| switch { |
| case errors.Is(err, media.ErrNotFound): |
| @@ -200,13 +203,10 @@ func (j *Jobs) checkOutputs(ctx context.Context, r Job, res *media.Result) (code |
| case h.Size != o.Bytes: |
| j.logf("output %s of %s is %d bytes, the result says %d", o.Name, keyOf(r), h.Size, o.Bytes) |
| return media.CodeEngineFailed, false |
| - case o.ETag != "" && o.ETag != h.ETag: |
| + case o.ETag != h.ETag: |
| j.logf("output %s of %s has ETag %q, the result says %q", o.Name, keyOf(r), h.ETag, o.ETag) |
| return media.CodeEngineFailed, false |
| } |
| - if o.ETag == "" { |
| - res.Outputs[i].ETag = h.ETag |
| - } |
| } |
| return "", false |
| } |
diff --git a/internal/sim/mediajobs/witness_test.go b/internal/sim/mediajobs/witness_test.go| index ae5e20571..3108ca90a 100644 |
| --- a/internal/sim/mediajobs/witness_test.go |
| +++ b/internal/sim/mediajobs/witness_test.go |
| @@ -612,8 +612,8 @@ func cleanFixture(t *testing.T) fixture { |
| func (w *world) codecSucceedsAt(execution, bucket, prefix string, durationMS int64) { |
| res := media.Result{V: 1, Execution: execution, Source: &media.SourceFacts{DurationMS: durationMS, Width: 1920, Height: 1080}, FFmpeg: "7.1.1"} |
| for _, n := range media.OutputNames(media.PresetVideo720p) { |
| - w.grants.Objects[bucket+"/"+prefix+n] = mediatest.Object{Size: 100, ETag: "o"} |
| - res.Outputs = append(res.Outputs, media.OutputFact{Name: n, Bytes: 100, ETag: "o", ContentType: media.ContentType(n)}) |
| + w.grants.Objects[bucket+"/"+prefix+n] = mediatest.Object{Size: 100, ETag: strings.Repeat("0", 32)} |
| + res.Outputs = append(res.Outputs, media.OutputFact{Name: n, Bytes: 100, ETag: strings.Repeat("0", 32), ContentType: media.ContentType(n)}) |
| } |
| b, _ := json.Marshal(res) |
| w.grants.Results[execution] = b |