carlos / platform Public

apps region: show and change an app's region, the default for its new instances

carlos apps region --app <x> [--set <code>], GET and PUT
/api/cli/apps/{account}/{app}/region, and a Region control on the app's
Settings > General page. An account owner or a deployment operator may
change it; members and service credentials are refused. The region is only
the default for new instances: the write is the console's apps row, no
bucket object, so no existing instance moves. Refusals up front: a region
not offered or unable to start instances now, one the app's manifest does
not allow, an app on a fleet, a pooled app, an app in the Trash, a
host-claim console. region_set_at moves the placement discrepancy cut.

Copy pending a Luna pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 1f11e6650ec065570f5c066fd0f7cb702b7e41f7 parent b1d00ca
19 files changed, +1,448 −7
  • apps.go +7 −0
  • apps_region_cmd.go +153 −0
  • apps_region_cmd_e2e_test.go +176 −0
  • docs/site/cli.md +13 −2
  • docs/superpowers/notes/copy-app-region-set.md +42 −0
  • docs/superpowers/specs/LUNA-COPY-BRIEF-APP-REGION-SET.md +86 −0
  • internal/console/appregionset.go +414 −0
  • internal/console/appregionset_test.go +460 −0
  • internal/console/authcli.go +5 −0
  • internal/console/claim_invariant_fixtures_test.go +15 −0
  • internal/console/claim_invariant_probes_read_test.go +1 −0
  • internal/console/claim_invariant_test.go +2 −0
  • internal/console/regionfacts.go +2 −0
  • internal/console/server.go +9 −0
  • internal/console/store.go +33 −5
  • internal/console/svcroutes_test.go +4 −0
  • internal/console/templates/app_settings.html +11 −0
  • internal/console/testdata/claim-routes.txt +3 −0
  • internal/regionlabel/regionlabel.go +12 −0
diff --git a/apps.go b/apps.go
index ed37ba017..bfd5701e6 100644
--- a/apps.go
+++ b/apps.go
@@ -73,6 +73,11 @@ const appsUsage = `usage: carlos apps <create|place|build-probe|set|show|delete|
silent clear (a fleet box retires an app's routes on its
next reconcile the moment placement reads empty).
+ region --app <name> [--set <region>] show the region the app's new
+ instances start in, or change it with --set. existing
+ instances stay where they are. changing it is for account
+ owners and deployment operators.
+
build-probe --app <name> </path|-> set (or clear, with "-") the path whose
response body names the RUNNING build, on an app that
already exists. "carlos deploy" polls it instead of the
@@ -151,6 +156,8 @@ func RunApps(args []string) {
runAppsCreate(args[1:])
case "place":
runAppsPlace(args[1:])
+ case "region":
+ runAppsRegion(args[1:])
case "build-probe":
runAppsBuildProbe(args[1:])
case "set":
diff --git a/apps_region_cmd.go b/apps_region_cmd.go
new file mode 100644
index 000000000..35d2ee13b
--- /dev/null
+++ b/apps_region_cmd.go
@@ -0,0 +1,153 @@
+package main
+
+// `carlos apps region` (Paul, 2026-10-26): show an app's region, or change
+// it with --set. The region is only where the app's NEW instances start;
+// existing instances never move. Console only, through GET and PUT
+// /api/cli/apps/{account}/{app}/region (internal/console/appregionset.go).
+// Any member may read it; an account owner or a deployment operator may
+// change it.
+
+import (
+ "context"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "log"
+ "net/http"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/updatewords"
+)
+
+// The verb's strings (deck docs/superpowers/notes/copy-app-region-set.md).
+const (
+ appsRegionUsage = "usage: carlos apps region --app <name> [--set <region>] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>]"
+ appsRegionFlagSet = "the region this app's new instances start in. existing instances stay where they are. account owners and deployment operators only"
+ appsRegionShow = "%s's region is %s. new instances start there." // AR-32: app, label
+ appsRegionShowFleet = "%s runs on your fleet %s, which decides where its instances run." // AR-33: app, fleet
+ appsRegionChanged = "%s's region changed from %s to %s. new instances start in %s. existing instances stay where they are." // AR-34: app, old, new, new
+ appsRegionSame = "%s's region is already %s. nothing changed." // AR-35: app, label
+ appsRegionDirectMode = "apps region works through a console, and this shell is in direct bucket mode (CARLOS_DEPLOYMENT_BUCKET or CARLOS_DEPLOYMENT_DIR is set). log in instead: carlos auth login --console <url>" // AR-36
+ appsRegionOldConsole = "not found: either %s is not an app in this account, or this console predates carlos apps region (deploy a console built from current main)" // AR-37: app
+)
+
+// apiAppRegion is the door's answer (the console's appRegionView).
+type apiAppRegion struct {
+ App string `json:"app"`
+ Region string `json:"region"`
+ Label string `json:"label"`
+ Source string `json:"source"`
+ Fleet string `json:"fleet"`
+ Previous string `json:"previous"`
+ PreviousLabel string `json:"previous_label"`
+ Changed bool `json:"changed"`
+}
+
+// runAppsRegion is `carlos apps region`.
+func runAppsRegion(args []string) {
+ fs := flag.NewFlagSet("apps region", flag.ExitOnError)
+ app := appFlag(fs, "app whose region to show or change")
+ set := fs.String("set", "", appsRegionFlagSet)
+ 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", "", updatewords.Text("settings.cli.flag-account-id"))
+ consoleFlag := consoleOption(fs, "console to act through (default: the only logged-in one)")
+ fs.Usage = flagUsage(fs, appsRegionUsage)
+ fs.Parse(args)
+ name := strings.TrimSpace(*app)
+ if name == "" || fs.NArg() != 0 {
+ log.Fatal(appsRegionUsage)
+ }
+ if err := validAppName(name); err != nil {
+ log.Fatal(err)
+ }
+ setGiven := false
+ fs.Visit(func(f *flag.Flag) {
+ if f.Name == "set" {
+ setGiven = true
+ }
+ })
+ sess, err := resolveMode(*consoleFlag)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if sess == nil {
+ log.Fatal(appsRegionDirectMode)
+ }
+ acct := resolvedAccount(sess, acctRaw, acctIDRaw)
+ ctx := context.Background()
+ if !setGiven {
+ got, err := sess.appRegion(ctx, acct, name)
+ if err != nil {
+ log.Fatalf("apps region: %v", err)
+ }
+ printAppRegionShow(got)
+ return
+ }
+ got, err := sess.setAppRegion(ctx, acct, name, strings.TrimSpace(*set))
+ if err != nil {
+ log.Fatalf("apps region: %v", err)
+ }
+ printAppRegionSet(got)
+}
+
+func printAppRegionShow(got apiAppRegion) {
+ if got.Fleet != "" {
+ fmt.Fprintf(stdout, appsRegionShowFleet+"\n", got.App, got.Fleet)
+ return
+ }
+ fmt.Fprintf(stdout, appsRegionShow+"\n", got.App, got.Label)
+}
+
+func printAppRegionSet(got apiAppRegion) {
+ if !got.Changed {
+ fmt.Fprintf(stdout, appsRegionSame+"\n", got.App, got.Label)
+ return
+ }
+ fmt.Fprintf(stdout, appsRegionChanged+"\n", got.App, got.PreviousLabel, got.Label, got.Label)
+}
+
+// appRegion is the door's GET.
+func (s *apiSession) appRegion(ctx context.Context, a apiAcct, app string) (apiAppRegion, error) {
+ a, err := s.policyAccount(ctx, a)
+ if err != nil {
+ return apiAppRegion{}, err
+ }
+ status, body, err := s.getJSON(ctx, apiPath(a, app, "/region"))
+ if err != nil {
+ return apiAppRegion{}, err
+ }
+ return appRegionReply(app, status, body)
+}
+
+// setAppRegion is the door's PUT.
+func (s *apiSession) setAppRegion(ctx context.Context, a apiAcct, app, region string) (apiAppRegion, error) {
+ a, err := s.policyAccount(ctx, a)
+ if err != nil {
+ return apiAppRegion{}, err
+ }
+ status, body, err := s.sendJSON(ctx, http.MethodPut, apiPath(a, app, "/region"), map[string]string{"region": region})
+ if err != nil {
+ return apiAppRegion{}, err
+ }
+ return appRegionReply(app, status, body)
+}
+
+// appRegionReply reads the door's answer. A 404 with no JSON error is an
+// unknown app, an account the caller cannot reach, or a console from
+// before the door, and the message names them.
+func appRegionReply(app string, status int, body []byte) (apiAppRegion, error) {
+ switch {
+ case status == http.StatusNotFound && !hasJSONError(body):
+ return apiAppRegion{}, fmt.Errorf(appsRegionOldConsole, app)
+ case status != http.StatusOK:
+ return apiAppRegion{}, apiErrorFromBody(status, body)
+ }
+ var out apiAppRegion
+ if err := json.Unmarshal(body, &out); err != nil {
+ return apiAppRegion{}, fmt.Errorf("unreadable region reply: %w", err)
+ }
+ if out.App == "" {
+ out.App = app
+ }
+ return out, nil
+}
diff --git a/apps_region_cmd_e2e_test.go b/apps_region_cmd_e2e_test.go
new file mode 100644
index 000000000..fc530c65a
--- /dev/null
+++ b/apps_region_cmd_e2e_test.go
@@ -0,0 +1,176 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/ecdh"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// newAppRegionE2E is a real console as newLabelsE2E builds it (HomeRegion
+// ie, the ops account bab owning shop, a signed-in CLI), with the secrets
+// key configured and both boxes publishing every eligibility fact and a
+// fresh status snapshot: the create door can place an instance in uk with
+// no region named, as on a production deployment.
+func newAppRegionE2E(t *testing.T) *labelsE2E {
+ t.Helper()
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ tmp := t.TempDir()
+ rel := release.NewDirStore(filepath.Join(tmp, "store"))
+ seed, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ priv, err := release.ParseSigningKey(seed, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := release.ParsePublicKey(pubB64, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ secrets, err := ecdh.P256().NewPrivateKey(bytes.Repeat([]byte{1}, 32))
+ if err != nil {
+ t.Fatal(err)
+ }
+ fp := appconfig.KeyFingerprint(secrets.PublicKey())
+ cst, err := console.Open(filepath.Join(tmp, "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cst.Close() })
+ var srv *console.Server
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv.ServeHTTP(w, r) }))
+ t.Cleanup(ts.Close)
+ regPath := filepath.Join(tmp, "registry.db")
+ srv, err = console.NewServer(console.Config{
+ Origin: ts.URL, Keymail: "http://keymail.invalid", Registry: regPath,
+ Releases: rel, ReleasePub: pub, Key: priv, AppScheme: "http",
+ AppsDomain: "oncarlos.test", HomeRegion: "ie",
+ SecretsPub: base64.StdEncoding.EncodeToString(secrets.PublicKey().Bytes()),
+ }, cst)
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ if err := cst.AddMember(console.OpsAccountID, labelsAddr, console.RoleOwner, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := cst.CreateAppIn(console.OpsAccountID, "shop", labelsAddr, now); err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ for _, b := range []struct{ machine, placement, aws string }{{"ie-machine", "", "eu-west-1"}, {"uk-machine", "uk", "eu-west-2"}} {
+ box := status.Label(b.machine)
+ body, err := json.Marshal(map[string]any{
+ "v": 1, "box": box, "box_id": box, "eip": "192.0.2.10", "region": b.aws, "placement": b.placement,
+ "hibernation_configured": true, "serves_shared_pool": true, "accepts_inbound": true,
+ "secrets_key_fp": fp, "hosts": map[string]any{},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := rel.Put(ctx, edgesfile.Key(box), body, ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := status.WriteBox(ctx, rel, status.Box{Label: box, GeneratedAt: now}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if !srv.LoadRegionNames(ctx) {
+ t.Fatal("the console did not read its region names")
+ }
+ token, expiresAt := e2eDeviceLogin(t, ts.URL, cst, labelsAddr, "e2e@laptop")
+ credFile, err := loadCredentials()
+ if err != nil {
+ t.Fatal(err)
+ }
+ credFile.put(credential{Console: ts.URL, Address: labelsAddr, Token: token, ExpiresAt: expiresAt})
+ if err := credFile.save(); err != nil {
+ t.Fatal(err)
+ }
+ return &labelsE2E{rel: rel, cst: cst, srv: srv, regPath: regPath, buf: captureStdout(t)}
+}
+
+// carlos apps region through a real console: it shows the region, a change
+// leaves the instance that already exists where it is, and the next
+// instance created with no region starts in the new one.
+func TestAppsRegionThroughTheConsole(t *testing.T) {
+ e := newAppRegionE2E(t)
+ ctx := context.Background()
+ e.out(t, runInstancesEnable, "-app", "shop", "-account", "ops", "-channel", "beta")
+ before := "home1." + labelsDomain
+ e.out(t, runInstancesCreate, "-app", "shop", "-account", "ops", "-host", before)
+
+ if got := e.out(t, runAppsRegion, "--app", "shop", "--account", "ops"); got != "shop's region is Dublin (ie). new instances start there.\n" {
+ t.Fatalf("apps region:\n%q", got)
+ }
+ got := e.out(t, runAppsRegion, "--app", "shop", "--account", "ops", "--set", "uk")
+ if !strings.HasSuffix(got, "shop's region changed from Dublin (ie) to London (uk). new instances start in London (uk). existing instances stay where they are.\n") {
+ t.Fatalf("apps region --set:\n%q", got)
+ }
+ if got := e.out(t, runAppsRegion, "--app", "shop", "--account", "ops", "--set", "uk"); !strings.HasSuffix(got, "shop's region is already London (uk). nothing changed.\n") {
+ t.Fatalf("apps region --set again:\n%q", got)
+ }
+
+ rec, err := provision.GetRecord(ctx, e.rel, release.OpsAccount, "shop", before)
+ if err != nil || rec.Region != "" {
+ t.Fatalf("the instance created before the change has region %q (%v), want the home still", rec.Region, err)
+ }
+ after := "new1." + labelsDomain
+ if got := e.out(t, runInstancesCreate, "-app", "shop", "-account", "ops", "-host", after); !strings.Contains(got,
+ "created instance "+after+" (channel beta, London (uk))") {
+ t.Fatalf("instances create after the change:\n%s", got)
+ }
+ rec, err = provision.GetRecord(ctx, e.rel, release.OpsAccount, "shop", after)
+ if err != nil || rec.Region != "uk" {
+ t.Fatalf("the new instance has region %q (%v), want uk", rec.Region, err)
+ }
+ if apps := e.out(t, runAppsList, "--account", "ops"); !strings.Contains(apps, "London (uk)") {
+ t.Fatalf("apps list after the change:\n%s", apps)
+ }
+}
+
+// deploy --region after a change: naming the new region ships, naming the
+// old one is refused before anything ships, as for any app. The app starts
+// in uk and moves to the home, which needs no box evidence.
+func TestDeployRegionAfterAppsRegionSet(t *testing.T) {
+ for _, c := range []struct {
+ asked string
+ ships bool
+ }{{"ie", true}, {"uk", false}} {
+ t.Run(c.asked, func(t *testing.T) {
+ e := regionE2EConsole(t, "uk")
+ if out, err := e.run(t, "apps", "region", "--app", "titogo", "--account", "ops", "--console", e.url, "--set", "ie"); err != nil ||
+ !strings.Contains(out, "titogo's region changed from uk to ie.") {
+ t.Fatalf("apps region --set: %v\n%s", err, out)
+ }
+ e.writes.Store(0)
+ out, err := e.deployAsking(t, c.asked)
+ if c.ships {
+ if strings.Contains(out, "already runs in") || e.releases(t) == 0 {
+ t.Fatalf("deploy --region %s did not ship: %v\n%s", c.asked, err, out)
+ }
+ return
+ }
+ if err == nil || !strings.Contains(out, deployRegionMismatch("titogo", "ie")) || e.writes.Load() != 0 || e.releases(t) != 0 {
+ t.Fatalf("deploy --region %s: err=%v writes=%d\n%s", c.asked, err, e.writes.Load(), out)
+ }
+ })
+ }
+}
diff --git a/docs/site/cli.md b/docs/site/cli.md
index a1ad9363e..8dd45cb8c 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -184,7 +184,16 @@ carlos apps ttl --app tmp-docs 5d
carlos apps keep --app tmp-docs
```
-carlos apps list shows each app's own region, the one it was given when it was created, or the fleet it runs on. Where new instances start can differ. For a pooled app, the app's Running page in the console shows where they start.
+carlos apps list shows each app's own region, the one it was given when it was created or changed to since, or the fleet it runs on. Where new instances start can differ. For a pooled app, the app's Running page in the console shows where they start.
+
+`carlos apps region` shows an app's region, and `--set` changes it:
+
+```sh
+carlos apps region --app hello
+carlos apps region --app hello --set uk
+```
+
+An app's region is only where its new instances start. Changing it moves nothing: instances that already exist stay where they are, and only instances created afterwards start in the new region. Use carlos move to move one that exists. The new region must be one the platform offers and can start instances in now, and one the app's instances may use. An app on a fleet is refused, because the fleet decides where its instances run; use `carlos apps place` instead. So is an app whose instances start in a pool, and an app in the Trash. Account owners and deployment operators can change the region, here or in the Region section of the app's settings in the console. The console records who changed it, from what and to what, in the app's activity. After a change, `carlos deploy --region` has to name the new region.
`carlos apps set` changes how the app's running instances take a new build:
@@ -342,7 +351,9 @@ nothing.
When `carlos deploy` creates your first app, it sends your timezone so the
console can pick the region nearest you, and prints the choice. `--region
<code>` chooses instead. On an app that already exists, `--region` must
-match the app's region, or deploy stops before shipping anything.
+match the app's region, or deploy stops before shipping anything. That is
+the region the app has now, after any `carlos apps region --set`, and deploy
+never moves an instance to match it.
`carlos deploy` takes the same repeatable `--assets` flag and passes it to the ship. Save the list as `"assets": ["/assets/"]` in `.carlos/config` and a bare `carlos deploy` declares it on every release. A flag on the command line replaces the saved list for that run, and `--no-assets` ships with none. A release that declares no folders gets no copies, so deploying a build without them turns copying off for that build. `--assets` and `--no-assets` cannot be given together.
diff --git a/docs/superpowers/notes/copy-app-region-set.md b/docs/superpowers/notes/copy-app-region-set.md
new file mode 100644
index 000000000..467188840
--- /dev/null
+++ b/docs/superpowers/notes/copy-app-region-set.md
@@ -0,0 +1,42 @@
+# Copy deck: carlos apps region (app-region-set)
+
+Every new human string of branch `app-region-set`: changing an existing app's region, the default for its NEW instances (Paul, 2026-10-26). Placeholders in order. `|` inside a cell is escaped.
+
+| id | kind | placeholders | text |
+|---|---|---|---|
+| AR-1 | door refusal, printed by the CLI as "apps region: <text>" | | only an account owner or a deployment operator can change an app's region |
+| AR-2 | door refusal, printed by the CLI as "apps region: <text>" | app | %s is in the Trash. Restore it before you change its region. |
+| AR-3 | door refusal, printed by the CLI as "apps region: <text>" | app, fleet name | %s runs on your fleet %s, which decides where its instances run. Use carlos apps place to change that. |
+| AR-4 | door refusal, printed by the CLI as "apps region: <text>" | app | %s starts its instances in a pool, so an app region would not be used. Nothing was changed. |
+| AR-5 | door refusal, printed by the CLI as "apps region: <text>" | | name the region to set, for example --set uk |
+| AR-6 | door refusal, printed by the CLI as "apps region: <text>" | code, list | region %s is not one this platform offers. Choose from: %s. |
+| AR-6b | door refusal, printed by the CLI as "apps region: <text>" | code | region %s is not one this platform offers right now. |
+| AR-7 | door refusal, printed by the CLI as "apps region: <text>" | code, list | region %s is not one this app's instances may use. Allowed: %s. |
+| AR-7b | door refusal, printed by the CLI as "apps region: <text>" | code | region %s is not one this app's instances may use, and none of the regions they may use is offered right now. |
+| AR-8 | door refusal, printed by the CLI as "apps region: <text>" | | this app's region changed while this ran. Run it again. |
+| AR-9 | door refusal, printed by the CLI as "apps region: <text>" | | could not read this app's instance policy, so its region was not changed. Try again. |
+| AR-9b | door refusal, printed by the CLI as "apps region: <text>" | | could not read the regions this platform offers, so the app's region was not changed. Try again. |
+| AR-10 | door refusal, printed by the CLI as "apps region: <text>" | | could not change this app's region. Nothing was changed. Try again. |
+| AR-11 | activity row (lower case, like "made shop permanent") | app, old label, new label | changed %s's region from %s to %s |
+| AR-12 | browser sentence | | Changed after the app was created. |
+| AR-13 | flash | new label | New instances now start in %s. Existing instances stay where they are. |
+| AR-14 | flash | label | This app's region is already %s. |
+| AR-15 | form label | | Region for new instances |
+| AR-16 | button | | Change region |
+| AR-17 | help paragraph | | Changing the region moves nothing. Only instances created after the change start in the new region. |
+| AR-19 | door refusal, printed by the CLI as "apps region: <text>" | code, reason text (R-*) | region %s can't take new instances right now (%s), so the app's region was not changed. |
+| AR-20 | door refusal, printed by the CLI as "apps region: <text>" | code | could not confirm that region %s can take new instances, so the app's region was not changed. Try again. |
+| AR-21 | door refusal, printed by the CLI as "apps region: <text>" | | changing an app's region is not supported on a console with host claims on |
+| AR-30 | usage line | | usage: carlos apps region --app <name> [--set <region>] [--account <sqid\|name>] [--account-id <sqid>] [--console <origin>] |
+| AR-31 | flag help for --set | | the region this app's new instances start in. existing instances stay where they are. account owners and deployment operators only |
+| AR-32 | CLI line | app, region label | %s's region is %s. new instances start there. |
+| AR-33 | CLI line | app, fleet name | %s runs on your fleet %s, which decides where its instances run. |
+| AR-34 | CLI line | app, old label, new label, new label | %s's region changed from %s to %s. new instances start in %s. existing instances stay where they are. |
+| AR-35 | CLI line | app, label | %s's region is already %s. nothing changed. |
+| AR-36 | CLI refusal | | apps region works through a console, and this shell is in direct bucket mode (CARLOS_DEPLOYMENT_BUCKET or CARLOS_DEPLOYMENT_DIR is set). log in instead: carlos auth login --console <url> |
+| AR-37 | CLI refusal | app | not found: either %s is not an app in this account, or this console predates carlos apps region (deploy a console built from current main) |
+| AR-38 | help paragraph in carlos apps usage (keep the indentation) | | region --app <name> [--set <region>] show the region the app's new<br> instances start in, or change it with --set. existing<br> instances stay where they are. changing it is for account<br> owners and deployment operators. |
+| AR-40 | docs (docs/site/cli.md) | | carlos apps list shows each app's own region, the one it was given when it was created or changed to since, or the fleet it runs on. Where new instances start can differ. For a pooled app, the app's Running page in the console shows where they start. |
+| AR-41 | docs (docs/site/cli.md) | | `carlos apps region` shows an app's region, and `--set` changes it: |
+| AR-42 | docs (docs/site/cli.md) | | An app's region is only where its new instances start. Changing it moves nothing: instances that already exist stay where they are, and only instances created afterwards start in the new region. Use carlos move to move one that exists. The new region must be one the platform offers and can start instances in now, and one the app's instances may use. An app on a fleet is refused, because the fleet decides where its instances run; use `carlos apps place` instead. So is an app whose instances start in a pool, and an app in the Trash. Account owners and deployment operators can change the region, here or in the Region section of the app's settings in the console. The console records who changed it, from what and to what, in the app's activity. After a change, `carlos deploy --region` has to name the new region. |
+| AR-43 | docs (docs/site/cli.md) | | That is the region the app has now, after any `carlos apps region --set`, and deploy never moves an instance to match it. |
diff --git a/docs/superpowers/specs/LUNA-COPY-BRIEF-APP-REGION-SET.md b/docs/superpowers/specs/LUNA-COPY-BRIEF-APP-REGION-SET.md
new file mode 100644
index 000000000..86d27e723
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-BRIEF-APP-REGION-SET.md
@@ -0,0 +1,86 @@
+# Copy pass brief: carlos apps region (branch app-region-set)
+
+You are reviewing user-facing strings for a hosting platform's CLI, console
+and docs. Paul, the owner, delegated this review to you. Apply his house
+rules and return improved strings.
+
+The feature: an app has a stored **region**, the place its NEW instances
+start when a create names no region. Until now it could only be set when the
+app was created. `carlos apps region --app <x>` now shows it, and `--set
+<code>` changes it; the console's app Settings > General page has a small
+Region control that does the same. The deck with every string, its id, kind
+and placeholders is `docs/superpowers/notes/copy-app-region-set.md`.
+
+## House rules
+
+- Plain words, short sentences, no jargon, no marketing tone, no
+ exclamation marks.
+- No em dashes or en dashes used as dashes. Where you would use one, end the
+ sentence with a full stop and start a separate sentence that **continues
+ in lower case**, the way Go error strings and this CLI write. Paul's own
+ example: "could not provision the store — re-run `carlos store create` to
+ resume" becomes "could not provision the store. re-run `carlos store
+ create` to resume". If the second half is a bare command with no verb,
+ give it a verb. Semicolons are fine; the rule is about em dashes.
+- Casing by kind:
+ - **door refusals, CLI lines, CLI refusals, the usage line, the flag help
+ and the activity row**: lower case at the start (a placeholder that
+ starts the string is fine) and after every full stop, and no full stop
+ at the very end. The newest approved CLI strings read this way, for
+ example "default size for %s set to %s. instances with their own size
+ are unchanged". Command names, flag names, `Trash` (a page name) and
+ environment variable names keep their own spelling.
+ - **flash, browser sentence, form label, button, help paragraph** and
+ **docs**: ordinary sentence case with full stops, as the surrounding
+ console and docs text has. Still no em dashes.
+ - AR-38 is a help paragraph inside the CLI's usage text: keep its
+ indentation and line breaks (`<br>`), and the lower-case style of the
+ usage text around it.
+- Keep every placeholder (`%s`) and their order. Go cannot reorder them. If
+ a placeholder must move, say so in Flags instead.
+- Leave flag names (`--set`, `--app`, `--account`, `--account-id`,
+ `--console`, `--region`), command names (`carlos apps region`, `carlos
+ apps place`, `carlos apps list`, `carlos deploy`, `carlos move`, `carlos
+ auth login --console <url>`) and environment variable names exactly as
+ they are.
+- Do not name the product. Use neutral examples only (`shop`, `hello`,
+ `uk`, `ie`); never a real customer.
+- Human text only. Log lines and JSON keys are out of scope and not listed.
+
+## Facts that must stay true
+
+- The region is ONLY the default for the app's new instances. Changing it
+ moves nothing: every instance that exists stays where it is. Only
+ instances created after the change, with no region named, start in the
+ new region. Every string that reports a change must leave no doubt about
+ that.
+- Placeholders that print a region print its label, for example
+ "London (uk)" or "Dublin (ie)"; AR-6, AR-7, AR-19 and AR-20 print the code
+ the person typed, and their lists are codes ("ie, uk").
+- Who may change it: an owner of the account, or a deployment operator.
+ Members and service credentials may not. Any member may read it.
+- Refusals: a region the platform does not offer (AR-6), one that cannot
+ start instances right now (AR-19, its bracket is one of "no box runs
+ there now", "boxes there can't start instances", "boxes there can't open
+ this deployment's secrets", "boxes there don't take ordinary instances"),
+ one the app's instances may not use (AR-7), an app on a fleet (AR-3: the
+ fleet decides; `carlos apps place` changes that), an app whose instances
+ start in a pool (AR-4: the region would not be used), an app in the Trash
+ (AR-2), a console with host claims on (AR-21). Nothing is written when
+ any of these is refused.
+- AR-8 is a race: someone else changed the app (its region, or deleted or
+ replaced it) while the command ran. Running it again is the fix.
+- AR-11 is a row on the app's Activity page, for example
+ "changed shop's region from Dublin (ie) to London (uk)".
+- AR-12 follows "This app's region is London (uk)." on the settings page,
+ in place of "Chosen when the app was created."
+- `carlos deploy --region` on an existing app must name the app's current
+ region, or deploy stops before shipping anything (AR-42, AR-43).
+
+## Output
+
+Do not edit any file. Answer with one markdown table, `| key | new | why |`,
+one row per deck id, every id included, `unchanged` in why when you keep a
+string as it is. Then a short **Flags** list for anything you could not fix
+within these rules (a fact you think is wrong, a placeholder that must
+move, a string that should be split). Nothing else.
diff --git a/internal/console/appregionset.go b/internal/console/appregionset.go
new file mode 100644
index 000000000..ab1b5847f
--- /dev/null
+++ b/internal/console/appregionset.go
@@ -0,0 +1,414 @@
+package console
+
+// Changing an existing app's region (Paul, 2026-10-26): `carlos apps region`
+// and the Region control on the app's Settings > General page. The stored
+// region (apps.region) is ONLY the default for the app's new instances:
+// nothing reads it to place an instance that exists, so a change moves
+// nothing. Its readers: the instance create door (apiinstances.go, a create
+// naming no region), the app_default answer on /regions that deploy
+// --region and canary --region compare against (regiondefault.go), the
+// region labels (regionfacts.go) and the placement discrepancy log
+// (regiondrift.go, which reads region_set_at).
+//
+// Who may: an owner of the account, or a deployment operator (an owner of
+// the ops account, or an address on CARLOS_SYSTEM_OPERATORS:
+// platformOperator), who need not be a member. A member is refused, and a
+// service credential never reaches the door (svcrole.Set{}). Every refusal
+// comes before the write, and the write is SQLite only: no bucket object
+// and no serial bump, because no box reads apps.region.
+//
+// The switch: the write is allowed with CONSOLE_APP_REGIONS off. The create
+// door honours the stored region with the switch off (apiinstances.go), and
+// Paul accepted writing it with the switch off for member moves (member
+// moves design §18, Q5), so the value is used either way.
+
+import (
+ "context"
+ "crypto/subtle"
+ "fmt"
+ "log"
+ "net/http"
+ "slices"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/regionlabel"
+)
+
+// appRegionSetCopy is every string this file adds (deck
+// docs/superpowers/notes/copy-app-region-set.md).
+type appRegionSetCopyStrings struct {
+ NotOwner string // AR-1
+ InTrash string // AR-2: app
+ OnFleet string // AR-3: app, fleet name
+ Pooled string // AR-4: app
+ NoRegion string // AR-5
+ NotOffered string // AR-6: code, list
+ NotOfferedNone string // AR-6b: code
+ NotAllowed string // AR-7: code, list
+ NotAllowedNone string // AR-7b: code
+ ClaimOff string // AR-21
+ Unavailable string // AR-19: code, reason text (R-*)
+ Unconfirmed string // AR-20: code
+ Changed string // AR-8
+ PolicyUnread string // AR-9
+ OptionsUnread string // AR-9b
+ WriteFailed string // AR-10
+ AuditChanged string // AR-11: app, old label, new label
+ SourceChanged string // AR-12
+ FlashChanged string // AR-13: new label
+ FlashSame string // AR-14: label
+ ControlLabel string // AR-15
+ ControlButton string // AR-16
+ ControlNote string // AR-17
+}
+
+var appRegionSetCopy = appRegionSetCopyStrings{
+ NotOwner: "only an account owner or a deployment operator can change an app's region",
+ InTrash: "%s is in the Trash. Restore it before you change its region.",
+ OnFleet: "%s runs on your fleet %s, which decides where its instances run. Use carlos apps place to change that.",
+ Pooled: "%s starts its instances in a pool, so an app region would not be used. Nothing was changed.",
+ NoRegion: "name the region to set, for example --set uk",
+ NotOffered: "region %s is not one this platform offers. Choose from: %s.",
+ NotOfferedNone: "region %s is not one this platform offers right now.",
+ NotAllowed: "region %s is not one this app's instances may use. Allowed: %s.",
+ NotAllowedNone: "region %s is not one this app's instances may use, and none of the regions they may use is offered right now.",
+ ClaimOff: "changing an app's region is not supported on a console with host claims on",
+ Unavailable: "region %s can't take new instances right now (%s), so the app's region was not changed.",
+ Unconfirmed: "could not confirm that region %s can take new instances, so the app's region was not changed. Try again.",
+ Changed: "this app's region changed while this ran. Run it again.",
+ PolicyUnread: "could not read this app's instance policy, so its region was not changed. Try again.",
+ OptionsUnread: "could not read the regions this platform offers, so the app's region was not changed. Try again.",
+ WriteFailed: "could not change this app's region. Nothing was changed. Try again.",
+ AuditChanged: "changed %s's region from %s to %s",
+ SourceChanged: "Changed after the app was created.",
+ FlashChanged: "New instances now start in %s. Existing instances stay where they are.",
+ FlashSame: "This app's region is already %s.",
+ ControlLabel: "Region for new instances",
+ ControlButton: "Change region",
+ ControlNote: "Changing the region moves nothing. Only instances created after the change start in the new region.",
+}
+
+// appRegionView is the door's answer. region is the display code (the
+// home's name for the home), label its region label.
+type appRegionView struct {
+ App string `json:"app"`
+ Region string `json:"region"`
+ Label string `json:"label"`
+ Source string `json:"source,omitempty"`
+ Fleet string `json:"fleet,omitempty"`
+ Previous string `json:"previous,omitempty"`
+ PreviousLabel string `json:"previous_label,omitempty"`
+ Changed bool `json:"changed"`
+}
+
+// appRegionCaller resolves the account a person may read or change an app's
+// region in. A deployment operator reaches any account by sqid; anyone else
+// goes through apiPrincipalAccount, so an unknown account and someone
+// else's are the family's byte-identical 404. write adds the owner rule
+// (apiOwnerAccountFor's: a member gets a 403, since membership is already
+// proved). A service principal never gets here (the route allows no role);
+// it is refused again here all the same.
+func (s *Server) appRegionCaller(w http.ResponseWriter, r *http.Request, write bool) (addr string, acct *Account, ok bool) {
+ p, pok := principalFrom(r.Context())
+ if !pok || p.Kind != PrincipalUser {
+ http.NotFound(w, r)
+ return "", nil, false
+ }
+ if s.principalPlatformOperator(p) {
+ a, err := s.store.AccountBySqid(r.PathValue("account"))
+ if err != nil {
+ log.Printf("console: app region: account: %v", err)
+ jsonError(w, http.StatusInternalServerError, "could not load accounts")
+ return "", nil, false
+ }
+ if a != nil {
+ return p.Address, a, true
+ }
+ // Not a sqid: an operator who is a member may still name the
+ // account, through the member path below.
+ }
+ p, acct, ok = s.apiPrincipalAccount(w, r)
+ if !ok {
+ return "", nil, false
+ }
+ if write && acct.Role != RoleOwner {
+ jsonError(w, http.StatusForbidden, appRegionSetCopy.NotOwner)
+ return "", nil, false
+ }
+ return p.Address, acct, true
+}
+
+// appRegionApp is the {app} half: a live app, or the Trash refusal for a
+// trashed one (the caller may already see the Trash), else the bare 404.
+func (s *Server) appRegionApp(w http.ResponseWriter, r *http.Request, acct *Account) (string, bool) {
+ app := r.PathValue("app")
+ live, err := s.store.HasAppIn(acct.ID, app)
+ if err != nil {
+ log.Printf("console: app region %s/%s: has app: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusInternalServerError, msgAppRegionUnreadable)
+ return "", false
+ }
+ if live {
+ return app, true
+ }
+ trashed, err := s.store.HasTrashedAppIn(acct.ID, app)
+ if err != nil {
+ log.Printf("console: app region %s/%s: has trashed app: %v", acct.Sqid, app, err)
+ }
+ if err == nil && trashed {
+ jsonError(w, http.StatusConflict, fmt.Sprintf(appRegionSetCopy.InTrash, app))
+ return "", false
+ }
+ http.NotFound(w, r)
+ return "", false
+}
+
+// handleAPIAppRegionGet is GET /api/cli/apps/{account}/{app}/region: the
+// stored region and its label, or the fleet that governs. SQLite and the
+// registry only.
+func (s *Server) handleAPIAppRegionGet(w http.ResponseWriter, r *http.Request) {
+ _, acct, ok := s.appRegionCaller(w, r, false)
+ if !ok {
+ return
+ }
+ app, ok := s.appRegionApp(w, r, acct)
+ if !ok {
+ return
+ }
+ routes, routesOK := s.registryRoutes()
+ f := s.regionFactsFor(acct, app, fleetFromRoutes(routes, acct.Sqid, app), routesOK)
+ if !f.Known {
+ jsonError(w, http.StatusBadGateway, msgAppRegionUnreadable)
+ return
+ }
+ writeJSON(w, http.StatusOK, appRegionView{App: app, Region: f.Code(), Label: f.Text(), Source: f.Source, Fleet: f.Fleet})
+}
+
+// handleAPIAppRegionSet is PUT /api/cli/apps/{account}/{app}/region with
+// {"region": "<code>"}.
+func (s *Server) handleAPIAppRegionSet(w http.ResponseWriter, r *http.Request) {
+ addr, acct, ok := s.appRegionCaller(w, r, true)
+ if !ok {
+ return
+ }
+ app, ok := s.appRegionApp(w, r, acct)
+ if !ok {
+ return
+ }
+ p, _ := principalFrom(r.Context())
+ if !s.allowWrite(p, time.Now()) {
+ jsonError(w, http.StatusTooManyRequests, "too many requests. Wait a minute and try again")
+ return
+ }
+ var req struct {
+ Region string `json:"region"`
+ }
+ if !readJSONStrictLimit(w, r, &req, 8<<10) {
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
+ defer cancel()
+ v, ref := s.setAppRegion(ctx, acct, app, req.Region, addr, "cli")
+ if ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ writeJSON(w, http.StatusOK, v)
+}
+
+// setAppRegion is both doors' mechanism. Every refusal is checked before
+// the write; the write holds the app lock and lands on the incarnation and
+// region it read, or not at all. via is appended to the audit line ("cli"
+// or "" for the browser).
+func (s *Server) setAppRegion(ctx context.Context, acct *Account, app, raw, addr, via string) (appRegionView, *doorRefusal) {
+ // A host-claim console gates every app-row write through a claim
+ // operation, and this one has none: refused before anything is read
+ // (host claims are shelved; claimRenameUnsupportedMsg is the precedent).
+ if s.cfg.HostClaim {
+ return appRegionView{}, &doorRefusal{http.StatusConflict, appRegionSetCopy.ClaimOff}
+ }
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return appRegionView{}, &doorRefusal{http.StatusBadRequest, appRegionSetCopy.NoRegion}
+ }
+ code := s.homeRegionIn(raw)
+ choices, ref := s.appRegionChoices(ctx)
+ if ref != nil {
+ return appRegionView{}, ref
+ }
+ if (code != "" && !provision.ValidRegion(code)) || !slices.Contains(choices, s.homeRegionOut(code)) {
+ if len(choices) == 0 {
+ return appRegionView{}, &doorRefusal{http.StatusBadRequest, fmt.Sprintf(appRegionSetCopy.NotOfferedNone, raw)}
+ }
+ return appRegionView{}, &doorRefusal{http.StatusBadRequest, fmt.Sprintf(appRegionSetCopy.NotOffered, raw, strings.Join(choices, ", "))}
+ }
+ // The region must also be able to take an instance now, by the same
+ // positive test the create door puts an app-derived region to
+ // (apiinstances.go): otherwise every create naming no region would be
+ // refused after the change. The home needs no evidence.
+ if code != "" {
+ snap, err := s.liveEdges(ctx)
+ if err != nil || !snap.EvidenceComplete() {
+ if err != nil {
+ log.Printf("console: app region %s/%s: read edges: %v", acct.Sqid, app, err)
+ }
+ return appRegionView{}, &doorRefusal{http.StatusServiceUnavailable, fmt.Sprintf(appRegionSetCopy.Unconfirmed, raw)}
+ }
+ reason := "absent"
+ if c, ok := findCandidate(s.regionCands(snap), code); ok {
+ reason = c.unavailableReason()
+ }
+ if reason != "" {
+ return appRegionView{}, &doorRefusal{http.StatusConflict, fmt.Sprintf(appRegionSetCopy.Unavailable, raw, reasonText(reason))}
+ }
+ }
+ pol := s.appPolicy(ctx, acct, app)
+ switch {
+ case pol.State == policyUnreadable:
+ return appRegionView{}, &doorRefusal{http.StatusBadGateway, appRegionSetCopy.PolicyUnread}
+ case pol.Placed != "":
+ name, _ := strings.CutPrefix(pol.Placed, "fleet/")
+ return appRegionView{}, &doorRefusal{http.StatusConflict, fmt.Sprintf(appRegionSetCopy.OnFleet, app, name)}
+ case pol.pooled():
+ return appRegionView{}, &doorRefusal{http.StatusConflict, fmt.Sprintf(appRegionSetCopy.Pooled, app)}
+ case !pol.allows(code):
+ var allowed []string
+ for _, c := range choices {
+ if pol.allows(s.homeRegionIn(c)) {
+ allowed = append(allowed, c)
+ }
+ }
+ if len(allowed) == 0 {
+ return appRegionView{}, &doorRefusal{http.StatusConflict, fmt.Sprintf(appRegionSetCopy.NotAllowedNone, raw)}
+ }
+ return appRegionView{}, &doorRefusal{http.StatusConflict, fmt.Sprintf(appRegionSetCopy.NotAllowed, raw, strings.Join(allowed, ", "))}
+ }
+
+ defer s.lockApp(acct.Sqid, app)()
+ inc, live, err := s.store.AppIncarnationContext(ctx, acct.ID, app)
+ if err != nil {
+ log.Printf("console: app region %s/%s: incarnation: %v", acct.Sqid, app, err)
+ return appRegionView{}, &doorRefusal{http.StatusInternalServerError, appRegionSetCopy.WriteFailed}
+ }
+ if !live {
+ return appRegionView{}, &doorRefusal{http.StatusConflict, appRegionSetCopy.Changed}
+ }
+ from, fromSource, err := s.store.AppRegion(acct.ID, app)
+ if err != nil {
+ log.Printf("console: app region %s/%s: read: %v", acct.Sqid, app, err)
+ return appRegionView{}, &doorRefusal{http.StatusBadGateway, msgAppRegionUnreadable}
+ }
+ home, names := s.regionHome(), s.regionNames()
+ newLabel := regionlabel.ForCode(code, home, names)
+ v := appRegionView{App: app, Region: s.homeRegionOut(code), Label: newLabel.Text, Source: "changed"}
+ if from == code {
+ v.Source = fromSource
+ return v, nil
+ }
+ oldLabel := regionlabel.ForCode(from, home, names)
+ ok, err := s.store.SetAppRegion(ctx, acct.ID, app, inc, from, code, time.Now())
+ if err != nil {
+ log.Printf("console: app region %s/%s: write: %v", acct.Sqid, app, err)
+ return appRegionView{}, &doorRefusal{http.StatusInternalServerError, appRegionSetCopy.WriteFailed}
+ }
+ if !ok {
+ return appRegionView{}, &doorRefusal{http.StatusConflict, appRegionSetCopy.Changed}
+ }
+ detail := fmt.Sprintf(appRegionSetCopy.AuditChanged, app, oldLabel.Text, newLabel.Text)
+ if via != "" {
+ detail += " (" + via + ")"
+ }
+ s.audit(acct, app, addr, "region", detail)
+ v.Previous, v.PreviousLabel, v.Changed = s.homeRegionOut(from), oldLabel.Text, true
+ return v, nil
+}
+
+// appRegionChoices is the regions an app's region may be set to, as display
+// codes, sorted: exactly the list the create door's explicit --region
+// accepts (explicitChoices: the home, and every published region that is
+// armed, hosting and not without the secrets key). One read of the edges
+// files, per change; never on a page view.
+func (s *Server) appRegionChoices(ctx context.Context) ([]string, *doorRefusal) {
+ if s.cfg.Releases == nil {
+ return nil, &doorRefusal{http.StatusServiceUnavailable, appRegionSetCopy.OptionsUnread}
+ }
+ return s.explicitChoices(s.readExplicitGate(ctx)), nil
+}
+
+// appRegionPageChoices is the Region control's options: the home and every
+// code the console's region name map knows (regionnames.go), held in memory,
+// so a page view reads no store. The door checks the choice when it is sent.
+func (s *Server) appRegionPageChoices() []regionOption {
+ home, names := s.regionHome(), s.regionNames()
+ set := map[string]bool{}
+ if home != "" {
+ set[home] = true
+ }
+ for _, c := range names.Codes() {
+ set[c] = true
+ }
+ out := make([]regionOption, 0, len(set))
+ for c := range set {
+ out = append(out, regionOption{Value: c, Label: regionlabel.ForCode(s.homeRegionIn(c), home, names).Text})
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].Value < out[j].Value })
+ return out
+}
+
+// AppRegionSetCopy hands the Region control its strings.
+func (p page) AppRegionSetCopy() appRegionSetCopyStrings { return appRegionSetCopy }
+
+// canSetAppRegion is the browser's form of the rule: an owner, or a
+// deployment operator.
+func (s *Server) canSetAppRegion(addr, role string) bool {
+ return role == RoleOwner || s.platformOperator(addr)
+}
+
+// handleAppRegionSet is POST /a/{sqid}/apps/{app}/region, the Settings >
+// General control: session, CSRF, then the owner-or-operator rule, whose
+// refusal is the same 404 a non-member gets.
+func (s *Server) handleAppRegionSet(w http.ResponseWriter, r *http.Request) {
+ addr, raw, acct, role, app, ok := s.accountApp(w, r)
+ if !ok {
+ return
+ }
+ if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
+ return
+ }
+ if !s.canSetAppRegion(addr, role) {
+ http.NotFound(w, r)
+ return
+ }
+ if s.cfg.HostClaim {
+ s.renderMessage(w, r, http.StatusConflict, "Not available", appRegionSetCopy.ClaimOff)
+ return
+ }
+ back := func(kind, msg string) {
+ s.setFlash(w, kind, msg)
+ http.Redirect(w, r, appSettingsURL(acct.Sqid, app, "general"), http.StatusSeeOther)
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
+ defer cancel()
+ v, ref := s.setAppRegion(ctx, acct, app, r.FormValue("region"), addr, "")
+ if ref != nil {
+ back("err", sentenceCase(ref.Msg))
+ return
+ }
+ if !v.Changed {
+ back("ok", fmt.Sprintf(appRegionSetCopy.FlashSame, v.Label))
+ return
+ }
+ back("ok", fmt.Sprintf(appRegionSetCopy.FlashChanged, v.Label))
+}
+
+// sentenceCase capitalizes a door message's first letter for a flash.
+func sentenceCase(msg string) string {
+ if msg == "" || msg[0] < 'a' || msg[0] > 'z' {
+ return msg
+ }
+ return strings.ToUpper(msg[:1]) + msg[1:]
+}
diff --git a/internal/console/appregionset_test.go b/internal/console/appregionset_test.go
new file mode 100644
index 000000000..314054ddd
--- /dev/null
+++ b/internal/console/appregionset_test.go
@@ -0,0 +1,460 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// appRegionFx is the console fixture with HomeRegion ie, two boxes
+// publishing themselves (the home box in eu-west-1 and a uk box in
+// eu-west-2, both armed), a region name map read from them, and a tenant
+// account cdef holding the app shop, owned by owner@example.test with
+// member@example.test as a member. paul@keymail.dev owns the ops account,
+// so he is a deployment operator and no member of cdef.
+type appRegionFx struct {
+ *consoleFixture
+ acct *Account
+}
+
+const (
+ arSqid = "cdef"
+ arOwner = "owner@example.test"
+ arMember = "member@example.test"
+)
+
+func newAppRegionFx(t *testing.T) *appRegionFx {
+ t.Helper()
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.HomeRegion = "ie"
+ pub, _, _ := sealedFor(t, "irrelevant")
+ fx.srv.cfg.SecretsPub = pub
+ ctx := context.Background()
+ for _, b := range []struct{ box, placement, aws, eip string }{
+ {"ie-machine", "", "eu-west-1", "192.0.2.10"},
+ {"uk-machine", "uk", "eu-west-2", "192.0.2.11"},
+ // Published, but with no dial address: known and not armed.
+ {"us-machine", "us", "us-east-1", ""},
+ // Armed, but serving named pools only: offered by the explicit
+ // gate, and no box there can take an ordinary instance.
+ {"fr-machine", "fr", "eu-west-3", "192.0.2.13"},
+ } {
+ publishAppRegionBox(t, fx, b.box, b.placement, b.aws, b.eip, b.box == "fr-machine")
+ }
+ if !fx.srv.LoadRegionNames(ctx) {
+ t.Fatal("the console did not read its region names")
+ }
+ now := time.Now()
+ if err := fx.st.CreateAccount(42, arSqid, "Shop Co", arOwner, now); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.AddMember(42, arMember, RoleMember, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(42, "shop", arOwner, now.Add(-time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ acct, err := fx.st.AccountBySqid(arSqid)
+ if err != nil || acct == nil {
+ t.Fatalf("account: %v %v", acct, err)
+ }
+ return &appRegionFx{consoleFixture: fx, acct: acct}
+}
+
+// publishAppRegionBox writes a box's edges file, every eligibility field
+// positively true, and a fresh status snapshot for it.
+func publishAppRegionBox(t *testing.T, fx *consoleFixture, box, placement, aws, eip string, poolsOnly bool) {
+ t.Helper()
+ ctx := context.Background()
+ body, err := json.Marshal(map[string]any{
+ "v": 1, "box": box, "box_id": box, "eip": eip, "region": aws, "placement": placement,
+ "hibernation_configured": true, "serves_shared_pool": !poolsOnly, "accepts_inbound": true,
+ "secrets_key_fp": fx.srv.expectedSecretsFP(), "hosts": map[string]any{},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.rel.Put(ctx, edgesfile.Key(box), body, ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := status.WriteBox(ctx, fx.rel, status.Box{Label: box, GeneratedAt: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func (fx *appRegionFx) put(t *testing.T, token, app, region string) (int, string) {
+ t.Helper()
+ st, _, out := rawReq(t, http.MethodPut, fx.ts.URL+"/api/cli/apps/"+arSqid+"/"+app+"/region?exact=sqid", token,
+ fmt.Sprintf(`{"region":%q}`, region))
+ return st, out
+}
+
+func (fx *appRegionFx) get(t *testing.T, token, app string) (int, string) {
+ t.Helper()
+ st, _, out := rawReq(t, http.MethodGet, fx.ts.URL+"/api/cli/apps/"+arSqid+"/"+app+"/region?exact=sqid", token, "")
+ return st, out
+}
+
+func (fx *appRegionFx) stored(t *testing.T, app string) (string, string) {
+ t.Helper()
+ r, src, err := fx.st.AppRegion(42, app)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return r, src
+}
+
+func (fx *appRegionFx) regionEvents(t *testing.T, app string) []Event {
+ t.Helper()
+ evs, err := fx.st.Events(42, app, 100)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []Event
+ for _, e := range evs {
+ if e.Action == "region" {
+ out = append(out, e)
+ }
+ }
+ return out
+}
+
+func decodeRegionView(t *testing.T, out string) appRegionView {
+ t.Helper()
+ var v appRegionView
+ if err := json.Unmarshal([]byte(out), &v); err != nil {
+ t.Fatalf("reply %q: %v", out, err)
+ }
+ return v
+}
+
+// Authorization: an owner may, a deployment operator may (an ops owner and
+// an address on CARLOS_SYSTEM_OPERATORS, neither a member), a member is
+// refused with the owner sentence, a service credential is refused by the
+// role gate, and an owner of another account gets the bare 404. Nothing a
+// refused caller sends is written or audited.
+func TestAppRegionSetAuthorization(t *testing.T) {
+ fx := newAppRegionFx(t)
+ fx.srv.cfg.SystemOperators = []string{"sysop@example.test"}
+ now := time.Now()
+ if err := fx.st.CreateAccount(43, "efgh", "Other Co", "other@example.test", now); err != nil {
+ t.Fatal(err)
+ }
+ owner := cliToken(t, fx.consoleFixture, arOwner, "code-ar-owner")
+ member := cliToken(t, fx.consoleFixture, arMember, "code-ar-member")
+ other := cliToken(t, fx.consoleFixture, "other@example.test", "code-ar-other")
+ sysop := cliToken(t, fx.consoleFixture, "sysop@example.test", "code-ar-sysop")
+ opsOwner := cliToken(t, fx.consoleFixture, "paul@keymail.dev", "code-ar-ops")
+ _, bare := getRaw(t, fx.ts.URL+"/api/cli/apps/zzzz/nosuch/region", other)
+
+ if st, out := fx.put(t, member, "shop", "uk"); st != http.StatusForbidden || !strings.Contains(out, appRegionSetCopy.NotOwner) {
+ t.Fatalf("member = %d %s, want 403 with the owner sentence", st, out)
+ }
+ if st, out := fx.put(t, other, "shop", "uk"); st != http.StatusNotFound || out != bare {
+ t.Fatalf("another account's owner = %d %q, want the bare 404 %q", st, out, bare)
+ }
+ for _, role := range []svcrole.Role{svcrole.Admin, svcrole.Publish, svcrole.Instance, svcrole.Operate} {
+ svc := serviceToken(t, fx.st, 42, "svc-"+string(role), "shop", role)
+ if st, out := fx.put(t, svc, "shop", "uk"); st != http.StatusForbidden {
+ t.Fatalf("service %s = %d %s, want 403", role, st, out)
+ }
+ if st, out := fx.get(t, svc, "shop"); st != http.StatusForbidden {
+ t.Fatalf("service %s GET = %d %s, want 403", role, st, out)
+ }
+ }
+ if r, _ := fx.stored(t, "shop"); r != "" {
+ t.Fatalf("a refused caller changed the region to %q", r)
+ }
+ if evs := fx.regionEvents(t, "shop"); len(evs) != 0 {
+ t.Fatalf("refused callers audited %d rows", len(evs))
+ }
+ // A member may read the region; another account may not.
+ if st, out := fx.get(t, member, "shop"); st != http.StatusOK || decodeRegionView(t, out).Label != "Dublin (ie)" {
+ t.Fatalf("member GET = %d %s", st, out)
+ }
+ if st, out := fx.get(t, other, "shop"); st != http.StatusNotFound || out != bare {
+ t.Fatalf("another account's GET = %d %q", st, out)
+ }
+
+ for i, c := range []struct {
+ who, token, to string
+ }{
+ {arOwner, owner, "uk"},
+ {"paul@keymail.dev", opsOwner, "ie"},
+ {"sysop@example.test", sysop, "uk"},
+ } {
+ st, out := fx.put(t, c.token, "shop", c.to)
+ if st != http.StatusOK {
+ t.Fatalf("%s = %d %s, want 200", c.who, st, out)
+ }
+ v := decodeRegionView(t, out)
+ if !v.Changed || v.Region != c.to {
+ t.Fatalf("%s reply = %+v", c.who, v)
+ }
+ evs := fx.regionEvents(t, "shop")
+ if len(evs) != i+1 || evs[0].Address != c.who {
+ t.Fatalf("%s: audit rows %+v", c.who, evs)
+ }
+ }
+ if r, src := fx.stored(t, "shop"); r != "uk" || src != "changed" {
+ t.Fatalf("stored = %q %q, want uk changed", r, src)
+ }
+}
+
+// The change is a SQLite write: no bucket object is written, changed or
+// removed, so no box sees anything and no instance record moves. The audit
+// row carries the old and the new region.
+func TestAppRegionSetWritesOnlyTheRowAndAudits(t *testing.T) {
+ fx := newAppRegionFx(t)
+ owner := cliToken(t, fx.consoleFixture, arOwner, "code-ar-owner")
+ ctx := context.Background()
+ if err := provision.CreateRecord(ctx, fx.rel, provision.Record{Schema: 1, Host: "one.shop.example", Slug: "one", App: "shop",
+ Account: arSqid, Channel: "edge", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ before := bucketSnapshot(t, fx.rel)
+ st, out := fx.put(t, owner, "shop", "uk")
+ if st != http.StatusOK {
+ t.Fatalf("set = %d %s", st, out)
+ }
+ v := decodeRegionView(t, out)
+ if v.Previous != "ie" || v.PreviousLabel != "Dublin (ie)" || v.Label != "London (uk)" {
+ t.Fatalf("reply = %+v", v)
+ }
+ if after := bucketSnapshot(t, fx.rel); !equalSnapshots(before, after) {
+ t.Fatalf("the change touched the bucket:\nbefore %v\nafter %v", before, after)
+ }
+ rec, err := provision.GetRecord(ctx, fx.rel, arSqid, "shop", "one.shop.example")
+ if err != nil || rec.Region != "" {
+ t.Fatalf("the existing instance's region is %q (%v), want it unchanged", rec.Region, err)
+ }
+ evs := fx.regionEvents(t, "shop")
+ if len(evs) != 1 || evs[0].Detail != "changed shop's region from Dublin (ie) to London (uk) (cli)" {
+ t.Fatalf("audit = %+v", evs)
+ }
+ // The same region again changes nothing and audits nothing.
+ st, out = fx.put(t, owner, "shop", "uk")
+ if v := decodeRegionView(t, out); st != http.StatusOK || v.Changed || v.Label != "London (uk)" {
+ t.Fatalf("same region = %d %s", st, out)
+ }
+ if evs := fx.regionEvents(t, "shop"); len(evs) != 1 {
+ t.Fatalf("a no-op change audited: %+v", evs)
+ }
+ // The home by name stores the record's "" again.
+ if st, out := fx.put(t, owner, "shop", "ie"); st != http.StatusOK {
+ t.Fatalf("back home = %d %s", st, out)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "" {
+ t.Fatalf("home stored as %q, want \"\"", r)
+ }
+}
+
+// Each refusal, checked before any write.
+func TestAppRegionSetRefusals(t *testing.T) {
+ fx := newAppRegionFx(t)
+ owner := cliToken(t, fx.consoleFixture, arOwner, "code-ar-owner")
+ ctx := context.Background()
+ now := time.Now()
+ for _, app := range []string{"fleeted", "pooled", "narrow", "binned"} {
+ if _, err := fx.st.CreateAppIn(42, app, arOwner, now); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := fx.st.SetAppPlacement(42, "fleeted", "fleet/racks"); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutManifest(ctx, fx.rel, arSqid, "pooled", provision.Manifest{Schema: 1, App: "pooled", Domain: "cdef.example", Pool: "web"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutManifest(ctx, fx.rel, arSqid, "narrow", provision.Manifest{Schema: 1, App: "narrow", Domain: "cdef.example", Regions: []string{"uk"}}); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.TrashAppRow(42, "binned", now); err != nil {
+ t.Fatal(err)
+ }
+ for _, c := range []struct {
+ name, app, region string
+ status int
+ want string
+ }{
+ {"unknown region", "shop", "zz", http.StatusBadRequest, "region zz is not one this platform offers. Choose from: fr, ie, uk."},
+ {"not armed", "shop", "us", http.StatusBadRequest, "region us is not one this platform offers. Choose from: fr, ie, uk."},
+ {"not a region", "shop", "UK!", http.StatusBadRequest, "region UK! is not one this platform offers. Choose from: fr, ie, uk."},
+ {"cannot start instances", "shop", "fr", http.StatusConflict, "region fr can't take new instances right now (boxes there don't take ordinary instances), so the app's region was not changed."},
+ {"no region", "shop", " ", http.StatusBadRequest, appRegionSetCopy.NoRegion},
+ {"fleet", "fleeted", "uk", http.StatusConflict, fmt.Sprintf(appRegionSetCopy.OnFleet, "fleeted", "racks")},
+ {"pooled", "pooled", "uk", http.StatusConflict, fmt.Sprintf(appRegionSetCopy.Pooled, "pooled")},
+ {"allow-list", "narrow", "ie", http.StatusConflict, "region ie is not one this app's instances may use. Allowed: uk."},
+ {"trash", "binned", "uk", http.StatusConflict, fmt.Sprintf(appRegionSetCopy.InTrash, "binned")},
+ } {
+ st, out := fx.put(t, owner, c.app, c.region)
+ var e struct{ Error string }
+ json.Unmarshal([]byte(out), &e)
+ if st != c.status || e.Error != c.want {
+ t.Errorf("%s = %d %q, want %d %q", c.name, st, out, c.status, c.want)
+ }
+ if r, _, _ := fx.st.AppRegion(42, c.app); r != "" {
+ t.Errorf("%s: stored %q", c.name, r)
+ }
+ }
+ if evs, _ := fx.st.Events(42, "", 100); len(evs) != 0 {
+ for _, e := range evs {
+ if e.Action == "region" {
+ t.Fatalf("a refusal audited: %+v", e)
+ }
+ }
+ }
+ // A temporary app is not pinned: its region changes like any other.
+ if _, err := insertAppRow(fx.st.db, newAppRow{AccountID: 42, App: "tmp-docs", CreatedBy: arOwner, CreatedAt: now.Unix(),
+ ExpiresAt: now.Add(time.Hour).Unix()}); err != nil {
+ t.Fatal(err)
+ }
+ if st, out := fx.put(t, owner, "tmp-docs", "uk"); st != http.StatusOK {
+ t.Fatalf("temporary app = %d %s", st, out)
+ }
+}
+
+// With CONSOLE_APP_REGIONS off (the fixture's default) the change is still
+// written, because the instance create door reads the stored region with
+// the switch off too (member moves Q5).
+func TestAppRegionSetWithTheSwitchOff(t *testing.T) {
+ fx := newAppRegionFx(t)
+ if fx.srv.appRegionsOn() {
+ t.Fatal("fixture has app regions on")
+ }
+ owner := cliToken(t, fx.consoleFixture, arOwner, "code-ar-owner")
+ if st, out := fx.put(t, owner, "shop", "uk"); st != http.StatusOK {
+ t.Fatalf("switch off = %d %s", st, out)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "uk" {
+ t.Fatalf("stored %q", r)
+ }
+}
+
+// The GET names a fleet that governs instead of a region.
+func TestAppRegionGetOnAFleet(t *testing.T) {
+ fx := newAppRegionFx(t)
+ owner := cliToken(t, fx.consoleFixture, arOwner, "code-ar-owner")
+ if err := fx.st.SetAppPlacement(42, "shop", "fleet/racks"); err != nil {
+ t.Fatal(err)
+ }
+ st, out := fx.get(t, owner, "shop")
+ if v := decodeRegionView(t, out); st != http.StatusOK || v.Fleet != "racks" {
+ t.Fatalf("GET = %d %s", st, out)
+ }
+}
+
+// The placement discrepancy log reads a record from before the change as
+// made under the old region.
+func TestAppRegionSetMovesTheDiscrepancyCut(t *testing.T) {
+ fx := newAppRegionFx(t)
+ created := time.Unix(1_700_000_000, 0)
+ if _, err := fx.st.CreateAppInRegion(42, "cart", arOwner, "uk", "chosen", created); err != nil {
+ t.Fatal(err)
+ }
+ inc, ok, err := fx.st.AppIncarnationContext(context.Background(), 42, "cart")
+ if err != nil || !ok {
+ t.Fatal(ok, err)
+ }
+ changed := created.Add(48 * time.Hour)
+ if ok, err := fx.st.SetAppRegion(context.Background(), 42, "cart", inc, "uk", "us", changed); err != nil || !ok {
+ t.Fatalf("set = %v %v", ok, err)
+ }
+ // A second write pinned to the old region lands nowhere.
+ if ok, err := fx.st.SetAppRegion(context.Background(), 42, "cart", inc, "uk", "ie", changed); err != nil || ok {
+ t.Fatalf("stale set = %v %v, want false", ok, err)
+ }
+ rows, err := fx.st.NonHomeAppRegions()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, r := range rows {
+ if r.App == "cart" {
+ if r.Region != "us" || !r.CreatedAt.Equal(changed) {
+ t.Fatalf("row = %+v, want us from %v", r, changed)
+ }
+ return
+ }
+ }
+ t.Fatalf("cart missing from %+v", rows)
+}
+
+// The browser control: shown to an owner on Settings > General, absent for
+// a member; the form changes the region for an owner, and a member's post
+// is the same 404 a non-member gets.
+func TestAppRegionSettingsControl(t *testing.T) {
+ fx := newAppRegionFx(t)
+ ownerC, ownerCSRF := signInAs(t, fx.consoleFixture, arOwner, "code-ar-owner-web")
+ memberC, memberCSRF := signInAs(t, fx.consoleFixture, arMember, "code-ar-member-web")
+ page := fx.ts.URL + "/a/" + arSqid + "/apps/shop/settings"
+ _, _, body := get(t, ownerC, page)
+ if !strings.Contains(body, appRegionSetCopy.ControlButton) || !strings.Contains(body, `<option value="uk">London (uk)</option>`) ||
+ !strings.Contains(body, `<option value="ie" selected>Dublin (ie)</option>`) {
+ t.Fatalf("owner's settings page has no region control:\n%s", body)
+ }
+ if _, _, body := get(t, memberC, page); strings.Contains(body, appRegionSetCopy.ControlButton) {
+ t.Fatal("a member sees the region control")
+ }
+ action := fx.ts.URL + "/a/" + arSqid + "/apps/shop/region"
+ if st, _, _ := postForm(t, memberC, action, url.Values{"csrf": {memberCSRF}, "region": {"uk"}}); st != http.StatusNotFound {
+ t.Fatalf("member post = %d, want 404", st)
+ }
+ if st, _, _ := postForm(t, ownerC, action, url.Values{"csrf": {"wrong"}, "region": {"uk"}}); st != http.StatusForbidden {
+ t.Fatalf("bad csrf = %d, want 403", st)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "" {
+ t.Fatalf("a refused post stored %q", r)
+ }
+ st, loc, _ := postForm(t, ownerC, action, url.Values{"csrf": {ownerCSRF}, "region": {"uk"}})
+ if st != http.StatusSeeOther || !strings.HasSuffix(loc, "/apps/shop/settings") {
+ t.Fatalf("owner post = %d %q", st, loc)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "uk" {
+ t.Fatalf("stored %q after the owner's post", r)
+ }
+ _, _, body = get(t, ownerC, page)
+ if !strings.Contains(body, fmt.Sprintf(appRegionSetCopy.FlashChanged, "London (uk)")) || !strings.Contains(body, appRegionSetCopy.SourceChanged) {
+ t.Fatalf("no flash or source sentence after the change:\n%s", body)
+ }
+}
+
+// bucketSnapshot is every key in the store with its bytes.
+func bucketSnapshot(t *testing.T, s release.Store) map[string]string {
+ t.Helper()
+ keys, err := s.List(context.Background(), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := map[string]string{}
+ for _, k := range keys {
+ b, _, err := s.Get(context.Background(), k)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out[k] = string(b)
+ }
+ return out
+}
+
+func equalSnapshots(a, b map[string]string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for k, v := range a {
+ if b[k] != v {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index c0a6ba816..0d1fc183a 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -536,6 +536,11 @@ func (s *Server) registerCLIRoutes() {
s.cliRoute("GET /api/cli/apps/{account}/list", svcrole.Allow(svcrole.Publish), s.handleAPIAppList)
s.cliRoute("POST /api/cli/apps/{account}/{app}/ttl", svcrole.Allow(svcrole.Publish), s.handleAPIAppTTL)
s.cliRoute("POST /api/cli/apps/{account}/{app}/keep", svcrole.Allow(svcrole.Publish), s.handleAPIAppKeep)
+ // The app's region, the default for its NEW instances (appregionset.go).
+ // A person only: an account owner or a deployment operator may change
+ // it, so no service role reaches either door.
+ s.cliRoute("GET /api/cli/apps/{account}/{app}/region", svcrole.Set{}, s.handleAPIAppRegionGet)
+ s.cliRoute("PUT /api/cli/apps/{account}/{app}/region", svcrole.Set{}, s.handleAPIAppRegionSet)
s.cliRoute("GET /api/cli/apps/{account}/{app}/channels", svcrole.Allow(svcrole.Publish, svcrole.Deploy), s.handleAPIChannels)
s.cliRoute("POST /api/cli/apps/{account}/{app}/promote", svcrole.Allow(svcrole.Publish, svcrole.Deploy), s.handleAPIPromote)
s.cliRoute("POST /api/cli/apps/{account}/{app}/rollback", svcrole.Allow(svcrole.Publish, svcrole.Deploy), s.handleAPIRollback)
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 41b56db35..9ce4e7565 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -848,6 +848,7 @@ var claimFixtures = map[string]claimFixture{
"route GET /api/cli/apps/{account}/{app}/pending": claimRead("lists pending proposals"),
"route GET /api/cli/apps/{account}/{app}/pipeline": claimRead("reads the pipeline"),
"route GET /api/cli/apps/{account}/{app}/regions": claimRead("reads armed regions"),
+ "route GET /api/cli/apps/{account}/{app}/region": claimRead("reads the app's stored region and placement from SQLite and the registry; writes nothing"),
"route GET /api/cli/apps/{account}/{app}/relay": claimRead("reads relay status and heartbeats"),
"route GET /api/cli/apps/{account}/{app}/releases": claimRead("lists releases"),
"route GET /api/cli/apps/{account}/{app}/releases/{version}/authorize": claimRead(
@@ -1253,6 +1254,20 @@ var claimFixtures = map[string]claimFixture{
},
do: claimForm("/a/bab/apps/titogo/ratelimit", "host", "acme.go.tito.io", "action", "set", "rate", "500"),
}},
+ // Changing an app's region (appregionset.go) has no claim operation:
+ // a host-claim console refuses it before reading anything.
+ "route POST /a/{sqid}/apps/{app}/region": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"),
+ do: claimRefusedForm("/a/bab/apps/titogo/region", "region", "ie"),
+ status: http.StatusConflict,
+ msg: appRegionSetCopy.ClaimOff,
+ }},
+ "route PUT /api/cli/apps/{account}/{app}/region": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"),
+ do: claimRefusedAPI(http.MethodPut, "/api/cli/apps/bab/titogo/region", `{"region":"ie"}`),
+ status: http.StatusConflict,
+ msg: appRegionSetCopy.ClaimOff,
+ }},
"route POST /a/{sqid}/apps/{app}/rename": {refused: &claimRefusalFixture{
apps: claimRefs("bab/titogo", "+bab/titogo-renamed"),
do: claimRefusedForm("/a/bab/apps/titogo/rename", "to", "titogo-renamed", "confirmed", "1"),
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index 0b5be7c63..5b56260af 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -234,6 +234,7 @@ var claimReadProbes = map[string]claimProbe{
"/api/cli/apps/bab/titogo/pending", "<pending>"),
"route GET /api/cli/apps/{account}/{app}/pipeline": claimAPIRead(nil, "/api/cli/apps/bab/titogo/pipeline", `"pipeline"`),
"route GET /api/cli/apps/{account}/{app}/regions": claimAPIRead(nil, "/api/cli/apps/bab/titogo/regions", `"regions"`),
+ "route GET /api/cli/apps/{account}/{app}/region": claimAPIRead(nil, "/api/cli/apps/bab/titogo/region", `"app":"titogo"`),
"route GET /api/cli/apps/{account}/{app}/relay": claimSerialProbe("relayEnabled stages the region's relay master through t.Setenv: process environment",
claimAPIRead(func(t *testing.T, cx *claimCase) { cx.relayEnabled(t) },
"/api/cli/apps/bab/titogo/relay", `"app":"titogo"`, `"enabled":true`)),
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go
index 8ae62d251..f4921d5e1 100644
--- a/internal/console/claim_invariant_test.go
+++ b/internal/console/claim_invariant_test.go
@@ -119,6 +119,8 @@ var claimUnsupported = map[string]string{
"the cutover door refuses after its operator check and before it reads or writes anything",
claimDBReadResidencyMsg: "a forwarded db read needs the root signer, which a host-claim console never uses for it " +
"(db region forward spec §6): the reads route reads the record and answers main's residency sentence, writing nothing",
+ appRegionSetCopy.ClaimOff: "changing an app's stored region writes its SQL row, and no claim operation gates that write; " +
+ "both doors refuse after their caller gates and before they read or write anything",
seedClaimConsoleRefusal().Msg: "seeded instances need nested boxes, and the claim-armed path waits for #250 (seeded-instances spec §3.4); " +
"every import door refuses before it reads the record, and the legacy route assignment before it reads anything",
}
diff --git a/internal/console/regionfacts.go b/internal/console/regionfacts.go
index b1eeb4580..c93c769b8 100644
--- a/internal/console/regionfacts.go
+++ b/internal/console/regionfacts.go
@@ -101,6 +101,8 @@ func (f appRegionFacts) SourceSentence() string {
return regionLabelCopy.SourceIP
case "default":
return regionLabelCopy.SourceDefault
+ case "changed":
+ return appRegionSetCopy.SourceChanged
}
return ""
}
diff --git a/internal/console/server.go b/internal/console/server.go
index 72027db93..1847972ea 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1735,6 +1735,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// The Deploys card's form (appswap.go): member-gated, like the gate.
s.registerRoute("POST /a/{sqid}/apps/{app}/swap", s.handleAppSwap)
s.registerRoute("POST /a/{sqid}/apps/{app}/rename", s.handleAppRename)
+ s.registerRoute("POST /a/{sqid}/apps/{app}/region", s.handleAppRegionSet)
s.registerRoute("POST /a/{sqid}/apps/{app}/keep", s.handleAppKeep)
s.registerRoute("POST /a/{sqid}/apps/{app}/delete", s.handleAppDelete)
s.registerRoute("POST /a/{sqid}/apps/{app}/move", s.handleAppMoveAccount)
@@ -2021,6 +2022,11 @@ type page struct {
// counts from the rows the page holds.
StoredRegion appRegionFacts
StoredElsewhere []regionCount
+ // CanSetRegion shows Settings > General's Region control (an owner or a
+ // deployment operator, appregionset.go); RegionOptions are its choices,
+ // from the region name map in memory.
+ CanSetRegion bool
+ RegionOptions []regionOption
InstanceDetail *instanceDetail
InstanceGroups []instanceGroup
@@ -4431,6 +4437,9 @@ func (s *Server) populateAppSettings(r *http.Request, p *page, acct *Account, se
if reads.swap {
s.loadSwapPolicy(r.Context(), p, acct)
}
+ if section == "general" && p.StoredRegion.Known && p.StoredRegion.Fleet == "" && s.canSetAppRegion(p.Address, p.Role) {
+ p.CanSetRegion, p.RegionOptions = true, s.appRegionPageChoices()
+ }
if !reads.telemetry {
return
}
diff --git a/internal/console/store.go b/internal/console/store.go
index b953f5be1..a73d38883 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -566,6 +566,12 @@ func (s *Store) migrate() error {
// predates the feature). No timezone, IP or coordinate is stored.
`ALTER TABLE apps ADD COLUMN region TEXT NOT NULL DEFAULT '';`,
`ALTER TABLE apps ADD COLUMN region_source TEXT NOT NULL DEFAULT '';`,
+ // When the app's region was last changed after its create (carlos
+ // apps region --set), Unix seconds; 0 = never. The placement
+ // discrepancy log reads a record created before it as made under the
+ // old region (regiondrift.go). Member moves' region write uses the
+ // same column (member-moves design §6.6).
+ `ALTER TABLE apps ADD COLUMN region_set_at INTEGER NOT NULL DEFAULT 0;`,
// How a session was proved (email sign-in spec §5.4). Every session
// that predates the column was made through Keymail, so the default
// is the backfill.
@@ -706,6 +712,7 @@ func (s *Store) migrateAppsKey() error {
build_probe TEXT NOT NULL DEFAULT '',
region TEXT NOT NULL DEFAULT '',
region_source TEXT NOT NULL DEFAULT '',
+ region_set_at INTEGER NOT NULL DEFAULT 0,
expires_at INTEGER NOT NULL DEFAULT 0,
restoring INTEGER NOT NULL DEFAULT 0,
purge_after INTEGER NOT NULL DEFAULT 0,
@@ -715,7 +722,7 @@ func (s *Store) migrateAppsKey() error {
);`,
// The ALTERs above run before migrateAppsKey in migrate(), so
// deleted_at, placement, control_plane, build_probe, region,
- // region_source and the temporary columns already exist on the old
+ // region_source, region_set_at and the temporary columns already exist on the old
// table by the time this rebuild copies them — a row already
// trashed, already placed, already the control plane, already
// carrying a build probe or an app region, or already temporary,
@@ -724,8 +731,8 @@ func (s *Store) migrateAppsKey() error {
// lifetime is carried across, and minted for a row that has none (the
// ALTER above adds it empty); randomblob(8) is 16 hex digits, the
// same form insertAppRow mints.
- `INSERT INTO apps_new (app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, expires_at, restoring, purge_after, purge_for, lifetime)
- SELECT app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, expires_at, restoring, purge_after, purge_for,
+ `INSERT INTO apps_new (app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, expires_at, restoring, purge_after, purge_for, lifetime)
+ SELECT app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, expires_at, restoring, purge_after, purge_for,
CASE WHEN lifetime = '' THEN lower(hex(randomblob(8))) ELSE lifetime END FROM apps;`,
`DROP TABLE apps;`,
`ALTER TABLE apps_new RENAME TO apps;`,
@@ -1687,15 +1694,36 @@ func (s *Store) AppRegion(accountID int64, app string) (region, source string, e
return region, source, err
}
+// SetAppRegion changes a live app's stored region, the default for its NEW
+// instances (carlos apps region --set). The update is pinned to the
+// incarnation and the region the caller read (inc, from), so a delete, a
+// rename that freed the name, a create that took it again, or another
+// change in between writes nothing: ok is false. region is in the record
+// vocabulary ("" is the home). The source becomes "changed" and
+// region_set_at the time of the change. Nothing else reads the row's region
+// to place an existing instance, so no instance moves.
+func (s *Store) SetAppRegion(ctx context.Context, accountID int64, app string, inc AppIncarnation, from, to string, now time.Time) (ok bool, err error) {
+ res, err := s.db.ExecContext(ctx, `UPDATE apps SET region = ?, region_source = 'changed', region_set_at = ?
+WHERE account_id = ? AND app = ? AND deleted_at = 0 AND created_at = ? AND region = ?`,
+ to, now.Unix(), accountID, app, inc.createdAt, from)
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ return n == 1, err
+}
+
// nonHomeAppRegion is one live app holding a non-home region, for the
-// roll-forward discrepancy log (spec §5.7).
+// roll-forward discrepancy log (spec §5.7). CreatedAt is the later of the
+// app's create and its last region change: a record from before either was
+// made under another default.
type nonHomeAppRegion struct {
Sqid, App, Region string
CreatedAt time.Time
}
func (s *Store) NonHomeAppRegions() ([]nonHomeAppRegion, error) {
- rows, err := s.db.Query(`SELECT a.sqid, p.app, p.region, p.created_at FROM apps p
+ rows, err := s.db.Query(`SELECT a.sqid, p.app, p.region, max(p.created_at, p.region_set_at) FROM apps p
JOIN accounts a ON a.id = p.account_id
WHERE p.region != '' AND p.deleted_at = 0 ORDER BY a.sqid, p.app`)
if err != nil {
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 614416b39..bbee0a8e7 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -255,6 +255,10 @@ var closedDoors = []string{
// no service role is the right holder of an operator's decision.
"GET /api/cli/apps/{account}/{app}/policy",
"PUT /api/cli/apps/{account}/{app}/policy",
+ // An app's region (appregionset.go): an account owner or a deployment
+ // operator changes it, a person in either case.
+ "GET /api/cli/apps/{account}/{app}/region",
+ "PUT /api/cli/apps/{account}/{app}/region",
// The sidecar manifest, shut for the instances manifest's reason and one
// of its own. It is standing policy — which domain, pool, regions and
// channel a sidecar may ever come up on — and it also carries `args`,
diff --git a/internal/console/templates/app_settings.html b/internal/console/templates/app_settings.html
index 452912542..6ec60d656 100644
--- a/internal/console/templates/app_settings.html
+++ b/internal/console/templates/app_settings.html
@@ -22,6 +22,17 @@ release moves through, and what each one takes to promote onto.</p>
{{if .StoredRegion.Known}}
<p>{{.StoredRegion.Sentence}}{{with .StoredRegion.SourceSentence}} {{.}}{{end}}</p>
<p class="small"><a href="{{.Nav}}/apps/{{.Detail.App}}/instances#app-region-line">{{.RegionLabelCopy.SeeRunning}}</a></p>
+{{if and .CanSetRegion .RegionOptions}}
+<form method="post" action="{{.Base}}/apps/{{.Detail.App}}/region" class="settings-row">
+ <input type="hidden" name="csrf" value="{{.CSRF}}">
+ <label for="app-region">{{.AppRegionSetCopy.ControlLabel}}</label>
+ <select id="app-region" name="region">
+ {{range .RegionOptions}}<option value="{{.Value}}"{{if eq .Value $.StoredRegion.Code}} selected{{end}}>{{.Label}}</option>{{end}}
+ </select>
+ <button type="submit" class="btn-sm">{{.AppRegionSetCopy.ControlButton}}</button>
+</form>
+<p class="small">{{.AppRegionSetCopy.ControlNote}}</p>
+{{end}}
{{else}}
<p class="small">Could not read where this app runs.</p>
{{end}}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 416a0401e..bf3fbd477 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -73,6 +73,7 @@ route GET /api/cli/apps/{account}/{app}/logs
route GET /api/cli/apps/{account}/{app}/pending
route GET /api/cli/apps/{account}/{app}/pipeline
route GET /api/cli/apps/{account}/{app}/policy
+route GET /api/cli/apps/{account}/{app}/region
route GET /api/cli/apps/{account}/{app}/regions
route GET /api/cli/apps/{account}/{app}/relay
route GET /api/cli/apps/{account}/{app}/releases
@@ -146,6 +147,7 @@ route POST /a/{sqid}/apps/{app}/place
route POST /a/{sqid}/apps/{app}/production
route POST /a/{sqid}/apps/{app}/promote
route POST /a/{sqid}/apps/{app}/ratelimit
+route POST /a/{sqid}/apps/{app}/region
route POST /a/{sqid}/apps/{app}/rename
route POST /a/{sqid}/apps/{app}/restart
route POST /a/{sqid}/apps/{app}/rollback
@@ -294,6 +296,7 @@ route PUT /api/cli/apps/{account}/{app}/instances/{host}/import
route PUT /api/cli/apps/{account}/{app}/instances/{host}/updates
route PUT /api/cli/apps/{account}/{app}/pipeline
route PUT /api/cli/apps/{account}/{app}/policy
+route PUT /api/cli/apps/{account}/{app}/region
route PUT /api/cli/apps/{account}/{app}/sidecars-manifest
route PUT /api/cli/apps/{account}/{app}/swap
route PUT /api/cli/apps/{account}/{app}/telemetry
diff --git a/internal/regionlabel/regionlabel.go b/internal/regionlabel/regionlabel.go
index d10388363..fd56d3dac 100644
--- a/internal/regionlabel/regionlabel.go
+++ b/internal/regionlabel/regionlabel.go
@@ -6,6 +6,7 @@
package regionlabel
import (
+ "sort"
"strings"
"github.com/carlosframework/platform/internal/edgesfile"
@@ -75,6 +76,17 @@ func NamesFrom(snap edgesfile.Snapshot, home string) Names {
return n
}
+// Codes is every display code an edges file names with an AWS region,
+// sorted: the places the map can label.
+func (n Names) Codes() []string {
+ out := make([]string, 0, len(n.aws))
+ for c := range n.aws {
+ out = append(out, c)
+ }
+ sort.Strings(out)
+ return out
+}
+
// BoxPlacement is a box's placement code in the record vocabulary. known
// is false for a box no edges file names; ("", true) is the home.
func (n Names) BoxPlacement(label string) (code string, known bool) {