carlos / platform Public

cli: media and uploads verbs return errors; main sets the exit

Task 12b (code-health ratchet, fatal). clireg gains DispatchErr, which
returns a leaf's or a FallbackErr's error that no OnError handles
instead of panicking (Dispatch is DispatchErr plus the same panic), and
Node.FallbackErr, a branch fallback whose error is routed like a
leaf's; Validate refuses both fallbacks set.

main walks the tree with DispatchErr through runCommandLine and has one
os.Exit, for a nonzero code. cliExitCode maps a returned error: an
errExit (exitCode) exits with its code and no message, anything else is
printed by log.Print, as log.Fatal printed it, and exits 1.

carlos media convert|status, carlos store uploads and carlos system
media status return errors, and exitCode(2) after a flag usage,
exitCode(1) after a branch usage or for --wait on a failed job (no
second message). Copy, messages and codes are unchanged; every recorded
golden case replays with the same exit and output.

The uploads and media API client moves unchanged from apimode.go and
media_cli.go to media_api.go, bringing apimode.go back to its record.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e6ed362bfeaf154c64af3fd03946935e6fd0409b parent 63b1cc0
12 files changed, +363 −218
  • apimode.go +0 −50
  • commands.go +30 −0
  • commands_test.go +6 −3
  • internal/clireg/clireg.go +4 −0
  • internal/clireg/dispatch.go +36 −16
  • internal/clireg/dispatch_test.go +58 −0
  • internal/clireg/validate.go +4 −1
  • internal/clireg/validate_test.go +3 −0
  • main.go +21 −6
  • media_api.go +157 −0
  • media_cli.go +35 −133
  • store_uploads.go +9 −9
