// Package carlosop is alta-adopt's CARLOS console client. It reads and // writes an app's config through carlos/platform 522 Plan 1's doors // (versions, digests, conditional writes and receipts; config-receipts // design §4), reads instance records, and restarts one host through the // narrowed restart door. It is never imported by the served `alta`. // // It holds one short-lived Admin credential, in memory only (Paul's Q1 // ruling, 2026-11-16). The token comes from a file descriptor, never the // environment or disk; it is never logged, and Close zeroes it. // // Nothing this package returns as an error carries the token, a config // value, a digest or a version: errors name the door, the HTTP status and // a fixed reason. The console's own error sentence is dropped, because it // can quote what it was sent. package carlosop import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/url" "strings" "sync" "time" ) // The errors callers act on. These are the only declarations; package // adopt reuses them rather than declaring its own. var ( // ErrVersionMismatch is a conditional write's 412: the layer was not at // the version sent, at the door's read or at its write. Nothing was // written. ErrVersionMismatch = errors.New("carlosop: the layer is not at the version sent, so nothing was written") // ErrNoConditional is a 400 to a conditional write: a console whose // store has no atomic conditional write refuses if_version this way. // Every Put is conditional, so every 400 to one reads as this. ErrNoConditional = errors.New("carlosop: the console refused the conditional write") // ErrNotFound is the console's 404: no such account, app, host or // record, which the console deliberately does not tell apart. ErrNotFound = errors.New("carlosop: not found") // ErrNoScopedRestart is a 404 from the narrowed restart door: a // console that predates it. Nothing was restarted, and nothing falls // back to the app-wide door. ErrNoScopedRestart = errors.New("carlosop: the console has no host-scoped restart") // ErrNoAnswer is a request that got no answer: it failed in transit, // timed out or was cancelled, or its answer could not be read. The // console may or may not have acted on it; only a reread can tell. ErrNoAnswer = errors.New("carlosop: no answer") // ErrMalformedAnswer is a 2xx answer that is not what the door // promises: unreadable, or a receipt that is absent, for another // bundle, or carries a malformed digest or version. The console did // answer, so this is a protocol failure, never a lost answer. ErrMalformedAnswer = errors.New("carlosop: malformed answer") // ErrNotSent is a Put refused before its request was sent, because // the read guarding it failed: nothing was written. ErrNotSent = errors.New("carlosop: PUT /config not sent") ) // StatusError is any other non-2xx answer, a redirect included. Door is // the method and path template ("GET /config"), never a value. type StatusError struct { Door string Code int } func (e *StatusError) Error() string { return fmt.Sprintf("carlosop: %s answered %d", e.Door, e.Code) } // Var is one variable of one stored layer. Value is set only for kind // "env"; a secret is its key, kind and digest. type Var struct{ Key, Kind, Value, Digest string } // Layer is one stored config bundle: "default", or a named environment. type Layer struct { Bundle, Version string Vars []Var } // EffectiveVar is one key of a host's merged config: From is the layer // whose value the host gets, Shadows the lower layers that also set it, // nearest first. No value: the effective view is compared by digest. type EffectiveVar struct { Key, Kind, Digest, From string Shadows []string } // Effective is GET /config/effective for one host. Layers maps "default" // (absent for an owned environment), "environment" (absent for a host // bound to none) and "overlay" to their versions. type Effective struct { Host, Environment string Owned bool Layers map[string]string Vars []EffectiveVar } // Receipt is a successful PUT's description of what it wrote (522 §4.6). // Others names other layers' versions either side of the write: the // default bundle's, for a write to a named environment. type Receipt struct { Bundle, VersionBefore, VersionAfter string Changed bool Set, Unset, UnsetAbsent []string Digests map[string]string Others map[string]struct{ Before, After string } } // Instance is the part of an instance record adoption compares. Move, // ReplicaAssignment and Seed are the record's JSON as stored, nil when // absent. // // The record's public_host is not read. It is the platform's display // name for the host under the apps domain (the account's namespace name // in place of its sqid, carlos/platform internal/console/canonical.go), // never a custom domain: an attached domain is a claim, read by Domains. type Instance struct { Host, Account, App, Slug, Environment, Channel, Region string CreatedAt time.Time RecordSeq uint64 Move, ReplicaAssignment, Seed json.RawMessage } // Domain is one row of an app's hostname claims, as GET /domains lists // them (`carlos domains list`): Host is served by the instance record // whose host is Route. State is the console's derived lifecycle word, // "live" when the host points at the platform and is served over HTTPS // with a current certificate; "" from a console that predates it. // Instances marks an instance catch-all's own row, and Via names the // catch-all a derived row came from: neither is a claim of its own. type Domain struct { Host, Route, State, Via string Instances bool } // PutRequest is one conditional write. Set holds plain values only; the // runner never sends a secret. type PutRequest struct { Environment string // "" = the default bundle Set map[string]string Unset []string IfVersion string } // RestartRoute is one route a restart addresses. type RestartRoute struct { Host, Environment, Unit string Hibernate bool } // Client is one console, one account (by sqid) and one Admin token. type Client struct { mu sync.Mutex base string baseErr error account string token []byte closed bool http *http.Client } // New builds a client. It takes token and does not copy it: Close zeroes // that slice in place, so the caller must not keep or reuse it. The token // is read from a file descriptor (Q1), never from the environment or disk. // // console must be https; plain http is admitted only to a loopback // address, for tests. func New(console, account string, token []byte) *Client { c := &Client{account: account, token: token, http: &http.Client{ Timeout: 60 * time.Second, // Never follow: a redirect is answered as the 3xx it is, so the // token is never sent to a second origin. CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, }} u, err := url.Parse(console) switch { case err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "": c.baseErr = errors.New("carlosop: the console address is not a plain https URL") case u.Scheme == "https": case u.Scheme == "http" && loopback(u.Hostname()): default: c.baseErr = errors.New("carlosop: the console must be https (plain http only to loopback)") } if c.baseErr == nil { c.base = strings.TrimRight(u.String(), "/") } return c } func loopback(host string) bool { if host == "localhost" { return true } ip := net.ParseIP(host) return ip != nil && ip.IsLoopback() } // Close zeroes the token and refuses every later call. Idempotent. A // request already in flight keeps the header it was built with. func (c *Client) Close() { c.mu.Lock() defer c.mu.Unlock() clear(c.token) c.closed = true c.http.CloseIdleConnections() } func (c *Client) bearer() (string, error) { c.mu.Lock() defer c.mu.Unlock() switch { case c.closed: return "", errors.New("carlosop: the client is closed") case c.baseErr != nil: return "", c.baseErr case len(c.token) == 0: return "", errors.New("carlosop: no token") case c.account == "": return "", errors.New("carlosop: no account") } return "Bearer " + string(c.token), nil } // do sends one request to path under the app; door is its fixed // template, for errors, and decodes a 2xx answer into out. Any other status is a // *StatusError. func (c *Client) do(ctx context.Context, method, app, door, path string, body, out any) error { auth, err := c.bearer() if err != nil { return err } if app == "" { return errors.New("carlosop: no app") } var rd io.Reader if body != nil { b, err := json.Marshal(body) if err != nil { return fmt.Errorf("carlosop: %s: could not encode the request", door) } rd = bytes.NewReader(b) } u := c.base + "/api/cli/apps/" + url.PathEscape(c.account) + "/" + url.PathEscape(app) + path req, err := http.NewRequestWithContext(ctx, method, u, rd) if err != nil { return fmt.Errorf("carlosop: %s: could not build the request", door) } req.Header.Set("Authorization", auth) req.Header.Set("Accept", "application/json") if body != nil { req.Header.Set("Content-Type", "application/json") } resp, err := c.http.Do(req) if err != nil { return transportError(door, err) } defer resp.Body.Close() raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) if err != nil { return fmt.Errorf("carlosop: %s: could not read the answer: %w", door, ErrNoAnswer) } if resp.StatusCode < 200 || resp.StatusCode > 299 { return &StatusError{Door: door, Code: resp.StatusCode} } if out != nil { // The decoder's own error can quote the answer; it is dropped. if json.Unmarshal(raw, out) != nil { return fmt.Errorf("carlosop: %s: unreadable answer: %w", door, ErrMalformedAnswer) } } 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: every // one is ErrNoAnswer, and the context's cancellation or deadline is // wrapped too, for errors.Is; a timeout is said as one. func transportError(door string, err error) error { var ne net.Error switch { case errors.Is(err, context.Canceled): return fmt.Errorf("carlosop: %s: %w: %w", door, ErrNoAnswer, context.Canceled) case errors.Is(err, context.DeadlineExceeded): return fmt.Errorf("carlosop: %s: %w: %w", door, ErrNoAnswer, context.DeadlineExceeded) case errors.As(err, &ne) && ne.Timeout(): return fmt.Errorf("carlosop: %s: %w: the request timed out", door, ErrNoAnswer) } return fmt.Errorf("carlosop: %s: %w: the request failed before an answer", door, ErrNoAnswer) } // 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 if errors.As(err, &se) { if e, ok := by[se.Code]; ok { return fmt.Errorf("%w (%s answered %d)", e, se.Door, se.Code) } } return err } var notFound = map[int]error{http.StatusNotFound: ErrNotFound} // malformed is ErrMalformedAnswer, saying which door and why. func malformed(door, why string) error { return fmt.Errorf("carlosop: %s answered %s: %w", door, why, ErrMalformedAnswer) } // Config reads one stored layer: the default bundle for env "", else the // named environment. An absent layer is version "none" with no vars. func (c *Client) Config(ctx context.Context, app, env string) (Layer, error) { const door = "GET /config" path := "/config" if env != "" { path += "?environment=" + url.QueryEscape(env) } var w struct { Bundle string `json:"bundle"` Version string `json:"version"` Vars []struct { Key string `json:"key"` Kind string `json:"kind"` Value *string `json:"value"` Digest string `json:"digest"` } `json:"vars"` } if err := c.do(ctx, http.MethodGet, app, door, path, nil, &w); err != nil { return Layer{}, as(err, notFound) } want := env if want == "" { want = "default" } if w.Bundle != want { return Layer{}, malformed(door, "another bundle") } if !validVersion(w.Version) { return Layer{}, malformed(door, "a malformed version") } l := Layer{Bundle: w.Bundle, Version: w.Version, Vars: make([]Var, 0, len(w.Vars))} seen := map[string]bool{} for _, v := range w.Vars { switch { case v.Key == "" || seen[v.Key]: return Layer{}, malformed(door, "an empty or repeated key") case v.Kind != "env" && v.Kind != "secret": return Layer{}, malformed(door, "an unknown kind") case v.Kind == "secret" && v.Value != nil: // Never hold a secret's plaintext, even if a console sent it. return Layer{}, malformed(door, "a secret with a value") case !validDigest(v.Digest): return Layer{}, malformed(door, "a malformed digest") } seen[v.Key] = true out := Var{Key: v.Key, Kind: v.Kind, Digest: v.Digest} if v.Value != nil { out.Value = *v.Value } l.Vars = append(l.Vars, out) } return l, nil } // Effective reads one host's merged config: each key's kind, digest, the // layer it comes from and the layers it shadows. Values are not read. func (c *Client) Effective(ctx context.Context, app, host string) (Effective, error) { const door = "GET /config/effective" if strings.TrimSpace(host) == "" { return Effective{}, errors.New("carlosop: Effective needs a host") } var w struct { Host string `json:"host"` Environment string `json:"environment"` Owned bool `json:"owned"` Layers map[string]struct { Name string `json:"name"` Version string `json:"version"` } `json:"layers"` Vars []struct { Key string `json:"key"` Kind string `json:"kind"` Digest string `json:"digest"` From string `json:"from"` Shadows []string `json:"shadows"` } `json:"vars"` } if err := c.do(ctx, http.MethodGet, app, door, "/config/effective?host="+url.QueryEscape(host), nil, &w); err != nil { return Effective{}, as(err, notFound) } if w.Host != host { return Effective{}, malformed(door, "another host") } e := Effective{Host: w.Host, Environment: w.Environment, Owned: w.Owned, Layers: map[string]string{}} for name, l := range w.Layers { if name != "default" && name != "environment" && name != "overlay" { return Effective{}, malformed(door, "an unknown layer") } if !validVersion(l.Version) { return Effective{}, malformed(door, "a malformed version") } e.Layers[name] = l.Version } _, hasDefault := e.Layers["default"] _, hasEnv := e.Layers["environment"] _, hasOverlay := e.Layers["overlay"] switch { case !hasOverlay: return Effective{}, malformed(door, "no overlay layer") case hasEnv != (w.Environment != "") || (hasEnv && w.Layers["environment"].Name != w.Environment): return Effective{}, malformed(door, "an environment layer that disagrees with the binding") case w.Owned == hasDefault: return Effective{}, malformed(door, "a default layer that disagrees with ownership") } seen := map[string]bool{} for _, v := range w.Vars { if v.Key == "" || seen[v.Key] || !validDigest(v.Digest) || (v.Kind != "env" && v.Kind != "secret") { return Effective{}, malformed(door, "a malformed var") } if _, ok := e.Layers[v.From]; !ok { return Effective{}, malformed(door, "a var from no listed layer") } for _, s := range v.Shadows { if _, ok := e.Layers[s]; !ok || s == v.From { return Effective{}, malformed(door, "a var shadowing no listed layer") } } seen[v.Key] = true e.Vars = append(e.Vars, EffectiveVar{Key: v.Key, Kind: v.Kind, Digest: v.Digest, From: v.From, Shadows: append([]string{}, v.Shadows...)}) } return e, nil } // Put makes one conditional write: Set's plain values and Unset's // removals in one request, if the layer is at IfVersion. It answers the // write's receipt. // // A 412 is ErrVersionMismatch and a 400 is ErrNoConditional; nothing was // written for either. A failed guarding read is ErrNotSent. No answer at // all is ErrNoAnswer: the write may have landed. A 200 that carries no // well-formed receipt for this bundle is ErrMalformedAnswer: the console // answered, and what it wrote is unknown. 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 { case r.IfVersion == "": return Receipt{}, errors.New("carlosop: every config write is conditional; IfVersion is required") case !validVersion(r.IfVersion): return Receipt{}, errors.New("carlosop: IfVersion is not a layer version") 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("%w: the layer's read failed or carried no version, so the console may not honour if_version: %w", ErrNotSent, err) } body := map[string]any{"if_version": r.IfVersion} if r.Environment != "" { body["environment"] = r.Environment } if len(r.Set) > 0 { set := make(map[string]any, len(r.Set)) for k, v := range r.Set { set[k] = map[string]string{"kind": "env", "value": v} } body["set"] = set } if len(r.Unset) > 0 { body["unset"] = r.Unset } var w struct { Receipt *struct { Bundle string `json:"bundle"` VersionBefore string `json:"version_before"` VersionAfter string `json:"version_after"` Changed bool `json:"changed"` Set []string `json:"set"` Unset []string `json:"unset"` UnsetAbsent []string `json:"unset_absent"` Digests map[string]string `json:"digests"` Others map[string]struct { Before string `json:"before"` After string `json:"after"` } `json:"others"` } `json:"receipt"` } if err := c.do(ctx, http.MethodPut, app, door, "/config", body, &w); err != nil { return Receipt{}, as(err, map[int]error{ http.StatusPreconditionFailed: ErrVersionMismatch, http.StatusBadRequest: ErrNoConditional, http.StatusNotFound: ErrNotFound, }) } rc := w.Receipt want := r.Environment if want == "" { want = "default" } switch { case rc == nil: return Receipt{}, malformed(door, "no receipt") case rc.Bundle != want: return Receipt{}, malformed(door, "a receipt for another bundle") case !validVersion(rc.VersionBefore) || !validVersion(rc.VersionAfter): return Receipt{}, malformed(door, "a malformed version") } for _, d := range rc.Digests { if !validDigest(d) { return Receipt{}, malformed(door, "a malformed digest") } } out := Receipt{Bundle: rc.Bundle, VersionBefore: rc.VersionBefore, VersionAfter: rc.VersionAfter, Changed: rc.Changed, Set: rc.Set, Unset: rc.Unset, UnsetAbsent: rc.UnsetAbsent, Digests: rc.Digests} if len(rc.Others) > 0 { out.Others = map[string]struct{ Before, After string }{} for k, p := range rc.Others { // A side the console could not read is empty, and compares // unequal to any version. if (p.Before != "" && !validVersion(p.Before)) || (p.After != "" && !validVersion(p.After)) { return Receipt{}, malformed(door, "a malformed version") } out.Others[k] = struct{ Before, After string }{p.Before, p.After} } } return out, nil } type wireInstance struct { Host string `json:"host"` Account string `json:"account"` App string `json:"app"` Slug string `json:"slug"` Environment string `json:"environment"` Channel string `json:"channel"` Region string `json:"region"` CreatedAt time.Time `json:"created_at"` RecordSeq uint64 `json:"record_seq"` Move json.RawMessage `json:"move"` ReplicaAssignment json.RawMessage `json:"replica_assignment"` Seed json.RawMessage `json:"seed"` } func rawOrNil(m json.RawMessage) json.RawMessage { if len(m) == 0 || string(m) == "null" { return nil } return append(json.RawMessage{}, m...) } func (c *Client) instance(door, app string, w wireInstance) (Instance, error) { if w.Host == "" || w.App != app || w.Account != c.account { return Instance{}, malformed(door, "a record of another app or account") } return Instance{Host: w.Host, Account: w.Account, App: w.App, Slug: w.Slug, Environment: w.Environment, Channel: w.Channel, Region: w.Region, CreatedAt: w.CreatedAt, RecordSeq: w.RecordSeq, Move: rawOrNil(w.Move), ReplicaAssignment: rawOrNil(w.ReplicaAssignment), Seed: rawOrNil(w.Seed)}, nil } // maxPages bounds the instance list's cursor walk. const maxPages = 100 // Instances lists every record of app, following the list's cursor. A // list the console says is truncated is refused: a record left out could // be the one that would inherit a key. func (c *Client) Instances(ctx context.Context, app string) ([]Instance, error) { const door = "GET /instances" var out []Instance cursor := "" for range maxPages { path := "/instances" if cursor != "" { path += "?cursor=" + url.QueryEscape(cursor) } var w struct { // 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 { in, err := c.instance(door, app, wi) if err != nil { return nil, err } out = append(out, in) } if w.NextCursor == "" { return out, nil } if w.NextCursor == cursor { return nil, malformed(door, "a cursor that does not move") } cursor = w.NextCursor } return nil, malformed(door, "more pages than the walk allows") } // Instance reads one record. An unknown host is ErrNotFound. func (c *Client) Instance(ctx context.Context, app, host string) (Instance, error) { const door = "GET /instances/{host}" if strings.TrimSpace(host) == "" { return Instance{}, errors.New("carlosop: Instance needs a host") } var w wireInstance if err := c.do(ctx, http.MethodGet, app, door, "/instances/"+url.PathEscape(host), nil, &w); err != nil { return Instance{}, as(err, notFound) } if w.Host != host { return Instance{}, malformed(door, "another host") } return c.instance(door, app, w) } // Domains lists app's hostname claims through the door `carlos domains // list` reads (carlos/platform internal/console/apidomains.go, // handleAPIDomainList). Its route admits the Publish and Instance roles // and so, as every route does, Admin: the same credential that lists the // instances reads it. // // The answer decides which record is canonical, so it is read field by // field rather than by json.Unmarshal, which lets the last of two repeated // fields win, matches names in any case and reads null as empty. The list // is required; a row needs a host and a route; state, via and instances // may be left out, never null. Any other shape is ErrMalformedAnswer. func (c *Client) Domains(ctx context.Context, app string) ([]Domain, error) { const door = "GET /domains" var raw json.RawMessage if err := c.do(ctx, http.MethodGet, app, door, "/domains", nil, &raw); err != nil { return nil, as(err, notFound) } top, ok := strictFields(raw, "domains") if !ok { return nil, malformed(door, "a repeated or ambiguous field") } var rows []json.RawMessage if json.Unmarshal(top["domains"], &rows) != nil || rows == nil { return nil, malformed(door, "no domain list") } out := make([]Domain, 0, len(rows)) for _, row := range rows { f, ok := strictFields(row, "host", "route", "state", "via", "instances") if !ok { return nil, malformed(door, "a repeated or ambiguous field") } var d Domain _, hasRoute := f["route"] if !hasRoute || !optional(f, "host", &d.Host) || !optional(f, "route", &d.Route) || !optional(f, "state", &d.State) || !optional(f, "via", &d.Via) || !optional(f, "instances", &d.Instances) { return nil, malformed(door, "a malformed row") } if d.Host == "" { return nil, malformed(door, "a row with no host") } out = append(out, d) } return out, nil } // strictFields splits one JSON object, already known to be valid JSON, // into its fields. It answers false for anything but an object, for a // field repeated, and for a field that is one of the read names in // another case. func strictFields(raw []byte, read ...string) (map[string]json.RawMessage, bool) { dec := json.NewDecoder(bytes.NewReader(raw)) if t, err := dec.Token(); err != nil || t != json.Delim('{') { return nil, false } out := map[string]json.RawMessage{} for dec.More() { t, err := dec.Token() key, isKey := t.(string) if err != nil || !isKey { return nil, false } if _, repeated := out[key]; repeated { return nil, false } for _, name := range read { if key != name && strings.EqualFold(key, name) { return nil, false } } var v json.RawMessage if dec.Decode(&v) != nil { return nil, false } out[key] = v } return out, true } // optional decodes field name into dst when it is present. It answers // false for a null or a value of another type. func optional[T any](f map[string]json.RawMessage, name string, dst *T) bool { v, ok := f[name] if !ok { return true } var p *T if json.Unmarshal(v, &p) != nil || p == nil { return false } *dst = *p return true } // RestartHost asks the narrowed restart door to cycle exactly host, or // with dryRun to say what it would cycle. It never calls the app-wide // door: a 404 is ErrNoScopedRestart (a console that predates the narrowed // door) and nothing falls back. An empty host is refused here, since the // narrowed door reads no selector as the whole app. // // Only adopt.RestartCanonical calls this. func (c *Client) RestartHost(ctx context.Context, app, host string, dryRun bool) ([]RestartRoute, error) { const door = "POST /restart/scope" if strings.TrimSpace(host) == "" || host != strings.TrimSpace(host) { return nil, errors.New("carlosop: a restart names exactly one host") } var w struct { Scope struct { Kind string `json:"kind"` Value string `json:"value"` } `json:"scope"` DryRun bool `json:"dry_run"` Requested bool `json:"requested"` Routes []struct { Host string `json:"host"` Environment string `json:"environment"` Unit string `json:"unit"` Hibernate bool `json:"hibernate"` } `json:"routes"` } body := map[string]any{"host": host, "dry_run": dryRun} if err := c.do(ctx, http.MethodPost, app, door, "/restart/scope", body, &w); err != nil { return nil, as(err, map[int]error{http.StatusNotFound: ErrNoScopedRestart}) } switch { case w.Scope.Kind != "host" || w.Scope.Value != host: return nil, malformed(door, "a scope other than the host") case w.DryRun != dryRun || w.Requested == dryRun: return nil, malformed(door, "a dry run or request it was not asked for") } out := make([]RestartRoute, 0, len(w.Routes)) for _, r := range w.Routes { out = append(out, RestartRoute{Host: r.Host, Environment: r.Environment, Unit: r.Unit, Hibernate: r.Hibernate}) } return out, nil }