oficina / alta Public

carlosop: fixed transport errors; require the list; Put reads version

Astra's Task 3 review, round 1:
- A failed request's error is now a fixed sentence. The Go client's text
  quotes a malformed redirect Location, which could carry a value. Only
  the context's cancellation or deadline and a timeout are kept.
- Instances refuses an answer whose instance list is missing or null,
  rather than reading it as "no neighbours".
- Put reads the layer just before the PUT and sends nothing unless the
  read carries a version. A pre-522 console would ignore if_version
  and write unconditionally.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev ee7067da86c48348734de7c04f7110ef950535af parent 60f4299
2 files changed, +137 −27
  • carlosop/client.go +41 −10
  • carlosop/client_test.go +96 −17
diff --git a/carlosop/client.go b/carlosop/client.go
index 1b5fd02..e42d5a6 100644
--- a/carlosop/client.go
+++ b/carlosop/client.go
@@ -228,9 +228,7 @@ func (c *Client) do(ctx context.Context, method, app, door, path string, body, o
}
resp, err := c.http.Do(req)
if err != nil {
- // A *url.Error names the URL (account, app, host) and the cause;
- // the token is a header and never part of it.
- return fmt.Errorf("carlosop: %s: %w", door, err)
+ return transportError(door, err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
@@ -249,6 +247,24 @@ func (c *Client) do(ctx context.Context, method, app, door, path string, body, o
return nil
}
+// transportError replaces a failed request's own text, which can quote
+// what the console sent (a malformed redirect Location, say), with a fixed
+// sentence. It keeps only the classifications a caller acts on: the
+// context's cancellation or deadline (wrapped, for errors.Is) and a
+// timeout.
+func transportError(door string, err error) error {
+ var ne net.Error
+ switch {
+ case errors.Is(err, context.Canceled):
+ return fmt.Errorf("carlosop: %s: %w", door, context.Canceled)
+ case errors.Is(err, context.DeadlineExceeded):
+ return fmt.Errorf("carlosop: %s: %w", door, context.DeadlineExceeded)
+ case errors.As(err, &ne) && ne.Timeout():
+ return fmt.Errorf("carlosop: %s: the request timed out", door)
+ }
+ return fmt.Errorf("carlosop: %s: the request failed before an answer", door)
+}
+
// as maps a status to the error callers act on, wrapping the status.
func as(err error, by map[int]error) error {
var se *StatusError
@@ -398,6 +414,12 @@ func (c *Client) Effective(ctx context.Context, app, host string) (Effective, er
// written for either. IfVersion is required, travels as one JSON string in
// the body (there is no If-Match), and is never combined with
// exec_delivery.
+//
+// Immediately before the PUT, Put reads the same layer and refuses, with
+// nothing sent, unless that read carries a well-formed version. A console
+// older than 522 Plan 1 (carlos v0.38.0) answers no version, and would
+// ignore the unknown if_version member and write unconditionally; the
+// carlos CLI guards its own conditional writes the same way.
func (c *Client) Put(ctx context.Context, app string, r PutRequest) (Receipt, error) {
const door = "PUT /config"
switch {
@@ -408,11 +430,17 @@ func (c *Client) Put(ctx context.Context, app string, r PutRequest) (Receipt, er
case len(r.Set) == 0 && len(r.Unset) == 0:
return Receipt{}, errors.New("carlosop: nothing to write")
}
+ if _, empty := r.Set[""]; empty {
+ return Receipt{}, errors.New("carlosop: a key is empty, or in both set and unset")
+ }
for _, k := range r.Unset {
if _, both := r.Set[k]; both || k == "" {
return Receipt{}, errors.New("carlosop: a key is empty, or in both set and unset")
}
}
+ if _, err := c.Config(ctx, app, r.Environment); err != nil {
+ return Receipt{}, fmt.Errorf("carlosop: PUT /config not sent: the layer's read failed or carried no version, so the console may not honour if_version: %w", err)
+ }
body := map[string]any{"if_version": r.IfVersion}
if r.Environment != "" {
body["environment"] = r.Environment
@@ -420,9 +448,6 @@ func (c *Client) Put(ctx context.Context, app string, r PutRequest) (Receipt, er
if len(r.Set) > 0 {
set := make(map[string]any, len(r.Set))
for k, v := range r.Set {
- if k == "" {
- return Receipt{}, errors.New("carlosop: a key is empty, or in both set and unset")
- }
set[k] = map[string]string{"kind": "env", "value": v}
}
body["set"] = set
@@ -535,17 +560,23 @@ func (c *Client) Instances(ctx context.Context, app string) ([]Instance, error)
path += "?cursor=" + url.QueryEscape(cursor)
}
var w struct {
- Instances []wireInstance `json:"instances"`
- Truncated bool `json:"truncated"`
- NextCursor string `json:"next_cursor"`
+ // A pointer, so an answer with no list, or a null one, is
+ // told apart from an empty list: it is refused rather than
+ // read as "no other instances".
+ Instances *[]wireInstance `json:"instances"`
+ Truncated bool `json:"truncated"`
+ NextCursor string `json:"next_cursor"`
}
if err := c.do(ctx, http.MethodGet, app, door, path, nil, &w); err != nil {
return nil, as(err, notFound)
}
+ if w.Instances == nil {
+ return nil, malformed(door, "no instance list")
+ }
if w.Truncated {
return nil, malformed(door, "a truncated list")
}
- for _, wi := range w.Instances {
+ for _, wi := range *w.Instances {
in, err := c.instance(door, app, wi)
if err != nil {
return nil, err
diff --git a/carlosop/client_test.go b/carlosop/client_test.go
index 5d781cd..37d3ad3 100644
--- a/carlosop/client_test.go
+++ b/carlosop/client_test.go
@@ -70,6 +70,10 @@ const d1 = "vd1:3333333333333333333333333333333333333333333333333333333333333333
func TestPutSendsIfVersionInBodyOnly(t *testing.T) {
srv, log := rawConsole(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodGet {
+ writeJSON(w, 200, map[string]any{"bundle": "default", "version": v1, "vars": []any{}})
+ return
+ }
writeJSON(w, 200, map[string]any{"result": "ok", "removed": 0, "receipt": map[string]any{
"bundle": "default", "version_before": v1, "version_after": v2, "changed": true,
"set": []string{"DOCS_AGENT_ISSUER"}, "unset": []string{}, "unset_absent": []string{},
@@ -93,10 +97,11 @@ func TestPutSendsIfVersionInBodyOnly(t *testing.T) {
if rc.VersionBefore != v1 || rc.VersionAfter != v2 || !rc.Changed || !slices.Equal(rc.Set, []string{"DOCS_AGENT_ISSUER"}) || rc.Digests["DOCS_AGENT_ISSUER"] != d1 {
t.Fatalf("receipt not decoded field for field")
}
- if len(*log) != 1 {
- t.Fatalf("want one request, got %d", len(*log))
+ // The layer's read first (it must carry a version), then the write.
+ if len(*log) != 2 || (*log)[0].Method != http.MethodGet || (*log)[0].Path != "/api/cli/apps/bds/docs/config" || (*log)[0].Query != "" {
+ t.Fatalf("want GET /config then PUT /config, got %d requests", len(*log))
}
- got := (*log)[0]
+ got := (*log)[1]
if got.Method != http.MethodPut || got.Path != "/api/cli/apps/bds/docs/config" || got.Query != "" {
t.Fatalf("wrong door: %s %s?%s", got.Method, got.Path, got.Query)
}
@@ -294,6 +299,31 @@ func TestErrorsCarryNoTokenOrValue(t *testing.T) {
}
}
}
+ // A redirect whose Location cannot be parsed: the client's own error
+ // quotes the Location, which here carries the token and a value.
+ srv, _ := rawConsole(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Location", "/%zz"+token+value)
+ w.WriteHeader(http.StatusFound)
+ })
+ rc := carlosop.New(srv.URL, acct, []byte(token))
+ for i, call := range []func() error{
+ func() error { _, err := rc.Config(ctx, "docs", ""); return err },
+ func() error { _, err := rc.Instances(ctx, "docs"); return err },
+ func() error { _, err := rc.RestartHost(ctx, "docs", "oficina-docs.bds.oncarlos.com", true); return err },
+ } {
+ if err := call(); err == nil || strings.Contains(err.Error(), token) || strings.Contains(err.Error(), value) {
+ t.Fatalf("malformed redirect call %d: error is nil or carries the token or a value", i)
+ }
+ }
+ rc.Close()
+ // A cancelled context stays recognisable.
+ cctx, cancel := context.WithCancel(ctx)
+ cancel()
+ cc := carlosop.New(srv.URL, acct, []byte(token))
+ if _, err := cc.Config(cctx, "docs", ""); !errors.Is(err, context.Canceled) {
+ t.Fatalf("a cancelled request lost its classification: %v", err)
+ }
+ cc.Close()
// A transport failure, too: the token is never in a URL.
c := carlosop.New("http://127.0.0.1:1", acct, []byte(token))
defer c.Close()
@@ -354,6 +384,7 @@ func TestReadsRefuseMalformedAnswers(t *testing.T) {
_, err := c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{"K": "v"}, IfVersion: v1})
return err
}
+ layerAnswer := map[string]any{"bundle": "default", "version": v1, "vars": []any{}}
receipt := map[string]any{"bundle": "default", "version_before": v1, "version_after": v2, "changed": true,
"set": []string{"K"}, "unset": []string{}, "unset_absent": []string{}, "digests": map[string]string{"K": d1}}
layers := map[string]any{"default": map[string]any{"version": v1}, "overlay": map[string]any{"version": "none"}}
@@ -361,27 +392,36 @@ func TestReadsRefuseMalformedAnswers(t *testing.T) {
name string
call func(*carlosop.Client) error
answer any
+ get any // a Put's read of the layer, when the case is a Put
}{
- {"bad version", config, map[string]any{"bundle": "default", "version": "cv1:abc", "vars": []any{}}},
- {"bad digest", config, map[string]any{"bundle": "default", "version": v1, "vars": []any{map[string]any{"key": "A", "kind": "env", "value": "x", "digest": "vd1:XYZ"}}}},
- {"secret value", config, map[string]any{"bundle": "default", "version": v1, "vars": []any{map[string]any{"key": "A", "kind": "secret", "value": "x", "digest": d1}}}},
- {"other bundle", config, map[string]any{"bundle": "beta", "version": v1, "vars": []any{}}},
- {"effective other host", effective, map[string]any{"host": "x.bds.oncarlos.com", "layers": layers, "vars": []any{}}},
- {"effective from unlisted layer", effective, map[string]any{"host": host, "layers": layers, "vars": []any{map[string]any{"key": "A", "kind": "env", "digest": d1, "from": "environment", "shadows": []string{}}}}},
- {"truncated list", instances, map[string]any{"instances": []any{}, "truncated": true}},
- {"list row of another app", instances, map[string]any{"instances": []any{map[string]any{"host": host, "app": "sheets", "account": acct}}}},
- {"record of another account", instance, map[string]any{"host": host, "app": "docs", "account": "zzz"}},
- {"restart of the whole app", restart, map[string]any{"scope": map[string]any{"kind": "app", "value": ""}, "dry_run": true, "routes": []any{}}},
- {"put with no receipt", put, map[string]any{"result": "ok", "removed": 0}},
+ {"bad version", config, map[string]any{"bundle": "default", "version": "cv1:abc", "vars": []any{}}, nil},
+ {"bad digest", config, map[string]any{"bundle": "default", "version": v1, "vars": []any{map[string]any{"key": "A", "kind": "env", "value": "x", "digest": "vd1:XYZ"}}}, nil},
+ {"secret value", config, map[string]any{"bundle": "default", "version": v1, "vars": []any{map[string]any{"key": "A", "kind": "secret", "value": "x", "digest": d1}}}, nil},
+ {"other bundle", config, map[string]any{"bundle": "beta", "version": v1, "vars": []any{}}, nil},
+ {"effective other host", effective, map[string]any{"host": "x.bds.oncarlos.com", "layers": layers, "vars": []any{}}, nil},
+ {"effective from unlisted layer", effective, map[string]any{"host": host, "layers": layers, "vars": []any{map[string]any{"key": "A", "kind": "env", "digest": d1, "from": "environment", "shadows": []string{}}}}, nil},
+ {"truncated list", instances, map[string]any{"instances": []any{}, "truncated": true}, nil},
+ {"list row of another app", instances, map[string]any{"instances": []any{map[string]any{"host": host, "app": "sheets", "account": acct}}}, nil},
+ {"record of another account", instance, map[string]any{"host": host, "app": "docs", "account": "zzz"}, nil},
+ {"restart of the whole app", restart, map[string]any{"scope": map[string]any{"kind": "app", "value": ""}, "dry_run": true, "routes": []any{}}, nil},
+ {"instance list missing", instances, map[string]any{"total": 0}, nil},
+ {"instance list null", instances, map[string]any{"instances": nil, "total": 0}, nil},
+ {"put with no receipt", put, map[string]any{"result": "ok", "removed": 0}, layerAnswer},
{"put receipt for another bundle", put, map[string]any{"result": "ok", "receipt": func() map[string]any {
r := maps.Clone(receipt)
r["bundle"] = "beta"
return r
- }()}},
- {"restart requested on a dry run", restart, map[string]any{"scope": map[string]any{"kind": "host", "value": host}, "dry_run": true, "requested": true, "routes": []any{}}},
+ }()}, layerAnswer},
+ {"restart requested on a dry run", restart, map[string]any{"scope": map[string]any{"kind": "host", "value": host}, "dry_run": true, "requested": true, "routes": []any{}}, nil},
}
for _, tc := range cases {
- srv, _ := rawConsole(t, func(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, tc.answer) })
+ srv, _ := rawConsole(t, func(w http.ResponseWriter, r *http.Request) {
+ if tc.get != nil && r.Method == http.MethodGet {
+ writeJSON(w, 200, tc.get)
+ return
+ }
+ writeJSON(w, 200, tc.answer)
+ })
c := carlosop.New(srv.URL, acct, []byte("svc_token"))
if err := tc.call(c); err == nil {
t.Fatalf("%s: accepted", tc.name)
@@ -471,3 +511,42 @@ func TestFakeLostAnswerLandsAndResealMovesDigest(t *testing.T) {
t.Fatalf("the write behind a lost answer did not land")
}
}
+
+func TestInstancesAcceptsAnEmptyList(t *testing.T) {
+ srv, _ := rawConsole(t, func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(w, 200, map[string]any{"instances": []any{}, "truncated": false, "total": 0, "next_cursor": ""})
+ })
+ c := carlosop.New(srv.URL, acct, []byte("svc_token"))
+ defer c.Close()
+ got, err := c.Instances(ctx, "docs")
+ if err != nil || len(got) != 0 {
+ t.Fatalf("an empty list: %d, %v", len(got), err)
+ }
+}
+
+// A console older than 522 Plan 1 answers its read with no version, and
+// would ignore if_version and write unconditionally: the PUT is never sent.
+func TestPutRefusedWhenConsoleAnswersNoVersion(t *testing.T) {
+ for name, layer := range map[string]map[string]any{
+ "no version": {"bundle": "default", "vars": []any{}},
+ "empty version": {"bundle": "default", "version": "", "vars": []any{}},
+ } {
+ srv, log := rawConsole(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodGet {
+ writeJSON(w, 200, layer)
+ return
+ }
+ writeJSON(w, 200, map[string]any{"result": "ok", "removed": 0})
+ })
+ c := carlosop.New(srv.URL, acct, []byte("svc_token"))
+ if _, err := c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{"DOCS_AGENT_TEAM": "tsqid"}, IfVersion: v1}); err == nil {
+ t.Fatalf("%s: Put against a console without versions was not refused", name)
+ }
+ for _, r := range *log {
+ if r.Method != http.MethodGet {
+ t.Fatalf("%s: a %s was sent to a console without versions", name, r.Method)
+ }
+ }
+ c.Close()
+ }
+}