oficina / alta Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package fakecarlos is an in-memory CARLOS console as an account's Admin
2// credential meets it through carlos/platform 522 Plan 1 (config-receipts
3// design §4) and the narrowed restart door (internal/console/
4// apirestartscope.go). It keeps each app's layers as stored bytes, so a
5// layer's `cv1:` version is a hash of exactly what is stored and a var's
6// `vd1:` digest is §4.3's, a secret's over its envelope:
7//
8// - the default bundle, apps/<acct>/<app>/config.json;
9// - named environments, standalone when owned by a scope;
10// - per-host instance overlays, written by the platform only.
11//
12// A host resolves default, then its environment, then its overlay; an
13// owned environment never folds the default in. Instance records are the
14// routes the restart door resolves.
15//
16// Hostname claims (AttachDomain) are listed as GET /domains lists them:
17// the canonical name of an app is a claim routed to one of its records,
18// never a field of the record.
19//
20// Hooks for adverse tests: BeforePut, LoseNextAnswer, SetSecret,
21// PlatformWrite, NoConditional, FailRestart, NoScopedRestart, and the
22// counters RestartCount and AppWideRestarts.
23package fakecarlos
24
25import (
26 "bytes"
27 "crypto/rand"
28 "crypto/sha256"
29 "encoding/base64"
30 "encoding/hex"
31 "encoding/json"
32 "io"
33 "net/http"
34 "net/http/httptest"
35 "regexp"
36 "sort"
37 "strconv"
38 "strings"
39 "sync"
40
41 "amadan.net/oficina/alta/carlosop"
42)
43
44// Var is one stored var, the four fields 522's digest covers.
45type Var struct {
46 Kind string `json:"kind"`
47 Value string `json:"value,omitempty"`
48 Envelope string `json:"envelope,omitempty"`
49 SealedTo string `json:"sealed_to,omitempty"`
50}
51
52// manifest is a stored layer's shape. It marshals deterministically
53// (MarshalIndent sorts map keys), as the platform's does.
54type manifest struct {
55 Schema int `json:"schema"`
56 App string `json:"app"`
57 OwnerScope string `json:"owner_scope,omitempty"`
58 Vars map[string]Var `json:"vars"`
59}
60
61type app struct {
62 def []byte // nil: absent
63 envs map[string][]byte // name -> stored bytes
64 overlays map[string][]byte // host -> stored bytes
65 recs map[string]carlosop.Instance
66 domains map[string]domain // host -> claim
67}
68
69// domain is one hostname claim: host served by the record at route.
70type domain struct{ route, state string }
71
72// Fake is the console.
73type Fake struct {
74 mu sync.Mutex
75 account string
76 token string
77 apps map[string]*app
78 srv *httptest.Server
79
80 // BeforePut runs on each PUT /config before the door reads the layer,
81 // outside the fake's lock, so it may call PlatformWrite or SetSecret:
82 // a platform writer landing between the caller's read and the write.
83 BeforePut func(app string)
84 // DuringDryRun runs on each dry run of POST /restart/scope, outside
85 // the fake's lock: a change landing after the caller decided to ask.
86 DuringDryRun func(app string)
87 // PageSize, when set, pages GET /instances by that many rows.
88 PageSize int
89
90 lose bool
91 noCond bool
92 noScope bool
93 failRestart int
94 failRead map[string]int // door -> status
95 restarts map[string]int
96 appWide int
97 requests []string
98}
99
100// New builds a console for account (a sqid) with one Admin token.
101func New(account string) *Fake {
102 b := make([]byte, 24)
103 _, _ = rand.Read(b)
104 f := &Fake{account: account, token: "svc_" + base64.RawURLEncoding.EncodeToString(b), apps: map[string]*app{}, restarts: map[string]int{}}
105 f.srv = httptest.NewServer(http.HandlerFunc(f.serve))
106 return f
107}
108
109func (f *Fake) Close() { f.srv.Close() }
110func (f *Fake) URL() string { return f.srv.URL }
111
112// Token is a fresh copy of the Admin token, for carlosop.New (which zeroes
113// what it is given on Close).
114func (f *Fake) Token() []byte { return []byte(f.token) }
115
116func (f *Fake) app(name string) *app {
117 a := f.apps[name]
118 if a == nil {
119 a = &app{envs: map[string][]byte{}, overlays: map[string][]byte{}, recs: map[string]carlosop.Instance{}, domains: map[string]domain{}}
120 f.apps[name] = a
121 }
122 return a
123}
124
125func decode(raw []byte, appName string) manifest {
126 m := manifest{Schema: 1, App: appName}
127 if raw != nil {
128 _ = json.Unmarshal(raw, &m)
129 }
130 if m.Vars == nil {
131 m.Vars = map[string]Var{}
132 }
133 return m
134}
135
136func encode(m manifest) []byte {
137 b, _ := json.MarshalIndent(m, "", " ")
138 return b
139}
140
141// Version is 522's cv1: over the stored bytes; "none" for an absent layer.
142func Version(raw []byte) string {
143 if raw == nil {
144 return "none"
145 }
146 s := sha256.Sum256(raw)
147 return "cv1:" + hex.EncodeToString(s[:])
148}
149
150// Digest is 522 §4.3's vd1: over a var's four stored fields.
151func Digest(v Var) string {
152 h := sha256.New()
153 for i, s := range []string{"carlos.config.var.v1", v.Kind, v.Value, v.Envelope, v.SealedTo} {
154 if i > 0 {
155 h.Write([]byte{0})
156 }
157 h.Write([]byte(s))
158 }
159 return "vd1:" + hex.EncodeToString(h.Sum(nil))
160}
161
162// layer is the stored bytes of env ("" = default); nil when absent.
163func (a *app) layer(env string) []byte {
164 if env == "" {
165 return a.def
166 }
167 return a.envs[env]
168}
169
170func (a *app) store(env string, raw []byte) {
171 if env == "" {
172 a.def = raw
173 } else {
174 a.envs[env] = raw
175 }
176}
177
178func (f *Fake) write(appName, env, key string, v Var) {
179 a := f.app(appName)
180 m := decode(a.layer(env), appName)
181 m.Vars[key] = v
182 a.store(env, encode(m))
183}
184
185// SetVar seeds a plain var into a bundle (env "" = default), creating it.
186func (f *Fake) SetVar(appName, env, key, value string) {
187 f.mu.Lock()
188 defer f.mu.Unlock()
189 f.write(appName, env, key, Var{Kind: "env", Value: value})
190}
191
192// PlatformWrite is a platform writer (mail, relay, scan, storage) setting
193// a plain var in a bundle: it moves the bundle's version like any write.
194func (f *Fake) PlatformWrite(appName, env, key, value string) { f.SetVar(appName, env, key, value) }
195
196// SetSecret seals key afresh into a bundle: a new random envelope, so a
197// new digest, whatever the plaintext. The fake holds no plaintext.
198func (f *Fake) SetSecret(appName, env, key string) {
199 b := make([]byte, 32)
200 _, _ = rand.Read(b)
201 f.mu.Lock()
202 defer f.mu.Unlock()
203 f.write(appName, env, key, Var{Kind: "secret", Envelope: base64.StdEncoding.EncodeToString(b), SealedTo: "fp-test"})
204}
205
206// Unset removes key from a bundle, as a person's or a platform's write.
207func (f *Fake) Unset(appName, env, key string) {
208 f.mu.Lock()
209 defer f.mu.Unlock()
210 a := f.app(appName)
211 m := decode(a.layer(env), appName)
212 delete(m.Vars, key)
213 a.store(env, encode(m))
214}
215
216// Own marks a named environment as owned by scope: standalone, never
217// folding the default in. Creates it if absent.
218func (f *Fake) Own(appName, env, scope string) {
219 f.mu.Lock()
220 defer f.mu.Unlock()
221 a := f.app(appName)
222 m := decode(a.layer(env), appName)
223 m.OwnerScope = scope
224 a.store(env, encode(m))
225}
226
227// SetOverlay is the platform's instance overlay for host.
228func (f *Fake) SetOverlay(appName, host, key, value string) {
229 f.mu.Lock()
230 defer f.mu.Unlock()
231 a := f.app(appName)
232 m := decode(a.overlays[host], appName)
233 m.Vars[key] = Var{Kind: "env", Value: value}
234 a.overlays[host] = encode(m)
235}
236
237// AddInstance stores a record; in.App names the app, and the record is
238// one route of it on this console's box.
239func (f *Fake) AddInstance(in carlosop.Instance) {
240 f.mu.Lock()
241 defer f.mu.Unlock()
242 if in.Account == "" {
243 in.Account = f.account
244 }
245 f.app(in.App).recs[in.Host] = in
246}
247
248// AttachDomain claims host for appName, served by the record at route,
249// in state (the console's derived word: "live", "pending-dns",
250// "unverified" and so on). Claims are keyed by host, as the platform's
251// are: attaching host again re-points it. Nothing checks that route is
252// a record, since the platform's list does not either.
253func (f *Fake) AttachDomain(appName, host, route, state string) {
254 f.mu.Lock()
255 defer f.mu.Unlock()
256 f.app(appName).domains[host] = domain{route: route, state: state}
257}
258
259// DetachDomain drops appName's claim on host.
260func (f *Fake) DetachDomain(appName, host string) {
261 f.mu.Lock()
262 defer f.mu.Unlock()
263 delete(f.app(appName).domains, host)
264}
265
266// Layer is a copy of a bundle's vars and its version; ok is false when the
267// bundle is absent.
268func (f *Fake) Layer(appName, env string) (map[string]Var, string, bool) {
269 f.mu.Lock()
270 defer f.mu.Unlock()
271 raw := f.app(appName).layer(env)
272 m := decode(raw, appName)
273 return m.Vars, Version(raw), raw != nil
274}
275
276// LoseNextAnswer applies the next PUT /config and then drops the
277// connection without an answer.
278func (f *Fake) LoseNextAnswer() { f.mu.Lock(); f.lose = true; f.mu.Unlock() }
279
280// NoConditional makes the console one whose store has no atomic
281// conditional write: if_version is refused with 400 before any read.
282func (f *Fake) NoConditional() { f.mu.Lock(); f.noCond = true; f.mu.Unlock() }
283
284// NoScopedRestart makes the console predate the narrowed restart door:
285// POST /restart/scope is a 404.
286func (f *Fake) NoScopedRestart() { f.mu.Lock(); f.noScope = true; f.mu.Unlock() }
287
288// FailRestart makes every POST /restart/scope answer status, with nothing
289// restarted; 0 restores it.
290func (f *Fake) FailRestart(status int) { f.mu.Lock(); f.failRestart = status; f.mu.Unlock() }
291
292// FailRead makes every GET of door ("/domains", "/instances") answer
293// status.
294func (f *Fake) FailRead(door string, status int) {
295 f.mu.Lock()
296 defer f.mu.Unlock()
297 if f.failRead == nil {
298 f.failRead = map[string]int{}
299 }
300 f.failRead[door] = status
301}
302
303// RestartCount is how many narrowed restarts were requested for host.
304func (f *Fake) RestartCount(host string) int {
305 f.mu.Lock()
306 defer f.mu.Unlock()
307 return f.restarts[host]
308}
309
310// AppWideRestarts is how many times the app-wide POST /restart was called.
311func (f *Fake) AppWideRestarts() int {
312 f.mu.Lock()
313 defer f.mu.Unlock()
314 return f.appWide
315}
316
317// Requests is every authenticated request as "METHOD /door", in order.
318func (f *Fake) Requests() []string {
319 f.mu.Lock()
320 defer f.mu.Unlock()
321 return append([]string{}, f.requests...)
322}
323
324// ---- the doors ----
325
326var pathRE = regexp.MustCompile(`^/api/cli/apps/([^/]+)/([^/]+)(/.*)$`)
327
328func writeJSON(w http.ResponseWriter, status int, v any) {
329 w.Header().Set("Content-Type", "application/json")
330 w.WriteHeader(status)
331 _ = json.NewEncoder(w).Encode(v)
332}
333
334func refuse(w http.ResponseWriter, status int, msg string) {
335 writeJSON(w, status, map[string]string{"error": msg})
336}
337
338func (f *Fake) serve(w http.ResponseWriter, r *http.Request) {
339 m := pathRE.FindStringSubmatch(r.URL.Path)
340 if m == nil {
341 http.NotFound(w, r)
342 return
343 }
344 account, appName, rest := m[1], m[2], m[3]
345 if r.Header.Get("Authorization") != "Bearer "+f.token {
346 refuse(w, 401, "not signed in")
347 return
348 }
349 door := rest
350 if strings.HasPrefix(rest, "/instances/") {
351 door = "/instances/{host}"
352 }
353 if r.Method == http.MethodPut && rest == "/config" && f.BeforePut != nil {
354 f.BeforePut(appName)
355 }
356 if r.Method == http.MethodPost && rest == "/restart/scope" && f.DuringDryRun != nil {
357 body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
358 r.Body = io.NopCloser(bytes.NewReader(body))
359 var q struct {
360 DryRun bool `json:"dry_run"`
361 }
362 if json.Unmarshal(body, &q) == nil && q.DryRun {
363 f.DuringDryRun(appName)
364 }
365 }
366 f.mu.Lock()
367 defer f.mu.Unlock()
368 f.requests = append(f.requests, r.Method+" "+door)
369 a := f.apps[appName]
370 if account != f.account || a == nil {
371 http.NotFound(w, r)
372 return
373 }
374 raw, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
375 if status := f.failRead[rest]; status != 0 && r.Method == http.MethodGet {
376 refuse(w, status, "this read is failing")
377 return
378 }
379 switch {
380 case r.Method == http.MethodGet && rest == "/config":
381 f.getConfig(w, r, appName, a)
382 case r.Method == http.MethodGet && rest == "/config/effective":
383 f.effective(w, r, appName, a)
384 case r.Method == http.MethodPut && rest == "/config":
385 f.putConfig(w, r, appName, a, raw)
386 case r.Method == http.MethodGet && rest == "/instances":
387 f.list(w, r, a)
388 case r.Method == http.MethodGet && rest == "/domains":
389 f.domainList(w, a)
390 case r.Method == http.MethodGet && strings.HasPrefix(rest, "/instances/"):
391 in, ok := a.recs[strings.TrimPrefix(rest, "/instances/")]
392 if !ok {
393 http.NotFound(w, r)
394 return
395 }
396 writeJSON(w, 200, record(in))
397 case r.Method == http.MethodPost && rest == "/restart/scope":
398 f.restartScope(w, r, appName, a, raw)
399 case r.Method == http.MethodPost && rest == "/restart":
400 // The app-wide door: counted, so a test can assert it is never
401 // called.
402 f.appWide++
403 writeJSON(w, 200, map[string]any{"result": "requested"})
404 default:
405 refuse(w, 405, "not a door this fake serves")
406 }
407}
408
409func record(in carlosop.Instance) map[string]any {
410 out := map[string]any{"schema": 1, "host": in.Host, "slug": in.Slug, "app": in.App, "account": in.Account,
411 "channel": in.Channel, "created_at": in.CreatedAt, "gated": false}
412 for k, v := range map[string]string{"environment": in.Environment, "region": in.Region} {
413 if v != "" {
414 out[k] = v
415 }
416 }
417 if in.RecordSeq != 0 {
418 out["record_seq"] = in.RecordSeq
419 }
420 for k, v := range map[string]json.RawMessage{"move": in.Move, "replica_assignment": in.ReplicaAssignment, "seed": in.Seed} {
421 if len(v) > 0 {
422 out[k] = v
423 }
424 }
425 return out
426}
427
428func varRows(m manifest) []map[string]any {
429 keys := make([]string, 0, len(m.Vars))
430 for k := range m.Vars {
431 keys = append(keys, k)
432 }
433 sort.Strings(keys)
434 rows := make([]map[string]any, 0, len(keys))
435 for _, k := range keys {
436 v := m.Vars[k]
437 row := map[string]any{"key": k, "kind": v.Kind, "digest": Digest(v)}
438 if v.Kind == "env" {
439 row["value"] = v.Value
440 }
441 rows = append(rows, row)
442 }
443 return rows
444}
445
446func bundleName(env string) string {
447 if env == "" {
448 return "default"
449 }
450 return env
451}
452
453func (f *Fake) getConfig(w http.ResponseWriter, r *http.Request, appName string, a *app) {
454 env := strings.TrimSpace(r.URL.Query().Get("environment"))
455 raw := a.layer(env)
456 envs := make([]string, 0, len(a.envs))
457 for n := range a.envs {
458 envs = append(envs, n)
459 }
460 sort.Strings(envs)
461 writeJSON(w, 200, map[string]any{"bundle": bundleName(env), "version": Version(raw), "environments": envs, "vars": varRows(decode(raw, appName))})
462}
463
464func (f *Fake) effective(w http.ResponseWriter, r *http.Request, appName string, a *app) {
465 host := strings.TrimSpace(r.URL.Query().Get("host"))
466 if host == "" {
467 refuse(w, 400, "host is required")
468 return
469 }
470 rec, ok := a.recs[host]
471 if !ok {
472 http.NotFound(w, r)
473 return
474 }
475 envName := rec.Environment
476 envRaw := a.layer(envName)
477 if envName != "" && envRaw == nil {
478 // The box renders nothing for a route bound to an environment
479 // that was never created; the platform refuses the view.
480 refuse(w, 502, "could not read the config — try again")
481 return
482 }
483 def, env, ov := decode(a.def, appName), decode(envRaw, appName), decode(a.overlays[host], appName)
484 owned := envName != "" && env.OwnerScope != ""
485 type source struct {
486 name string
487 m manifest
488 }
489 var order []source // highest first
490 if a.overlays[host] != nil {
491 order = append(order, source{"overlay", ov})
492 }
493 if envName != "" {
494 order = append(order, source{"environment", env})
495 }
496 if !owned && a.def != nil {
497 order = append(order, source{"default", def})
498 }
499 merged := map[string]Var{}
500 for i := len(order) - 1; i >= 0; i-- {
501 for k, v := range order[i].m.Vars {
502 merged[k] = v
503 }
504 }
505 keys := make([]string, 0, len(merged))
506 for k := range merged {
507 keys = append(keys, k)
508 }
509 sort.Strings(keys)
510 vars := make([]map[string]any, 0, len(keys))
511 for _, k := range keys {
512 v := merged[k]
513 from, shadows := "", []string{}
514 for _, s := range order {
515 if _, ok := s.m.Vars[k]; !ok {
516 continue
517 }
518 if from == "" {
519 from = s.name
520 } else {
521 shadows = append(shadows, s.name)
522 }
523 }
524 row := map[string]any{"key": k, "kind": v.Kind, "digest": Digest(v), "from": from, "shadows": shadows}
525 if v.Kind == "env" && from != "overlay" {
526 row["value"] = v.Value
527 }
528 vars = append(vars, row)
529 }
530 layers := map[string]any{"overlay": map[string]any{"version": Version(a.overlays[host])}}
531 if !owned {
532 layers["default"] = map[string]any{"version": Version(a.def)}
533 }
534 if envName != "" {
535 layers["environment"] = map[string]any{"name": envName, "version": Version(envRaw)}
536 }
537 writeJSON(w, 200, map[string]any{"host": host, "environment": envName, "owned": owned, "layers": layers, "vars": vars})
538}
539
540func (f *Fake) putConfig(w http.ResponseWriter, r *http.Request, appName string, a *app, raw []byte) {
541 if len(r.Header.Values("If-Match")) > 0 {
542 refuse(w, 400, "this request takes if_version in the body, not an If-Match header")
543 return
544 }
545 var req struct {
546 Environment string `json:"environment"`
547 Set map[string]Var `json:"set"`
548 Unset []string `json:"unset"`
549 ExecDelivery *string `json:"exec_delivery"`
550 }
551 var members map[string]json.RawMessage
552 if json.Unmarshal(raw, &req) != nil || json.Unmarshal(raw, &members) != nil {
553 refuse(w, 400, "malformed JSON body")
554 return
555 }
556 if len(req.Set) == 0 && len(req.Unset) == 0 && req.ExecDelivery == nil {
557 refuse(w, 400, "nothing to do — send set, unset or exec_delivery")
558 return
559 }
560 ifVersion := ""
561 conditional := false
562 if m, ok := members["if_version"]; ok {
563 conditional = true
564 if json.Unmarshal(m, &ifVersion) != nil || strings.TrimSpace(ifVersion) == "" {
565 refuse(w, 400, "if_version must be a version string")
566 return
567 }
568 }
569 if conditional {
570 switch {
571 case f.noCond:
572 refuse(w, 400, "conditional writes need a store that supports them")
573 return
574 case req.ExecDelivery != nil:
575 refuse(w, 400, "if_version cannot cover exec_delivery. send exec_delivery in a request of its own")
576 return
577 }
578 for _, k := range req.Unset {
579 if _, both := req.Set[k]; both {
580 refuse(w, 400, k+" is in both set and unset")
581 return
582 }
583 }
584 }
585 env := req.Environment
586 before := a.layer(env)
587 if conditional && Version(before) != ifVersion {
588 writeJSON(w, http.StatusPreconditionFailed, map[string]any{
589 "error": "the bundle is not at the version you sent, so nothing was written. read it again before you retry",
590 "version": Version(before)})
591 return
592 }
593 defBefore := Version(a.def)
594 m := decode(before, appName)
595 rc := map[string]any{"bundle": bundleName(env), "version_before": Version(before)}
596 set, unset, absent, digests := []string{}, []string{}, []string{}, map[string]string{}
597 seen := map[string]bool{}
598 for _, k := range req.Unset {
599 if seen[k] {
600 continue
601 }
602 seen[k] = true
603 if _, ok := m.Vars[k]; ok {
604 delete(m.Vars, k)
605 unset = append(unset, k)
606 } else {
607 absent = append(absent, k)
608 }
609 }
610 for k, v := range req.Set {
611 m.Vars[k] = v
612 set = append(set, k)
613 digests[k] = Digest(v)
614 }
615 sort.Strings(set)
616 sort.Strings(unset)
617 sort.Strings(absent)
618 after := encode(m)
619 a.store(env, after)
620 rc["version_after"] = Version(after)
621 rc["changed"] = Version(before) != Version(after)
622 rc["set"], rc["unset"], rc["unset_absent"], rc["digests"] = set, unset, absent, digests
623 if env != "" && m.OwnerScope == "" {
624 rc["others"] = map[string]any{"default": map[string]string{"before": defBefore, "after": Version(a.def)}}
625 }
626 if f.lose {
627 f.lose = false
628 if hj, ok := w.(http.Hijacker); ok {
629 if conn, _, err := hj.Hijack(); err == nil {
630 _ = conn.Close()
631 return
632 }
633 }
634 }
635 writeJSON(w, 200, map[string]any{"result": "ok", "removed": len(unset), "receipt": rc})
636}
637
638func (f *Fake) list(w http.ResponseWriter, r *http.Request, a *app) {
639 hosts := make([]string, 0, len(a.recs))
640 for h := range a.recs {
641 hosts = append(hosts, h)
642 }
643 sort.Strings(hosts)
644 start := 0
645 if c := r.URL.Query().Get("cursor"); c != "" {
646 n, err := strconv.Atoi(c)
647 if err != nil || n < 0 || n > len(hosts) {
648 refuse(w, 400, "bad cursor")
649 return
650 }
651 start = n
652 }
653 end, next := len(hosts), ""
654 if f.PageSize > 0 && start+f.PageSize < len(hosts) {
655 end = start + f.PageSize
656 next = strconv.Itoa(end)
657 }
658 rows := make([]map[string]any, 0, end-start)
659 for _, h := range hosts[start:end] {
660 rows = append(rows, record(a.recs[h]))
661 }
662 writeJSON(w, 200, map[string]any{"instances": rows, "truncated": false, "total": len(hosts), "next_cursor": next})
663}
664
665// domainList is handleAPIDomainList's answer for plain claims: host
666// sorted, each with the fields the platform always sends, and the
667// self-describing deployment block.
668func (f *Fake) domainList(w http.ResponseWriter, a *app) {
669 hosts := make([]string, 0, len(a.domains))
670 for h := range a.domains {
671 hosts = append(hosts, h)
672 }
673 sort.Strings(hosts)
674 rows := make([]map[string]any, 0, len(hosts))
675 for _, h := range hosts {
676 d := a.domains[h]
677 status := "pending"
678 if d.state == "live" {
679 status = "live"
680 }
681 rows = append(rows, map[string]any{"host": h, "route": d.route, "status": status, "state": d.state,
682 "wildcard": false, "catchall": false, "verified": d.state != "unverified"})
683 }
684 writeJSON(w, 200, map[string]any{"domains": rows, "deployment": map[string]any{"managed_domains": true}})
685}
686
687func (f *Fake) restartScope(w http.ResponseWriter, r *http.Request, appName string, a *app, raw []byte) {
688 if f.noScope {
689 http.NotFound(w, r)
690 return
691 }
692 if f.failRestart != 0 {
693 refuse(w, f.failRestart, "restart refused")
694 return
695 }
696 var req struct {
697 Host string `json:"host"`
698 Environment string `json:"environment"`
699 DryRun bool `json:"dry_run"`
700 Message string `json:"message"`
701 }
702 dec := json.NewDecoder(bytes.NewReader(raw))
703 dec.DisallowUnknownFields() // the door is strict: a misspelt selector must not read as none
704 if len(raw) > 0 && dec.Decode(&req) != nil {
705 refuse(w, 400, "malformed or unknown field")
706 return
707 }
708 host, envName := strings.TrimSpace(req.Host), strings.TrimSpace(req.Environment)
709 var routes []carlosop.Instance
710 kind, value := "app", ""
711 switch {
712 case host != "":
713 rec, ok := a.recs[host]
714 if !ok {
715 refuse(w, 400, "no route "+host+" on this app")
716 return
717 }
718 if envName != "" && rec.Environment != envName {
719 refuse(w, 400, "one of --host and --environment is a typo, so nothing was cycled")
720 return
721 }
722 kind, value, routes = "host", host, []carlosop.Instance{rec}
723 case envName != "":
724 for _, rec := range a.recs {
725 if rec.Environment == envName {
726 routes = append(routes, rec)
727 }
728 }
729 if len(routes) == 0 {
730 refuse(w, 400, "no route of this app reads environment "+envName)
731 return
732 }
733 kind, value = "environment", envName
734 default:
735 for _, rec := range a.recs {
736 routes = append(routes, rec)
737 }
738 }
739 if kind == "app" && !req.DryRun {
740 refuse(w, 400, "this door only narrows a restart")
741 return
742 }
743 sort.Slice(routes, func(i, j int) bool { return routes[i].Host < routes[j].Host })
744 rows := make([]map[string]any, 0, len(routes))
745 for _, rt := range routes {
746 rows = append(rows, map[string]any{"host": rt.Host, "environment": rt.Environment, "hibernate": false})
747 }
748 answer := map[string]any{"account": f.account, "app": appName, "scope": map[string]string{"kind": kind, "value": value},
749 "dry_run": req.DryRun, "requested": false, "routes": rows}
750 if !req.DryRun {
751 for _, rt := range routes {
752 f.restarts[rt.Host]++
753 }
754 answer["requested"] = true
755 }
756 writeJSON(w, 200, answer)
757}
758