carlos / platform Public

console, cli: carlos instances set-pages; page cache docs

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5978469b00433609132c1c814aaf032b3ef625df parent 84b2162
11 files changed, +403 −3
  • apimode.go +30 −0
  • approved_page_cache_copy_test.go +97 −0
  • cli.go +3 −0
  • docs/site/cli.md +23 −1
  • instances_cli.go +1 −0
  • instances_pages.go +68 −0
  • internal/console/apiinstances.go +15 −1
  • internal/console/apipages.go +24 −0
  • internal/console/apipages_test.go +83 −0
  • main.go +1 −1
  • pages_cli_test.go +58 −0

CI cancelled — superseded by a newer push — run details

Intent

Attributed to this commit: 35.2 g CO₂e (4,626,147 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on edge-page-cache-1, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/apimode.go b/apimode.go
index 15b8e0e09..7f1bc301c 100644
--- a/apimode.go
+++ b/apimode.go
@@ -5717,6 +5717,36 @@ func (s *apiSession) instanceSetAssets(ctx context.Context, a apiAcct, app, host
return out, nil
}
+// instanceSetPages turns one instance's page caching on or off through the
+// console, as instanceSetAssets does for asset copying. A console older than
+// the field answers 400 "nothing to update" to a body of only this key,
+// reported as EPC-5.
+func (s *apiSession) instanceSetPages(ctx context.Context, a apiAcct, app, host string, on bool, messages ...string) (apiInstanceRecord, error) {
+ word := "off"
+ if on {
+ word = "on"
+ }
+ in := struct {
+ Pages string `json:"pages"`
+ Message string `json:"message,omitempty"`
+ }{word, firstMutationMessage(messages)}
+ status, body, err := s.patchJSON(ctx, apiPath(a, app, "/instances/"+url.PathEscape(host)), in)
+ if err != nil {
+ return apiInstanceRecord{}, err
+ }
+ if status != http.StatusOK {
+ if status == http.StatusBadRequest && strings.Contains(string(body), "nothing to update") {
+ return apiInstanceRecord{}, fmt.Errorf("this console predates `carlos instances set-pages` (deploy a console built from current main)")
+ }
+ return apiInstanceRecord{}, apiErrorFromBody(status, body)
+ }
+ var out apiInstanceRecord
+ if err := json.Unmarshal(body, &out); err != nil {
+ return apiInstanceRecord{}, fmt.Errorf("set-pages: unreadable response: %w", err)
+ }
+ return out, nil
+}
+
// apiAssetsPurgeResult mirrors the purge door's reply (internal/console
// handleAPIAssetsPurge): one line per instance, and Complete true only when
// every write landed.
diff --git a/approved_page_cache_copy_test.go b/approved_page_cache_copy_test.go
new file mode 100644
index 000000000..40b708c10
--- /dev/null
+++ b/approved_page_cache_copy_test.go
@@ -0,0 +1,97 @@
+// approved_page_cache_copy_test.go
+package main
+
+import (
+ "os"
+ "regexp"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// The copy gate of the edge page cache plan 1 (spec 2026-11-08). The record
+// is docs/superpowers/plans/2026-11-08-edge-page-cache-copy.md. It reuses the
+// asset cache gate's helpers (entryBuiltRows) and the moves gate's, so the
+// parser, the em dash rule and the "text is in the file" match are the record
+// formats' already.
+//
+// - TestPageCacheCopyInventory: the record names exactly pageCacheCopyIDs,
+// and no row holds an em dash;
+// - TestPageCacheCopyBuiltRowsAreApprovedAndPresent: an id in
+// pageCacheCopyBuilt is an approved row, and its text is in the file it
+// names. No pending string reaches code or docs.
+const pageCacheCopyRecordPath = "docs/superpowers/plans/2026-11-08-edge-page-cache-copy.md"
+
+var pageCacheCopyIDPattern = regexp.MustCompile(`^EPC-[0-9]+$`)
+
+// pageCacheCopyIDs is the record's inventory, pinned: EPC-1 to EPC-17.
+var pageCacheCopyIDs = func() []string {
+ ids := make([]string, 0, 17)
+ for i := 1; i <= 17; i++ {
+ ids = append(ids, "EPC-"+strconv.Itoa(i))
+ }
+ return ids
+}()
+
+// pageCacheCopyBuilt is every row whose text the code or docs carry. The task
+// that writes a row's text adds its entry here in the same commit.
+var pageCacheCopyBuilt = []string{
+ "EPC-1", "EPC-2", "EPC-3", "EPC-4", "EPC-5", "EPC-6", "EPC-7",
+ "EPC-8", "EPC-9", "EPC-10", "EPC-11", "EPC-12", "EPC-13", "EPC-14",
+ "EPC-15", "EPC-16", "EPC-17",
+}
+
+func mustParsePageCacheCopyRecord(t *testing.T) []copyRow {
+ t.Helper()
+ raw, err := os.ReadFile(pageCacheCopyRecordPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rows, err := parseCopyTable(string(raw), pageCacheCopyRecordPath, pageCacheCopyIDPattern, "an EPC-<n>")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return rows
+}
+
+func TestPageCacheCopyInventory(t *testing.T) {
+ rows := mustParsePageCacheCopyRecord(t)
+ reportAll(t, checkMovesInventory(rows, pageCacheCopyIDs))
+ // EPC-7 keeps the em dash already in today's help text (Paul left it).
+ var rest []copyRow
+ for _, r := range rows {
+ if r.ID != "EPC-7" {
+ rest = append(rest, r)
+ }
+ }
+ reportAll(t, checkMovesNoEmDash(rest))
+}
+
+// pageCacheFragments are the rows whose text sits inside a larger literal
+// (the usage constant ends in a newline, the two help lines are lines of a
+// raw string). They must be inside some string literal of their file, never
+// only in a comment (goLiteralMatches, approved_copy_test.go).
+var pageCacheFragments = map[string]bool{"EPC-2": true, "EPC-6": true, "EPC-7": true}
+
+func TestApprovedPageCacheCopy(t *testing.T) {
+ built, problems := entryBuiltRows(mustParsePageCacheCopyRecord(t), pageCacheCopyBuilt, "pageCacheCopyBuilt")
+ // The record is a markdown table, where a literal pipe in a cell is
+ // written \|; the code and docs carry the plain pipe.
+ var whole []copyRow
+ for _, r := range built {
+ r.Text = strings.ReplaceAll(r.Text, `\|`, "|")
+ if !pageCacheFragments[r.ID] {
+ whole = append(whole, r)
+ continue
+ }
+ body, err := os.ReadFile(r.Path())
+ if err != nil {
+ problems = append(problems, r.ID+": "+err.Error())
+ continue
+ }
+ if !goLiteralMatches(body, func(v string) bool { return strings.Contains(v, r.Text) }) {
+ problems = append(problems, r.ID+": "+r.Path()+" has no string literal holding the approved text "+strconv.Quote(r.Text))
+ }
+ }
+ reportAll(t, append(problems, checkMovesApplied(whole, ".")...))
+}
diff --git a/cli.go b/cli.go
index c2cf5d01a..22868a824 100644
--- a/cli.go
+++ b/cli.go
@@ -615,6 +615,9 @@ func runInstances(args []string) {
case "set-assets":
runInstancesSetAssets(args[1:])
return
+ case "set-pages":
+ runInstancesSetPages(args[1:])
+ return
case "retry":
runInstancesRetry(args[1:])
return
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 421f56a9b..654645719 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -1183,7 +1183,7 @@ no bundle can override:
| `CARLOS_HOST` | the instance's hostname, exactly as in `carlos instances list`. Read this, never the socket's file name, which says nothing about the host on an isolated box |
| `CARLOS_REGION` | the box's region code, such as `ie` |
| `CARLOS_CONTROL_SOCKET` | the socket the platform listens on for your app's purge and scheduling calls |
-| `CARLOS_PURGE` | `header` when the edge honours a `Carlos-Purge` response header |
+| `CARLOS_PURGE` | `header` when the edge honours a `Carlos-Purge` response header, including `all` for every host of the instance |
| `CARLOS_ADMIN_TOKEN` | a secret shared with this one instance: the platform presents it when it calls your app, and your app presents it on `CARLOS_CONTROL_SOCKET` |
The box keeps a sealed copy of each instance's `<host>.env`. It also keeps sealed copies of the `instance.key` and `report.token` files an app keeps at the top of its own directory. These copies are stored in the region's data bucket. Each copy is sealed to the box's secrets key and bound to your app. Only a box that can already read your app's secrets can open it. When a box starts an instance whose `<host>.env` is missing, it puts the sealed copy back first. This keeps the instance's `CARLOS_ADMIN_TOKEN` and `CARLOS_INSTANCE_KEY` instead of giving it new ones. A file that is there is never replaced. You can edit other values in `<host>.env`. The box seals the new contents within a minute. `CARLOS_ADMIN_TOKEN`, `CARLOS_INSTANCE_KEY`, `instance.key` and `report.token` cannot change once sealed. If the box finds a different value, it refuses to start the instance and raises an alert. Deleting the file does not reset it. A box without the secrets key a copy was sealed to will not start that instance. This includes a box whose key was changed. Put the old key back.
@@ -1201,6 +1201,20 @@ A command started with carlos run gets the same environment, without CARLOS_CONT
Its arguments are exactly what followed --, after your binary. The platform adds nothing. It runs in the instance's data directory. On a cancel, a timeout or an instance stop it gets SIGTERM, then SIGKILL 20 seconds later.
+#### Caching pages at the edge
+
+Your app can ask the edge to keep a copy of a page and serve it without waking the app. Send `Carlos-Page-Cache: on` with the page, and a `Cache-Control` that says how long the copy may last, for example `public, s-maxage=31536000, max-age=0`. The edge keeps the copy until it expires, until your app clears it, or until the instance gets a new release or new config.
+
+Use a long `s-maxage` and `max-age=0`. The edge can clear its own copy but not the one in a visitor's browser, so `max-age=0` makes the browser check with the edge each time, and the edge answers from its copy. If a page changes at a set time, such as a post scheduled for 9:00, make `s-maxage` end then, because nothing else will tell the edge.
+
+Copies are kept only for visitors who send no cookies and no `Authorization` header, and served only to visitors in the same position, so a signed-in page is never shared. If a cookie doesn't change the page, such as a consent cookie, name it: `Carlos-Page-Cache: on; ignore-cookies="consent"`. A visitor carrying only that cookie still gets the copy.
+
+A page is kept only when your app answers with status 200, no `Set-Cookie`, no `Vary` other than `Accept-Encoding`, an uncompressed body of at most 8 MiB, and a path outside your release's asset folders. Instances that run as `carlos-app@` systemd units are not cached yet.
+
+Clear copies with the `Carlos-Purge` header or `CARLOS_CONTROL_SOCKET`, as you would for the response cache. `*` clears one host, a path clears that path with any query, `/path?query` clears one address, and `all` clears every host of the instance, including its aliases and custom domains. Each response says what happened in a `Carlos-Cache` header, in the same words as for asset files.
+
+Once a page has been marked, the instance's other responses are no longer kept in the five-minute response cache, so mark every page you want cached.
+
#### Storage of its own, for every instance
`--private-storage` on `enable` is one declaration that changes what every
@@ -1322,6 +1336,14 @@ Turns asset copying on or off for one instance. `off` means requests for its ass
carlos instances set-assets --app shop a.shop.example.com off
```
+### carlos instances set-pages
+
+Turns page caching on or off for one instance. `off` throws away the pages it keeps, and every request reaches the app, which helps while you are debugging or if a page was cached that shouldn't have been. `on` goes back to keeping the pages the app marks. Instances start with it on.
+
+```sh
+carlos instances set-pages --app shop a.shop.example.com off
+```
+
### carlos sidecars
A sidecar is a member that nothing can dial: a process the platform runs for
diff --git a/instances_cli.go b/instances_cli.go
index 510a2dbf1..2342db522 100644
--- a/instances_cli.go
+++ b/instances_cli.go
@@ -228,6 +228,7 @@ var instancesRecordsUsage = `usage: carlos instances create --app <a> --host <h>
carlos instances set-channel --app <a> --host <h> --channel <c>
carlos instances set-environment --app <a> --host <h> --environment <e> [--scope <s>]
carlos instances set-assets --app <a> <host> on|off
+ carlos instances set-pages --app <a> <host> on|off
carlos instances retry --app <a> <host>
` + updatewords.Text("settings.cli.instances-usage-lines") + `
diff --git a/instances_pages.go b/instances_pages.go
new file mode 100644
index 000000000..31673a358
--- /dev/null
+++ b/instances_pages.go
@@ -0,0 +1,68 @@
+// `carlos instances set-pages <host> on|off` (edge page cache plan 1, task
+// 12): the per-instance switch for page caching, built as set-pages is. It
+// rides the instance PATCH door, so it is signed-in only.
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "strings"
+)
+
+const instancesSetPagesUsage = `usage: carlos instances set-pages --app <a> [--account <a>] [--account-id <id>] [--console <origin>] <host> on|off
+`
+
+func runInstancesSetPages(args []string) {
+ fs := flag.NewFlagSet("instances set-pages", flag.ExitOnError)
+ messageFlags := addMutationMessageFlags(fs)
+ app := appFlag(fs, "app the instance belongs to")
+ consoleFlag := consoleOption(fs, "console to act through (default: the only logged-in one)")
+ acctRaw := fs.String("account", "", "account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one)")
+ acctIDRaw := fs.String("account-id", "", "account sqid, matched as a sqid ONLY, supersedes --account")
+ fs.Usage = flagUsage(fs, instancesSetPagesUsage)
+ // The host and the word are positional and may come before or after the
+ // flags: parse, take the leading words, parse what is left.
+ var words []string
+ rest := args
+ for {
+ fs.Parse(rest)
+ rest = fs.Args()
+ if len(rest) == 0 {
+ break
+ }
+ words = append(words, rest[0])
+ rest = rest[1:]
+ }
+ if len(words) != 2 || (words[1] != "on" && words[1] != "off") {
+ log.Fatal(instancesSetPagesUsage)
+ }
+ // Records are keyed lowercase, so a host typed with capitals would miss
+ // and read as a typo (#264).
+ host := strings.ToLower(strings.TrimSpace(words[0]))
+ on := words[1] == "on"
+ sess := requireAPISession("set-pages", *consoleFlag)
+ printUsing(stdout, sess)
+ acct := resolvedAccount(sess, acctRaw, acctIDRaw)
+ app2 := resolvedApp(sess, acct, *app, instancesSetPagesUsage)
+ message, merr := resolveMutationMessage(fs, messageFlags)
+ if merr != nil {
+ log.Fatalf("instances set-pages: %v", merr)
+ }
+ if _, err := sess.instanceSetPages(context.Background(), acct, app2, host, on, message); err != nil {
+ log.Fatalf("instances set-pages: %v", err)
+ }
+ printSetPages(stdout, host, on)
+}
+
+// printSetPages is the result line of set-pages (EPC-3 for on, EPC-4 for
+// off).
+func printSetPages(w io.Writer, host string, on bool) {
+ if on {
+ fmt.Fprintln(w, fmt.Sprintf("%s will keep copies of the pages its app marks for caching. servers pick this up within a minute.", host))
+ return
+ }
+ fmt.Fprintln(w, fmt.Sprintf("%s will keep no copies of its pages, so every request reaches the app. servers pick this up within a minute.", host))
+}
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index b9519bf0b..f5d8162df 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -2947,6 +2947,10 @@ func (s *Server) handleAPIInstanceUpdate(w http.ResponseWriter, r *http.Request)
// Absent leaves the record alone. assetsSwitch (apiassets.go) reads
// it and holds the refusal for anything else.
Assets *string `json:"assets"`
+ // Pages is the instance's page-cache opt-out, shaped like Assets:
+ // "on" takes part, "off" publishes no page index. pagesSwitch
+ // (apipages.go) reads it and holds the refusal for anything else.
+ Pages *string `json:"pages"`
// Message is the caller's optional reason for the change, recorded on
// the audit row (checkedActivityMessage owns its refusal).
Message string `json:"message"`
@@ -2962,7 +2966,7 @@ func (s *Server) handleAPIInstanceUpdate(w http.ResponseWriter, r *http.Request)
return
}
if req.Addrs == nil && req.Probe == nil && req.Steering == nil && req.Environment == nil && req.Gate == nil &&
- req.RateLimit == nil && req.Assets == nil {
+ req.RateLimit == nil && req.Assets == nil && req.Pages == nil {
jsonError(w, http.StatusBadRequest,
"nothing to update — send addrs, probe, steering, environment, gate, or a combination")
return
@@ -2992,6 +2996,10 @@ func (s *Server) handleAPIInstanceUpdate(w http.ResponseWriter, r *http.Request)
if !ok {
return
}
+ pages, ok := pagesSwitch(w, req.Pages)
+ if !ok {
+ return
+ }
ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
defer cancel()
rec, etag, err := s.readRecord(ctx, acct.Sqid, app, host)
@@ -3096,6 +3104,9 @@ func (s *Server) handleAPIInstanceUpdate(w http.ResponseWriter, r *http.Request)
if req.Assets != nil {
rec.Assets = assets
}
+ if req.Pages != nil {
+ rec.Pages = pages
+ }
// Checked here rather than left to ValidateShape so that a value above
// the account's plan ceiling is refused in the plan's terms (approved
// copy), and a failure to read the plan is the console's fault, not a
@@ -3241,6 +3252,9 @@ func (s *Server) handleAPIInstanceUpdate(w http.ResponseWriter, r *http.Request)
if req.Assets != nil {
changed = append(changed, "assets")
}
+ if req.Pages != nil {
+ changed = append(changed, "pages")
+ }
if req.RateLimit != nil {
changed = append(changed, "rate_limit")
}
diff --git a/internal/console/apipages.go b/internal/console/apipages.go
new file mode 100644
index 000000000..b902b6cca
--- /dev/null
+++ b/internal/console/apipages.go
@@ -0,0 +1,24 @@
+package console
+
+import "net/http"
+
+// The edge page cache's PATCH door sentence (design §4), the approved copy
+// row EPC-1 (docs/superpowers/plans/2026-11-08-edge-page-cache-copy.md). It
+// lives here, not in apiinstances.go, as apiAssetsOnOff does.
+const apiPagesOnOff = "pages must be on or off."
+
+// pagesSwitch reads the PATCH body's pages value as the record's field: "on"
+// is nil (take part), "off" is false. Absent (v nil) is ok and the caller
+// leaves the record alone. Anything else answers EPC-1 and reports ok false;
+// the caller runs this before reading the record, so nothing is written.
+func pagesSwitch(w http.ResponseWriter, v *string) (pages *bool, ok bool) {
+ if v == nil || *v == "on" {
+ return nil, true
+ }
+ if *v == "off" {
+ off := false
+ return &off, true
+ }
+ jsonError(w, http.StatusBadRequest, apiPagesOnOff)
+ return nil, false
+}
diff --git a/internal/console/apipages_test.go b/internal/console/apipages_test.go
new file mode 100644
index 000000000..93b86b60b
--- /dev/null
+++ b/internal/console/apipages_test.go
@@ -0,0 +1,83 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// epc1Text is the approved copy row EPC-1.
+const epc1Text = "pages must be on or off."
+
+// TestPatchInstancePagesOffAndOn: "off" stores false, "on" clears the field,
+// anything else is EPC-1 with nothing written and nothing announced, and the
+// audit line names the field.
+func TestPatchInstancePagesOffAndOn(t *testing.T) {
+ fx, token := assetsFixture(t, "code-pages-patch")
+ const host = "shop.example.com"
+ putAssetRecord(t, fx, host, "0123456789abcdef")
+ pu := fx.ts.URL + "/api/cli/apps/" + shipAssetsAccount + "/" + assetsApp + "/instances/" + host
+ key := provision.RecordKey(shipAssetsAccount, assetsApp, host)
+
+ before := serial(t, fx)
+ status, _, out := rawReq(t, http.MethodPatch, pu, token, `{"pages":"off"}`)
+ if status != http.StatusOK {
+ t.Fatalf("patch pages off = %d %s", status, out)
+ }
+ var echoed provision.Record
+ if err := json.Unmarshal([]byte(out), &echoed); err != nil {
+ t.Fatal(err)
+ }
+ if echoed.Pages == nil || *echoed.Pages {
+ t.Fatalf("echoed pages = %v, want false", echoed.Pages)
+ }
+ if rec := assetRecord(t, fx, host); rec.Pages == nil || *rec.Pages || rec.PagesOn() {
+ t.Fatalf("stored pages = %v, want false", rec.Pages)
+ }
+ if got := serial(t, fx); got != before+1 {
+ t.Fatalf("serial after off = %d, want one bump past %d", got, before)
+ }
+ details := assetEventDetails(t, fx, "instance-update")
+ if len(details) == 0 || details[0] != "updated instance shop.example.com (pages) (cli)" {
+ t.Fatalf("instance-update details = %q, want the newest to name pages", details)
+ }
+
+ status, _, out = rawReq(t, http.MethodPatch, pu, token, `{"pages":"on"}`)
+ if status != http.StatusOK {
+ t.Fatalf("patch pages on = %d %s", status, out)
+ }
+ if rec := assetRecord(t, fx, host); rec.Pages != nil || !rec.PagesOn() {
+ t.Fatalf("stored pages after on = %v, want absent", rec.Pages)
+ }
+ raw, _, err := fx.rel.Get(context.Background(), key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(raw), `"pages"`) {
+ t.Fatalf("an on record still carries the key: %s", raw)
+ }
+
+ for _, bad := range []string{`"maybe"`, `""`, `"ON"`, `"true"`} {
+ before := serial(t, fx)
+ status, _, out := rawReq(t, http.MethodPatch, pu, token, `{"pages":`+bad+`}`)
+ var body map[string]string
+ _ = json.Unmarshal([]byte(out), &body)
+ if status != http.StatusBadRequest || body["error"] != epc1Text {
+ t.Fatalf("patch pages %s = %d %s, want 400 %q", bad, status, out, epc1Text)
+ }
+ after, _, err := fx.rel.Get(context.Background(), key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(after) != string(raw) {
+ t.Fatalf("a refused patch %s wrote:\n%s\nwas\n%s", bad, after, raw)
+ }
+ if got := serial(t, fx); got != before {
+ t.Fatalf("a refused patch %s bumped the serial", bad)
+ }
+ }
+}
diff --git a/main.go b/main.go
index a483cfae8..51f45701a 100644
--- a/main.go
+++ b/main.go
@@ -298,7 +298,7 @@ Your apps — ship and run software on a CARLOS deployment
env plain per-app config vars: set | unset | list
secrets sealed per-app secrets: set | unset | list | genkey
instances an app's instances: enable | create | list | delete |
- set-upstreams | set-channel | set-assets — set-channel is
+ set-upstreams | set-channel | set-assets | set-pages — set-channel is
the only door onto which channel a route follows
sidecars a process nothing dials, one per enrolled member: enable |
create | ls | wake | rm | logs
diff --git a/pages_cli_test.go b/pages_cli_test.go
new file mode 100644
index 000000000..5c26534a2
--- /dev/null
+++ b/pages_cli_test.go
@@ -0,0 +1,58 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "net/http"
+ "strings"
+ "testing"
+)
+
+// TestSetPagesCLI pins instanceSetPages's wire (a PATCH carrying "pages"),
+// the older-console refusal (EPC-5) and the two result lines (EPC-3, EPC-4).
+//
+// Not acceptance: the console is a stand-in that returns canned JSON; the real
+// door is tested in internal/console (TestPatchInstancePagesOffAndOn).
+func TestSetPagesCLI(t *testing.T) {
+ sess, got := assetsDoor(t, http.StatusOK, `{"host":"shop.example.com"}`)
+ acct := apiAcct{Seg: "abc"}
+ if _, err := sess.instanceSetPages(context.Background(), acct, "shop", "shop.example.com", false, "debugging"); err != nil {
+ t.Fatal(err)
+ }
+ if got.Method != http.MethodPatch || got.Path != "/api/cli/apps/abc/shop/instances/shop.example.com" {
+ t.Fatalf("request = %s %s", got.Method, got.Path)
+ }
+ if got.Body != `{"pages":"off","message":"debugging"}` {
+ t.Fatalf("off body = %q", got.Body)
+ }
+ if _, err := sess.instanceSetPages(context.Background(), acct, "shop", "shop.example.com", true); err != nil {
+ t.Fatal(err)
+ }
+ if got.Body != `{"pages":"on"}` {
+ t.Fatalf("on body = %q", got.Body)
+ }
+
+ old, _ := assetsDoor(t, http.StatusBadRequest, `{"error":"nothing to update — send addrs, probe, steering, environment, gate, or a combination"}`)
+ _, err := old.instanceSetPages(context.Background(), acct, "shop", "shop.example.com", false)
+ want := "this console predates `carlos instances set-pages` (deploy a console built from current main)"
+ if err == nil || err.Error() != want {
+ t.Fatalf("err = %v, want %q", err, want)
+ }
+ refused, _ := assetsDoor(t, http.StatusBadRequest, `{"error":"pages must be on or off."}`)
+ _, err = refused.instanceSetPages(context.Background(), acct, "shop", "shop.example.com", true)
+ if err == nil || err.Error() != "pages must be on or off." {
+ t.Fatalf("err = %v", err)
+ }
+
+ var b bytes.Buffer
+ printSetPages(&b, "shop.example.com", true)
+ printSetPages(&b, "shop.example.com", false)
+ wantOut := "shop.example.com will keep copies of the pages its app marks for caching. servers pick this up within a minute.\n" +
+ "shop.example.com will keep no copies of its pages, so every request reaches the app. servers pick this up within a minute.\n"
+ if b.String() != wantOut {
+ t.Fatalf("got\n%q\nwant\n%q", b.String(), wantOut)
+ }
+ if !strings.Contains(instancesSetPagesUsage, "set-pages --app <a>") {
+ t.Fatal("usage does not name set-pages")
+ }
+}