cli: carlos media and carlos system media status
Adds media convert (with --wait polling every 3 s), media status and system media status, printing the copy deck's lines. Answers decode into local structs. Parity rows, generated parity doc and cli.md headings (docs.cli.* sentences) included.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
8 files changed,
+732
−2
commands.go+1 −0docs/parity.md+4 −2docs/site/cli.md+38 −0media_cli.go+475 −0media_cli_test.go+207 −0parity/cli.tsv+3 −0parity/parity.tsv+2 −0system.go+2 −0
diff --git a/commands.go b/commands.go| index 538b8ce32..4108cbe9a 100644 |
| --- a/commands.go |
| +++ b/commands.go |
| @@ -128,6 +128,7 @@ func buildCommandRoot() *clireg.Node { |
| scheduleCommand(), |
| economicsCommand(), |
| storeCommand(), |
| + mediaCommand(), |
| relayCommand(), |
| mailerCommand(), |
| emailCommand(), |
diff --git a/docs/parity.md b/docs/parity.md| index 2b91b911f..f1b799fc8 100644 |
| --- a/docs/parity.md |
| +++ b/docs/parity.md |
| @@ -13,9 +13,9 @@ CLI rows are checked against the command registry (`parity/cli.tsv`). |
| | both | 44 | |
| | partial | 9 | |
| | gap | 66 | |
| -| cli-only | 17 | |
| +| cli-only | 18 | |
| | console-only | 17 | |
| -| Total | 153 | |
| +| Total | 154 | |
| ## account |
| @@ -58,6 +58,7 @@ CLI rows are checked against the command registry (`parity/cli.tsv`). |
| | apps-production | console-only | | `POST /a/{sqid}/apps/{app}/production` | | Turning the production flag on or off needs a passkey. | |
| | apps-star | console-only | | `POST /a/{sqid}/apps/{app}/star` | | A browser list preference. | |
| | apps-account-review | console-only | | `GET /a/{sqid}/apps/{app}/account-review` | | A page that explains an account mismatch to the person in the browser. | |
| +| media-convert | cli-only | `media convert`<br>`media status` | | | Apps call the conversion door; the CLI is how a person tries it. | |
| ## billing |
| @@ -420,6 +421,7 @@ Discussion #742. |
| | op-system-update | operator | `system update`<br>`system status`<br>`system rollback`<br>`system cancel-activation` | | Platform self-update. | |
| | op-system-antivirus | operator | `system antivirus status`<br>`system antivirus enable`<br>`system antivirus disable`<br>`system antivirus rotate-webhook-key` | | Deployment-wide scanning. | |
| | op-system-pdf | operator | `system pdf status` | | The PDF service. | |
| +| op-system-media | operator | `system media status` | | The media conversion engine. | |
| | op-system-layout | operator | `system layout status`<br>`system layout migrate`<br>`system layout revert` | | Instance layout; the Architecture page reads it. | |
| | op-system-geoip | operator | `system geoip publish`<br>`system geoip status`<br>`system geoip off` | | The platform GeoIP database. | |
| | op-system-cutovers | operator | `system seeds-floor publish`<br>`system legacy-routes assign`<br>`system lifetimes cutover`<br>`system hosts-used status` | | One-off cutovers and floors. | |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 6dd60f1d6..d6ec1d057 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -2192,6 +2192,16 @@ receives the same 404 as everyone else. `approvals`, `approve` and `decline` |
| require both the fleet-operator role and that allowlist entry, but the operator |
| does not need membership in the account being reviewed. |
| +#### carlos store uploads |
| + |
| +```sh |
| +carlos store uploads enable --app shop |
| +carlos store uploads status --app shop |
| +carlos store uploads disable --app shop |
| +``` |
| + |
| +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. |
| + |
| #### carlos store scan |
| Virus scanning over the objects in an app's store. **Off by default and |
| @@ -2312,6 +2322,26 @@ carlos store scan rotate-webhook-key --app hello |
| This changes only `hello`. A scan grant can also deliver a callback secret. Delivering changed config restarts affected apps. |
| +### carlos media |
| + |
| +Convert an object from a terminal and follow the job. Apps call the same API with a Service token. See the Media conversion page. |
| + |
| +#### carlos media convert |
| + |
| +```sh |
| +carlos media convert uploads/a1b2.mov --app shop --wait |
| +``` |
| + |
| +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. |
| + |
| +#### carlos media status |
| + |
| +```sh |
| +carlos media status 5e0b7a9c1d3f5b7d9e1a3c5e7f9b1d03 --app shop |
| +``` |
| + |
| +Shows a conversion's state, its output files once it is done, and why it failed if it did. |
| + |
| ### carlos relay |
| A STUN and TURN relay the platform runs for your app's WebRTC calls, so a |
| @@ -3368,6 +3398,14 @@ carlos system pdf status |
| System operators (`CARLOS_SYSTEM_OPERATORS`) and store operators (`CARLOS_STORE_OPERATORS`) can run this read-only command. |
| +#### carlos system media status |
| + |
| +```sh |
| +carlos 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. |
| + |
| #### Deployment-wide object scanning |
| ```sh |
diff --git a/media_cli.go b/media_cli.go| new file mode 100644 |
| index 000000000..cef426809 |
| --- /dev/null |
| +++ b/media_cli.go |
| @@ -0,0 +1,475 @@ |
| +// media_cli.go is `carlos media convert`, `carlos media status` and `carlos |
| +// system media status` (media conversion spec §5.2, §5.5). The verbs call |
| +// the console's doors and print the copy deck's lines |
| +// (docs/superpowers/notes/media-conversion-copy-deck.md, "CLI output"). |
| +// The root package never imports internal/media or internal/mediajobs, so |
| +// the answers decode into the local structs below. |
| +package main |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "flag" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "sort" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/clireg" |
| +) |
| + |
| +// The deck's lines (cli.media.*, cli.system_media.*). |
| +const ( |
| + cliMediaID = "id %s" |
| + cliMediaState = "state %s" |
| + cliMediaStateFailed = "state failed (%s)" |
| + cliMediaError = "error %s" |
| + cliMediaNext = "next carlos media status %s --app %s" |
| + cliMediaSource = "source %s, %s" |
| + cliMediaSourceAudio = "source %s" |
| + cliMediaPrefix = "prefix %s" |
| + cliMediaOutput = "output %-10s %-7s %s" |
| + |
| + cliSysMediaEngine = "engine configured in %s" |
| + cliSysMediaEngineOff = "engine not configured" |
| + cliSysMediaImage = "image %s, built %s, 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" |
| + cliSysMediaCheckError = "check %-17s could not be read (%s), so these jobs wait" |
| + cliSysMediaQueued = "queued %d short, %d long" |
| + cliSysMediaRunning = "running %d short, %d long" |
| + cliSysMediaDone = "done %d in the last 24 hours" |
| + cliSysMediaFailed = "failed %d in the last 24 hours" |
| + cliSysMediaFailedBy = "failed %d in the last 24 hours: %s" |
| +) |
| + |
| +// 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" |
| + |
| + 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>]" |
| +) |
| + |
| +// mediaPollEvery is how often --wait asks again. |
| +var mediaPollEvery = 3 * time.Second |
| + |
| +// mediaJobAnswer mirrors the console's answer for one conversion. |
| +type mediaJobAnswer struct { |
| + ID string `json:"id"` |
| + State string `json:"state"` |
| + Key string `json:"key"` |
| + Preset string `json:"preset"` |
| + Class string `json:"class"` |
| + Error *struct { |
| + Code string `json:"code"` |
| + Message string `json:"message"` |
| + } `json:"error"` |
| + Source *struct { |
| + DurationMS int64 `json:"duration_ms"` |
| + Width int `json:"width"` |
| + Height int `json:"height"` |
| + } `json:"source"` |
| + Outputs []struct { |
| + Key string `json:"key"` |
| + Bytes int64 `json:"bytes"` |
| + Width int `json:"width"` |
| + Height int `json:"height"` |
| + } `json:"outputs"` |
| +} |
| + |
| +func (j mediaJobAnswer) settled() bool { return j.State == "done" || j.State == "failed" } |
| + |
| +// mediaConvert POSTs a conversion; 200 (an existing job) and 202 (a new |
| +// one) both answer a job. |
| +func (a *apiSession) mediaConvert(ctx context.Context, acct apiAcct, app string, body map[string]string) (mediaJobAnswer, int, error) { |
| + status, resp, err := a.postJSON(ctx, apiPath(acct, app, "/media/conversions"), body) |
| + if err != nil { |
| + return mediaJobAnswer{}, 0, err |
| + } |
| + if status != http.StatusOK && status != http.StatusAccepted { |
| + return mediaJobAnswer{}, status, apiErrorFromBody(status, resp) |
| + } |
| + return decodeMediaJob(status, resp) |
| +} |
| + |
| +// mediaJob reads one conversion. |
| +func (a *apiSession) mediaJob(ctx context.Context, acct apiAcct, app, id string) (mediaJobAnswer, int, error) { |
| + status, resp, err := a.getJSON(ctx, apiPath(acct, app, "/media/conversions/"+url.PathEscape(id))) |
| + if err != nil { |
| + return mediaJobAnswer{}, 0, err |
| + } |
| + if status != http.StatusOK { |
| + return mediaJobAnswer{}, status, apiErrorFromBody(status, resp) |
| + } |
| + return decodeMediaJob(status, resp) |
| +} |
| + |
| +func decodeMediaJob(status int, resp []byte) (mediaJobAnswer, int, error) { |
| + var out mediaJobAnswer |
| + if err := json.Unmarshal(resp, &out); err != nil { |
| + return mediaJobAnswer{}, status, fmt.Errorf("media: unreadable response: %w", err) |
| + } |
| + return out, status, nil |
| +} |
| + |
| +// mediaSystemStatus mirrors GET /api/cli/system/media. |
| +type mediaSystemStatus struct { |
| + Configured bool `json:"configured"` |
| + Region string `json:"region"` |
| + Image struct { |
| + Digest string `json:"digest"` |
| + BuiltAt string `json:"built_at"` |
| + FFmpeg string `json:"ffmpeg"` |
| + AgeDays *int `json:"age_days"` |
| + } `json:"image"` |
| + Checks map[string]string `json:"checks"` |
| + Queued map[string]int `json:"queued"` |
| + Running map[string]int `json:"running"` |
| + Done24h int `json:"done_24h"` |
| + Failed24h int `json:"failed_24h"` |
| + FailedBy24 map[string]int `json:"failed_by_code_24h"` |
| +} |
| + |
| +func (a *apiSession) systemMediaStatus(ctx context.Context) (mediaSystemStatus, error) { |
| + status, body, err := a.getJSON(ctx, "/api/cli/system/media") |
| + if err != nil { |
| + return mediaSystemStatus{}, err |
| + } |
| + if status != http.StatusOK { |
| + return mediaSystemStatus{}, apiErrorFromBody(status, body) |
| + } |
| + var out mediaSystemStatus |
| + if err := json.Unmarshal(body, &out); err != nil { |
| + return mediaSystemStatus{}, fmt.Errorf("system media status: unreadable response: %w", err) |
| + } |
| + return out, nil |
| +} |
| + |
| +// ---- carlos media ------------------------------------------------------ |
| + |
| +// mediaCommand is `carlos media`. Bare or any other word is the usage on |
| +// stderr, exit 1. |
| +func mediaCommand() *clireg.Node { |
| + const cust = clireg.Customer |
| + return &clireg.Node{ |
| + Name: "media", |
| + 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) |
| + os.Exit(1) |
| + }, |
| + } |
| +} |
| + |
| +func runMediaConvert(args []string) { |
| + fs := flag.NewFlagSet("media convert", flag.ExitOnError) |
| + app := appFlag(fs, "") |
| + preset := fs.String("preset", "", mediaPresetHelp) |
| + 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)") |
| + fs.Usage = flagUsage(fs, mediaUsageConvert+"\n\n"+docsCLIMediaConvert) |
| + pos, _ := parseInterspersed(fs, args) |
| + if len(pos) != 1 { |
| + fs.Usage() |
| + os.Exit(2) |
| + } |
| + sess, acct, name := mediaSession(*consoleFlag, acctRaw, acctIDRaw, *app, mediaUsageConvert) |
| + body := map[string]string{"key": pos[0]} |
| + if *preset != "" { |
| + body["preset"] = *preset |
| + } |
| + if *class != "" { |
| + body["class"] = *class |
| + } |
| + if err := runMediaConvertWith(context.Background(), sess, acct, name, body, *wait, stdout); err != nil { |
| + log.Fatal(err) |
| + } |
| +} |
| + |
| +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)") |
| + fs.Usage = flagUsage(fs, mediaUsageStatus+"\n\n"+docsCLIMediaStatus) |
| + pos, _ := parseInterspersed(fs, args) |
| + if len(pos) != 1 { |
| + fs.Usage() |
| + os.Exit(2) |
| + } |
| + sess, acct, name := mediaSession(*consoleFlag, acctRaw, acctIDRaw, *app, mediaUsageStatus) |
| + if err := runMediaStatusWith(context.Background(), sess, acct, name, pos[0], stdout); err != nil { |
| + log.Fatal(err) |
| + } |
| +} |
| + |
| +func mediaSession(consoleFlag string, acctRaw, acctIDRaw *string, app, usage string) (*apiSession, apiAcct, string) { |
| + app = strings.TrimSpace(app) |
| + if app != "" { |
| + if err := validAppName(app); err != nil { |
| + log.Fatalf("media: %v", err) |
| + } |
| + } |
| + sess := requireStoreAPISession(consoleFlag) |
| + printUsing(stdout, sess) |
| + acct := resolvedAccount(sess, acctRaw, acctIDRaw) |
| + return sess, acct, resolvedApp(sess, acct, app, usage) |
| +} |
| + |
| +// runMediaConvertWith submits the conversion and prints the job; with wait |
| +// it asks every mediaPollEvery until the job is done or failed, printing a |
| +// state line each time the state changes. |
| +func runMediaConvertWith(ctx context.Context, s *apiSession, acct apiAcct, app string, body map[string]string, wait bool, w io.Writer) error { |
| + job, _, err := s.mediaConvert(ctx, acct, app, body) |
| + if err != nil { |
| + return err |
| + } |
| + fmt.Fprintf(w, cliMediaID+"\n", job.ID) |
| + printMediaState(w, job) |
| + for wait && !job.settled() { |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-time.After(mediaPollEvery): |
| + } |
| + next, _, err := s.mediaJob(ctx, acct, app, job.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if next.State != job.State { |
| + printMediaState(w, next) |
| + } |
| + job = next |
| + } |
| + printMediaRest(w, job, app) |
| + return nil |
| +} |
| + |
| +// runMediaStatusWith reads one job and prints it whole. |
| +func runMediaStatusWith(ctx context.Context, s *apiSession, acct apiAcct, app, id string, w io.Writer) error { |
| + job, _, err := s.mediaJob(ctx, acct, app, id) |
| + if err != nil { |
| + return err |
| + } |
| + fmt.Fprintf(w, cliMediaID+"\n", job.ID) |
| + printMediaState(w, job) |
| + printMediaRest(w, job, app) |
| + return nil |
| +} |
| + |
| +// printMediaState is the state line, with a failed job's code. |
| +func printMediaState(w io.Writer, j mediaJobAnswer) { |
| + if j.State == "failed" && j.Error != nil { |
| + fmt.Fprintf(w, cliMediaStateFailed+"\n", j.Error.Code) |
| + return |
| + } |
| + fmt.Fprintf(w, cliMediaState+"\n", j.State) |
| +} |
| + |
| +// printMediaRest is everything after the id and state lines: the failed |
| +// job's error, the done job's source and outputs, or the next command for |
| +// a job not settled. |
| +func printMediaRest(w io.Writer, j mediaJobAnswer, app string) { |
| + switch j.State { |
| + case "failed": |
| + if j.Error != nil { |
| + printMediaWrapped(w, cliMediaError, j.Error.Message) |
| + } |
| + case "done": |
| + if j.Source != nil { |
| + d := (time.Duration(j.Source.DurationMS) * time.Millisecond).Round(time.Second) |
| + if j.Source.Width > 0 && j.Source.Height > 0 { |
| + fmt.Fprintf(w, cliMediaSource+"\n", d, fmt.Sprintf("%dx%d", j.Source.Width, j.Source.Height)) |
| + } else { |
| + fmt.Fprintf(w, cliMediaSourceAudio+"\n", d) |
| + } |
| + } |
| + if len(j.Outputs) == 0 { |
| + return |
| + } |
| + prefix := "" |
| + if i := strings.LastIndex(j.Outputs[0].Key, "/"); i >= 0 { |
| + prefix = j.Outputs[0].Key[:i+1] |
| + } |
| + fmt.Fprintf(w, cliMediaPrefix+"\n", prefix) |
| + for _, o := range j.Outputs { |
| + size := o.Bytes |
| + dims := "" |
| + if o.Width > 0 && o.Height > 0 { |
| + dims = fmt.Sprintf("%dx%d", o.Width, o.Height) |
| + } |
| + fmt.Fprintln(w, strings.TrimRight(fmt.Sprintf(cliMediaOutput, strings.TrimPrefix(o.Key, prefix), humanBytes(&size), dims), " ")) |
| + } |
| + default: |
| + fmt.Fprintf(w, cliMediaNext+"\n", j.ID, app) |
| + } |
| +} |
| + |
| +// printMediaWrapped prints format filled with text, wrapped at 80 columns |
| +// with continuation lines under the nine-column indent. |
| +func printMediaWrapped(w io.Writer, format, text string) { |
| + line := fmt.Sprintf(format, "") |
| + indent := strings.Repeat(" ", len(line)) |
| + line = strings.TrimRight(line, " ") |
| + first := true |
| + for _, word := range strings.Fields(text) { |
| + switch { |
| + case first: |
| + line += strings.Repeat(" ", len(indent)-len(line)) + word |
| + first = false |
| + case len(line)+1+len(word) > 80: |
| + fmt.Fprintln(w, line) |
| + line = indent + word |
| + default: |
| + line += " " + word |
| + } |
| + } |
| + fmt.Fprintln(w, line) |
| +} |
| + |
| +// ---- carlos system media ----------------------------------------------- |
| + |
| +// systemMediaCommand is `carlos system media status`, shaped like |
| +// systemPDFCommand. |
| +func systemMediaCommand() *clireg.Node { |
| + return &clireg.Node{ |
| + Name: "media", |
| + Audience: clireg.Operator, |
| + Children: []*clireg.Node{raw("status", clireg.Operator, runSystemMediaStatus)}, |
| + Fallback: func(args, _ []string) { |
| + if len(args) == 0 { |
| + systemUsage() |
| + os.Exit(2) |
| + } |
| + switch args[0] { |
| + case "help", "-h", "--help": |
| + systemUsage() |
| + return |
| + default: |
| + systemUsage() |
| + os.Exit(2) |
| + } |
| + }, |
| + } |
| +} |
| + |
| +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, "") |
| + fs.Parse(args) |
| + if fs.NArg() != 0 { |
| + fs.Usage() |
| + os.Exit(2) |
| + } |
| + sess := requireStoreAPISession(*consoleFlag) |
| + st, err := sess.systemMediaStatus(context.Background()) |
| + if err != nil { |
| + log.Fatal(err) |
| + } |
| + printSystemMedia(stdout, st) |
| +} |
| + |
| +// mediaCheckOrder is the classes in the order the deck prints them. |
| +var mediaCheckOrder = []string{"video-720p/short", "video-720p/long", "audio-aac/short", "audio-aac/long"} |
| + |
| +func printSystemMedia(w io.Writer, st mediaSystemStatus) { |
| + if !st.Configured { |
| + fmt.Fprintln(w, cliSysMediaEngineOff) |
| + return |
| + } |
| + fmt.Fprintf(w, cliSysMediaEngine+"\n", st.Region) |
| + digest := st.Image.Digest |
| + 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, built, st.Image.FFmpeg) |
| + if st.Image.AgeDays != nil && *st.Image.AgeDays > 30 { |
| + fmt.Fprintf(w, cliSysMediaStale+"\n", *st.Image.AgeDays) |
| + } |
| + // The image check first when it could not be read, then the classes in |
| + // the deck's order, then any check this binary does not know, sorted. |
| + seen := map[string]bool{} |
| + var names []string |
| + if _, ok := st.Checks["image"]; ok { |
| + names = append(names, "image") |
| + seen["image"] = true |
| + } |
| + for _, n := range mediaCheckOrder { |
| + if _, ok := st.Checks[n]; ok { |
| + names = append(names, n) |
| + seen[n] = true |
| + } |
| + } |
| + var extra []string |
| + for n := range st.Checks { |
| + if !seen[n] { |
| + extra = append(extra, n) |
| + } |
| + } |
| + sort.Strings(extra) |
| + for _, n := range append(names, extra...) { |
| + v := st.Checks[n] |
| + switch { |
| + case v == "ok": |
| + fmt.Fprintf(w, cliSysMediaCheckOK+"\n", n) |
| + case strings.HasPrefix(v, "refused: "): |
| + fmt.Fprintf(w, cliSysMediaCheckRefuse+"\n", n, cleanControl(strings.TrimPrefix(v, "refused: "))) |
| + case strings.HasPrefix(v, "error: "): |
| + fmt.Fprintf(w, cliSysMediaCheckError+"\n", n, cleanControl(strings.TrimPrefix(v, "error: "))) |
| + default: |
| + fmt.Fprintf(w, cliSysMediaCheckError+"\n", n, cleanControl(v)) |
| + } |
| + } |
| + fmt.Fprintf(w, cliSysMediaQueued+"\n", st.Queued["short"], st.Queued["long"]) |
| + fmt.Fprintf(w, cliSysMediaRunning+"\n", st.Running["short"], st.Running["long"]) |
| + fmt.Fprintf(w, cliSysMediaDone+"\n", st.Done24h) |
| + if len(st.FailedBy24) == 0 { |
| + fmt.Fprintf(w, cliSysMediaFailed+"\n", st.Failed24h) |
| + return |
| + } |
| + codes := make([]string, 0, len(st.FailedBy24)) |
| + for c := range st.FailedBy24 { |
| + codes = append(codes, c) |
| + } |
| + sort.Slice(codes, func(i, j int) bool { |
| + if st.FailedBy24[codes[i]] != st.FailedBy24[codes[j]] { |
| + return st.FailedBy24[codes[i]] > st.FailedBy24[codes[j]] |
| + } |
| + return codes[i] < codes[j] |
| + }) |
| + parts := make([]string, len(codes)) |
| + for i, c := range codes { |
| + parts[i] = fmt.Sprintf("%s %d", cleanControl(c), st.FailedBy24[c]) |
| + } |
| + fmt.Fprintf(w, cliSysMediaFailedBy+"\n", st.Failed24h, strings.Join(parts, ", ")) |
| +} |
| + |
| +// cleanControl drops control characters from text the console sent. |
| +func cleanControl(s string) string { |
| + return strings.Map(func(r rune) rune { |
| + if r < 0x20 || r == 0x7f { |
| + return -1 |
| + } |
| + return r |
| + }, s) |
| +} |
diff --git a/media_cli_test.go b/media_cli_test.go| new file mode 100644 |
| index 000000000..e07d8f664 |
| --- /dev/null |
| +++ b/media_cli_test.go |
| @@ -0,0 +1,207 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| +) |
| + |
| +const mediaTestID = "3f9a0c2e7b1d4a6f8e0c2b4d6f8a0c1e" |
| + |
| +func TestMediaConvertPrintsTheJob(t *testing.T) { |
| + var got string |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + b, _ := io.ReadAll(r.Body) |
| + got = r.Method + " " + r.URL.RequestURI() + " " + string(b) |
| + w.WriteHeader(http.StatusAccepted) |
| + io.WriteString(w, `{"id":"`+mediaTestID+`","state":"queued","key":"uploads/a1b2.mov"}`) |
| + })) |
| + defer ts.Close() |
| + var out bytes.Buffer |
| + err := runMediaConvertWith(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", |
| + map[string]string{"key": "uploads/a1b2.mov"}, false, &out) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := "id " + mediaTestID + "\nstate queued\nnext carlos media status " + mediaTestID + " --app shop\n" |
| + if out.String() != want { |
| + t.Fatalf("got:\n%s\nwant:\n%s", out.String(), want) |
| + } |
| + if got != `POST /api/cli/apps/bab/shop/media/conversions {"key":"uploads/a1b2.mov"}` { |
| + t.Fatalf("request: %s", got) |
| + } |
| +} |
| + |
| +func TestMediaConvertWaitPollsUntilDone(t *testing.T) { |
| + old := mediaPollEvery |
| + mediaPollEvery = time.Millisecond |
| + defer func() { mediaPollEvery = old }() |
| + var gets atomic.Int32 |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method == http.MethodPost { |
| + w.WriteHeader(http.StatusAccepted) |
| + io.WriteString(w, `{"id":"x1","state":"queued"}`) |
| + return |
| + } |
| + if r.URL.Path != "/api/cli/apps/bab/shop/media/conversions/x1" { |
| + t.Errorf("path %s", r.URL.Path) |
| + } |
| + switch gets.Add(1) { |
| + case 1, 2: |
| + io.WriteString(w, `{"id":"x1","state":"running"}`) |
| + default: |
| + io.WriteString(w, `{"id":"x1","state":"done","source":{"duration_ms":102400,"width":1920,"height":1080},"outputs":[ |
| +{"key":"derived/uploads/a1b2.mov/e/video-720p/x/video.mp4","bytes":22440960,"width":1280,"height":720}, |
| +{"key":"derived/uploads/a1b2.mov/e/video-720p/x/video.m3u8","bytes":1126}, |
| +{"key":"derived/uploads/a1b2.mov/e/video-720p/x/poster.jpg","bytes":98304,"width":1280,"height":720}]}`) |
| + } |
| + })) |
| + defer ts.Close() |
| + var out bytes.Buffer |
| + if err := runMediaConvertWith(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", |
| + map[string]string{"key": "uploads/a1b2.mov"}, true, &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := "id x1\nstate queued\nstate running\nstate done\n" + |
| + "source 1m42s, 1920x1080\n" + |
| + "prefix derived/uploads/a1b2.mov/e/video-720p/x/\n" + |
| + "output video.mp4 21.4MB 1280x720\n" + |
| + "output video.m3u8 1.1KB\n" + |
| + "output poster.jpg 96.0KB 1280x720\n" |
| + if out.String() != want { |
| + t.Fatalf("got:\n%s\nwant:\n%s", out.String(), want) |
| + } |
| + if gets.Load() != 3 { |
| + t.Fatalf("polled %d times, want 3", gets.Load()) |
| + } |
| +} |
| + |
| +func TestMediaConvertWaitFailed(t *testing.T) { |
| + old := mediaPollEvery |
| + mediaPollEvery = time.Millisecond |
| + defer func() { mediaPollEvery = old }() |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method == http.MethodPost { |
| + io.WriteString(w, `{"id":"x2","state":"running"}`) |
| + return |
| + } |
| + io.WriteString(w, `{"id":"x2","state":"failed","error":{"code":"no_video","message":"the file has no video track. convert it with the audio-aac preset"}}`) |
| + })) |
| + 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) |
| + } |
| + 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 { |
| + t.Fatalf("got:\n%s\nwant:\n%s", out.String(), want) |
| + } |
| +} |
| + |
| +func TestMediaStatusFailedPrintsCodeAndMessage(t *testing.T) { |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + io.WriteString(w, `{"id":"5e0b","state":"failed","error":{"code":"unsupported_container","message":"the file is not in a format conversion reads: MP4, MOV, 3GP, WebM or MKV, and for audio also MP3, WAV, FLAC or Ogg"}}`) |
| + })) |
| + defer ts.Close() |
| + var out bytes.Buffer |
| + if err := runMediaStatusWith(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", "5e0b", &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := "id 5e0b\nstate failed (unsupported_container)\n" + |
| + "error the file is not in a format conversion reads: MP4, MOV, 3GP, WebM or\n" + |
| + " MKV, and for audio also MP3, WAV, FLAC or Ogg\n" |
| + if out.String() != want { |
| + t.Fatalf("got:\n%s\nwant:\n%s", out.String(), want) |
| + } |
| +} |
| + |
| +func TestMediaStatusAudioDone(t *testing.T) { |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + io.WriteString(w, `{"id":"a07e","state":"done","source":{"duration_ms":2890000},"outputs":[ |
| +{"key":"derived/u/c4d9.m4a/e/audio-aac/x/audio.mp4","bytes":46444339}, |
| +{"key":"derived/u/c4d9.m4a/e/audio-aac/x/peaks.json","bytes":3891}]}`) |
| + })) |
| + defer ts.Close() |
| + var out bytes.Buffer |
| + if err := runMediaStatusWith(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", "a07e", &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := "id a07e\nstate done\nsource 48m10s\nprefix derived/u/c4d9.m4a/e/audio-aac/x/\n" + |
| + "output audio.mp4 44.3MB\noutput peaks.json 3.8KB\n" |
| + if out.String() != want { |
| + t.Fatalf("got:\n%s\nwant:\n%s", out.String(), want) |
| + } |
| +} |
| + |
| +func TestMediaConvertRefusal(t *testing.T) { |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusBadRequest) |
| + io.WriteString(w, `{"error":"class is short or long"}`) |
| + })) |
| + defer ts.Close() |
| + var out bytes.Buffer |
| + err := runMediaConvertWith(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", map[string]string{"key": "k"}, false, &out) |
| + if err == nil || !strings.Contains(err.Error(), "class is short or long") || out.Len() != 0 { |
| + t.Fatalf("err %v, out %q", err, out.String()) |
| + } |
| +} |
| + |
| +func decodeMediaStatus(t *testing.T, js string) mediaSystemStatus { |
| + t.Helper() |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/api/cli/system/media" { |
| + t.Errorf("path %s", r.URL.Path) |
| + } |
| + io.WriteString(w, js) |
| + })) |
| + defer ts.Close() |
| + st, err := newTestSession(ts.URL).systemMediaStatus(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return st |
| +} |
| + |
| +func TestPrintSystemMedia(t *testing.T) { |
| + cases := []struct{ name, js, want string }{ |
| + {"healthy", `{"configured":true,"region":"eu-west-1","image":{"digest":"sha256:9f2c4e1a7b3d0000000000000000","built_at":"2026-11-10T08:00:00Z","ffmpeg":"7.1.2","age_days":7}, |
| +"checks":{"video-720p/short":"ok","video-720p/long":"ok","audio-aac/short":"ok","audio-aac/long":"ok"}, |
| +"queued":{"short":3,"long":0},"running":{"short":2,"long":1},"done_24h":41,"failed_24h":0,"failed_by_code_24h":{}}`, |
| + "engine configured in eu-west-1\n" + |
| + "image sha256:9f2c4e1a7b3d, built 2026-11-10, ffmpeg 7.1.2\n" + |
| + "check video-720p/short ok\ncheck video-720p/long ok\ncheck audio-aac/short ok\ncheck audio-aac/long ok\n" + |
| + "queued 3 short, 0 long\nrunning 2 short, 1 long\ndone 41 in the last 24 hours\nfailed 0 in the last 24 hours\n"}, |
| + {"stale and refused", `{"configured":true,"region":"eu-west-1","image":{"digest":"sha256:9f2c4e1a7b3d0000","built_at":"2026-10-01T00:00:00Z","ffmpeg":"7.1.2","age_days":47}, |
| +"checks":{"audio-aac/long":"refused: read_only","video-720p/short":"ok","video-720p/long":"ok","audio-aac/short":"ok"}, |
| +"queued":{"short":0,"long":0},"running":{"short":1,"long":0},"done_24h":12,"failed_24h":3,"failed_by_code_24h":{"engine_failed":1,"no_video":2}}`, |
| + "engine configured in eu-west-1\n" + |
| + "image sha256:9f2c4e1a7b3d, built 2026-10-01, ffmpeg 7.1.2\n" + |
| + "warning the image is 47 days old. rebuild it and roll it out\n" + |
| + "check video-720p/short ok\ncheck video-720p/long ok\ncheck audio-aac/short ok\n" + |
| + "check audio-aac/long refused (read_only), so these jobs do not start\n" + |
| + "queued 0 short, 0 long\nrunning 1 short, 0 long\ndone 12 in the last 24 hours\nfailed 3 in the last 24 hours: no_video 2, engine_failed 1\n"}, |
| + {"thirty days is not stale", `{"configured":true,"region":"r","image":{"digest":"sha256:abc","built_at":"2026-10-18T00:00:00Z","ffmpeg":"7","age_days":30},"checks":{},"queued":{},"running":{},"done_24h":0,"failed_24h":0}`, |
| + "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" + |
| + "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"}, |
| + {"not configured", `{"configured":false,"region":"","image":{},"checks":{}}`, "engine not configured\n"}, |
| + } |
| + for _, c := range cases { |
| + var out bytes.Buffer |
| + printSystemMedia(&out, decodeMediaStatus(t, c.js)) |
| + if out.String() != c.want { |
| + t.Errorf("%s:\n%s\nwant:\n%s", c.name, out.String(), c.want) |
| + } |
| + } |
| +} |
diff --git a/parity/cli.tsv b/parity/cli.tsv| index fd426d02c..0d8aaef3a 100644 |
| --- a/parity/cli.tsv |
| +++ b/parity/cli.tsv |
| @@ -161,6 +161,8 @@ link unpublish operator - - - - - |
| links ls customer - - - - - |
| logs customer - - - - - |
| mailer serve box-local - - - - - |
| +media convert customer - - - - - |
| +media status customer - - - - - |
| move customer - - - - - |
| move abort customer - - - - - |
| move cut customer - - - - - |
| @@ -306,6 +308,7 @@ system legacy-routes assign operator - - - - - |
| system lifetimes cutover operator - - - - - |
| system managed-fleets set operator - - - - - |
| system managed-fleets show operator - - - - - |
| +system media status operator - - - - - |
| system named-units box-local - - - - - |
| system pdf status operator - - - - - |
| system proxy-allows-prev box-local - - - - - |
diff --git a/parity/parity.tsv b/parity/parity.tsv| index aede8cde2..ea4128223 100644 |
| --- a/parity/parity.tsv |
| +++ b/parity/parity.tsv |
| @@ -128,6 +128,7 @@ store-apply storage both store apply GET /a/{sqid}/settings ; POST /a/{sqid}/sto |
| store-rotate storage gap store rotate wp-email-storage |
| store-scan storage gap store scan request ; store scan status ; store scan grant ; store scan revoke ; store scan sweep ; store scan enforce ; store scan rotate-webhook-key wp-email-storage |
| store-uploads storage gap store uploads enable ; store uploads status ; store uploads disable wp-email-storage |
| +media-convert apps cli-only media convert ; media status Apps call the conversion door; the CLI is how a person tries it. |
| store-destroy storage console-only POST /a/{sqid}/apps/{app}/store/destroy Needs a passkey. |
| @@ -217,6 +218,7 @@ op-host-resolve operator operator ops host resolve Host-claim resolution for |
| op-system-update operator operator system update ; system status ; system rollback ; system cancel-activation Platform self-update. |
| op-system-antivirus operator operator system antivirus status ; system antivirus enable ; system antivirus disable ; system antivirus rotate-webhook-key Deployment-wide scanning. |
| op-system-pdf operator operator system pdf status The PDF service. |
| +op-system-media operator operator system media status The media conversion engine. |
| op-system-layout operator operator system layout status ; system layout migrate ; system layout revert Instance layout; the Architecture page reads it. |
| op-system-geoip operator operator system geoip publish ; system geoip status ; system geoip off The platform GeoIP database. |
| op-system-cutovers operator operator system seeds-floor publish ; system legacy-routes assign ; system lifetimes cutover ; system hosts-used status One-off cutovers and floors. |
diff --git a/system.go b/system.go| index 3dc87b9c9..6e82c3c72 100644 |
| --- a/system.go |
| +++ b/system.go |
| @@ -81,6 +81,7 @@ func systemCommand() *clireg.Node { |
| raw("apply", box, host.RunSystemApply), |
| systemAntivirusCommand(), |
| systemPDFCommand(), |
| + systemMediaCommand(), |
| systemLayoutCommand(), |
| systemGeoipCommand(), |
| systemOneVerbCommand("seeds-floor", "publish", runSystemSeedsFloorPublish), |
| @@ -212,6 +213,7 @@ func systemUsage() { |
| carlos system managed-fleets <show|set --file f.json> |
| carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags] |
| carlos system pdf status |
| + carlos system media status |
| carlos system geoip <publish|status|off> [flags] |
| carlos system seeds-floor publish --min-release <release> |
| carlos system legacy-routes assign --name <name> --to <account>/<app> |