| 1 | package adopt |
| 2 | |
| 3 | // The rehearsal: the whole adoption in the order Paul runs it, against |
| 4 | // the in-memory Home, the fake console and the six apps' origins. Home |
| 5 | // preflights, CARLOS preflight, initialize, Plan A, configure (with its |
| 6 | // delivery check) for each app, Plan B for the canary, Plan C. Then the |
| 7 | // same run killed at every act, Home's and CARLOS's, and resumed by a |
| 8 | // fresh process. |
| 9 | |
| 10 | import ( |
| 11 | "bytes" |
| 12 | "context" |
| 13 | "database/sql" |
| 14 | "encoding/json" |
| 15 | "errors" |
| 16 | "fmt" |
| 17 | "io" |
| 18 | "log/slog" |
| 19 | "net" |
| 20 | "net/http" |
| 21 | "net/http/httptest" |
| 22 | "net/http/httputil" |
| 23 | "net/url" |
| 24 | "path/filepath" |
| 25 | "reflect" |
| 26 | "slices" |
| 27 | "strings" |
| 28 | "sync" |
| 29 | "testing" |
| 30 | "time" |
| 31 | |
| 32 | "amadan.net/oficina/alta/carlosop" |
| 33 | "amadan.net/oficina/alta/carlosop/fakecarlos" |
| 34 | "amadan.net/oficina/alta/console" |
| 35 | "amadan.net/oficina/alta/homeop" |
| 36 | "amadan.net/oficina/alta/homeop/fakehome" |
| 37 | "amadan.net/oficina/alta/provision" |
| 38 | family "amadan.net/rastrillo/rastrillo/crypto" |
| 39 | ) |
| 40 | |
| 41 | const rehearsalOwner = "rehearsal-owner-canary@oficina.test" |
| 42 | |
| 43 | // crashPoint is where a CARLOS process dies: on its first request of that |
| 44 | // kind for an app, once per app. Before: the request never reaches the |
| 45 | // console. After: the console has acted, and the answer never arrives. |
| 46 | type crashPoint string |
| 47 | |
| 48 | const ( |
| 49 | noCrash crashPoint = "" |
| 50 | beforePut crashPoint = "before-put" |
| 51 | afterPut crashPoint = "after-put" |
| 52 | afterRestart crashPoint = "after-restart" |
| 53 | ) |
| 54 | |
| 55 | // rehearsal is one adoption, start to finish. |
| 56 | type rehearsal struct { |
| 57 | t *testing.T |
| 58 | |
| 59 | mu sync.Mutex |
| 60 | now time.Time |
| 61 | |
| 62 | home *fakehome.Home |
| 63 | hc *homeop.Client |
| 64 | carlos *fakecarlos.Fake |
| 65 | h *http.Client // the apps' origins |
| 66 | |
| 67 | path string // the state database |
| 68 | ps *provision.Store |
| 69 | js *Store |
| 70 | cfg provision.Config |
| 71 | actsMu sync.Mutex |
| 72 | acts []string // every Home act, in order |
| 73 | |
| 74 | sites map[string]*appSite |
| 75 | |
| 76 | // CARLOS crashes: which apps have died at the point already, and what |
| 77 | // the console saw. |
| 78 | crashed map[string]bool |
| 79 | puts map[string]int // PUT /config reaching the console, per app |
| 80 | foreign []string // an unset of a value the runner did not write |
| 81 | sealed map[string][]byte // each baseline's sealed bytes, as first seen |
| 82 | before map[string]layerState |
| 83 | release chan struct{} |
| 84 | zombies sync.WaitGroup |
| 85 | cancels []context.CancelFunc |
| 86 | closers []func() |
| 87 | sqid string |
| 88 | planARun int64 |
| 89 | } |
| 90 | |
| 91 | // layerState is an app's two stored layers: the canonical host's default |
| 92 | // bundle and its neighbour's own environment. |
| 93 | type layerState struct { |
| 94 | def, env map[string]fakecarlos.Var |
| 95 | defVer, envVer string |
| 96 | } |
| 97 | |
| 98 | // appSite is one app's process: it serves agent-access's challenge only |
| 99 | // once a restart has loaded both of its agent keys. |
| 100 | type appSite struct { |
| 101 | mu sync.Mutex |
| 102 | seen int |
| 103 | loaded bool |
| 104 | } |
| 105 | |
| 106 | func neighbourHost(app string) string { return "staging." + app + ".example" } |
| 107 | func neighbourEnv(app string) string { return "acme-" + app } |
| 108 | |
| 109 | func newRehearsal(t *testing.T) *rehearsal { |
| 110 | t.Helper() |
| 111 | r := &rehearsal{t: t, now: time.Unix(2_000_000_000, 0), sites: map[string]*appSite{}, |
| 112 | crashed: map[string]bool{}, puts: map[string]int{}, sealed: map[string][]byte{}, before: map[string]layerState{}, |
| 113 | release: make(chan struct{})} |
| 114 | // First registered, so it runs last: a dead process is let go, waited |
| 115 | // for, and only then are its console door and journal closed. |
| 116 | t.Cleanup(func() { |
| 117 | close(r.release) |
| 118 | for _, c := range r.cancels { |
| 119 | c() |
| 120 | } |
| 121 | r.zombies.Wait() |
| 122 | for i := len(r.closers) - 1; i >= 0; i-- { |
| 123 | r.closers[i]() |
| 124 | } |
| 125 | }) |
| 126 | fastPolls(t, 5*time.Millisecond, 2*time.Second) |
| 127 | |
| 128 | key, err := family.Generate() |
| 129 | if err != nil { |
| 130 | t.Fatal(err) |
| 131 | } |
| 132 | pre := homeop.Token() |
| 133 | const credOrigin, dirOrigin = HomeIssuerOrigin, "https://oficina.works" |
| 134 | r.home = fakehome.New(key.SignPub(), pre, credOrigin, dirOrigin, r.clock) |
| 135 | pins := r.home.SharePins() |
| 136 | r.home.AddPerson(rehearsalOwner) |
| 137 | for _, a := range provision.Slugs() { |
| 138 | r.home.AddEnvConsumer(a, homeop.CanonicalOrigin(a)) |
| 139 | } |
| 140 | roles := map[string]homeop.Role{} |
| 141 | for name, origin := range map[string]string{homeop.Credential: credOrigin, homeop.Directory: dirOrigin} { |
| 142 | srv := httptest.NewServer(r.home.Handler(name)) |
| 143 | t.Cleanup(srv.Close) |
| 144 | roles[name] = homeop.Role{Name: name, Origin: origin, URL: srv.URL, Installation: pins.Installation, Registry: pins.Registry, Device: pins.Device} |
| 145 | } |
| 146 | r.hc = &homeop.Client{Key: key, Prefilter: pre, Roles: roles, Now: r.clock} |
| 147 | |
| 148 | r.carlos = fakecarlos.New(fixtureAccount) |
| 149 | t.Cleanup(r.carlos.Close) |
| 150 | r.carlos.BeforePut = func(app string) { |
| 151 | r.mu.Lock() |
| 152 | r.puts[app]++ |
| 153 | r.mu.Unlock() |
| 154 | } |
| 155 | for _, a := range provision.Apps { |
| 156 | p := a.Prefix |
| 157 | r.carlos.SetVar(a.Slug, "", p+"_HOME_ISSUER", HomeIssuerOrigin) |
| 158 | r.carlos.SetVar(a.Slug, "", p+"_HOME_CONSUMER_ID", provision.ConsumerID(provision.AdoptionLabel, a.Slug)) |
| 159 | r.carlos.SetVar(a.Slug, "", p+"_ORIGIN", valueOrigin) |
| 160 | r.carlos.SetSecret(a.Slug, "", p+"_INSTANCE_KEY") |
| 161 | r.carlos.SetSecret(a.Slug, "", p+"_DB_KEY") |
| 162 | r.carlos.AddInstance(carlosop.Instance{ |
| 163 | Host: routeOf(a), App: a.Slug, Slug: "s-" + a.Slug, Channel: "stable", Region: "eu", |
| 164 | CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, |
| 165 | ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`), |
| 166 | }) |
| 167 | attachCanonical(r.carlos, a) |
| 168 | // A neighbour on its own owned environment: it shares no layer |
| 169 | // with the canonical host, so it never sees the keys, and it is |
| 170 | // never restarted. |
| 171 | r.carlos.SetVar(a.Slug, neighbourEnv(a.Slug), p+"_HOME_ISSUER", HomeIssuerOrigin) |
| 172 | r.carlos.SetSecret(a.Slug, neighbourEnv(a.Slug), p+"_INSTANCE_KEY") |
| 173 | r.carlos.Own(a.Slug, neighbourEnv(a.Slug), "alta") |
| 174 | r.carlos.AddInstance(carlosop.Instance{Host: neighbourHost(a.Slug), App: a.Slug, Slug: "s-n-" + a.Slug, Environment: neighbourEnv(a.Slug), |
| 175 | Channel: "stable", Region: "eu", CreatedAt: time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)}) |
| 176 | r.sites[a.Slug] = &appSite{} |
| 177 | r.before[a.Slug] = r.layers(a.Slug) |
| 178 | } |
| 179 | |
| 180 | site := httptest.NewTLSServer(http.HandlerFunc(r.site)) |
| 181 | t.Cleanup(site.Close) |
| 182 | tr := site.Client().Transport.(*http.Transport).Clone() |
| 183 | addr := site.Listener.Addr().String() |
| 184 | tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { |
| 185 | var d net.Dialer |
| 186 | return d.DialContext(ctx, network, addr) |
| 187 | } |
| 188 | tr.TLSClientConfig.ServerName = "example.com" |
| 189 | r.h = &http.Client{Transport: tr, Timeout: 10 * time.Second} |
| 190 | |
| 191 | r.path = filepath.Join(t.TempDir(), "alta.db") |
| 192 | r.ps, r.js = r.journal() |
| 193 | r.cfg = provision.Config{ |
| 194 | Store: r.ps, Home: r.hc, |
| 195 | Console: &console.Client{HTTP: &http.Client{Transport: offlineNet{}}, Base: "https://console.invalid", Account: fixtureAccount, Tokens: map[string]string{}}, |
| 196 | Public: &http.Client{Transport: offlineNet{}}, |
| 197 | HomeCfg: provision.HomeConfig{Issuer: credOrigin, Directory: dirOrigin, Provisioner: r.home.ProvisioningPublic()}, |
| 198 | Account: fixtureAccount, Now: r.clock, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), |
| 199 | AfterAct: func(key string) error { |
| 200 | r.actsMu.Lock() |
| 201 | r.acts = append(r.acts, key) |
| 202 | r.actsMu.Unlock() |
| 203 | return nil |
| 204 | }, |
| 205 | } |
| 206 | return r |
| 207 | } |
| 208 | |
| 209 | func (r *rehearsal) clock() time.Time { |
| 210 | r.mu.Lock() |
| 211 | defer r.mu.Unlock() |
| 212 | return r.now |
| 213 | } |
| 214 | |
| 215 | func (r *rehearsal) tick(d time.Duration) { |
| 216 | r.mu.Lock() |
| 217 | defer r.mu.Unlock() |
| 218 | r.now = r.now.Add(d) |
| 219 | } |
| 220 | |
| 221 | // journal opens the state database as a fresh process does. |
| 222 | func (r *rehearsal) journal() (*provision.Store, *Store) { |
| 223 | r.t.Helper() |
| 224 | db, err := provision.OpenDB(r.path) |
| 225 | if err != nil { |
| 226 | r.t.Fatal(err) |
| 227 | } |
| 228 | r.closers = append(r.closers, func() { db.Close() }) |
| 229 | ps, err := provision.NewStore(context.Background(), db, bytes.Repeat([]byte{4}, 32), r.clock, Schema) |
| 230 | if err != nil { |
| 231 | r.t.Fatal(err) |
| 232 | } |
| 233 | js, err := NewStore(ps) |
| 234 | if err != nil { |
| 235 | r.t.Fatal(err) |
| 236 | } |
| 237 | return ps, js |
| 238 | } |
| 239 | |
| 240 | func (r *rehearsal) layers(app string) layerState { |
| 241 | var s layerState |
| 242 | s.def, s.defVer, _ = r.carlos.Layer(app, "") |
| 243 | s.env, s.envVer, _ = r.carlos.Layer(app, neighbourEnv(app)) |
| 244 | return s |
| 245 | } |
| 246 | |
| 247 | func (r *rehearsal) site(w http.ResponseWriter, req *http.Request) { |
| 248 | host, _, err := net.SplitHostPort(req.Host) |
| 249 | if err != nil { |
| 250 | host = req.Host |
| 251 | } |
| 252 | slug := strings.TrimSuffix(host, ".oficina.works") |
| 253 | switch req.URL.Path { |
| 254 | case "/api/version": |
| 255 | w.Header().Set("X-Carlos-Version", valueVersion) |
| 256 | _, _ = io.WriteString(w, valueVersion) |
| 257 | case "/healthz": |
| 258 | w.WriteHeader(http.StatusOK) |
| 259 | case "/api/v1/operations": |
| 260 | switch a, _ := provision.AppBySlug(slug); { |
| 261 | case r.serving(slug): |
| 262 | agent401(w) |
| 263 | case BaselineOps(a) == OpsApp401: |
| 264 | app401(w) |
| 265 | case BaselineOps(a) == OpsAgent401: |
| 266 | baseOps401(w) // Base's own door, held through adoption |
| 267 | default: |
| 268 | http.NotFound(w, req) |
| 269 | } |
| 270 | default: |
| 271 | http.NotFound(w, req) |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | func (r *rehearsal) serving(slug string) bool { |
| 276 | s, ok := r.sites[slug] |
| 277 | a, known := provision.AppBySlug(slug) |
| 278 | if !ok || !known { |
| 279 | return false |
| 280 | } |
| 281 | s.mu.Lock() |
| 282 | defer s.mu.Unlock() |
| 283 | if n := r.carlos.RestartCount(routeOf(a)); n != s.seen { |
| 284 | vars, _, _ := r.carlos.Layer(slug, "") |
| 285 | keys := AgentKeys(a) |
| 286 | _, i := vars[keys[0]] |
| 287 | _, t := vars[keys[1]] |
| 288 | s.seen, s.loaded = n, i && t |
| 289 | } |
| 290 | return s.loaded |
| 291 | } |
| 292 | |
| 293 | // ---- Home's half ---- |
| 294 | |
| 295 | func (r *rehearsal) confirm(kind string) { |
| 296 | r.t.Helper() |
| 297 | if err := r.home.Confirm(homeop.Directory, ""); err != nil { |
| 298 | r.t.Fatal(err) |
| 299 | } |
| 300 | if kind == homeop.KindInitialize { |
| 301 | return |
| 302 | } |
| 303 | owner := "" |
| 304 | if kind == homeop.KindCreateTeam { |
| 305 | owner = rehearsalOwner |
| 306 | } |
| 307 | if err := r.home.Confirm(homeop.Credential, owner); err != nil { |
| 308 | r.t.Fatal(err) |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | // drive advances run until it is done or failed, each pass a fresh |
| 313 | // engine, as alta-adopt advance is: a pass killed by AfterAct resumes in |
| 314 | // the next. |
| 315 | func (r *rehearsal) drive(run int64, obs provision.Observer) provision.Run { |
| 316 | r.t.Helper() |
| 317 | var out provision.Run |
| 318 | for i := 0; i < 30; i++ { |
| 319 | cfg := r.cfg |
| 320 | if obs != nil { |
| 321 | cfg.Observer = obs |
| 322 | } |
| 323 | if err := provision.New(cfg).Advance(context.Background(), run); err != nil { |
| 324 | var fl *provision.Fail |
| 325 | if errors.As(err, &fl) { |
| 326 | r.t.Fatalf("run %d failed: %s", run, fl.Code) |
| 327 | } |
| 328 | } |
| 329 | var err error |
| 330 | if out, err = r.ps.Run(context.Background(), run); err != nil { |
| 331 | r.t.Fatal(err) |
| 332 | } |
| 333 | if out.State == "done" || out.State == "failed" { |
| 334 | return out |
| 335 | } |
| 336 | r.tick(5 * time.Second) |
| 337 | } |
| 338 | return out |
| 339 | } |
| 340 | |
| 341 | func (r *rehearsal) engine(obs provision.Observer) *provision.Engine { |
| 342 | cfg := r.cfg |
| 343 | if obs != nil { |
| 344 | cfg.Observer = obs |
| 345 | } |
| 346 | return provision.New(cfg) |
| 347 | } |
| 348 | |
| 349 | // homePreflight is alta-adopt home-preflight --apply: Paul's pasted |
| 350 | // counts, both roles inspected, recorded only when nothing is refused. |
| 351 | func (r *rehearsal) homePreflight(phase string) { |
| 352 | r.t.Helper() |
| 353 | counts := map[string]int64{} |
| 354 | for _, q := range HomeQueries() { |
| 355 | counts[q[strings.LastIndex(q, " ")+1:]] = 0 |
| 356 | } |
| 357 | if phase == PhasePrePlanA { |
| 358 | counts["roster_generation"], counts["roster_operator_receipts"] = 1, 1 |
| 359 | } |
| 360 | rec, codes, err := CheckHome(context.Background(), r.hc, r.ps, counts, phase) |
| 361 | if err != nil || len(codes) > 0 { |
| 362 | r.t.Fatalf("home preflight %s: %v %v", phase, codes, err) |
| 363 | } |
| 364 | if err := r.js.SaveHomePreflight(context.Background(), rec); err != nil { |
| 365 | r.t.Fatal(err) |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | func (r *rehearsal) initialize() { |
| 370 | r.t.Helper() |
| 371 | run, err := r.engine(nil).StartInitialize(context.Background(), provision.InitializeAttestation) |
| 372 | if err != nil { |
| 373 | r.t.Fatal(err) |
| 374 | } |
| 375 | r.confirm(homeop.KindInitialize) |
| 376 | if got := r.drive(run, nil); got.State != "done" { |
| 377 | r.t.Fatalf("initialize: %s %s", got.State, got.Code) |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | func (r *rehearsal) planA() { |
| 382 | r.t.Helper() |
| 383 | run, err := r.engine(nil).StartAdoption(context.Background(), "Oficina", rehearsalOwner) |
| 384 | if err != nil { |
| 385 | r.t.Fatal(err) |
| 386 | } |
| 387 | r.planARun = run |
| 388 | r.confirm(homeop.KindCreateTeam) |
| 389 | if got := r.drive(run, nil); got.State != "done" || got.Code != "awaiting-configuration" { |
| 390 | r.t.Fatalf("plan A: %s %s", got.State, got.Code) |
| 391 | } |
| 392 | team, err := r.ps.Team(context.Background(), provision.AdoptionLabel) |
| 393 | if err != nil || team.TeamSQID == "" { |
| 394 | r.t.Fatalf("no seeded team: %v", err) |
| 395 | } |
| 396 | r.sqid = team.TeamSQID |
| 397 | } |
| 398 | |
| 399 | // observer is the activation gate as alta-adopt builds it, over a fresh |
| 400 | // console client. |
| 401 | func (r *rehearsal) observer() *Observer { |
| 402 | c := carlosop.New(r.carlos.URL(), fixtureAccount, r.carlos.Token()) |
| 403 | r.closers = append(r.closers, c.Close) |
| 404 | artifacts := map[string]string{} |
| 405 | for _, a := range provision.Slugs() { |
| 406 | artifacts[a] = sha256Hex(valueVersion) |
| 407 | } |
| 408 | return &Observer{C: c, H: r.h, S: r.js, Artifacts: artifacts, Now: r.clock} |
| 409 | } |
| 410 | |
| 411 | // activate is Plan B or C: alta-adopt activate --apply, the two |
| 412 | // confirmations, then advance until done. |
| 413 | func (r *rehearsal) activate(apps ...string) { |
| 414 | r.t.Helper() |
| 415 | // Each plan waits out the last one's window. |
| 416 | r.tick(homeop.WindowLifetime * time.Second) |
| 417 | obs := r.observer() |
| 418 | run, err := r.engine(obs).ActivateAdopted(context.Background(), apps) |
| 419 | if err != nil { |
| 420 | r.t.Fatalf("activate %v: %v", apps, err) |
| 421 | } |
| 422 | r.confirm(homeop.KindAddApps) |
| 423 | if got := r.drive(run, obs); got.State != "done" { |
| 424 | r.t.Fatalf("activate %v: %s %s", apps, got.State, got.Code) |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | // ---- CARLOS's half: each step is a process that may die ---- |
| 429 | |
| 430 | // proc is one alta-adopt process's console client, through a door that |
| 431 | // kills the process at its crash point: the request is held for good |
| 432 | // (before) or answered to no one (after). From then on the door forwards |
| 433 | // nothing, and process.await cuts the process off (its journal handle |
| 434 | // closed, its context cancelled), so nothing it does next, even after |
| 435 | // its client's own timeout, reaches the console or the journal. |
| 436 | type proc struct { |
| 437 | c *carlosop.Client |
| 438 | dead chan struct{} |
| 439 | once sync.Once |
| 440 | } |
| 441 | |
| 442 | func (p *proc) die() { p.once.Do(func() { close(p.dead) }) } |
| 443 | |
| 444 | func (r *rehearsal) newProc(point crashPoint) *proc { |
| 445 | p := &proc{dead: make(chan struct{})} |
| 446 | target, err := url.Parse(r.carlos.URL()) |
| 447 | if err != nil { |
| 448 | r.t.Fatal(err) |
| 449 | } |
| 450 | rp := httputil.NewSingleHostReverseProxy(target) |
| 451 | // A connection the console dropped is dropped here too: the runner |
| 452 | // meets a lost answer, never a 502 of the door's making. |
| 453 | rp.ErrorHandler = func(http.ResponseWriter, *http.Request, error) { panic(http.ErrAbortHandler) } |
| 454 | hold := func() { |
| 455 | <-r.release |
| 456 | panic(http.ErrAbortHandler) |
| 457 | } |
| 458 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 459 | select { |
| 460 | case <-p.dead: |
| 461 | hold() |
| 462 | default: |
| 463 | } |
| 464 | body, _ := io.ReadAll(req.Body) |
| 465 | req.Body = io.NopCloser(bytes.NewReader(body)) |
| 466 | app, kind := r.classify(req, body) |
| 467 | hit := kind == "put" && (point == beforePut || point == afterPut) || kind == "restart" && point == afterRestart |
| 468 | if hit && r.dies(app) { |
| 469 | if point == beforePut { |
| 470 | p.die() |
| 471 | hold() |
| 472 | } |
| 473 | rp.ServeHTTP(httptest.NewRecorder(), req) |
| 474 | p.die() |
| 475 | hold() |
| 476 | } |
| 477 | rp.ServeHTTP(w, req) |
| 478 | })) |
| 479 | p.c = carlosop.New(srv.URL, fixtureAccount, r.carlos.Token()) |
| 480 | r.closers = append(r.closers, srv.Close, p.c.Close) |
| 481 | return p |
| 482 | } |
| 483 | |
| 484 | // dies reports whether app has yet to die at the crash point, and marks |
| 485 | // it dead. |
| 486 | func (r *rehearsal) dies(app string) bool { |
| 487 | r.mu.Lock() |
| 488 | defer r.mu.Unlock() |
| 489 | if r.crashed[app] { |
| 490 | return false |
| 491 | } |
| 492 | r.crashed[app] = true |
| 493 | return true |
| 494 | } |
| 495 | |
| 496 | // classify names a console request's app and kind ("put", "restart" for |
| 497 | // a scoped restart that is not a dry run, or ""), and checks every unset |
| 498 | // against the stored values: the runner unsets only what it wrote. |
| 499 | func (r *rehearsal) classify(req *http.Request, body []byte) (app, kind string) { |
| 500 | parts := strings.Split(strings.TrimPrefix(req.URL.Path, "/api/cli/apps/"), "/") |
| 501 | if len(parts) < 3 { |
| 502 | return "", "" |
| 503 | } |
| 504 | app, door := parts[1], "/"+strings.Join(parts[2:], "/") |
| 505 | switch { |
| 506 | case req.Method == http.MethodPut && door == "/config": |
| 507 | var w struct { |
| 508 | Environment string `json:"environment"` |
| 509 | Unset []string `json:"unset"` |
| 510 | } |
| 511 | _ = json.Unmarshal(body, &w) |
| 512 | if a, ok := provision.AppBySlug(app); ok && len(w.Unset) > 0 { |
| 513 | vars, _, _ := r.carlos.Layer(app, w.Environment) |
| 514 | keys := AgentKeys(a) |
| 515 | ours := map[string]string{keys[0]: Issuer, keys[1]: r.sqid} |
| 516 | for _, k := range w.Unset { |
| 517 | if v, ok := vars[k]; ok && (v.Kind != "env" || v.Value != ours[k]) { |
| 518 | r.mu.Lock() |
| 519 | r.foreign = append(r.foreign, app+":"+k) |
| 520 | r.mu.Unlock() |
| 521 | } |
| 522 | } |
| 523 | } |
| 524 | return app, "put" |
| 525 | case req.Method == http.MethodPost && door == "/restart/scope": |
| 526 | var w struct { |
| 527 | DryRun bool `json:"dry_run"` |
| 528 | } |
| 529 | if json.Unmarshal(body, &w) == nil && !w.DryRun { |
| 530 | return app, "restart" |
| 531 | } |
| 532 | } |
| 533 | return app, "" |
| 534 | } |
| 535 | |
| 536 | // step runs fn as one alta-adopt process at a time, killed at point the |
| 537 | // first time app reaches it, until a process finishes. A dead process is |
| 538 | // cut off where it died; the next one opens the journal afresh. |
| 539 | func (r *rehearsal) step(app string, point crashPoint, fn func(ctx context.Context, c *carlosop.Client, js *Store) error) (deaths int) { |
| 540 | r.t.Helper() |
| 541 | for { |
| 542 | died, err := r.spawn(point, fn).await() |
| 543 | if !died { |
| 544 | if err != nil { |
| 545 | r.t.Fatalf("%s: %v", app, err) |
| 546 | } |
| 547 | return deaths |
| 548 | } |
| 549 | deaths++ |
| 550 | if deaths > 1 { |
| 551 | r.t.Fatalf("%s died twice", app) |
| 552 | } |
| 553 | r.sawBaseline(app) |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | // processLimit bounds how long one process may run before it either |
| 558 | // finishes or dies: a test that hangs fails here, not at the package |
| 559 | // timeout. |
| 560 | const processLimit = time.Minute |
| 561 | |
| 562 | // process is one alta-adopt process: fn on its own console door, journal |
| 563 | // handle and context. |
| 564 | type process struct { |
| 565 | r *rehearsal |
| 566 | p *proc |
| 567 | db *sql.DB |
| 568 | cancel context.CancelFunc |
| 569 | done chan error |
| 570 | } |
| 571 | |
| 572 | func (r *rehearsal) spawn(point crashPoint, fn func(ctx context.Context, c *carlosop.Client, js *Store) error) *process { |
| 573 | x := &process{r: r, p: r.newProc(point), done: make(chan error, 1)} |
| 574 | ps, js := r.journal() |
| 575 | x.db = ps.DB() |
| 576 | ctx, cancel := context.WithCancel(context.Background()) |
| 577 | x.cancel = cancel |
| 578 | r.cancels = append(r.cancels, cancel) |
| 579 | r.zombies.Add(1) |
| 580 | go func() { |
| 581 | defer r.zombies.Done() |
| 582 | x.done <- fn(ctx, x.p.c, js) |
| 583 | }() |
| 584 | return x |
| 585 | } |
| 586 | |
| 587 | // await waits, at most processLimit, for the process to finish (its |
| 588 | // error) or die (died). A process dies while blocked in its console |
| 589 | // request, so it is cut off there and then: its journal handle is closed |
| 590 | // and its context cancelled. Whatever it tries next fails at once, |
| 591 | // whatever the client's own timeout: a write to the journal finds the |
| 592 | // handle closed, and its console door forwards nothing more. |
| 593 | func (x *process) await() (died bool, err error) { |
| 594 | x.r.t.Helper() |
| 595 | select { |
| 596 | case err := <-x.done: |
| 597 | return false, err |
| 598 | case <-x.p.dead: |
| 599 | x.db.Close() |
| 600 | x.cancel() |
| 601 | return true, nil |
| 602 | case <-time.After(processLimit): |
| 603 | x.r.t.Fatalf("a process neither finished nor died within %s", processLimit) |
| 604 | return false, nil |
| 605 | } |
| 606 | } |
| 607 | |
| 608 | // sawBaseline keeps app's sealed baseline bytes the first time they are |
| 609 | // seen; checkBaselines fails if any has moved since. |
| 610 | func (r *rehearsal) sawBaseline(app string) { |
| 611 | r.t.Helper() |
| 612 | var b []byte |
| 613 | err := r.ps.DB().QueryRow("SELECT sealed FROM adopt_baselines WHERE app=?", app).Scan(&b) |
| 614 | if errors.Is(err, sql.ErrNoRows) { |
| 615 | return |
| 616 | } |
| 617 | if err != nil { |
| 618 | r.t.Fatal(err) |
| 619 | } |
| 620 | if _, ok := r.sealed[app]; !ok { |
| 621 | r.sealed[app] = b |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | func (r *rehearsal) checkBaselines() { |
| 626 | r.t.Helper() |
| 627 | for app, want := range r.sealed { |
| 628 | var got []byte |
| 629 | if err := r.ps.DB().QueryRow("SELECT sealed FROM adopt_baselines WHERE app=?", app).Scan(&got); err != nil { |
| 630 | r.t.Fatal(err) |
| 631 | } |
| 632 | if !bytes.Equal(got, want) { |
| 633 | r.t.Fatalf("%s: the sealed baseline moved", app) |
| 634 | } |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | // configure is alta-adopt configure --app --apply: the write, then, unless |
| 639 | // the after snapshot is already taken, the restart until delivered and |
| 640 | // the after snapshot, then the delivery check. |
| 641 | func configureApp(ctx context.Context, c *carlosop.Client, h *http.Client, js *Store, a provision.App, sqid string) error { |
| 642 | if _, err := WriteAgentKeys(ctx, c, h, js, a, sqid, sha256Hex(valueVersion), true); err != nil { |
| 643 | return err |
| 644 | } |
| 645 | if _, ok, err := js.After(ctx, a.Slug); err != nil { |
| 646 | return err |
| 647 | } else if !ok { |
| 648 | base, ok, err := js.Baseline(ctx, a.Slug) |
| 649 | if err != nil || !ok { |
| 650 | return fmt.Errorf("no baseline: %v", err) |
| 651 | } |
| 652 | if _, err := RestartAndWait(ctx, c, h, a, base.Identity, func(d Delivery) error { return Delivered(a, base.Delivery, d) }, true); err != nil { |
| 653 | return err |
| 654 | } |
| 655 | if _, err := CaptureAfter(ctx, c, h, js, a); err != nil { |
| 656 | return err |
| 657 | } |
| 658 | } |
| 659 | return CheckDelivery(ctx, js, c, h, a, sha256Hex(valueVersion)) |
| 660 | } |
| 661 | |
| 662 | func (r *rehearsal) configure(a provision.App, point crashPoint) int { |
| 663 | r.t.Helper() |
| 664 | deaths := r.step(a.Slug, point, func(ctx context.Context, c *carlosop.Client, js *Store) error { |
| 665 | return configureApp(ctx, c, r.h, js, a, r.sqid) |
| 666 | }) |
| 667 | r.sawBaseline(a.Slug) |
| 668 | return deaths |
| 669 | } |
| 670 | |
| 671 | func (r *rehearsal) rollback(a provision.App, point crashPoint) int { |
| 672 | r.t.Helper() |
| 673 | return r.step(a.Slug, point, func(ctx context.Context, c *carlosop.Client, js *Store) error { |
| 674 | return RollbackAgentKeys(ctx, c, r.h, js, a, true) |
| 675 | }) |
| 676 | } |
| 677 | |
| 678 | // carlosPreflight is alta-adopt preflight: every app clean. |
| 679 | func (r *rehearsal) carlosPreflight() { |
| 680 | r.t.Helper() |
| 681 | c := carlosop.New(r.carlos.URL(), fixtureAccount, r.carlos.Token()) |
| 682 | defer c.Close() |
| 683 | for _, a := range provision.Apps { |
| 684 | if _, codes, err := Preflight(context.Background(), c, r.h, a, nil); err != nil || len(codes) > 0 { |
| 685 | r.t.Fatalf("preflight %s: %v %v", a.Slug, codes, err) |
| 686 | } |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | // ---- the run ---- |
| 691 | |
| 692 | // options bends one run: where a CARLOS process dies, and a hook on every |
| 693 | // Home act. |
| 694 | type options struct { |
| 695 | configure crashPoint |
| 696 | lose bool // the first answer to each app's PUT is lost |
| 697 | afterAct func(string) error |
| 698 | } |
| 699 | |
| 700 | // run is the whole adoption, in order, through Plan C. |
| 701 | func (r *rehearsal) run(o options) { |
| 702 | r.t.Helper() |
| 703 | if o.afterAct != nil { |
| 704 | record := r.cfg.AfterAct |
| 705 | r.cfg.AfterAct = func(key string) error { |
| 706 | if err := o.afterAct(key); err != nil { |
| 707 | return err |
| 708 | } |
| 709 | return record(key) |
| 710 | } |
| 711 | } |
| 712 | r.untilPlanA() |
| 713 | for _, a := range provision.Apps { |
| 714 | if o.lose { |
| 715 | r.carlos.LoseNextAnswer() |
| 716 | } |
| 717 | if deaths := r.configure(a, o.configure); o.configure != noCrash && deaths != 1 { |
| 718 | r.t.Fatalf("%s: died %d times at %s", a.Slug, deaths, o.configure) |
| 719 | } |
| 720 | } |
| 721 | r.activate(CanaryApp) |
| 722 | var rest []string |
| 723 | for _, s := range provision.Slugs() { |
| 724 | if s != CanaryApp { |
| 725 | rest = append(rest, s) |
| 726 | } |
| 727 | } |
| 728 | r.activate(rest...) |
| 729 | } |
| 730 | |
| 731 | // untilPlanA is the run through Plan A: both preflights, initialize, the |
| 732 | // wait for its window to lapse, the second Home preflight, Plan A. |
| 733 | func (r *rehearsal) untilPlanA() { |
| 734 | r.t.Helper() |
| 735 | r.homePreflight(PhasePreInitialize) |
| 736 | r.carlosPreflight() |
| 737 | r.initialize() |
| 738 | // pre-plan-a refuses while the initialize window is open. |
| 739 | r.tick(homeop.WindowLifetime * time.Second) |
| 740 | r.homePreflight(PhasePrePlanA) |
| 741 | r.planA() |
| 742 | } |
| 743 | |
| 744 | // ---- what must hold at the end ---- |
| 745 | |
| 746 | // adopted fails unless the run ended as it must: six live routes, every |
| 747 | // preserved digest equal along baseline, after and fresh, each layer |
| 748 | // changed by the two keys alone, nothing else restarted, nothing |
| 749 | // committed twice at Home. |
| 750 | func (r *rehearsal) adopted() { |
| 751 | r.t.Helper() |
| 752 | t := r.t |
| 753 | ctx := context.Background() |
| 754 | for _, s := range provision.Slugs() { |
| 755 | if st := r.home.InstanceState(s); st != "live" { |
| 756 | t.Fatalf("%s is %q at Home, want live", s, st) |
| 757 | } |
| 758 | } |
| 759 | reqs := r.home.Requests() |
| 760 | onceEachRequest(t, reqs) |
| 761 | for _, s := range provision.Slugs() { |
| 762 | for _, action := range []string{homeop.DirectoryProvision, homeop.CredentialRegister, homeop.DirectoryVerify, homeop.DirectoryActivate} { |
| 763 | if n := countRequests(reqs, action+":"+s); n != 1 { |
| 764 | t.Fatalf("%s:%s committed %d times", action, s, n) |
| 765 | } |
| 766 | } |
| 767 | } |
| 768 | |
| 769 | c := carlosop.New(r.carlos.URL(), fixtureAccount, r.carlos.Token()) |
| 770 | defer c.Close() |
| 771 | for _, a := range provision.Apps { |
| 772 | keys := AgentKeys(a) |
| 773 | base, ok, err := r.js.Baseline(ctx, a.Slug) |
| 774 | if err != nil || !ok { |
| 775 | t.Fatalf("%s: no baseline", a.Slug) |
| 776 | } |
| 777 | after, ok, err := r.js.After(ctx, a.Slug) |
| 778 | if err != nil || !ok { |
| 779 | t.Fatalf("%s: no after snapshot", a.Slug) |
| 780 | } |
| 781 | fresh, err := Observe(ctx, c, r.h, a) |
| 782 | if err != nil { |
| 783 | t.Fatal(err) |
| 784 | } |
| 785 | if p := Preserved(base, after, keys); len(p) > 0 { |
| 786 | t.Fatalf("%s: after not preserved: %v", a.Slug, p) |
| 787 | } |
| 788 | if p := Preserved(base, fresh, keys); len(p) > 0 { |
| 789 | t.Fatalf("%s: drifted: %v", a.Slug, p) |
| 790 | } |
| 791 | for _, v := range base.Vars { |
| 792 | if v.Key == keys[0] || v.Key == keys[1] { |
| 793 | t.Fatalf("%s: the baseline held %s", a.Slug, v.Key) |
| 794 | } |
| 795 | for _, snap := range []Snapshot{after, fresh} { |
| 796 | w := findVar(snap.Vars, v.Key) |
| 797 | if w == nil || w.Digest != v.Digest || w.Kind != v.Kind || w.From != v.From { |
| 798 | t.Fatalf("%s: %s not preserved", a.Slug, v.Key) |
| 799 | } |
| 800 | } |
| 801 | } |
| 802 | if len(after.Vars) != len(base.Vars)+2 || len(fresh.Vars) != len(base.Vars)+2 { |
| 803 | t.Fatalf("%s: %d vars before, %d after, %d now", a.Slug, len(base.Vars), len(after.Vars), len(fresh.Vars)) |
| 804 | } |
| 805 | |
| 806 | // Each stored layer differs by the two keys alone. |
| 807 | was, now := r.before[a.Slug], r.layers(a.Slug) |
| 808 | if len(now.def) != len(was.def)+2 { |
| 809 | t.Fatalf("%s: default bundle %d keys, was %d", a.Slug, len(now.def), len(was.def)) |
| 810 | } |
| 811 | for k, v := range was.def { |
| 812 | if now.def[k] != v { |
| 813 | t.Fatalf("%s: %s changed", a.Slug, k) |
| 814 | } |
| 815 | } |
| 816 | if now.def[keys[0]] != (fakecarlos.Var{Kind: "env", Value: Issuer}) || now.def[keys[1]] != (fakecarlos.Var{Kind: "env", Value: r.sqid}) { |
| 817 | t.Fatalf("%s: the agent keys are not as written", a.Slug) |
| 818 | } |
| 819 | if now.envVer != was.envVer || !reflect.DeepEqual(now.env, was.env) { |
| 820 | t.Fatalf("%s: the neighbour's environment changed", a.Slug) |
| 821 | } |
| 822 | |
| 823 | if n := r.carlos.RestartCount(neighbourHost(a.Slug)); n != 0 { |
| 824 | t.Fatalf("%s restarted %d times", neighbourHost(a.Slug), n) |
| 825 | } |
| 826 | if n := r.carlos.RestartCount(routeOf(a)); n < 1 || n > 2 { |
| 827 | t.Fatalf("%s restarted %d times", routeOf(a), n) |
| 828 | } |
| 829 | } |
| 830 | if n := r.carlos.AppWideRestarts(); n != 0 { |
| 831 | t.Fatalf("app-wide restarts %d", n) |
| 832 | } |
| 833 | r.checkBaselines() |
| 834 | r.noForeignUnset() |
| 835 | } |
| 836 | |
| 837 | func (r *rehearsal) noForeignUnset() { |
| 838 | r.t.Helper() |
| 839 | r.mu.Lock() |
| 840 | defer r.mu.Unlock() |
| 841 | if len(r.foreign) > 0 { |
| 842 | r.t.Fatalf("unset a value the runner did not write: %v", r.foreign) |
| 843 | } |
| 844 | } |
| 845 | |
| 846 | func (r *rehearsal) putsOf(app string) int { |
| 847 | r.mu.Lock() |
| 848 | defer r.mu.Unlock() |
| 849 | return r.puts[app] |
| 850 | } |
| 851 | |
| 852 | func onceEachRequest(t *testing.T, reqs []string) { |
| 853 | t.Helper() |
| 854 | seen := map[string]int{} |
| 855 | for _, q := range reqs { |
| 856 | if seen[q]++; seen[q] > 1 { |
| 857 | t.Fatalf("%s committed twice: %v", q, reqs) |
| 858 | } |
| 859 | } |
| 860 | } |
| 861 | |
| 862 | func countRequests(reqs []string, entry string) int { |
| 863 | n := 0 |
| 864 | for _, q := range reqs { |
| 865 | if q == entry { |
| 866 | n++ |
| 867 | } |
| 868 | } |
| 869 | return n |
| 870 | } |
| 871 | |
| 872 | // ---- the tests ---- |
| 873 | |
| 874 | func TestRehearsalFullRun(t *testing.T) { |
| 875 | r := newRehearsal(t) |
| 876 | r.run(options{}) |
| 877 | r.adopted() |
| 878 | for _, a := range provision.Apps { |
| 879 | if n := r.putsOf(a.Slug); n != 1 { |
| 880 | t.Fatalf("%s: %d PUTs, want one", a.Slug, n) |
| 881 | } |
| 882 | if n := r.carlos.RestartCount(routeOf(a)); n != 1 { |
| 883 | t.Fatalf("%s: %d restarts, want one", a.Slug, n) |
| 884 | } |
| 885 | } |
| 886 | if !slices.Contains(r.home.Requests(), homeop.DirectoryActivate+":"+CanaryApp) { |
| 887 | t.Fatal("the canary was not activated") |
| 888 | } |
| 889 | } |
| 890 | |
| 891 | // The same run, killed once at each act. Home's: after the act took effect |
| 892 | // at Home and before Alta recorded it (AfterAct). CARLOS's: before the |
| 893 | // PUT reaches the console, after it lands with its answer lost to a dead |
| 894 | // process, after the restart, and mid-rollback. A fresh process resumes |
| 895 | // from the journal each time. |
| 896 | func TestRehearsalCrashAfterEveryAct(t *testing.T) { |
| 897 | clean := newRehearsal(t) |
| 898 | clean.run(options{}) |
| 899 | acts := slices.Clone(clean.acts) |
| 900 | want := clean.home.Requests() |
| 901 | if len(acts) < 2+2*len(provision.Apps)+2*len(provision.Apps) { |
| 902 | t.Fatalf("acts %v", acts) |
| 903 | } |
| 904 | |
| 905 | for i, key := range acts { |
| 906 | t.Run(fmt.Sprintf("home-%02d-%s", i, key), func(t *testing.T) { |
| 907 | r := newRehearsal(t) |
| 908 | n, crashed := 0, false |
| 909 | r.run(options{afterAct: func(string) error { |
| 910 | if n == i && !crashed { |
| 911 | crashed = true |
| 912 | return errors.New("kill -9") |
| 913 | } |
| 914 | n++ |
| 915 | return nil |
| 916 | }}) |
| 917 | if !crashed { |
| 918 | t.Fatalf("act %d never reached", i) |
| 919 | } |
| 920 | r.adopted() |
| 921 | if got := r.home.Requests(); !reflect.DeepEqual(sortedCopy(got), sortedCopy(want)) { |
| 922 | t.Fatalf("requests\n got %v\nwant %v", got, want) |
| 923 | } |
| 924 | for _, a := range provision.Apps { |
| 925 | if n := r.putsOf(a.Slug); n != 1 { |
| 926 | t.Fatalf("%s: %d PUTs", a.Slug, n) |
| 927 | } |
| 928 | } |
| 929 | }) |
| 930 | } |
| 931 | |
| 932 | for _, point := range []crashPoint{beforePut, afterPut, afterRestart} { |
| 933 | t.Run("carlos-"+string(point), func(t *testing.T) { |
| 934 | r := newRehearsal(t) |
| 935 | r.run(options{configure: point}) |
| 936 | r.adopted() |
| 937 | for _, a := range provision.Apps { |
| 938 | if n := r.putsOf(a.Slug); n < 1 || n > 2 { |
| 939 | t.Fatalf("%s: %d PUTs", a.Slug, n) |
| 940 | } |
| 941 | } |
| 942 | }) |
| 943 | } |
| 944 | |
| 945 | t.Run("carlos-answer-lost", func(t *testing.T) { |
| 946 | r := newRehearsal(t) |
| 947 | r.run(options{lose: true}) |
| 948 | r.adopted() |
| 949 | for _, a := range provision.Apps { |
| 950 | if n := r.putsOf(a.Slug); n != 1 { |
| 951 | t.Fatalf("%s: %d PUTs, want exactly one", a.Slug, n) |
| 952 | } |
| 953 | } |
| 954 | }) |
| 955 | |
| 956 | // Mid-rollback: every app configured and its delivery checked, then |
| 957 | // rolled back, each killed once at the point. |
| 958 | for _, point := range []crashPoint{beforePut, afterPut, afterRestart} { |
| 959 | t.Run("rollback-"+string(point), func(t *testing.T) { |
| 960 | r := newRehearsal(t) |
| 961 | r.untilPlanA() |
| 962 | for _, a := range provision.Apps { |
| 963 | r.configure(a, noCrash) |
| 964 | } |
| 965 | r.crashed = map[string]bool{} |
| 966 | for _, a := range provision.Apps { |
| 967 | if deaths := r.rollback(a, point); deaths != 1 { |
| 968 | t.Fatalf("%s: died %d times", a.Slug, deaths) |
| 969 | } |
| 970 | } |
| 971 | ctx := context.Background() |
| 972 | for _, a := range provision.Apps { |
| 973 | rec, ok, err := r.js.Rollback(ctx, a.Slug) |
| 974 | if err != nil || !ok || rec.State != "restarted" { |
| 975 | t.Fatalf("%s: rollback %q %v", a.Slug, rec.State, err) |
| 976 | } |
| 977 | if n := r.putsOf(a.Slug); n < 1 || n > 2 { |
| 978 | t.Fatalf("%s: %d PUTs", a.Slug, n) |
| 979 | } |
| 980 | was, now := r.before[a.Slug], r.layers(a.Slug) |
| 981 | if !reflect.DeepEqual(now.def, was.def) || !reflect.DeepEqual(now.env, was.env) || now.envVer != was.envVer { |
| 982 | t.Fatalf("%s: the layers are not back to the baseline", a.Slug) |
| 983 | } |
| 984 | if r.carlos.RestartCount(neighbourHost(a.Slug)) != 0 { |
| 985 | t.Fatalf("%s: the neighbour restarted", a.Slug) |
| 986 | } |
| 987 | if r.home.InstanceState(a.Slug) != "pending" { |
| 988 | t.Fatalf("%s is %q at Home", a.Slug, r.home.InstanceState(a.Slug)) |
| 989 | } |
| 990 | } |
| 991 | if r.carlos.AppWideRestarts() != 0 { |
| 992 | t.Fatal("an app-wide restart") |
| 993 | } |
| 994 | r.checkBaselines() |
| 995 | r.noForeignUnset() |
| 996 | onceEachRequest(t, r.home.Requests()) |
| 997 | }) |
| 998 | } |
| 999 | |
| 1000 | // A process killed before its unset, and another writer then puts its |
| 1001 | // own team in the key: the resume stops and unsets nothing. |
| 1002 | t.Run("rollback-foreign-after-crash", func(t *testing.T) { |
| 1003 | r := newRehearsal(t) |
| 1004 | r.untilPlanA() |
| 1005 | a, _ := provision.AppBySlug("docs") |
| 1006 | r.configure(a, noCrash) |
| 1007 | r.crashed = map[string]bool{} |
| 1008 | dying := r.spawn(beforePut, func(ctx context.Context, c *carlosop.Client, js *Store) error { |
| 1009 | return RollbackAgentKeys(ctx, c, r.h, js, a, true) |
| 1010 | }) |
| 1011 | if died, err := dying.await(); !died { |
| 1012 | t.Fatalf("the rollback finished (%v) instead of dying before its unset", err) |
| 1013 | } |
| 1014 | r.sawBaseline(a.Slug) |
| 1015 | keys := AgentKeys(a) |
| 1016 | r.carlos.SetVar("docs", "", keys[1], "tForeignTeam") |
| 1017 | p2 := r.newProc(noCrash) |
| 1018 | _, js2 := r.journal() |
| 1019 | err := RollbackAgentKeys(context.Background(), p2.c, r.h, js2, a, true) |
| 1020 | r.noForeignUnset() |
| 1021 | if !errors.Is(err, ErrStopForeign) { |
| 1022 | t.Fatalf("resume: %v, want ErrStopForeign", err) |
| 1023 | } |
| 1024 | vars, _, _ := r.carlos.Layer("docs", "") |
| 1025 | if vars[keys[1]].Value != "tForeignTeam" || vars[keys[0]].Value != Issuer { |
| 1026 | t.Fatal("the resume unset a value it did not write") |
| 1027 | } |
| 1028 | if n := r.putsOf("docs"); n != 1 { |
| 1029 | t.Fatalf("%d PUTs, want the write alone", n) |
| 1030 | } |
| 1031 | r.checkBaselines() |
| 1032 | r.noForeignUnset() |
| 1033 | }) |
| 1034 | } |
| 1035 | |
| 1036 | // A process killed in its PUT stays dead: it is cut off at once, not when |
| 1037 | // its console client gives up (60 s), and what it tries afterwards, a |
| 1038 | // journal write here, lands nowhere. |
| 1039 | func TestRehearsalDeadProcessTouchesNothing(t *testing.T) { |
| 1040 | r := newRehearsal(t) |
| 1041 | _, version, _ := r.carlos.Layer("docs", "") |
| 1042 | keys := AgentKeys(appNamed(t, "docs")) |
| 1043 | x := r.spawn(beforePut, func(ctx context.Context, c *carlosop.Client, js *Store) error { |
| 1044 | _, err := c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{keys[0]: Issuer, keys[1]: fixtureSQID}, IfVersion: version}) |
| 1045 | if err == nil { |
| 1046 | return errors.New("the PUT was answered") |
| 1047 | } |
| 1048 | // Whatever a dead process would do next. |
| 1049 | return js.SaveDeliveryCheck(context.Background(), DeliveryCheck{App: "docs"}) |
| 1050 | }) |
| 1051 | if died, err := x.await(); !died { |
| 1052 | t.Fatalf("the process finished (%v) instead of dying in its PUT", err) |
| 1053 | } |
| 1054 | select { |
| 1055 | case err := <-x.done: |
| 1056 | if err == nil { |
| 1057 | t.Fatal("the dead process wrote to the journal") |
| 1058 | } |
| 1059 | case <-time.After(10 * time.Second): |
| 1060 | t.Fatal("the dead process was not cut off") |
| 1061 | } |
| 1062 | var n int |
| 1063 | if err := r.ps.DB().QueryRow("SELECT count(*) FROM adopt_witnesses").Scan(&n); err != nil || n != 0 { |
| 1064 | t.Fatalf("journal delivery checks %d (%v)", n, err) |
| 1065 | } |
| 1066 | if n := r.putsOf("docs"); n != 0 { |
| 1067 | t.Fatalf("%d PUTs reached the console", n) |
| 1068 | } |
| 1069 | } |
| 1070 | |
| 1071 | func sortedCopy(s []string) []string { |
| 1072 | c := slices.Clone(s) |
| 1073 | slices.Sort(c) |
| 1074 | return c |
| 1075 | } |
| 1076 | |