cli: media --wait exits 1 on failure, handles interrupt and poll errors
A failed job under --wait returns a sentinel and exits 1 with no extra line. The wait is signal-aware and tolerates three failed polls in a row. Unknown build date prints its own image line. Pending Luna pass 4 rows added to the copy deck for the strings Task 10 introduced.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
3 files changed,
+144
−19
docs/superpowers/notes/media-conversion-copy-deck.md+23 −0media_cli.go+48 −16media_cli_test.go+73 −3
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md| index fd3dbfdd1..ad43c79d0 100644 |
| --- a/docs/superpowers/notes/media-conversion-copy-deck.md |
| +++ b/docs/superpowers/notes/media-conversion-copy-deck.md |
| @@ -377,3 +377,26 @@ itself as `docs.media.*` rows in this file. |
| | `docs.cli.media_status` | `Shows a conversion's state, its output files once it is done, and why it failed if it did.` | |
| | `docs.cli.store_uploads` | `Lets browsers on the origins you name upload large files in parts straight to the app's store. With no --origin, it uses and prints the app's hostnames today. disable removes the rules again.` | |
| | `docs.cli.system_media_status` | `System operators (CARLOS_SYSTEM_OPERATORS) and store operators (CARLOS_STORE_OPERATORS) can run this read-only command. It shows whether the conversion engine is set up, how old its image is, whether each kind of job passes the engine's safety checks, and the queue.` | |
| + |
| +## Pending Luna pass 4 (Task 10 fix round 1) |
| + |
| +User-facing strings Task 10 added that had no deck row. The code reads |
| +them by these keys (`media_cli.go`). Until the pass, the text is the |
| +author's proposal. |
| + |
| +| Key | Text | |
| +|---|---| |
| +| `cli.media.usage` | `usage: carlos media <convert\|status> --app <a> [flags]` | |
| +| `cli.media.usage_convert` | `usage: carlos media convert <key> --app <a> [--preset <p>] [--class <c>] [--wait] [--account <sqid-or-name>] [--console <origin>]` | |
| +| `cli.media.usage_status` | `usage: carlos media status <id> --app <a> [--account <sqid-or-name>] [--console <origin>]` | |
| +| `cli.media.flag_preset` | `preset is video-720p or audio-aac` (the text of `media.unknown_preset`) | |
| +| `cli.media.flag_class` | `class is short or long` (the text of `media.unknown_class`) | |
| +| `cli.media.flag_wait` | `follow the job until it is done or failed` | |
| +| `cli.media.flag_console` | `console origin to act through (default: the only logged-in one)` | |
| +| `cli.system_media.usage` | `usage: carlos system media status [--console <origin>]` | |
| +| `cli.system_media.usage_line` | the `carlos system` usage entry: ` carlos system media status` | |
| +| `cli.system_media.flag_console` | `console to act through (default: the only logged-in one)` | |
| +| `cli.system_media.image_no_date` | `image %s, build date unknown, ffmpeg %s` (the image's build date is missing or unreadable; the `image` check line says why; today's draft was `built -`) | |
| + |
| +A failed job under `--wait` prints the deck's lines and exits 1 with no |
| +extra message. |
diff --git a/media_cli.go b/media_cli.go| index cef426809..db84a008f 100644 |
| --- a/media_cli.go |
| +++ b/media_cli.go |
| @@ -9,6 +9,7 @@ package main |
| import ( |
| "context" |
| "encoding/json" |
| + "errors" |
| "flag" |
| "fmt" |
| "io" |
| @@ -16,6 +17,7 @@ import ( |
| "net/http" |
| "net/url" |
| "os" |
| + "os/signal" |
| "sort" |
| "strings" |
| "time" |
| @@ -38,6 +40,7 @@ const ( |
| cliSysMediaEngine = "engine configured in %s" |
| cliSysMediaEngineOff = "engine not configured" |
| cliSysMediaImage = "image %s, built %s, ffmpeg %s" |
| + cliSysMediaImageNoDate = "image %s, build date unknown, ffmpeg %s" |
| cliSysMediaStale = "warning the image is %d days old. rebuild it and roll it out" |
| cliSysMediaCheckOK = "check %-17s ok" |
| cliSysMediaCheckRefuse = "check %-17s refused (%s), so these jobs do not start" |
| @@ -51,17 +54,29 @@ const ( |
| // The deck's help sentences, from docs.cli.media* and media.unknown_*. |
| const ( |
| - docsCLIMedia = "Convert an object from a terminal and follow the job. Apps call the same API with a Service token. See the Media conversion page." |
| - docsCLIMediaConvert = "Starts converting one object, or shows the existing job when that object was already sent with the same preset and class. With --wait it follows the job until it is done or failed." |
| - docsCLIMediaStatus = "Shows a conversion's state, its output files once it is done, and why it failed if it did." |
| - mediaPresetHelp = "preset is video-720p or audio-aac" |
| - mediaClassHelp = "class is short or long" |
| - mediaWaitHelp = "follow the job until it is done or failed" |
| + docsCLIMedia = "Convert an object from a terminal and follow the job. Apps call the same API with a Service token. See the Media conversion page." |
| + docsCLIMediaConvert = "Starts converting one object, or shows the existing job when that object was already sent with the same preset and class. With --wait it follows the job until it is done or failed." |
| + docsCLIMediaStatus = "Shows a conversion's state, its output files once it is done, and why it failed if it did." |
| + mediaPresetHelp = "preset is video-720p or audio-aac" |
| + mediaClassHelp = "class is short or long" |
| + mediaWaitHelp = "follow the job until it is done or failed" |
| + mediaConsoleHelp = "console origin to act through (default: the only logged-in one)" |
| + mediaSystemConsoleHelp = "console to act through (default: the only logged-in one)" |
| + mediaSystemUsage = "usage: carlos system media status [--console <origin>]" |
| + mediaUsage = "usage: carlos media <convert|status> --app <a> [flags]" |
| mediaUsageConvert = "usage: carlos media convert <key> --app <a> [--preset <p>] [--class <c>] [--wait] [--account <sqid-or-name>] [--console <origin>]" |
| mediaUsageStatus = "usage: carlos media status <id> --app <a> [--account <sqid-or-name>] [--console <origin>]" |
| ) |
| +// errMediaJobFailed is what --wait returns for a job that ended failed. The |
| +// job's lines are printed already, so the caller exits 1 and says no more. |
| +var errMediaJobFailed = errors.New("media job failed") |
| + |
| +// mediaPollErrors is how many polls in a row may fail before --wait gives |
| +// up; the next one is returned. |
| +const mediaPollErrors = 3 |
| + |
| // mediaPollEvery is how often --wait asks again. |
| var mediaPollEvery = 3 * time.Second |
| @@ -168,7 +183,7 @@ func mediaCommand() *clireg.Node { |
| Audience: cust, |
| Children: []*clireg.Node{raw("convert", cust, runMediaConvert), raw("status", cust, runMediaStatus)}, |
| Fallback: func(args, consumed []string) { |
| - fmt.Fprintf(os.Stderr, "usage: carlos media <convert|status> --app <a> [flags]\n\n%s\n\n%s\n", docsCLIMedia, mediaUsageConvert+"\n"+mediaUsageStatus) |
| + fmt.Fprintf(os.Stderr, mediaUsage+"\n\n%s\n\n%s\n", docsCLIMedia, mediaUsageConvert+"\n"+mediaUsageStatus) |
| os.Exit(1) |
| }, |
| } |
| @@ -181,7 +196,7 @@ func runMediaConvert(args []string) { |
| class := fs.String("class", "", mediaClassHelp) |
| wait := fs.Bool("wait", false, mediaWaitHelp) |
| acctRaw, acctIDRaw, _ := accountFlags(fs) |
| - consoleFlag := consoleOption(fs, "console origin to act through (default: the only logged-in one)") |
| + consoleFlag := consoleOption(fs, mediaConsoleHelp) |
| fs.Usage = flagUsage(fs, mediaUsageConvert+"\n\n"+docsCLIMediaConvert) |
| pos, _ := parseInterspersed(fs, args) |
| if len(pos) != 1 { |
| @@ -196,7 +211,13 @@ func runMediaConvert(args []string) { |
| if *class != "" { |
| body["class"] = *class |
| } |
| - if err := runMediaConvertWith(context.Background(), sess, acct, name, body, *wait, stdout); err != nil { |
| + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) |
| + err := runMediaConvertWith(ctx, sess, acct, name, body, *wait, stdout) |
| + stop() |
| + switch { |
| + case errors.Is(err, errMediaJobFailed): |
| + os.Exit(1) |
| + case err != nil: |
| log.Fatal(err) |
| } |
| } |
| @@ -205,7 +226,7 @@ func runMediaStatus(args []string) { |
| fs := flag.NewFlagSet("media status", flag.ExitOnError) |
| app := appFlag(fs, "") |
| acctRaw, acctIDRaw, _ := accountFlags(fs) |
| - consoleFlag := consoleOption(fs, "console origin to act through (default: the only logged-in one)") |
| + consoleFlag := consoleOption(fs, mediaConsoleHelp) |
| fs.Usage = flagUsage(fs, mediaUsageStatus+"\n\n"+docsCLIMediaStatus) |
| pos, _ := parseInterspersed(fs, args) |
| if len(pos) != 1 { |
| @@ -241,6 +262,7 @@ func runMediaConvertWith(ctx context.Context, s *apiSession, acct apiAcct, app s |
| } |
| fmt.Fprintf(w, cliMediaID+"\n", job.ID) |
| printMediaState(w, job) |
| + failures := 0 |
| for wait && !job.settled() { |
| select { |
| case <-ctx.Done(): |
| @@ -249,14 +271,24 @@ func runMediaConvertWith(ctx context.Context, s *apiSession, acct apiAcct, app s |
| } |
| next, _, err := s.mediaJob(ctx, acct, app, job.ID) |
| if err != nil { |
| - return err |
| + if ctx.Err() != nil { |
| + return ctx.Err() |
| + } |
| + if failures++; failures > mediaPollErrors { |
| + return err |
| + } |
| + continue |
| } |
| + failures = 0 |
| if next.State != job.State { |
| printMediaState(w, next) |
| } |
| job = next |
| } |
| printMediaRest(w, job, app) |
| + if wait && job.State == "failed" { |
| + return errMediaJobFailed |
| + } |
| return nil |
| } |
| @@ -370,8 +402,8 @@ func systemMediaCommand() *clireg.Node { |
| func runSystemMediaStatus(args []string) { |
| fs := flag.NewFlagSet("system media status", flag.ExitOnError) |
| - consoleFlag := consoleOption(fs, "console to act through (default: the only logged-in one)") |
| - fs.Usage = flagUsage(fs, "") |
| + consoleFlag := consoleOption(fs, mediaSystemConsoleHelp) |
| + fs.Usage = flagUsage(fs, mediaSystemUsage) |
| fs.Parse(args) |
| if fs.NArg() != 0 { |
| fs.Usage() |
| @@ -398,11 +430,11 @@ func printSystemMedia(w io.Writer, st mediaSystemStatus) { |
| if len(digest) > 19 { |
| digest = digest[:19] |
| } |
| - built := "-" // no readable build date; the image check says so |
| if t, err := time.Parse(time.RFC3339, st.Image.BuiltAt); err == nil { |
| - built = t.UTC().Format("2006-01-02") |
| + fmt.Fprintf(w, cliSysMediaImage+"\n", digest, t.UTC().Format("2006-01-02"), st.Image.FFmpeg) |
| + } else { |
| + fmt.Fprintf(w, cliSysMediaImageNoDate+"\n", digest, st.Image.FFmpeg) |
| } |
| - fmt.Fprintf(w, cliSysMediaImage+"\n", digest, built, st.Image.FFmpeg) |
| if st.Image.AgeDays != nil && *st.Image.AgeDays > 30 { |
| fmt.Fprintf(w, cliSysMediaStale+"\n", *st.Image.AgeDays) |
| } |
diff --git a/media_cli_test.go b/media_cli_test.go| index e07d8f664..118e18aa7 100644 |
| --- a/media_cli_test.go |
| +++ b/media_cli_test.go |
| @@ -3,6 +3,7 @@ package main |
| import ( |
| "bytes" |
| "context" |
| + "errors" |
| "io" |
| "net/http" |
| "net/http/httptest" |
| @@ -96,8 +97,8 @@ func TestMediaConvertWaitFailed(t *testing.T) { |
| defer ts.Close() |
| var out bytes.Buffer |
| if err := runMediaConvertWith(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", |
| - map[string]string{"key": "uploads/b7c1.mov"}, true, &out); err != nil { |
| - t.Fatal(err) |
| + map[string]string{"key": "uploads/b7c1.mov"}, true, &out); !errors.Is(err, errMediaJobFailed) { |
| + t.Fatalf("err %v, want errMediaJobFailed", err) |
| } |
| want := "id x2\nstate running\nstate failed (no_video)\nerror the file has no video track. convert it with the audio-aac preset\n" |
| if out.String() != want { |
| @@ -191,7 +192,7 @@ func TestPrintSystemMedia(t *testing.T) { |
| "engine configured in r\nimage sha256:abc, built 2026-10-18, ffmpeg 7\nqueued 0 short, 0 long\nrunning 0 short, 0 long\ndone 0 in the last 24 hours\nfailed 0 in the last 24 hours\n"}, |
| {"image unreadable, no age", `{"configured":true,"region":"r","image":{"digest":"sha256:abc","built_at":"","ffmpeg":"7","age_days":null}, |
| "checks":{"image":"error: no build date","video-720p/short":"ok"},"queued":{},"running":{},"done_24h":0,"failed_24h":0}`, |
| - "engine configured in r\nimage sha256:abc, built -, ffmpeg 7\n" + |
| + "engine configured in r\nimage sha256:abc, build date unknown, ffmpeg 7\n" + |
| "check image could not be read (no build date), so these jobs wait\n" + |
| "check video-720p/short ok\n" + |
| "queued 0 short, 0 long\nrunning 0 short, 0 long\ndone 0 in the last 24 hours\nfailed 0 in the last 24 hours\n"}, |
| @@ -205,3 +206,72 @@ func TestPrintSystemMedia(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func TestMediaConvertWaitCancelled(t *testing.T) { |
| + old := mediaPollEvery |
| + mediaPollEvery = time.Hour |
| + defer func() { mediaPollEvery = old }() |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + io.WriteString(w, `{"id":"x3","state":"queued"}`) |
| + })) |
| + defer ts.Close() |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + var out bytes.Buffer |
| + err := runMediaConvertWith(ctx, newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", map[string]string{"key": "k"}, true, &out) |
| + if err == nil { |
| + t.Fatal("a cancelled wait returned nil") |
| + } |
| +} |
| + |
| +func TestMediaConvertWaitToleratesPollErrors(t *testing.T) { |
| + old := mediaPollEvery |
| + mediaPollEvery = time.Millisecond |
| + defer func() { mediaPollEvery = old }() |
| + run := func(failures int) (string, error) { |
| + var gets atomic.Int32 |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method == http.MethodPost { |
| + io.WriteString(w, `{"id":"x4","state":"queued"}`) |
| + return |
| + } |
| + if int(gets.Add(1)) <= failures { |
| + w.WriteHeader(http.StatusBadGateway) |
| + return |
| + } |
| + io.WriteString(w, `{"id":"x4","state":"done"}`) |
| + })) |
| + defer ts.Close() |
| + var out bytes.Buffer |
| + err := runMediaConvertWith(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", map[string]string{"key": "k"}, true, &out) |
| + return out.String(), err |
| + } |
| + if out, err := run(3); err != nil || out != "id x4\nstate queued\nstate done\n" { |
| + t.Fatalf("three failed polls: %v\n%s", err, out) |
| + } |
| + if _, err := run(4); err == nil { |
| + t.Fatal("four failed polls in a row did not give up") |
| + } |
| +} |
| + |
| +func TestMediaStatusNotFound(t *testing.T) { |
| + ts := httptest.NewServer(http.NotFoundHandler()) |
| + defer ts.Close() |
| + var out bytes.Buffer |
| + if err := runMediaStatusWith(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", "nope", &out); err == nil || out.Len() != 0 { |
| + t.Fatalf("err %v, out %q", err, out.String()) |
| + } |
| +} |
| + |
| +func TestPrintSystemMediaOddChecks(t *testing.T) { |
| + st := decodeMediaStatus(t, `{"configured":true,"region":"r","image":{"digest":"sha256:abc","built_at":"2026-10-18T00:00:00Z","ffmpeg":"7","age_days":1}, |
| +"checks":{"video-720p/short":"error: timeout","zzz/new":"ok","aaa/new":"refused: read_only"},"queued":{},"running":{},"done_24h":0,"failed_24h":0}`) |
| + var out bytes.Buffer |
| + printSystemMedia(&out, st) |
| + want := "check video-720p/short could not be read (timeout), so these jobs wait\n" + |
| + "check aaa/new refused (read_only), so these jobs do not start\n" + |
| + "check zzz/new ok\n" |
| + if !strings.Contains(out.String(), want) { |
| + t.Fatalf("got:\n%s", out.String()) |
| + } |
| +} |