diff --git a/apimode.go b/apimode.go
index 85ed6b3a0..2e3373dc1 100644
--- a/apimode.go
+++ b/apimode.go
@@ -2492,56 +2492,6 @@ func (s *apiSession) scanRotateCallbackKey(ctx context.Context, a apiAcct, app s
return s.scanCall(ctx, "store scan rotate-webhook-key", apiPath(a, app, "/store/scan/callback-key/rotate"), struct{}{})
}
-// apiUploadsReply is both browser-uploads doors' answer
-// (internal/console/apistoreuploads.go uploadsAnswer).
-type apiUploadsReply struct {
- Enabled bool `json:"enabled"`
- Origins []string `json:"origins"`
- BucketMatches bool `json:"bucket_matches"`
- Mismatch string `json:"mismatch"`
-}
-
-// storeUploadsCall is one round trip to .../store/uploads: GET when in is
-// nil, else POST.
-func (s *apiSession) storeUploadsCall(ctx context.Context, a apiAcct, app string, in any) (apiUploadsReply, error) {
- path := apiPath(a, app, "/store/uploads")
- var status int
- var body []byte
- var err error
- if in == nil {
- status, body, err = s.getJSON(ctx, path)
- } else {
- status, body, err = s.postJSON(ctx, path, in)
- }
- if err != nil {
- return apiUploadsReply{}, err
- }
- if status != http.StatusOK {
- return apiUploadsReply{}, apiErrorFromBody(status, body)
- }
- var out apiUploadsReply
- if err := json.Unmarshal(body, &out); err != nil {
- return apiUploadsReply{}, fmt.Errorf(storeUploadsText("cli.uploads.unreadable"), err)
- }
- return out, nil
-}
-
-// storeUploadsSet turns browser uploads on (with origins, none meaning the
-// app's hostnames) or off.
-func (s *apiSession) storeUploadsSet(ctx context.Context, a apiAcct, app string, enabled bool, origins []string) (apiUploadsReply, error) {
- in := struct {
- Enabled bool `json:"enabled"`
- Origins []string `json:"origins,omitempty"`
- }{enabled, origins}
- return s.storeUploadsCall(ctx, a, app, in)
-}
-
-// storeUploadsStatus reads browser uploads' state and whether the bucket
-// still holds the rules the platform wrote.
-func (s *apiSession) storeUploadsStatus(ctx context.Context, a apiAcct, app string) (apiUploadsReply, error) {
- return s.storeUploadsCall(ctx, a, app, nil)
-}
-
// storeCreate asks the console to declare (or re-declare) a store for app,
// under envPrefix ("" takes the console's own default — objstore.
// DefaultEnvPrefix). Mirrors restart's shape (apimode.go:438): postJSON, a
diff --git a/commands.go b/commands.go
index 4108cbe9a..fbafdc6f3 100644
--- a/commands.go
+++ b/commands.go
@@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"log"
@@ -40,6 +41,35 @@ func raw(name string, aud clireg.Audience, f func([]string)) *clireg.Node {
return &clireg.Node{Name: name, Audience: aud, Run: clireg.RawArgs(f)}
}
+// rawErr is raw for a handler that returns its error rather than exiting
+// (AGENTS.md, "Writing Go here"): main prints it and picks the exit code
+// (cliExitCode).
+func rawErr(name string, aud clireg.Audience, f func([]string) error) *clireg.Node {
+ return &clireg.Node{Name: name, Audience: aud, Run: clireg.RawArgsErr(f)}
+}
+
+// errExit is a command's failure it has already shown in full (its usage,
+// or a failed job's state): main exits with code and prints nothing more.
+type errExit struct{ code int }
+
+func (e errExit) Error() string { return fmt.Sprintf("exit status %d", e.code) }
+
+// exitCode is the error a command returns to end with code and no
+// further message.
+func exitCode(code int) error { return errExit{code} }
+
+// cliExitCode is the process exit code for an error a command returned:
+// an errExit's own code, silently; anything else printed as log.Fatal
+// prints it, and 1.
+func cliExitCode(err error) int {
+ var done errExit
+ if errors.As(err, &done) {
+ return done.code
+ }
+ log.Print(err)
+ return 1
+}
+
// noHint marks n as one of the words the update hint stays out of: box,
// daemon and plumbing verbs, and verbs whose output is parsed.
func noHint(n *clireg.Node) *clireg.Node {
diff --git a/commands_test.go b/commands_test.go
index c39d4dbaf..a141b051e 100644
--- a/commands_test.go
+++ b/commands_test.go
@@ -58,9 +58,9 @@ func TestTopLevelWordsUnchanged(t *testing.T) {
}
}
-// inertTree copies n with every Run and Fallback replaced by one that does
-// nothing, so a test can ask Dispatch which path a command line takes
-// without running it.
+// inertTree copies n with every Run, Fallback and FallbackErr replaced by
+// one that does nothing, so a test can ask Dispatch which path a command
+// line takes without running it.
func inertTree(n *clireg.Node) *clireg.Node {
if n == nil {
return nil
@@ -72,6 +72,9 @@ func inertTree(n *clireg.Node) *clireg.Node {
if c.Fallback != nil {
c.Fallback = func(args, consumed []string) {}
}
+ if c.FallbackErr != nil {
+ c.FallbackErr = func(args, consumed []string) error { return nil }
+ }
c.Children = nil
for _, ch := range n.Children {
c.Children = append(c.Children, inertTree(ch))
diff --git a/internal/clireg/clireg.go b/internal/clireg/clireg.go
index 55cab9500..25179c8b8 100644
--- a/internal/clireg/clireg.go
+++ b/internal/clireg/clireg.go
@@ -58,6 +58,10 @@ type Node struct {
// are the remaining arguments; consumed is every word the walk
// dropped, transparent words included.
Fallback func(args, consumed []string)
+ // FallbackErr is Fallback for a branch whose fallback can fail: its
+ // error goes where a leaf's would (OnError, else DispatchErr's
+ // result). At most one of Fallback and FallbackErr is set.
+ FallbackErr func(args, consumed []string) error
// OnError handles a non-nil error from a leaf at or below this node.
// The nearest one on the path is called, with the leaf's canonical
// path.
diff --git a/internal/clireg/dispatch.go b/internal/clireg/dispatch.go
index 6f77c3399..bba5ada81 100644
--- a/internal/clireg/dispatch.go
+++ b/internal/clireg/dispatch.go
@@ -14,18 +14,29 @@ import "fmt"
// DefaultOn admits the case, with every remaining argument unchanged;
// otherwise Fallback(args, consumed) runs.
//
-// A leaf's Run gets the remaining arguments unchanged. If it returns an
-// error, the nearest OnError on the path (leaf first) handles it; with
-// none, Dispatch panics.
+// A leaf's Run gets the remaining arguments unchanged. If it, or a
+// branch's FallbackErr, returns an error, the nearest OnError on the path
+// (leaf first) handles it; with none, Dispatch panics.
func Dispatch(root *Node, args []string) []*Node {
+ path, err := DispatchErr(root, args)
+ if err != nil {
+ panic(fmt.Sprintf("clireg: %s returned an error and no OnError handles it: %v", idOrRoot(path), err))
+ }
+ return path
+}
+
+// DispatchErr is Dispatch for a caller that ends the process itself: an
+// error from a leaf or a FallbackErr that no OnError on the path handles
+// is returned with the path, rather than a panic. main maps it to an exit
+// code, so a command returns its error instead of exiting.
+func DispatchErr(root *Node, args []string) ([]*Node, error) {
path := []*Node{root}
var words, consumed []string
n := root
dropped := map[*Node]bool{} // transparent children dropped at n
for {
if n.isLeaf() && !n.isBranch() {
- runLeaf(path, words, args)
- return path
+ return path, runLeaf(path, words, args)
}
if len(args) > 0 {
if c := matchChild(n, args[0], false, nil); c != nil {
@@ -47,22 +58,23 @@ func Dispatch(root *Node, args []string) []*Node {
if (n.DefaultLeaf != nil || n.Default != "") && n.admits(args) {
if n.DefaultLeaf != nil {
path = append(path, n.DefaultLeaf)
- runLeaf(path, words, args)
- return path
+ return path, runLeaf(path, words, args)
}
c := n.child(n.Default)
if c == nil {
panic(fmt.Sprintf("clireg: %s: Default %q names no child", idOrRoot(path), n.Default))
}
path = append(path, c)
- runLeaf(path, append(words, c.Name), args)
- return path
+ return path, runLeaf(path, append(words, c.Name), args)
+ }
+ if n.FallbackErr != nil {
+ return path, handled(path, words, n.FallbackErr(args, append([]string{}, consumed...)))
}
if n.Fallback == nil {
panic(fmt.Sprintf("clireg: %s: no child, default or Fallback for %q", idOrRoot(path), args))
}
n.Fallback(args, append([]string{}, consumed...))
- return path
+ return path, nil
}
}
@@ -81,8 +93,8 @@ func matchChild(n *Node, word string, transparent bool, skip map[*Node]bool) *No
}
// runLeaf runs the last node on path with args, routing an error to the
-// nearest OnError.
-func runLeaf(path []*Node, words, args []string) {
+// nearest OnError; an error none handles is returned.
+func runLeaf(path []*Node, words, args []string) error {
leaf := path[len(path)-1]
if leaf.Run == nil || leaf.isBranch() {
panic(fmt.Sprintf("clireg: %s: not a leaf", idOrRoot(path)))
@@ -93,17 +105,25 @@ func runLeaf(path []*Node, words, args []string) {
if args == nil {
args = []string{}
}
- err := leaf.Run(&Invocation{Path: words, Raw: args})
+ return handled(path, words, leaf.Run(&Invocation{Path: words, Raw: args}))
+}
+
+// handled gives err to the nearest OnError on path (last node first) and
+// returns nil, or returns err when no node on path has one.
+func handled(path []*Node, words []string, err error) error {
if err == nil {
- return
+ return nil
+ }
+ if words == nil {
+ words = []string{}
}
for i := len(path) - 1; i >= 0; i-- {
if h := path[i].OnError; h != nil {
h(append([]string{}, words...), err)
- return
+ return nil
}
}
- panic(fmt.Sprintf("clireg: %s returned an error and no OnError handles it: %v", idOrRoot(path), err))
+ return err
}
func idOrRoot(path []*Node) string {
diff --git a/internal/clireg/dispatch_test.go b/internal/clireg/dispatch_test.go
index c25ce536a..0d183f0c0 100644
--- a/internal/clireg/dispatch_test.go
+++ b/internal/clireg/dispatch_test.go
@@ -2,6 +2,7 @@ package clireg
import (
"errors"
+ "fmt"
"reflect"
"strings"
"testing"
@@ -272,6 +273,63 @@ func TestDispatchErrorWithoutOnErrorPanics(t *testing.T) {
Dispatch(root, []string{"auth", "login"})
}
+// TestDispatchErrReturnsUnhandled: DispatchErr returns, with the path, the
+// error a leaf or a FallbackErr returned when no OnError on the path takes
+// it, and nil when one does or nothing failed.
+func TestDispatchErrReturnsUnhandled(t *testing.T) {
+ boom := errors.New("e")
+ var handledBy []string
+ root := &Node{
+ Name: "carlos",
+ Fallback: func(_, _ []string) {},
+ Children: []*Node{{
+ Name: "media",
+ FallbackErr: func(args, _ []string) error { return fmt.Errorf("usage %q: %w", args, boom) },
+ Children: []*Node{
+ {Name: "convert", Audience: Customer, Run: func(*Invocation) error { return boom }},
+ {Name: "status", Audience: Customer, Run: func(*Invocation) error { return nil }},
+ },
+ }, {
+ Name: "auth",
+ OnError: func(path []string, err error) { handledBy = append(handledBy, strings.Join(path, " ")) },
+ FallbackErr: func(_, _ []string) error { return boom },
+ Children: []*Node{{Name: "login", Audience: Customer, Run: func(*Invocation) error { return boom }}},
+ }},
+ }
+ if errs := Validate(root); len(errs) != 0 {
+ t.Fatalf("a branch with only FallbackErr does not validate: %v", errs)
+ }
+ for _, tc := range []struct {
+ args []string
+ want error
+ last string
+ }{
+ {[]string{"media", "convert"}, boom, "convert"},
+ {[]string{"media", "status"}, nil, "status"},
+ {[]string{"media", "nope"}, boom, "media"},
+ {[]string{"auth", "login"}, nil, "login"},
+ {[]string{"auth"}, nil, "auth"},
+ } {
+ path, err := DispatchErr(root, tc.args)
+ if !errors.Is(err, tc.want) || (tc.want == nil && err != nil) {
+ t.Errorf("DispatchErr(%q) = %v, want %v", tc.args, err, tc.want)
+ }
+ if got := path[len(path)-1].Name; got != tc.last {
+ t.Errorf("DispatchErr(%q) path ends at %q, want %q", tc.args, got, tc.last)
+ }
+ }
+ if want := []string{"auth login", "auth"}; !reflect.DeepEqual(handledBy, want) {
+ t.Errorf("auth's OnError saw %q, want %q", handledBy, want)
+ }
+ // Dispatch keeps its contract: an unhandled FallbackErr error panics.
+ defer func() {
+ if r := recover(); r == nil {
+ t.Fatal("Dispatch did not panic on an unhandled FallbackErr error")
+ }
+ }()
+ Dispatch(root, []string{"media"})
+}
+
func TestRawArgs(t *testing.T) {
var seen []string
run := RawArgs(func(args []string) { seen = args })
diff --git a/internal/clireg/validate.go b/internal/clireg/validate.go
index d8db47014..a52fefdd3 100644
--- a/internal/clireg/validate.go
+++ b/internal/clireg/validate.go
@@ -66,7 +66,10 @@ func (v *validator) branch(n *Node, id string) {
if hasDefault && n.DefaultOn == 0 {
v.fail(id, "a default with an empty DefaultOn")
}
- if n.Fallback == nil {
+ if n.Fallback != nil && n.FallbackErr != nil {
+ v.fail(id, "Fallback and FallbackErr both set")
+ }
+ if n.Fallback == nil && n.FallbackErr == nil {
all := OnAbsent | OnFlag | OnWord
switch {
case !hasDefault:
diff --git a/internal/clireg/validate_test.go b/internal/clireg/validate_test.go
index a39117d0e..6604b62b5 100644
--- a/internal/clireg/validate_test.go
+++ b/internal/clireg/validate_test.go
@@ -8,6 +8,7 @@ import (
func TestValidate(t *testing.T) {
run := func(*Invocation) error { return nil }
fb := func(_, _ []string) {}
+ fbErr := func(_, _ []string) error { return nil }
leaf := func(name string, aliases ...string) *Node {
return &Node{Name: name, Aliases: aliases, Run: run, Audience: Customer}
}
@@ -63,6 +64,8 @@ func TestValidate(t *testing.T) {
"system router: "},
{"root with no fallback", &Node{Name: "carlos", Children: []*Node{leaf("x")}},
"<root>: "},
+ {"Fallback and FallbackErr both set", under(&Node{Name: "media", Children: []*Node{leaf("convert")}, Fallback: fb, FallbackErr: fbErr}),
+ "media: "},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
diff --git a/main.go b/main.go
index a2c62efe8..4cb95a843 100644
--- a/main.go
+++ b/main.go
@@ -28,16 +28,31 @@ func main() {
// than at a few hundred call sites. Off unless stderr is a terminal, so
// journald and CI logs see exactly what they saw before.
log.SetOutput(newErrorWriter(os.Stderr))
+ code := 2
if len(os.Args) < 2 {
usage(os.Stderr)
- os.Exit(2)
+ } else {
+ code = runCommandLine(os.Args[1:])
+ }
+ // The binary's one exit for a command that returns its error
+ // (cliExitCode); success returns from main as before.
+ if code != 0 {
+ os.Exit(code)
+ }
+}
+
+// runCommandLine runs the command args name and answers the exit code.
+// After a verb that ran to success: the once-a-day newer-release hint
+// (#161). Verbs that fail never reach it (they return an error, or
+// log.Fatal exits), so a broken command is never followed by an upsell.
+// Paths through a NoUpdateHint node skip it (maybeUpdateHint).
+func runCommandLine(args []string) int {
+ path, err := clireg.DispatchErr(commandRoot(), args)
+ if err != nil {
+ return cliExitCode(err)
}
- path := clireg.Dispatch(commandRoot(), os.Args[1:])
- // After a verb that ran to success: the once-a-day newer-release hint
- // (#161). Verbs that fail never reach here (log.Fatal exits), so a
- // broken command is never followed by an upsell. Paths through a
- // NoUpdateHint node skip it (maybeUpdateHint).
maybeUpdateHint(path)
+ return 0
}
// usage prints the top-level command list, grouped by the role you are in
diff --git a/media_api.go b/media_api.go
new file mode 100644
index 000000000..8601414c3
--- /dev/null
+++ b/media_api.go
@@ -0,0 +1,157 @@
+// media_api.go is the console API client for media conversion and browser
+// uploads (media conversion spec §5.2, §5.5, §5.6): the doors' answers,
+// decoded into local structs (the root package never imports
+// internal/media or internal/mediajobs), and one round trip per call
+// through apiSession. The verbs that print them are media_cli.go and
+// store_uploads.go.
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+)
+
+// apiUploadsReply is both browser-uploads doors' answer
+// (internal/console/apistoreuploads.go uploadsAnswer).
+type apiUploadsReply struct {
+ Enabled bool `json:"enabled"`
+ Origins []string `json:"origins"`
+ BucketMatches bool `json:"bucket_matches"`
+ Mismatch string `json:"mismatch"`
+}
+
+// storeUploadsCall is one round trip to .../store/uploads: GET when in is
+// nil, else POST.
+func (s *apiSession) storeUploadsCall(ctx context.Context, a apiAcct, app string, in any) (apiUploadsReply, error) {
+ path := apiPath(a, app, "/store/uploads")
+ var status int
+ var body []byte
+ var err error
+ if in == nil {
+ status, body, err = s.getJSON(ctx, path)
+ } else {
+ status, body, err = s.postJSON(ctx, path, in)
+ }
+ if err != nil {
+ return apiUploadsReply{}, err
+ }
+ if status != http.StatusOK {
+ return apiUploadsReply{}, apiErrorFromBody(status, body)
+ }
+ var out apiUploadsReply
+ if err := json.Unmarshal(body, &out); err != nil {
+ return apiUploadsReply{}, fmt.Errorf(storeUploadsText("cli.uploads.unreadable"), err)
+ }
+ return out, nil
+}
+
+// storeUploadsSet turns browser uploads on (with origins, none meaning the
+// app's hostnames) or off.
+func (s *apiSession) storeUploadsSet(ctx context.Context, a apiAcct, app string, enabled bool, origins []string) (apiUploadsReply, error) {
+ in := struct {
+ Enabled bool `json:"enabled"`
+ Origins []string `json:"origins,omitempty"`
+ }{enabled, origins}
+ return s.storeUploadsCall(ctx, a, app, in)
+}
+
+// storeUploadsStatus reads browser uploads' state and whether the bucket
+// still holds the rules the platform wrote.
+func (s *apiSession) storeUploadsStatus(ctx context.Context, a apiAcct, app string) (apiUploadsReply, error) {
+ return s.storeUploadsCall(ctx, a, app, nil)
+}
+
+// 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
+}
diff --git a/media_cli.go b/media_cli.go
index db84a008f..b921d75d8 100644
--- a/media_cli.go
+++ b/media_cli.go
@@ -8,14 +8,10 @@ package main
import (
"context"
- "encoding/json"
"errors"
"flag"
"fmt"
"io"
- "log"
- "net/http"
- "net/url"
"os"
"os/signal"
"sort"
@@ -80,116 +76,24 @@ const mediaPollErrors = 3
// 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.
+// stderr, exit 1. Its verbs return their errors to main (cliExitCode).
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) {
+ Children: []*clireg.Node{rawErr("convert", cust, runMediaConvert), rawErr("status", cust, runMediaStatus)},
+ FallbackErr: func(args, consumed []string) error {
fmt.Fprintf(os.Stderr, mediaUsage+"\n\n%s\n\n%s\n", docsCLIMedia, mediaUsageConvert+"\n"+mediaUsageStatus)
- os.Exit(1)
+ return exitCode(1)
},
}
}
-func runMediaConvert(args []string) {
+func runMediaConvert(args []string) error {
fs := flag.NewFlagSet("media convert", flag.ExitOnError)
app := appFlag(fs, "")
preset := fs.String("preset", "", mediaPresetHelp)
@@ -201,9 +105,12 @@ func runMediaConvert(args []string) {
pos, _ := parseInterspersed(fs, args)
if len(pos) != 1 {
fs.Usage()
- os.Exit(2)
+ return exitCode(2)
+ }
+ sess, acct, name, err := mediaSession(*consoleFlag, acctRaw, acctIDRaw, *app, mediaUsageConvert)
+ if err != nil {
+ return err
}
- sess, acct, name := mediaSession(*consoleFlag, acctRaw, acctIDRaw, *app, mediaUsageConvert)
body := map[string]string{"key": pos[0]}
if *preset != "" {
body["preset"] = *preset
@@ -212,17 +119,17 @@ func runMediaConvert(args []string) {
body["class"] = *class
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
- err := runMediaConvertWith(ctx, sess, acct, name, body, *wait, stdout)
+ 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)
+ if errors.Is(err, errMediaJobFailed) {
+ // The job's failed state and error are printed already: exit 1
+ // with no second message.
+ return exitCode(1)
}
+ return err
}
-func runMediaStatus(args []string) {
+func runMediaStatus(args []string) error {
fs := flag.NewFlagSet("media status", flag.ExitOnError)
app := appFlag(fs, "")
acctRaw, acctIDRaw, _ := accountFlags(fs)
@@ -231,25 +138,26 @@ func runMediaStatus(args []string) {
pos, _ := parseInterspersed(fs, args)
if len(pos) != 1 {
fs.Usage()
- os.Exit(2)
+ return exitCode(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)
+ sess, acct, name, err := mediaSession(*consoleFlag, acctRaw, acctIDRaw, *app, mediaUsageStatus)
+ if err != nil {
+ return err
}
+ return runMediaStatusWith(context.Background(), sess, acct, name, pos[0], stdout)
}
-func mediaSession(consoleFlag string, acctRaw, acctIDRaw *string, app, usage string) (*apiSession, apiAcct, string) {
+func mediaSession(consoleFlag string, acctRaw, acctIDRaw *string, app, usage string) (*apiSession, apiAcct, string, error) {
app = strings.TrimSpace(app)
if app != "" {
if err := validAppName(app); err != nil {
- log.Fatalf("media: %v", err)
+ return nil, apiAcct{}, "", fmt.Errorf("media: %w", err)
}
}
sess := requireStoreAPISession(consoleFlag)
printUsing(stdout, sess)
acct := resolvedAccount(sess, acctRaw, acctIDRaw)
- return sess, acct, resolvedApp(sess, acct, app, usage)
+ return sess, acct, resolvedApp(sess, acct, app, usage), nil
}
// runMediaConvertWith submits the conversion and prints the job; with wait
@@ -382,39 +290,33 @@ 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)
+ Children: []*clireg.Node{rawErr("status", clireg.Operator, runSystemMediaStatus)},
+ FallbackErr: func(args, _ []string) error {
+ systemUsage()
+ if len(args) > 0 && (args[0] == "help" || args[0] == "-h" || args[0] == "--help") {
+ return nil
}
+ return exitCode(2)
},
}
}
-func runSystemMediaStatus(args []string) {
+func runSystemMediaStatus(args []string) error {
fs := flag.NewFlagSet("system media status", flag.ExitOnError)
consoleFlag := consoleOption(fs, mediaSystemConsoleHelp)
fs.Usage = flagUsage(fs, mediaSystemUsage)
fs.Parse(args)
if fs.NArg() != 0 {
fs.Usage()
- os.Exit(2)
+ return exitCode(2)
}
sess := requireStoreAPISession(*consoleFlag)
st, err := sess.systemMediaStatus(context.Background())
if err != nil {
- log.Fatal(err)
+ return err
}
printSystemMedia(stdout, st)
+ return nil
}
// mediaCheckOrder is the classes in the order the deck prints them.
diff --git a/store_uploads.go b/store_uploads.go
index 2da5f1d69..482c23dc0 100644
--- a/store_uploads.go
+++ b/store_uploads.go
@@ -12,7 +12,6 @@ import (
"flag"
"fmt"
"io"
- "log"
"os"
"strings"
@@ -65,25 +64,25 @@ const (
)
// storeUploadsCommand is `carlos store uploads`: three raw leaves sharing
-// runStoreUploads. Bare or any other word is storeUploadsUsage on stderr,
-// exit 1.
+// runStoreUploads, which return their errors to main (cliExitCode). Bare
+// or any other word is storeUploadsUsage on stderr, exit 1.
func storeUploadsCommand() *clireg.Node {
const cust = clireg.Customer
leaf := func(verb string) *clireg.Node {
- return raw(verb, cust, func(args []string) { runStoreUploads(args, verb) })
+ return rawErr(verb, cust, func(args []string) error { return runStoreUploads(args, verb) })
}
return &clireg.Node{
Name: "uploads",
Audience: cust,
Children: []*clireg.Node{leaf("enable"), leaf("status"), leaf("disable")},
- Fallback: func(args, consumed []string) {
+ FallbackErr: func(args, consumed []string) error {
fmt.Fprint(os.Stderr, storeUploadsUsage)
- os.Exit(1)
+ return exitCode(1)
},
}
}
-func runStoreUploads(args []string, verb string) {
+func runStoreUploads(args []string, verb string) error {
fs := flag.NewFlagSet("store uploads "+verb, flag.ExitOnError)
app := appFlag(fs, storeUploadsText("cli.uploads.flag_app"))
var origins multiFlag
@@ -99,7 +98,7 @@ func runStoreUploads(args []string, verb string) {
usage := fmt.Sprintf(storeUploadsText("cli.uploads.usage_verb"), verb)
if name != "" {
if err := validAppName(name); err != nil {
- log.Fatalf("store uploads %s: %v", verb, err)
+ return fmt.Errorf("store uploads %s: %w", verb, err)
}
}
sess := requireStoreAPISession(*consoleFlag)
@@ -107,8 +106,9 @@ func runStoreUploads(args []string, verb string) {
acct := resolvedAccount(sess, acctRaw, acctIDRaw)
name = resolvedApp(sess, acct, name, usage)
if err := runStoreUploadsWith(context.Background(), sess, acct, name, verb, origins, stdout); err != nil {
- log.Fatalf("store uploads %s: %v", verb, err)
+ return fmt.Errorf("store uploads %s: %w", verb, err)
}
+ return nil
}
// runStoreUploadsWith calls the door for verb and prints its answer: