oficina / alta Public

Clone
git clone https://amadan.net/oficina/alta

Plain git — no account needed to clone.

Download

Download this file

1// Package carlosop is alta-adopt's CARLOS console client. It reads and
2// writes an app's config through carlos/platform 522 Plan 1's doors
3// (versions, digests, conditional writes and receipts; config-receipts
4// design §4), reads instance records, and restarts one host through the
5// narrowed restart door. It is never imported by the served `alta`.
6//
7// It holds one short-lived Admin credential, in memory only (Paul's Q1
8// ruling, 2026-11-16). The token comes from a file descriptor, never the
9// environment or disk; it is never logged, and Close zeroes it.
10//
11// Nothing this package returns as an error carries the token, a config
12// value, a digest or a version: errors name the door, the HTTP status and
13// a fixed reason. The console's own error sentence is dropped, because it
14// can quote what it was sent.
15package carlosop
16
17import (
18 "bytes"
19 "context"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "io"
24 "net"
25 "net/http"
26 "net/url"
27 "strings"
28 "sync"
29 "time"
30)
31
32// The errors callers act on. These are the only declarations; package
33// adopt reuses them rather than declaring its own.
34var (
35 // ErrVersionMismatch is a conditional write's 412: the layer was not at
36 // the version sent, at the door's read or at its write. Nothing was
37 // written.
38 ErrVersionMismatch = errors.New("carlosop: the layer is not at the version sent, so nothing was written")
39 // ErrNoConditional is a 400 to a conditional write: a console whose
40 // store has no atomic conditional write refuses if_version this way.
41 // Every Put is conditional, so every 400 to one reads as this.
42 ErrNoConditional = errors.New("carlosop: the console refused the conditional write")
43 // ErrNotFound is the console's 404: no such account, app, host or
44 // record, which the console deliberately does not tell apart.
45 ErrNotFound = errors.New("carlosop: not found")
46 // ErrNoScopedRestart is a 404 from the narrowed restart door: a
47 // console that predates it. Nothing was restarted, and nothing falls
48 // back to the app-wide door.
49 ErrNoScopedRestart = errors.New("carlosop: the console has no host-scoped restart")
50 // ErrNoAnswer is a request that got no answer: it failed in transit,
51 // timed out or was cancelled, or its answer could not be read. The
52 // console may or may not have acted on it; only a reread can tell.
53 ErrNoAnswer = errors.New("carlosop: no answer")
54 // ErrMalformedAnswer is a 2xx answer that is not what the door
55 // promises: unreadable, or a receipt that is absent, for another
56 // bundle, or carries a malformed digest or version. The console did
57 // answer, so this is a protocol failure, never a lost answer.
58 ErrMalformedAnswer = errors.New("carlosop: malformed answer")
59 // ErrNotSent is a Put refused before its request was sent, because
60 // the read guarding it failed: nothing was written.
61 ErrNotSent = errors.New("carlosop: PUT /config not sent")
62)
63
64// StatusError is any other non-2xx answer, a redirect included. Door is
65// the method and path template ("GET /config"), never a value.
66type StatusError struct {
67 Door string
68 Code int
69}
70
71func (e *StatusError) Error() string {
72 return fmt.Sprintf("carlosop: %s answered %d", e.Door, e.Code)
73}
74
75// Var is one variable of one stored layer. Value is set only for kind
76// "env"; a secret is its key, kind and digest.
77type Var struct{ Key, Kind, Value, Digest string }
78
79// Layer is one stored config bundle: "default", or a named environment.
80type Layer struct {
81 Bundle, Version string
82 Vars []Var
83}
84
85// EffectiveVar is one key of a host's merged config: From is the layer
86// whose value the host gets, Shadows the lower layers that also set it,
87// nearest first. No value: the effective view is compared by digest.
88type EffectiveVar struct {
89 Key, Kind, Digest, From string
90 Shadows []string
91}
92
93// Effective is GET /config/effective for one host. Layers maps "default"
94// (absent for an owned environment), "environment" (absent for a host
95// bound to none) and "overlay" to their versions.
96type Effective struct {
97 Host, Environment string
98 Owned bool
99 Layers map[string]string
100 Vars []EffectiveVar
101}
102
103// Receipt is a successful PUT's description of what it wrote (522 §4.6).
104// Others names other layers' versions either side of the write: the
105// default bundle's, for a write to a named environment.
106type Receipt struct {
107 Bundle, VersionBefore, VersionAfter string
108 Changed bool
109 Set, Unset, UnsetAbsent []string
110 Digests map[string]string
111 Others map[string]struct{ Before, After string }
112}
113
114// Instance is the part of an instance record adoption compares. Move,
115// ReplicaAssignment and Seed are the record's JSON as stored, nil when
116// absent.
117//
118// The record's public_host is not read. It is the platform's display
119// name for the host under the apps domain (the account's namespace name
120// in place of its sqid, carlos/platform internal/console/canonical.go),
121// never a custom domain: an attached domain is a claim, read by Domains.
122type Instance struct {
123 Host, Account, App, Slug, Environment, Channel, Region string
124 CreatedAt time.Time
125 RecordSeq uint64
126 Move, ReplicaAssignment, Seed json.RawMessage
127}
128
129// Domain is one row of an app's hostname claims, as GET /domains lists
130// them (`carlos domains list`): Host is served by the instance record
131// whose host is Route. State is the console's derived lifecycle word,
132// "live" when the host points at the platform and is served over HTTPS
133// with a current certificate; "" from a console that predates it.
134// Instances marks an instance catch-all's own row, and Via names the
135// catch-all a derived row came from: neither is a claim of its own.
136type Domain struct {
137 Host, Route, State, Via string
138 Instances bool
139}
140
141// PutRequest is one conditional write. Set holds plain values only; the
142// runner never sends a secret.
143type PutRequest struct {
144 Environment string // "" = the default bundle
145 Set map[string]string
146 Unset []string
147 IfVersion string
148}
149
150// RestartRoute is one route a restart addresses.
151type RestartRoute struct {
152 Host, Environment, Unit string
153 Hibernate bool
154}
155
156// Client is one console, one account (by sqid) and one Admin token.
157type Client struct {
158 mu sync.Mutex
159 base string
160 baseErr error
161 account string
162 token []byte
163 closed bool
164 http *http.Client
165}
166
167// New builds a client. It takes token and does not copy it: Close zeroes
168// that slice in place, so the caller must not keep or reuse it. The token
169// is read from a file descriptor (Q1), never from the environment or disk.
170//
171// console must be https; plain http is admitted only to a loopback
172// address, for tests.
173func New(console, account string, token []byte) *Client {
174 c := &Client{account: account, token: token, http: &http.Client{
175 Timeout: 60 * time.Second,
176 // Never follow: a redirect is answered as the 3xx it is, so the
177 // token is never sent to a second origin.
178 CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
179 }}
180 u, err := url.Parse(console)
181 switch {
182 case err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "":
183 c.baseErr = errors.New("carlosop: the console address is not a plain https URL")
184 case u.Scheme == "https":
185 case u.Scheme == "http" && loopback(u.Hostname()):
186 default:
187 c.baseErr = errors.New("carlosop: the console must be https (plain http only to loopback)")
188 }
189 if c.baseErr == nil {
190 c.base = strings.TrimRight(u.String(), "/")
191 }
192 return c
193}
194
195func loopback(host string) bool {
196 if host == "localhost" {
197 return true
198 }
199 ip := net.ParseIP(host)
200 return ip != nil && ip.IsLoopback()
201}
202
203// Close zeroes the token and refuses every later call. Idempotent. A
204// request already in flight keeps the header it was built with.
205func (c *Client) Close() {
206 c.mu.Lock()
207 defer c.mu.Unlock()
208 clear(c.token)
209 c.closed = true
210 c.http.CloseIdleConnections()
211}
212
213func (c *Client) bearer() (string, error) {
214 c.mu.Lock()
215 defer c.mu.Unlock()
216 switch {
217 case c.closed:
218 return "", errors.New("carlosop: the client is closed")
219 case c.baseErr != nil:
220 return "", c.baseErr
221 case len(c.token) == 0:
222 return "", errors.New("carlosop: no token")
223 case c.account == "":
224 return "", errors.New("carlosop: no account")
225 }
226 return "Bearer " + string(c.token), nil
227}
228
229// do sends one request to path under the app; door is its fixed
230// template, for errors, and decodes a 2xx answer into out. Any other status is a
231// *StatusError.
232func (c *Client) do(ctx context.Context, method, app, door, path string, body, out any) error {
233 auth, err := c.bearer()
234 if err != nil {
235 return err
236 }
237 if app == "" {
238 return errors.New("carlosop: no app")
239 }
240 var rd io.Reader
241 if body != nil {
242 b, err := json.Marshal(body)
243 if err != nil {
244 return fmt.Errorf("carlosop: %s: could not encode the request", door)
245 }
246 rd = bytes.NewReader(b)
247 }
248 u := c.base + "/api/cli/apps/" + url.PathEscape(c.account) + "/" + url.PathEscape(app) + path
249 req, err := http.NewRequestWithContext(ctx, method, u, rd)
250 if err != nil {
251 return fmt.Errorf("carlosop: %s: could not build the request", door)
252 }
253 req.Header.Set("Authorization", auth)
254 req.Header.Set("Accept", "application/json")
255 if body != nil {
256 req.Header.Set("Content-Type", "application/json")
257 }
258 resp, err := c.http.Do(req)
259 if err != nil {
260 return transportError(door, err)
261 }
262 defer resp.Body.Close()
263 raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
264 if err != nil {
265 return fmt.Errorf("carlosop: %s: could not read the answer: %w", door, ErrNoAnswer)
266 }
267 if resp.StatusCode < 200 || resp.StatusCode > 299 {
268 return &StatusError{Door: door, Code: resp.StatusCode}
269 }
270 if out != nil {
271 // The decoder's own error can quote the answer; it is dropped.
272 if json.Unmarshal(raw, out) != nil {
273 return fmt.Errorf("carlosop: %s: unreadable answer: %w", door, ErrMalformedAnswer)
274 }
275 }
276 return nil
277}
278
279// transportError replaces a failed request's own text, which can quote
280// what the console sent (a malformed redirect Location, say), with a fixed
281// sentence. It keeps only the classifications a caller acts on: every
282// one is ErrNoAnswer, and the context's cancellation or deadline is
283// wrapped too, for errors.Is; a timeout is said as one.
284func transportError(door string, err error) error {
285 var ne net.Error
286 switch {
287 case errors.Is(err, context.Canceled):
288 return fmt.Errorf("carlosop: %s: %w: %w", door, ErrNoAnswer, context.Canceled)
289 case errors.Is(err, context.DeadlineExceeded):
290 return fmt.Errorf("carlosop: %s: %w: %w", door, ErrNoAnswer, context.DeadlineExceeded)
291 case errors.As(err, &ne) && ne.Timeout():
292 return fmt.Errorf("carlosop: %s: %w: the request timed out", door, ErrNoAnswer)
293 }
294 return fmt.Errorf("carlosop: %s: %w: the request failed before an answer", door, ErrNoAnswer)
295}
296
297// as maps a status to the error callers act on, wrapping the status.
298func as(err error, by map[int]error) error {
299 var se *StatusError
300 if errors.As(err, &se) {
301 if e, ok := by[se.Code]; ok {
302 return fmt.Errorf("%w (%s answered %d)", e, se.Door, se.Code)
303 }
304 }
305 return err
306}
307
308var notFound = map[int]error{http.StatusNotFound: ErrNotFound}
309
310// malformed is ErrMalformedAnswer, saying which door and why.
311func malformed(door, why string) error {
312 return fmt.Errorf("carlosop: %s answered %s: %w", door, why, ErrMalformedAnswer)
313}
314
315// Config reads one stored layer: the default bundle for env "", else the
316// named environment. An absent layer is version "none" with no vars.
317func (c *Client) Config(ctx context.Context, app, env string) (Layer, error) {
318 const door = "GET /config"
319 path := "/config"
320 if env != "" {
321 path += "?environment=" + url.QueryEscape(env)
322 }
323 var w struct {
324 Bundle string `json:"bundle"`
325 Version string `json:"version"`
326 Vars []struct {
327 Key string `json:"key"`
328 Kind string `json:"kind"`
329 Value *string `json:"value"`
330 Digest string `json:"digest"`
331 } `json:"vars"`
332 }
333 if err := c.do(ctx, http.MethodGet, app, door, path, nil, &w); err != nil {
334 return Layer{}, as(err, notFound)
335 }
336 want := env
337 if want == "" {
338 want = "default"
339 }
340 if w.Bundle != want {
341 return Layer{}, malformed(door, "another bundle")
342 }
343 if !validVersion(w.Version) {
344 return Layer{}, malformed(door, "a malformed version")
345 }
346 l := Layer{Bundle: w.Bundle, Version: w.Version, Vars: make([]Var, 0, len(w.Vars))}
347 seen := map[string]bool{}
348 for _, v := range w.Vars {
349 switch {
350 case v.Key == "" || seen[v.Key]:
351 return Layer{}, malformed(door, "an empty or repeated key")
352 case v.Kind != "env" && v.Kind != "secret":
353 return Layer{}, malformed(door, "an unknown kind")
354 case v.Kind == "secret" && v.Value != nil:
355 // Never hold a secret's plaintext, even if a console sent it.
356 return Layer{}, malformed(door, "a secret with a value")
357 case !validDigest(v.Digest):
358 return Layer{}, malformed(door, "a malformed digest")
359 }
360 seen[v.Key] = true
361 out := Var{Key: v.Key, Kind: v.Kind, Digest: v.Digest}
362 if v.Value != nil {
363 out.Value = *v.Value
364 }
365 l.Vars = append(l.Vars, out)
366 }
367 return l, nil
368}
369
370// Effective reads one host's merged config: each key's kind, digest, the
371// layer it comes from and the layers it shadows. Values are not read.
372func (c *Client) Effective(ctx context.Context, app, host string) (Effective, error) {
373 const door = "GET /config/effective"
374 if strings.TrimSpace(host) == "" {
375 return Effective{}, errors.New("carlosop: Effective needs a host")
376 }
377 var w struct {
378 Host string `json:"host"`
379 Environment string `json:"environment"`
380 Owned bool `json:"owned"`
381 Layers map[string]struct {
382 Name string `json:"name"`
383 Version string `json:"version"`
384 } `json:"layers"`
385 Vars []struct {
386 Key string `json:"key"`
387 Kind string `json:"kind"`
388 Digest string `json:"digest"`
389 From string `json:"from"`
390 Shadows []string `json:"shadows"`
391 } `json:"vars"`
392 }
393 if err := c.do(ctx, http.MethodGet, app, door, "/config/effective?host="+url.QueryEscape(host), nil, &w); err != nil {
394 return Effective{}, as(err, notFound)
395 }
396 if w.Host != host {
397 return Effective{}, malformed(door, "another host")
398 }
399 e := Effective{Host: w.Host, Environment: w.Environment, Owned: w.Owned, Layers: map[string]string{}}
400 for name, l := range w.Layers {
401 if name != "default" && name != "environment" && name != "overlay" {
402 return Effective{}, malformed(door, "an unknown layer")
403 }
404 if !validVersion(l.Version) {
405 return Effective{}, malformed(door, "a malformed version")
406 }
407 e.Layers[name] = l.Version
408 }
409 _, hasDefault := e.Layers["default"]
410 _, hasEnv := e.Layers["environment"]
411 _, hasOverlay := e.Layers["overlay"]
412 switch {
413 case !hasOverlay:
414 return Effective{}, malformed(door, "no overlay layer")
415 case hasEnv != (w.Environment != "") || (hasEnv && w.Layers["environment"].Name != w.Environment):
416 return Effective{}, malformed(door, "an environment layer that disagrees with the binding")
417 case w.Owned == hasDefault:
418 return Effective{}, malformed(door, "a default layer that disagrees with ownership")
419 }
420 seen := map[string]bool{}
421 for _, v := range w.Vars {
422 if v.Key == "" || seen[v.Key] || !validDigest(v.Digest) || (v.Kind != "env" && v.Kind != "secret") {
423 return Effective{}, malformed(door, "a malformed var")
424 }
425 if _, ok := e.Layers[v.From]; !ok {
426 return Effective{}, malformed(door, "a var from no listed layer")
427 }
428 for _, s := range v.Shadows {
429 if _, ok := e.Layers[s]; !ok || s == v.From {
430 return Effective{}, malformed(door, "a var shadowing no listed layer")
431 }
432 }
433 seen[v.Key] = true
434 e.Vars = append(e.Vars, EffectiveVar{Key: v.Key, Kind: v.Kind, Digest: v.Digest, From: v.From, Shadows: append([]string{}, v.Shadows...)})
435 }
436 return e, nil
437}
438
439// Put makes one conditional write: Set's plain values and Unset's
440// removals in one request, if the layer is at IfVersion. It answers the
441// write's receipt.
442//
443// A 412 is ErrVersionMismatch and a 400 is ErrNoConditional; nothing was
444// written for either. A failed guarding read is ErrNotSent. No answer at
445// all is ErrNoAnswer: the write may have landed. A 200 that carries no
446// well-formed receipt for this bundle is ErrMalformedAnswer: the console
447// answered, and what it wrote is unknown. IfVersion is required, travels as one JSON string in
448// the body (there is no If-Match), and is never combined with
449// exec_delivery.
450//
451// Immediately before the PUT, Put reads the same layer and refuses, with
452// nothing sent, unless that read carries a well-formed version. A console
453// older than 522 Plan 1 (carlos v0.38.0) answers no version, and would
454// ignore the unknown if_version member and write unconditionally; the
455// carlos CLI guards its own conditional writes the same way.
456func (c *Client) Put(ctx context.Context, app string, r PutRequest) (Receipt, error) {
457 const door = "PUT /config"
458 switch {
459 case r.IfVersion == "":
460 return Receipt{}, errors.New("carlosop: every config write is conditional; IfVersion is required")
461 case !validVersion(r.IfVersion):
462 return Receipt{}, errors.New("carlosop: IfVersion is not a layer version")
463 case len(r.Set) == 0 && len(r.Unset) == 0:
464 return Receipt{}, errors.New("carlosop: nothing to write")
465 }
466 if _, empty := r.Set[""]; empty {
467 return Receipt{}, errors.New("carlosop: a key is empty, or in both set and unset")
468 }
469 for _, k := range r.Unset {
470 if _, both := r.Set[k]; both || k == "" {
471 return Receipt{}, errors.New("carlosop: a key is empty, or in both set and unset")
472 }
473 }
474 if _, err := c.Config(ctx, app, r.Environment); err != nil {
475 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)
476 }
477 body := map[string]any{"if_version": r.IfVersion}
478 if r.Environment != "" {
479 body["environment"] = r.Environment
480 }
481 if len(r.Set) > 0 {
482 set := make(map[string]any, len(r.Set))
483 for k, v := range r.Set {
484 set[k] = map[string]string{"kind": "env", "value": v}
485 }
486 body["set"] = set
487 }
488 if len(r.Unset) > 0 {
489 body["unset"] = r.Unset
490 }
491 var w struct {
492 Receipt *struct {
493 Bundle string `json:"bundle"`
494 VersionBefore string `json:"version_before"`
495 VersionAfter string `json:"version_after"`
496 Changed bool `json:"changed"`
497 Set []string `json:"set"`
498 Unset []string `json:"unset"`
499 UnsetAbsent []string `json:"unset_absent"`
500 Digests map[string]string `json:"digests"`
501 Others map[string]struct {
502 Before string `json:"before"`
503 After string `json:"after"`
504 } `json:"others"`
505 } `json:"receipt"`
506 }
507 if err := c.do(ctx, http.MethodPut, app, door, "/config", body, &w); err != nil {
508 return Receipt{}, as(err, map[int]error{
509 http.StatusPreconditionFailed: ErrVersionMismatch,
510 http.StatusBadRequest: ErrNoConditional,
511 http.StatusNotFound: ErrNotFound,
512 })
513 }
514 rc := w.Receipt
515 want := r.Environment
516 if want == "" {
517 want = "default"
518 }
519 switch {
520 case rc == nil:
521 return Receipt{}, malformed(door, "no receipt")
522 case rc.Bundle != want:
523 return Receipt{}, malformed(door, "a receipt for another bundle")
524 case !validVersion(rc.VersionBefore) || !validVersion(rc.VersionAfter):
525 return Receipt{}, malformed(door, "a malformed version")
526 }
527 for _, d := range rc.Digests {
528 if !validDigest(d) {
529 return Receipt{}, malformed(door, "a malformed digest")
530 }
531 }
532 out := Receipt{Bundle: rc.Bundle, VersionBefore: rc.VersionBefore, VersionAfter: rc.VersionAfter, Changed: rc.Changed,
533 Set: rc.Set, Unset: rc.Unset, UnsetAbsent: rc.UnsetAbsent, Digests: rc.Digests}
534 if len(rc.Others) > 0 {
535 out.Others = map[string]struct{ Before, After string }{}
536 for k, p := range rc.Others {
537 // A side the console could not read is empty, and compares
538 // unequal to any version.
539 if (p.Before != "" && !validVersion(p.Before)) || (p.After != "" && !validVersion(p.After)) {
540 return Receipt{}, malformed(door, "a malformed version")
541 }
542 out.Others[k] = struct{ Before, After string }{p.Before, p.After}
543 }
544 }
545 return out, nil
546}
547
548type wireInstance struct {
549 Host string `json:"host"`
550 Account string `json:"account"`
551 App string `json:"app"`
552 Slug string `json:"slug"`
553 Environment string `json:"environment"`
554 Channel string `json:"channel"`
555 Region string `json:"region"`
556 CreatedAt time.Time `json:"created_at"`
557 RecordSeq uint64 `json:"record_seq"`
558 Move json.RawMessage `json:"move"`
559 ReplicaAssignment json.RawMessage `json:"replica_assignment"`
560 Seed json.RawMessage `json:"seed"`
561}
562
563func rawOrNil(m json.RawMessage) json.RawMessage {
564 if len(m) == 0 || string(m) == "null" {
565 return nil
566 }
567 return append(json.RawMessage{}, m...)
568}
569
570func (c *Client) instance(door, app string, w wireInstance) (Instance, error) {
571 if w.Host == "" || w.App != app || w.Account != c.account {
572 return Instance{}, malformed(door, "a record of another app or account")
573 }
574 return Instance{Host: w.Host, Account: w.Account, App: w.App, Slug: w.Slug,
575 Environment: w.Environment, Channel: w.Channel, Region: w.Region, CreatedAt: w.CreatedAt, RecordSeq: w.RecordSeq,
576 Move: rawOrNil(w.Move), ReplicaAssignment: rawOrNil(w.ReplicaAssignment), Seed: rawOrNil(w.Seed)}, nil
577}
578
579// maxPages bounds the instance list's cursor walk.
580const maxPages = 100
581
582// Instances lists every record of app, following the list's cursor. A
583// list the console says is truncated is refused: a record left out could
584// be the one that would inherit a key.
585func (c *Client) Instances(ctx context.Context, app string) ([]Instance, error) {
586 const door = "GET /instances"
587 var out []Instance
588 cursor := ""
589 for range maxPages {
590 path := "/instances"
591 if cursor != "" {
592 path += "?cursor=" + url.QueryEscape(cursor)
593 }
594 var w struct {
595 // A pointer, so an answer with no list, or a null one, is
596 // told apart from an empty list: it is refused rather than
597 // read as "no other instances".
598 Instances *[]wireInstance `json:"instances"`
599 Truncated bool `json:"truncated"`
600 NextCursor string `json:"next_cursor"`
601 }
602 if err := c.do(ctx, http.MethodGet, app, door, path, nil, &w); err != nil {
603 return nil, as(err, notFound)
604 }
605 if w.Instances == nil {
606 return nil, malformed(door, "no instance list")
607 }
608 if w.Truncated {
609 return nil, malformed(door, "a truncated list")
610 }
611 for _, wi := range *w.Instances {
612 in, err := c.instance(door, app, wi)
613 if err != nil {
614 return nil, err
615 }
616 out = append(out, in)
617 }
618 if w.NextCursor == "" {
619 return out, nil
620 }
621 if w.NextCursor == cursor {
622 return nil, malformed(door, "a cursor that does not move")
623 }
624 cursor = w.NextCursor
625 }
626 return nil, malformed(door, "more pages than the walk allows")
627}
628
629// Instance reads one record. An unknown host is ErrNotFound.
630func (c *Client) Instance(ctx context.Context, app, host string) (Instance, error) {
631 const door = "GET /instances/{host}"
632 if strings.TrimSpace(host) == "" {
633 return Instance{}, errors.New("carlosop: Instance needs a host")
634 }
635 var w wireInstance
636 if err := c.do(ctx, http.MethodGet, app, door, "/instances/"+url.PathEscape(host), nil, &w); err != nil {
637 return Instance{}, as(err, notFound)
638 }
639 if w.Host != host {
640 return Instance{}, malformed(door, "another host")
641 }
642 return c.instance(door, app, w)
643}
644
645// Domains lists app's hostname claims through the door `carlos domains
646// list` reads (carlos/platform internal/console/apidomains.go,
647// handleAPIDomainList). Its route admits the Publish and Instance roles
648// and so, as every route does, Admin: the same credential that lists the
649// instances reads it.
650//
651// The answer decides which record is canonical, so it is read field by
652// field rather than by json.Unmarshal, which lets the last of two repeated
653// fields win, matches names in any case and reads null as empty. The list
654// is required; a row needs a host and a route; state, via and instances
655// may be left out, never null. Any other shape is ErrMalformedAnswer.
656func (c *Client) Domains(ctx context.Context, app string) ([]Domain, error) {
657 const door = "GET /domains"
658 var raw json.RawMessage
659 if err := c.do(ctx, http.MethodGet, app, door, "/domains", nil, &raw); err != nil {
660 return nil, as(err, notFound)
661 }
662 top, ok := strictFields(raw, "domains")
663 if !ok {
664 return nil, malformed(door, "a repeated or ambiguous field")
665 }
666 var rows []json.RawMessage
667 if json.Unmarshal(top["domains"], &rows) != nil || rows == nil {
668 return nil, malformed(door, "no domain list")
669 }
670 out := make([]Domain, 0, len(rows))
671 for _, row := range rows {
672 f, ok := strictFields(row, "host", "route", "state", "via", "instances")
673 if !ok {
674 return nil, malformed(door, "a repeated or ambiguous field")
675 }
676 var d Domain
677 _, hasRoute := f["route"]
678 if !hasRoute || !optional(f, "host", &d.Host) || !optional(f, "route", &d.Route) || !optional(f, "state", &d.State) ||
679 !optional(f, "via", &d.Via) || !optional(f, "instances", &d.Instances) {
680 return nil, malformed(door, "a malformed row")
681 }
682 if d.Host == "" {
683 return nil, malformed(door, "a row with no host")
684 }
685 out = append(out, d)
686 }
687 return out, nil
688}
689
690// strictFields splits one JSON object, already known to be valid JSON,
691// into its fields. It answers false for anything but an object, for a
692// field repeated, and for a field that is one of the read names in
693// another case.
694func strictFields(raw []byte, read ...string) (map[string]json.RawMessage, bool) {
695 dec := json.NewDecoder(bytes.NewReader(raw))
696 if t, err := dec.Token(); err != nil || t != json.Delim('{') {
697 return nil, false
698 }
699 out := map[string]json.RawMessage{}
700 for dec.More() {
701 t, err := dec.Token()
702 key, isKey := t.(string)
703 if err != nil || !isKey {
704 return nil, false
705 }
706 if _, repeated := out[key]; repeated {
707 return nil, false
708 }
709 for _, name := range read {
710 if key != name && strings.EqualFold(key, name) {
711 return nil, false
712 }
713 }
714 var v json.RawMessage
715 if dec.Decode(&v) != nil {
716 return nil, false
717 }
718 out[key] = v
719 }
720 return out, true
721}
722
723// optional decodes field name into dst when it is present. It answers
724// false for a null or a value of another type.
725func optional[T any](f map[string]json.RawMessage, name string, dst *T) bool {
726 v, ok := f[name]
727 if !ok {
728 return true
729 }
730 var p *T
731 if json.Unmarshal(v, &p) != nil || p == nil {
732 return false
733 }
734 *dst = *p
735 return true
736}
737
738// RestartHost asks the narrowed restart door to cycle exactly host, or
739// with dryRun to say what it would cycle. It never calls the app-wide
740// door: a 404 is ErrNoScopedRestart (a console that predates the narrowed
741// door) and nothing falls back. An empty host is refused here, since the
742// narrowed door reads no selector as the whole app.
743//
744// Only adopt.RestartCanonical calls this.
745func (c *Client) RestartHost(ctx context.Context, app, host string, dryRun bool) ([]RestartRoute, error) {
746 const door = "POST /restart/scope"
747 if strings.TrimSpace(host) == "" || host != strings.TrimSpace(host) {
748 return nil, errors.New("carlosop: a restart names exactly one host")
749 }
750 var w struct {
751 Scope struct {
752 Kind string `json:"kind"`
753 Value string `json:"value"`
754 } `json:"scope"`
755 DryRun bool `json:"dry_run"`
756 Requested bool `json:"requested"`
757 Routes []struct {
758 Host string `json:"host"`
759 Environment string `json:"environment"`
760 Unit string `json:"unit"`
761 Hibernate bool `json:"hibernate"`
762 } `json:"routes"`
763 }
764 body := map[string]any{"host": host, "dry_run": dryRun}
765 if err := c.do(ctx, http.MethodPost, app, door, "/restart/scope", body, &w); err != nil {
766 return nil, as(err, map[int]error{http.StatusNotFound: ErrNoScopedRestart})
767 }
768 switch {
769 case w.Scope.Kind != "host" || w.Scope.Value != host:
770 return nil, malformed(door, "a scope other than the host")
771 case w.DryRun != dryRun || w.Requested == dryRun:
772 return nil, malformed(door, "a dry run or request it was not asked for")
773 }
774 out := make([]RestartRoute, 0, len(w.Routes))
775 for _, r := range w.Routes {
776 out = append(out, RestartRoute{Host: r.Host, Environment: r.Environment, Unit: r.Unit, Hibernate: r.Hibernate})
777 }
778 return out, nil
779}
780