carlos / platform Public

media: the deadline container

cmd/carlos-media is the engine image's one binary. Its deadline command
sleeps until the earlier of its start plus CARLOS_MEDIA_DEADLINE_S and
CARLOS_MEDIA_GRANT_EXPIRY less the 30 s stop grace (media.DeadlineSleep),
then exits 0 so ECS stops the task; it exits 0 at once when that moment
has passed, 143 on SIGTERM and 3 at once on bad input. Both values must
be canonical decimal (no sign, no leading zero), the deadline in
1..3000 and the expiry in 1..9999-12-31; the command takes no argument
and prints nothing. codec, selftest and drill are stubs that exit 1
until Tasks 2 and 7. The usage line is a new deck row, pending Luna.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev db89b19e2084228f292bfda2d5a05392d14fac1c parent e446cfc
4 files changed, +463 −0
  • cmd/carlos-media/deadline.go +78 −0
  • cmd/carlos-media/deadline_test.go +301 −0
  • cmd/carlos-media/main.go +74 −0
  • docs/superpowers/notes/media-conversion-copy-deck.md +10 −0
diff --git a/cmd/carlos-media/deadline.go b/cmd/carlos-media/deadline.go
new file mode 100644
index 000000000..161f4c462
--- /dev/null
+++ b/cmd/carlos-media/deadline.go
@@ -0,0 +1,78 @@
+package main
+
+import (
+ "os"
+ "strconv"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// The deadline container (spec §5.5, astra R5-1 and R7-1). ECS stops the
+// whole task when this essential container exits, so its exit is what
+// bounds a conversion. It sleeps until the earlier of its own start plus
+// the job's relative deadline and the grant's absolute expiry less the
+// 30 s stop grace, then exits DeadlineExitReached. It exits
+// DeadlineExitReached at once when that moment has already passed (a task
+// that waited in PENDING past its grant never converts),
+// DeadlineExitStopped on SIGTERM (ECS stopping the task after codec
+// exits), and DeadlineExitBadInput at once on anything it cannot read.
+// Every outcome is an exit, so every outcome ends the task: there is no
+// path on which a bad or missing value leaves the task running unbounded.
+//
+// It prints nothing and listens on nothing; it imports only os (for the
+// signal type), strconv, time and internal/media, which
+// TestDeadlineFilePrintsAndListensOnNothing holds.
+
+// maxDeadlineS is the largest relative deadline the console sends,
+// media.MaxDeadline (50 minutes) in seconds.
+const maxDeadlineS = int64(media.MaxDeadline / time.Second)
+
+// maxExpiryUnix is 9999-12-31T23:59:59Z. A larger expiry is not a time
+// the console could have minted, and past it time.Unix's arithmetic can
+// wrap, so it is refused as bad input rather than trusted to wrap safely.
+const maxExpiryUnix = 253402300799
+
+// runDeadline is the deadline container's whole program. getenv supplies
+// media.DeadlineEnv (whole seconds, 1..3000) and media.ExpiryEnv (Unix
+// seconds, 1..maxExpiryUnix), both as canonical decimal: no sign, no
+// leading zero, no space. now is read once, as the start. stop delivers
+// SIGTERM.
+func runDeadline(getenv func(string) string, now func() time.Time, stop <-chan os.Signal) int {
+ deadlineS, ok := parseCanonical(getenv(media.DeadlineEnv), maxDeadlineS)
+ if !ok {
+ return media.DeadlineExitBadInput
+ }
+ expiryUnix, ok := parseCanonical(getenv(media.ExpiryEnv), maxExpiryUnix)
+ if !ok {
+ return media.DeadlineExitBadInput
+ }
+ // The sleep is at most the relative deadline whatever the expiry
+ // says: DeadlineSleep takes the earlier of the two ends.
+ d := media.DeadlineSleep(now(), time.Duration(deadlineS)*time.Second, time.Unix(expiryUnix, 0))
+ if d <= 0 {
+ return media.DeadlineExitReached
+ }
+ // time.Timer runs on the monotonic clock: once started, a step of
+ // the wall clock neither shortens nor lengthens the sleep.
+ t := time.NewTimer(d)
+ defer t.Stop()
+ select {
+ case <-t.C:
+ return media.DeadlineExitReached
+ case <-stop:
+ return media.DeadlineExitStopped
+ }
+}
+
+// parseCanonical reads s as a decimal integer in 1..max, written the one
+// way strconv.FormatInt writes it. The console writes both values with
+// FormatInt, so anything else ("+5", "05", " 5", "1e3", "5.0") did not
+// come from it and is refused.
+func parseCanonical(s string, max int64) (int64, bool) {
+ v, err := strconv.ParseInt(s, 10, 64)
+ if err != nil || v < 1 || v > max || strconv.FormatInt(v, 10) != s {
+ return 0, false
+ }
+ return v, true
+}
diff --git a/cmd/carlos-media/deadline_test.go b/cmd/carlos-media/deadline_test.go
new file mode 100644
index 000000000..ecc23e780
--- /dev/null
+++ b/cmd/carlos-media/deadline_test.go
@@ -0,0 +1,301 @@
+package main
+
+import (
+ "bytes"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "strconv"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// fakeStart is the clock the tests hand runDeadline as its start.
+var fakeStart = time.Unix(1_800_000_000, 0)
+
+func fixedNow() time.Time { return fakeStart }
+
+func env(deadline, expiry string) func(string) string {
+ return func(k string) string {
+ switch k {
+ case media.DeadlineEnv:
+ return deadline
+ case media.ExpiryEnv:
+ return expiry
+ }
+ return ""
+ }
+}
+
+func unix(t time.Time) string { return strconv.FormatInt(t.Unix(), 10) }
+
+// preStopped is a stop channel already holding SIGTERM. A call that
+// should return at once must not reach the wait: if it did, it would
+// answer DeadlineExitStopped instead.
+func preStopped() chan os.Signal {
+ c := make(chan os.Signal, 1)
+ c <- syscall.SIGTERM
+ return c
+}
+
+// await runs runDeadline in the background and gives its answer, failing
+// the test if none comes within limit.
+func await(t *testing.T, limit time.Duration, getenv func(string) string, now func() time.Time, stop <-chan os.Signal) (int, time.Duration) {
+ t.Helper()
+ done := make(chan int, 1)
+ began := time.Now()
+ go func() { done <- runDeadline(getenv, now, stop) }()
+ select {
+ case code := <-done:
+ return code, time.Since(began)
+ case <-time.After(limit):
+ t.Fatalf("runDeadline did not return within %s", limit)
+ return 0, 0
+ }
+}
+
+// TestDeadlineExitsAtOnceWhenExpired: when the expiry less the stop grace
+// is at or before the start, the container exits 0 at once (spec §5.5,
+// astra R7-1: a task that waited in PENDING past its grant never
+// converts). Repeated so that a version which reaches the wait with a
+// zero timer and a pending SIGTERM would answer 143 at least once.
+func TestDeadlineExitsAtOnceWhenExpired(t *testing.T) {
+ for _, c := range []struct{ name, expiry string }{
+ {"long past", "1"},
+ {"an hour ago", unix(fakeStart.Add(-time.Hour))},
+ {"exactly the grace away", unix(fakeStart.Add(media.StopGrace))},
+ {"inside the grace", unix(fakeStart.Add(media.StopGrace - time.Second))},
+ } {
+ for range 20 {
+ began := time.Now()
+ code := runDeadline(env("3000", c.expiry), fixedNow, preStopped())
+ took := time.Since(began)
+ if code != media.DeadlineExitReached {
+ t.Fatalf("%s: exit %d, want %d", c.name, code, media.DeadlineExitReached)
+ }
+ if took > 10*time.Millisecond {
+ t.Fatalf("%s: took %s, want at once", c.name, took)
+ }
+ }
+ }
+}
+
+// TestDeadlineBadInput: anything but a canonical decimal deadline in
+// 1..3000 and a canonical decimal expiry in 1..maxExpiryUnix exits 3 at
+// once, before any wait.
+func TestDeadlineBadInput(t *testing.T) {
+ future := unix(fakeStart.Add(time.Hour))
+ for _, c := range []struct{ name, deadline, expiry string }{
+ {"empty deadline", "", future},
+ {"zero deadline", "0", future},
+ {"deadline over 3000", "3001", future},
+ {"negative deadline", "-5", future},
+ {"exponent deadline", "1e3", future},
+ {"signed deadline", "+5", future},
+ {"padded deadline", "05", future},
+ {"spaced deadline", " 5", future},
+ {"fractional deadline", "5.0", future},
+ {"huge deadline", "99999999999999999999", future},
+ {"unit deadline", "900s", future},
+ {"non-number expiry", "900", "soon"},
+ {"empty expiry", "900", ""},
+ {"zero expiry", "900", "0"},
+ {"negative expiry", "900", "-1"},
+ {"signed expiry", "900", "+" + future},
+ {"padded expiry", "900", "0" + future},
+ {"RFC 3339 expiry", "900", fakeStart.Add(time.Hour).UTC().Format(time.RFC3339)},
+ {"milliseconds expiry", "900", strconv.FormatInt(fakeStart.Add(time.Hour).UnixMilli(), 10)},
+ {"expiry past year 9999", "900", strconv.FormatInt(maxExpiryUnix+1, 10)},
+ {"int64 max expiry", "900", "9223372036854775807"},
+ {"both empty", "", ""},
+ } {
+ began := time.Now()
+ code := runDeadline(env(c.deadline, c.expiry), fixedNow, preStopped())
+ took := time.Since(began)
+ if code != media.DeadlineExitBadInput {
+ t.Errorf("%s (%q, %q): exit %d, want %d", c.name, c.deadline, c.expiry, code, media.DeadlineExitBadInput)
+ }
+ if took > 10*time.Millisecond {
+ t.Errorf("%s: took %s, want at once", c.name, took)
+ }
+ }
+}
+
+// TestDeadlineAcceptsTheBounds: the edges of the valid ranges reach the
+// wait (and so answer the pending SIGTERM with 143).
+func TestDeadlineAcceptsTheBounds(t *testing.T) {
+ far := strconv.FormatInt(maxExpiryUnix, 10)
+ for _, c := range []struct{ name, deadline, expiry string }{
+ {"deadline 1", "1", far},
+ {"deadline 3000", "3000", far},
+ {"expiry at year 9999", "900", far},
+ {"expiry an hour on", "900", unix(fakeStart.Add(time.Hour))},
+ } {
+ if code, _ := await(t, 5*time.Second, env(c.deadline, c.expiry), fixedNow, preStopped()); code != media.DeadlineExitStopped {
+ t.Errorf("%s: exit %d, want %d (the wait)", c.name, code, media.DeadlineExitStopped)
+ }
+ }
+}
+
+// TestDeadlineStopped: SIGTERM during the wait (ECS stopping the task
+// because codec finished) exits 143, which the console does not read as
+// deadline_exceeded.
+func TestDeadlineStopped(t *testing.T) {
+ stop := make(chan os.Signal, 1)
+ done := make(chan int, 1)
+ go func() { done <- runDeadline(env("3000", unix(fakeStart.Add(time.Hour))), fixedNow, stop) }()
+ stop <- syscall.SIGTERM
+ select {
+ case code := <-done:
+ if code != media.DeadlineExitStopped {
+ t.Fatalf("exit %d, want %d", code, media.DeadlineExitStopped)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("runDeadline did not return on SIGTERM")
+ }
+ if got := media.ClassifyStop("", nil, ptr(media.DeadlineExitStopped)); got == media.CodeDeadlineExceeded {
+ t.Fatalf("a stopped deadline classifies as %s", got)
+ }
+}
+
+func ptr(v int) *int { return &v }
+
+// TestDeadlineReached: a 1 s deadline from the fake start returns 0 after
+// the timer, not before, with no SIGTERM.
+func TestDeadlineReached(t *testing.T) {
+ code, took := await(t, 5*time.Second, env("1", unix(fakeStart.Add(time.Hour))), fixedNow, nil)
+ if code != media.DeadlineExitReached {
+ t.Fatalf("exit %d, want %d", code, media.DeadlineExitReached)
+ }
+ if took < time.Second {
+ t.Fatalf("returned after %s, before the 1 s deadline", took)
+ }
+ if got := media.ClassifyStop("", nil, ptr(code)); got != media.CodeDeadlineExceeded {
+ t.Fatalf("a reached deadline classifies as %s, want %s", got, media.CodeDeadlineExceeded)
+ }
+}
+
+// TestDeadlineReachedAtExpiry: with a 3000 s deadline and the grant
+// expiring 31 s after the start, the sleep is the expiry less the 30 s
+// stop grace, 1 s. Fails (by the 5 s limit) if the expiry or the grace is
+// ignored.
+func TestDeadlineReachedAtExpiry(t *testing.T) {
+ expiry := unix(fakeStart.Add(media.StopGrace + time.Second))
+ code, took := await(t, 5*time.Second, env("3000", expiry), fixedNow, nil)
+ if code != media.DeadlineExitReached {
+ t.Fatalf("exit %d, want %d", code, media.DeadlineExitReached)
+ }
+ if took < time.Second {
+ t.Fatalf("returned after %s, before the expiry less the grace", took)
+ }
+}
+
+// TestDeadlineReadsTheClockOnce: the start is read once, before the
+// wait; a clock that moves on later calls changes nothing.
+func TestDeadlineReadsTheClockOnce(t *testing.T) {
+ calls := 0
+ now := func() time.Time {
+ calls++
+ return fakeStart.Add(time.Duration(calls-1) * time.Hour)
+ }
+ if code, _ := await(t, 5*time.Second, env("900", unix(fakeStart.Add(time.Hour))), now, preStopped()); code != media.DeadlineExitStopped {
+ t.Fatalf("exit %d, want %d", code, media.DeadlineExitStopped)
+ }
+ if calls != 1 {
+ t.Fatalf("now called %d times, want 1", calls)
+ }
+}
+
+// TestDeadlineDispatch: the binary's "deadline" command takes no
+// argument and reads only the environment, and prints nothing. Other
+// commands, and none, are refused with the usage line.
+func TestDeadlineDispatch(t *testing.T) {
+ run := func(env1, env2 string, args ...string) (int, string, string) {
+ t.Setenv(media.DeadlineEnv, env1)
+ t.Setenv(media.ExpiryEnv, env2)
+ var stdout, stderr bytes.Buffer
+ done := make(chan int, 1)
+ go func() { done <- dispatch(args, &stdout, &stderr) }()
+ select {
+ case code := <-done:
+ return code, stdout.String(), stderr.String()
+ case <-time.After(5 * time.Second):
+ t.Fatalf("dispatch(%q) did not return within 5 s", args)
+ return 0, "", ""
+ }
+ }
+ for _, c := range []struct {
+ name, deadline, expiry string
+ args []string
+ want int
+ }{
+ // Neither variable set: bad input.
+ {"unset", "", "", []string{media.DeadlineCommand}, media.DeadlineExitBadInput},
+ // An expired grant: os.Getenv reached runDeadline.
+ {"expired", "900", "1", []string{media.DeadlineCommand}, media.DeadlineExitReached},
+ // The same values with an argument: refused before reading them.
+ {"an argument", "900", "1", []string{media.DeadlineCommand, "900"}, media.DeadlineExitBadInput},
+ } {
+ code, out, errOut := run(c.deadline, c.expiry, c.args...)
+ if code != c.want {
+ t.Errorf("%s: dispatch(%q) = %d, want %d", c.name, c.args, code, c.want)
+ }
+ if out != "" || errOut != "" {
+ t.Errorf("%s: dispatch(%q) printed %q / %q, want nothing", c.name, c.args, out, errOut)
+ }
+ }
+ for _, args := range [][]string{nil, {"sleep"}, {"Deadline"}, {""}} {
+ code, out, errOut := run("900", "1", args...)
+ if code != exitUsage || out != "" || errOut != usageLine+"\n" {
+ t.Errorf("dispatch(%q) = %d, %q / %q; want %d and the usage line", args, code, out, errOut, exitUsage)
+ }
+ }
+}
+
+// TestDeadlineCommandMatchesTheGate: the command the binary answers to
+// is the one the refusal gate requires.
+func TestDeadlineCommandMatchesTheGate(t *testing.T) {
+ if media.EngineEntryPoint != "/usr/local/bin/carlos-media" || media.DeadlineCommand != "deadline" {
+ t.Fatalf("gate expects %s %s; this binary is carlos-media deadline", media.EngineEntryPoint, media.DeadlineCommand)
+ }
+}
+
+// TestDeadlineFilePrintsAndListensOnNothing: deadline.go imports only
+// what a timer needs and never names stdout or stderr (spec §5.5:
+// deadline listens on nothing).
+func TestDeadlineFilePrintsAndListensOnNothing(t *testing.T) {
+ f, err := parser.ParseFile(token.NewFileSet(), "deadline.go", nil, parser.ImportsOnly|parser.ParseComments)
+ if err != nil {
+ t.Fatal(err)
+ }
+ allowed := map[string]bool{
+ `"os"`: true, `"strconv"`: true, `"time"`: true,
+ `"github.com/carlosframework/platform/internal/media"`: true,
+ }
+ for _, imp := range f.Imports {
+ if !allowed[imp.Path.Value] {
+ t.Errorf("deadline.go imports %s", imp.Path.Value)
+ }
+ }
+ full, err := parser.ParseFile(token.NewFileSet(), "deadline.go", nil, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ast.Inspect(full, func(n ast.Node) bool {
+ switch x := n.(type) {
+ case *ast.SelectorExpr:
+ if id, ok := x.X.(*ast.Ident); ok && id.Name == "os" && x.Sel.Name != "Signal" {
+ t.Errorf("deadline.go uses os.%s", x.Sel.Name)
+ }
+ case *ast.Ident:
+ if x.Name == "print" || x.Name == "println" {
+ t.Errorf("deadline.go calls %s", x.Name)
+ }
+ }
+ return true
+ })
+}
diff --git a/cmd/carlos-media/main.go b/cmd/carlos-media/main.go
new file mode 100644
index 000000000..99eb63b57
--- /dev/null
+++ b/cmd/carlos-media/main.go
@@ -0,0 +1,74 @@
+// Command carlos-media is the media engine image's one binary, installed
+// at media.EngineEntryPoint (/usr/local/bin/carlos-media). Its first
+// argument picks the role (spec §5.5; internal/media/gate.go):
+//
+// - deadline: the task's timer (deadline.go). It reads its two values
+// from the environment, media.DeadlineEnv and media.ExpiryEnv, and
+// takes no argument.
+// - codec: the conversion handler (plan 3 Task 2), reading
+// media.PayloadEnv.
+// - selftest, drill: rollout checks (plan 3 Task 7).
+// - version: prints the build.
+//
+// The refusal gate requires each container's entry point and command to
+// be exactly [EngineEntryPoint] and [DeadlineCommand] or [CodecCommand],
+// and every per-run value arrives as an environment override, never as
+// an argument.
+package main
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "os/signal"
+ "syscall"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/version"
+)
+
+// exitUsage is the exit for an unknown command or none.
+const exitUsage = 2
+
+// usageLine is copy deck row engine.usage (pending Luna pass).
+const usageLine = "usage: carlos-media <deadline|codec|selftest|drill|version>"
+
+func main() {
+ os.Exit(dispatch(os.Args[1:], os.Stdout, os.Stderr))
+}
+
+// dispatch runs the command named by args[0] and answers its exit code.
+func dispatch(args []string, stdout, stderr io.Writer) int {
+ if len(args) == 0 {
+ fmt.Fprintln(stderr, usageLine)
+ return exitUsage
+ }
+ switch args[0] {
+ case media.DeadlineCommand:
+ return deadlineCommand(args[1:])
+ case media.CodecCommand, "selftest", "drill":
+ // Filled by plan 3 Task 2 (codec) and Task 7 (selftest, drill).
+ // Until then each fails, so no image built from this commit
+ // can report a conversion done.
+ return media.ExitFailed
+ case "version":
+ fmt.Fprintln(stdout, version.Build)
+ return 0
+ }
+ fmt.Fprintln(stderr, usageLine)
+ return exitUsage
+}
+
+// deadlineCommand is the deadline container's entry: it takes no
+// argument (the gate compares the command whole), catches SIGTERM before
+// it reads anything, and prints nothing.
+func deadlineCommand(rest []string) int {
+ if len(rest) != 0 {
+ return media.DeadlineExitBadInput
+ }
+ stop := make(chan os.Signal, 1)
+ signal.Notify(stop, syscall.SIGTERM)
+ defer signal.Stop(stop)
+ return runDeadline(os.Getenv, time.Now, stop)
+}
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index 5414d8bc7..0f5878428 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -521,3 +521,13 @@ carries them yet (plan 3 writes it); the pack's price is left out.
| `docs.plans.media.ceiling` | - **Media minutes.** At twice your account's monthly media allowance, new conversions are refused with `402` until the 1st of the UTC month, or until you buy a media pack or move to a larger plan. This does not wait for notice. Conversions already running finish. |
| `docs.plans.media.notice` | Apart from the ceilings above (email, storage, bandwidth, PDFs and media minutes at twice their limits), whatever acts after grace starts only once grace has ended and an owner received notice at least 3 days earlier. (only the parenthesis changed) |
| `docs.readme.media` | For video and audio, [media conversion](docs/site/media-conversion.md) runs in the region of the app's store, and a store in a region with no conversion engine is refused rather than converted elsewhere. (README.md, after the PDF service sentence) |
+
+## The engine binary (plan 3)
+
+Operator-facing text from `cmd/carlos-media`, the engine image's one
+binary; it reaches a task's log only when the binary is started wrongly.
+The `deadline` command prints nothing.
+
+| Key | Text |
+|---|---|
+| `engine.usage` | `usage: carlos-media <deadline\|codec\|selftest\|drill\|version>` (pending Luna pass; plan 3 Task 1) |