moves: offline run's doors send once; one loop waits, one gate posts
Right course after the third Astra round on carlos move offline run. Each round guarded the loop and found another place that could wait, post or speak by itself: the doors' 429 retry loop (R3 P1), the doors' first-read loop, a second classification of a status body (R3 P2), and a watcher that put "Moving ... back" off to a later view (R3 P2). This removes those places instead of guarding them. - offlinerun.HTTPDoors (new, doors.go) are the production doors over a Transport: one request a call, no loop, no wait, no output. The CLI's runWire is one roundTrip a call. A 429 comes back as Answer.Limited; the Runner's loop waits its back-off, reads status, decides again and goes back through the gate, which forgets the limited action. - Runner.Run is the only loop that waits: the poll, the back-off, and the first reads' tries (moved in from the CLI). - offlinerun.ClassifyStatus is the only judge of a status answer, its decoding included; the CLI's fuller view is a second decode target. - Runner.judge is the only place a Ctrl-C is promised an abort, and it takes the view by value. A Ctrl-C taken with no view in hand waits for the next one: an opened move is said to be served, another's move or none ends the run in its own words. Guards: TestDoorsAreSingleShot, TestLoopOwnsEveryWait, TestOneStatusClassifier, TestAbortIsPromisedOnlyWithAView, TestRunDoorsWireIsSingleShot, beside TestGateIsTheOnlyWayToPost. The two-box simulation now drives Runner.Run over HTTPDoors over the console's real handlers, with 429s, status failures that pass and that do not, and checks one POST per status read. No new operator sentences. A limited POST's line now ends with the console's own answer (OR13), then MV-N355 once.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
9 files changed,
+1,781
−554
internal/host/movesoffline_e2e_test.go+250 −93internal/moves/offlinerun/construction_test.go+704 −0internal/moves/offlinerun/decide.go+7 −4internal/moves/offlinerun/doors.go+211 −0internal/moves/offlinerun/gate_test.go+5 −5internal/moves/offlinerun/run.go+183 −63internal/moves/offlinerun/run_test.go+28 −10move_offline_run.go+132 −322move_offline_run_test.go+261 −57
Intent
diff --git a/internal/host/movesoffline_e2e_test.go b/internal/host/movesoffline_e2e_test.go| index 8fb780c63..4a8a722f7 100644 |
| --- a/internal/host/movesoffline_e2e_test.go |
| +++ b/internal/host/movesoffline_e2e_test.go |
| @@ -1965,6 +1965,8 @@ type e2eRunPost struct { |
| verb, id string |
| code int |
| lost bool // the reply was lost after the door answered |
| + limited bool // the rate limit answered it: it reached no door |
| + stale bool // the run had made no status read since its last POST |
| before, after e2eRecSnap |
| } |
| @@ -1988,17 +1990,21 @@ func (w *e2eWorld) snap() e2eRecSnap { |
| return s |
| } |
| -// e2eRunDoors are offlinerun.Doors over the console's real HTTP doors, as |
| -// the CLI's runDoors send them: the bound move's id in the body, the region |
| -// on stage and start; a 2xx accepted with the move its view names, a 4xx |
| -// refused, anything else no answer. lose, when set, throws a reply away |
| -// after the door answered it (the write, if any, has committed). Every |
| -// POST is kept with the record either side of it. |
| +// e2eRunDoors is the run's offlinerun.Transport over the console's real |
| +// HTTP doors: the production doors (offlinerun.HTTPDoors) and their status |
| +// classifier run over it, as they do over the CLI's wire, so what the run |
| +// sends, how it reads an answer and what a status failure means are the |
| +// production code's, not a model's. Each call is one request. The faults |
| +// are the wire's: lose throws a reply away after the door answered it (the |
| +// write, if any, has committed); limit answers a POST 429 before any door; |
| +// statusFault answers a status read itself. Every POST is kept with the |
| +// record either side of it. |
| type e2eRunDoors struct { |
| w *e2eWorld |
| tokens map[bool]*e2eToken // the run's and the hand's |
| posts []e2eRunPost |
| lose func(verb string) bool |
| + limit func(verb string) bool |
| accepted func(verb string) // called after a POST the door accepted |
| // beforeRunPost, when set, runs as the run is about to send verb: |
| // after its status read, before its POST (a second operator's hand in |
| @@ -2008,8 +2014,25 @@ type e2eRunDoors struct { |
| // one: each run POST is kept with both as it was dispatched. |
| ints *offlinerun.Interrupts |
| aborted bool |
| - // onStatus, when set, runs inside each status read. |
| + // onStatus, when set, runs inside each status read. A Ctrl-C it |
| + // presses ends the read, as it ends the CLI's: unanswered, unless |
| + // deliver says the answer got through first. |
| onStatus func() |
| + deliver func() bool |
| + // onLimit, when set, runs as the rate limit answers a POST. |
| + onLimit func() |
| + // statusFault, when set, may answer a status read itself. |
| + statusFault func() (offlinerun.Exchange, bool) |
| + // reads counts the run's status reads; sent every request it made. |
| + // lastView is the latest status view the run was answered with, and |
| + // mine the move its create-only stage made. |
| + reads, sent int |
| + lastView offlinerun.View |
| + mine string |
| + // fresh: the run has read status since its last POST. The loop does |
| + // at most one thing a read, so a POST with no read before it was not |
| + // decided by the loop: a door sent it again by itself. |
| + fresh bool |
| } |
| // e2eToken is a CLI login's token and the requests it has made. The |
| @@ -2036,32 +2059,73 @@ func (d *e2eRunDoors) do(hand bool, method, u, body string) (int, string) { |
| return d.w.doAs(tk.token, method, u, body) |
| } |
| -func (d *e2eRunDoors) Status(context.Context) (offlinerun.View, error) { |
| - code, out := d.do(false, http.MethodGet, d.w.base, "") |
| - if d.onStatus != nil { |
| - d.onStatus() |
| +// Do is one request of the run's (offlinerun.Transport). |
| +func (d *e2eRunDoors) Do(ctx context.Context, method, tail string, body any) offlinerun.Exchange { |
| + d.sent++ |
| + if method == http.MethodGet { |
| + d.reads++ |
| + d.fresh = true |
| + if d.statusFault != nil { |
| + if x, ok := d.statusFault(); ok { |
| + return x |
| + } |
| + } |
| + code, out := d.do(false, http.MethodGet, d.w.base, "") |
| + if d.onStatus != nil { |
| + d.onStatus() |
| + } |
| + if ctx.Err() != nil && (d.deliver == nil || !d.deliver()) { |
| + return offlinerun.Exchange{} // the Ctrl-C ended the read |
| + } |
| + if code == http.StatusOK { |
| + var v offlinerun.View |
| + if json.Unmarshal([]byte(out), &v) == nil { |
| + d.lastView = v |
| + } |
| + } |
| + return offlinerun.Exchange{Status: code, Body: []byte(out)} |
| } |
| - if code != http.StatusOK { |
| - return offlinerun.View{}, fmt.Errorf("status = %d %s", code, out) |
| + verb := strings.TrimPrefix(tail, "/") |
| + if tail == "" { |
| + verb = offlinerun.VerbStart |
| } |
| - var v offlinerun.View |
| - if err := json.Unmarshal([]byte(out), &v); err != nil { |
| - return offlinerun.View{}, err |
| + sent, _ := body.(map[string]any) |
| + id, _ := sent["id"].(string) |
| + pending, aborted, stale := d.ints.Pending(), d.aborted, !d.fresh |
| + d.fresh = false |
| + if d.beforeRunPost != nil && verb != "nudge" { |
| + d.beforeRunPost(verb) |
| + } |
| + if d.limit != nil && d.limit(verb) { |
| + // The rate limit answers before any door: nothing is asked of it. |
| + snap := d.w.snap() |
| + d.posts = append(d.posts, e2eRunPost{verb: verb, id: id, code: http.StatusTooManyRequests, limited: true, |
| + pending: pending, afterAbort: aborted, stale: stale, before: snap, after: snap}) |
| + if d.onLimit != nil { |
| + d.onLimit() |
| + } |
| + return offlinerun.Exchange{Status: http.StatusTooManyRequests} |
| + } |
| + raw, _ := json.Marshal(body) |
| + code, out := d.send(false, verb, id, d.w.base+tail, string(raw)) |
| + last := &d.posts[len(d.posts)-1] |
| + last.pending, last.afterAbort, last.stale = pending, aborted, stale |
| + if d.mine == "" && verb == offlinerun.VerbStage && id == "" && code == http.StatusAccepted { |
| + d.mine = last.after.id |
| + } |
| + if last.lost { |
| + return offlinerun.Exchange{} |
| } |
| - return v, nil |
| + return offlinerun.Exchange{Status: code, Body: []byte(out)} |
| } |
| -// post sends one door, by the run (hand false) or by a second operator. |
| -// The run's first stage (no id yet) is create-only, as the CLI sends it; |
| -// a hand's is not, as the hand verbs send it. |
| +// post sends one door by a second operator's hand: no id and no "new", as |
| +// the hand verbs send it. |
| func (d *e2eRunDoors) post(hand bool, verb, id string) (int, string) { |
| body := map[string]any{} |
| if id != "" { |
| body["id"] = id |
| } |
| - if !hand && verb == offlinerun.VerbStage && id == "" { |
| - body["new"] = true |
| - } |
| if verb == offlinerun.VerbStage || verb == offlinerun.VerbStart { |
| body["region"] = "uk" |
| } |
| @@ -2070,8 +2134,13 @@ func (d *e2eRunDoors) post(hand bool, verb, id string) (int, string) { |
| if verb != offlinerun.VerbStart { |
| u += "/" + verb |
| } |
| + return d.send(hand, verb, id, u, string(raw)) |
| +} |
| + |
| +// send is one POST to the console, kept with the record either side. |
| +func (d *e2eRunDoors) send(hand bool, verb, id, u, raw string) (int, string) { |
| p := e2eRunPost{hand: hand, verb: verb, id: id, before: d.w.snap()} |
| - code, out := d.do(hand, http.MethodPost, u, string(raw)) |
| + code, out := d.do(hand, http.MethodPost, u, raw) |
| p.code, p.after = code, d.w.snap() |
| p.lost = !hand && d.lose != nil && d.lose(verb) |
| d.posts = append(d.posts, p) |
| @@ -2081,48 +2150,6 @@ func (d *e2eRunDoors) post(hand bool, verb, id string) (int, string) { |
| return code, out |
| } |
| -func (d *e2eRunDoors) answer(code int, out string) offlinerun.Answer { |
| - p := d.posts[len(d.posts)-1] |
| - if p.lost { |
| - return offlinerun.Answer{} |
| - } |
| - switch { |
| - case code >= 200 && code <= 299: |
| - var v struct { |
| - offlinerun.View |
| - New bool `json:"new"` |
| - } |
| - _ = json.Unmarshal([]byte(out), &v) |
| - if p.verb == offlinerun.VerbStage && p.id == "" && !v.New { |
| - // A first stage binds only to a move its reply says it created. |
| - return offlinerun.Answer{Accepted: true} |
| - } |
| - return offlinerun.Answer{Accepted: true, ID: v.ID} |
| - case code >= 400 && code <= 499: |
| - return offlinerun.Answer{Refused: true} |
| - } |
| - return offlinerun.Answer{} |
| -} |
| - |
| -func (d *e2eRunDoors) Post(_ context.Context, verb, id string) offlinerun.Answer { |
| - pending, aborted := d.ints.Pending(), d.aborted |
| - if d.beforeRunPost != nil { |
| - d.beforeRunPost(verb) |
| - } |
| - code, out := d.post(false, verb, id) |
| - last := &d.posts[len(d.posts)-1] |
| - last.pending, last.afterAbort = pending, aborted |
| - return d.answer(code, out) |
| -} |
| - |
| -func (d *e2eRunDoors) Nudge(_ context.Context, id string) offlinerun.Answer { |
| - pending, aborted := d.ints.Pending(), d.aborted |
| - code, out := d.post(false, "nudge", id) |
| - last := &d.posts[len(d.posts)-1] |
| - last.pending, last.afterAbort = pending, aborted |
| - return d.answer(code, out) |
| -} |
| - |
| // e2ePressWatch is the simulation's Watcher: it may press Ctrl-C while it |
| // "writes" (Saw, Acting), and keeps every Ctrl-C the run took. |
| type e2ePressWatch struct { |
| @@ -2131,8 +2158,15 @@ type e2ePressWatch struct { |
| kinds []offlinerun.Interrupt |
| takes int |
| pressN *int |
| + // unread counts the status reads that got no view; bad keeps each |
| + // abort the run promised (InterruptAbort) with the view it had read |
| + // last not its own move in a state abort applies to (invariant C). |
| + unread int |
| + bad []string |
| } |
| +func (w *e2ePressWatch) Unread(bool, time.Duration) { w.unread++ } |
| + |
| func (w *e2ePressWatch) Saw(offlinerun.View) { w.press() } |
| func (w *e2ePressWatch) Acting(offlinerun.Action, offlinerun.Memory) { w.press() } |
| func (w *e2ePressWatch) Withdrawn(offlinerun.Action) {} |
| @@ -2142,14 +2176,20 @@ func (w *e2ePressWatch) Interrupted(i offlinerun.Interrupt, _ offlinerun.Memory) |
| w.kinds = append(w.kinds, i) |
| if i == offlinerun.InterruptAbort { |
| w.doors.aborted = true |
| + switch v := w.doors.lastView; { |
| + case v.ID == "" || v.ID != w.doors.mine: |
| + w.bad = append(w.bad, fmt.Sprintf("promised an abort on a view of %q in %s; the run's move is %q", v.ID, v.State, w.doors.mine)) |
| + case v.State == provision.OfflineOpen || v.State == provision.OfflineFinishing || v.State == "none": |
| + w.bad = append(w.bad, "promised an abort on a view in "+v.State) |
| + } |
| } |
| } |
| -// runVerbs lists the run's POSTs as "<verb>" in order. |
| +// runVerbs lists the run's POSTs that reached a door, as "<verb>" in order. |
| func (d *e2eRunDoors) runVerbs() []string { |
| var out []string |
| for _, p := range d.posts { |
| - if !p.hand { |
| + if !p.hand && !p.limited { |
| out = append(out, p.verb) |
| } |
| } |
| @@ -2164,6 +2204,7 @@ func (e2eQuiet) Acting(offlinerun.Action, offlinerun.Memory) { |
| func (e2eQuiet) Withdrawn(offlinerun.Action) {} |
| func (e2eQuiet) Acted(offlinerun.Action, offlinerun.Result, offlinerun.Memory) {} |
| func (e2eQuiet) Interrupted(offlinerun.Interrupt, offlinerun.Memory) {} |
| +func (e2eQuiet) Unread(bool, time.Duration) {} |
| // e2eSerialOnly is the boxes woken by the serial and by nothing else: each |
| // box's fastTick (the real serial rule) with the agent's pass set behind |
| @@ -2229,10 +2270,13 @@ func (s *e2eSerialOnly) settle() { |
| } |
| } |
| -// e2eRun drives one offlinerun.Runner over the world, one Step a tick, the |
| -// boxes woken between ticks only by the serial; between ticks also runs |
| -// between (a second operator, say). The run's clock is virtual, two seconds |
| -// a tick. It answers how the run ended. |
| +// e2eRun drives one offlinerun.Runner over the world: the production loop |
| +// (Runner.Run) over the production doors (offlinerun.HTTPDoors) over the |
| +// console's real handlers. The world's time is the loop's waits: each one |
| +// moves the virtual clock on by what the loop asked for (a poll's 2 s, or |
| +// the back-off after a rate limit), wakes the boxes by the serial only, |
| +// and runs between (a second operator, say). It answers how the run ended; |
| +// err is the loop's own error, when its first status reads never answered. |
| type e2eRun struct { |
| w *e2eWorld |
| doors *e2eRunDoors |
| @@ -2241,6 +2285,7 @@ type e2eRun struct { |
| now time.Duration |
| between func() |
| ticks int |
| + err error |
| // ints and watch, when set, are the run's Ctrl-Cs and its Watcher |
| // (e2eQuiet when nil). |
| ints *offlinerun.Interrupts |
| @@ -2262,27 +2307,26 @@ func (r *e2eRun) run(maxTicks int) offlinerun.Done { |
| if r.watch != nil { |
| watch = r.watch |
| } |
| - runner := &offlinerun.Runner{Doors: r.doors, Probe: r.probe, Policy: r.policy, |
| + doors := &offlinerun.HTTPDoors{Wire: r.doors, Region: "uk", Interrupts: r.ints} |
| + runner := &offlinerun.Runner{Doors: doors, Probe: r.probe, Policy: r.policy, |
| Clock: func() time.Duration { return r.now }, Poll: offlinerun.DefaultPoll, Watch: watch, Interrupts: r.ints} |
| - m := offlinerun.NewMemory("") |
| - for ; r.ticks < maxTicks; r.ticks++ { |
| - next, done, err := runner.Step(context.Background(), m) |
| - if err != nil { |
| - t.Fatalf("tick %d: %v", r.ticks, err) |
| + runner.After = func(d time.Duration) <-chan time.Time { |
| + if r.ticks++; r.ticks > maxTicks { |
| + t.Fatalf("the run did not end in %d ticks; the record is %s; POSTs %v", maxTicks, r.w.snap(), r.doors.runVerbs()) |
| } |
| - m = next |
| - if done != nil { |
| - return *done |
| - } |
| - r.now += offlinerun.DefaultPoll |
| + r.now += d |
| r.boxes.settle() |
| if r.between != nil { |
| r.between() |
| r.boxes.settle() |
| } |
| + fired := make(chan time.Time, 1) |
| + fired <- time.Time{} |
| + return fired |
| } |
| - t.Fatalf("the run did not end in %d ticks; the record is %s; POSTs %v", maxTicks, r.w.snap(), r.doors.runVerbs()) |
| - return offlinerun.Done{} |
| + done, _, err := runner.Run(context.Background(), offlinerun.NewMemory("")) |
| + r.err = err |
| + return done |
| } |
| // newRun is a run over w, before anything is posted: the source's timers |
| @@ -2318,8 +2362,9 @@ func (w *e2eWorld) newRun(deaf func(b *offBox) bool) *e2eRun { |
| const e2eRunHappy = "stage,start,seal,flip,open,finish,nudge,finish" |
| // TestOfflineMoveRunE2E is the two-box witness for carlos move offline |
| -// run's loop: offlinerun.Runner's Step, one a tick, over the console's real |
| -// doors, and both boxes' production passes woken only by the serial (the |
| +// run's loop: offlinerun.Runner's Run over its production doors |
| +// (offlinerun.HTTPDoors), over the console's real handlers, and both boxes' |
| +// production passes woken only by the serial (the |
| // doors' bumps and the boxes' own), nothing else. The move goes from |
| // nothing through a stage round to done and the target holds the source's |
| // instance. Then a box that misses one wake: the move stands still until |
| @@ -2327,7 +2372,7 @@ const e2eRunHappy = "stage,start,seal,flip,open,finish,nudge,finish" |
| // does. Without the nudge the same miss stalls the stop until its budget |
| // aborts the move. |
| func TestOfflineMoveRunE2E(t *testing.T) { |
| - t.Run("done by Step, woken by the serial", func(t *testing.T) { |
| + t.Run("done by the loop, woken by the serial", func(t *testing.T) { |
| w := newE2EWorld(t, landOpts{}) |
| r := w.newRun(nil) |
| done := r.run(200) |
| @@ -2545,9 +2590,14 @@ func TestOfflineMoveRunE2E(t *testing.T) { |
| } |
| // TestOfflineMoveRunSimulation is Task 7's seeded simulation: the run's |
| -// Step over the two-box world as TestOfflineMoveRunE2E drives it, with, at |
| -// points each seed picks, replies lost after the door answered (the write, |
| -// if any, committed), serial wakes a box misses, and a second operator |
| +// production loop, gate, doors and status classifier (offlinerun.Runner.Run |
| +// over offlinerun.HTTPDoors) over the two-box world as TestOfflineMoveRunE2E |
| +// drives it, with, at points each seed picks, replies lost after the door |
| +// answered (the write, if any, committed), POSTs and status reads the rate |
| +// limit answers, status reads that fail in ways that pass (no answer, a |
| +// 5xx, a body cut short) and, on some seeds, one that will not (a revoked |
| +// token, a redirect to a login page, a 200 that is not a status view), |
| +// Ctrl-Cs wherever one can land, serial wakes a box misses, and a second operator |
| // posting any door by hand between ticks (no id, as the hand verbs send) or |
| // taking the host over (abort, finish, a stage of their own). Half the seeds |
| // run on short budgets, so the run's own aborts land at random points too. |
| @@ -2559,7 +2609,14 @@ func TestOfflineMoveRunE2E(t *testing.T) { |
| // writes the record; |
| // - the run ends cleared, done or aborted as last says (exit 0 or 3), or |
| // stopped (exit 4) with the record still carrying a move in a named |
| -// state. |
| +// state; |
| +// - invariant A: no POST leaves with a Ctrl-C pending, and no forward |
| +// POST after a Ctrl-C before open, the rate limit's answers included |
| +// (each is one request, and the next is decided afresh); |
| +// - invariant B: a status read that won't pass ends the run at that |
| +// read, with nothing sent after it; one that may pass never does; |
| +// - invariant C: the run promises an abort only with its own move's |
| +// view in hand, in a state abort applies to. |
| // |
| // CI runs offlineRunSimSeeds seeds; OFFLINE_RUN_SIM_SEEDS=<n> runs n. |
| func TestOfflineMoveRunSimulation(t *testing.T) { |
| @@ -2581,7 +2638,8 @@ func TestOfflineMoveRunSimulation(t *testing.T) { |
| // The faults happened: a simulation that injected none proves nothing. |
| if !t.Failed() && seeds >= offlineRunSimSeeds && |
| (all.done == 0 || all.aborted == 0 || all.stopped == 0 || all.refused == 0 || all.runAborts == 0 || all.lost == 0 || all.missed == 0 || all.handWrites == 0 || |
| - all.pressAbort == 0 || all.pressOpen == 0 || all.pressStop == 0) { |
| + all.pressAbort == 0 || all.pressOpen == 0 || all.pressStop == 0 || |
| + all.limited == 0 || all.unread == 0 || all.gone == 0 || all.goneFirst == 0) { |
| t.Fatalf("the seeds did not exercise every fault and ending: %+v", all) |
| } |
| } |
| @@ -2604,6 +2662,12 @@ const ( |
| // simPress is a Ctrl-C at each point one can land on, on the seeds |
| // that press. |
| simPress = 0.015 |
| + // simLimitPost is a POST the rate limit answers; simStatusPasses a |
| + // status read that fails in a way that may pass; simStatusGone, on the |
| + // seeds that have one, a status read that will not (the run ends). |
| + simLimitPost = 0.06 |
| + simStatusPasses = 0.06 |
| + simStatusGone = 0.06 |
| ) |
| type offlineRunSimTally struct { |
| @@ -2617,6 +2681,10 @@ type offlineRunSimTally struct { |
| lost, missed, handPosts int |
| handWrites, nudges, ticks int |
| runAborts int |
| + // limited: POSTs the rate limit answered. unread: status reads that |
| + // got no view. gone: runs a status read that won't pass ended, and |
| + // goneFirst those it ended before any view. |
| + limited, unread, gone, goneFirst int |
| } |
| func (a *offlineRunSimTally) add(b offlineRunSimTally) { |
| @@ -2636,6 +2704,10 @@ func (a *offlineRunSimTally) add(b offlineRunSimTally) { |
| a.nudges += b.nudges |
| a.ticks += b.ticks |
| a.runAborts += b.runAborts |
| + a.limited += b.limited |
| + a.unread += b.unread |
| + a.gone += b.gone |
| + a.goneFirst += b.goneFirst |
| } |
| func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally { |
| @@ -2696,6 +2768,15 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally { |
| watch := &e2ePressWatch{press: press, doors: r.doors} |
| r.watch = watch |
| r.doors.onStatus = press |
| + // As the rate limit answers a POST: the case round 3 found, where a |
| + // door that sent the POST again by itself would send it past a Ctrl-C. |
| + // It is pressed more often here than elsewhere, the point being rare. |
| + r.doors.onLimit = func() { |
| + if pressing && rng.Float64() < 20*simPress { |
| + pressed++ |
| + r.ints.Add() |
| + } |
| + } |
| hand := r.between |
| r.between = func() { |
| hand() |
| @@ -2713,6 +2794,36 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally { |
| r.policy.Stop, r.policy.Seal, r.policy.Landing, r.policy.OpenCheck = d(), d(), d(), d() |
| r.policy.Offline = d() + d() |
| } |
| + // The wire's own faults, through the production doors and classifier. |
| + // The rate limit answers a POST before any door. A status read fails |
| + // in a way that may pass. A Ctrl-C that ends a read may still lose the |
| + // race with its answer. And on a third of the seeds one status read is |
| + // answered in a way that will not pass: the run must end at that read |
| + // (goneAt is the read, goneSent the requests the run had made by then). |
| + r.doors.limit = func(string) bool { return rng.Float64() < simLimitPost } |
| + r.doors.deliver = func() bool { return rng.IntN(2) == 0 } |
| + notAView := []byte(`{"state":"offline-landed","id":"mv-not-a-view","next":123}`) |
| + passes := []offlinerun.Exchange{{}, {Status: http.StatusBadGateway}, {Status: http.StatusServiceUnavailable, Body: []byte(`{"error":"x"}`)}, |
| + {Status: http.StatusTooManyRequests}, {Status: http.StatusOK, Cut: true}} |
| + gone := []offlinerun.Exchange{{Status: http.StatusUnauthorized}, {Status: http.StatusUnauthorized, Cut: true}, {Status: http.StatusForbidden}, |
| + {Status: http.StatusNotFound}, {Status: http.StatusFound}, {Status: http.StatusMovedPermanently}, {Status: http.StatusNoContent}, |
| + {Status: http.StatusOK, Body: []byte("<html>")}, {Status: http.StatusOK, Body: notAView}} |
| + goes := rng.IntN(3) == 0 |
| + goneAt, goneSent, statusFaults := 0, 0, 0 |
| + r.doors.statusFault = func() (offlinerun.Exchange, bool) { |
| + if goneAt != 0 { |
| + return gone[0], true // asked again after the end: the check below fails on it |
| + } |
| + switch x := rng.Float64(); { |
| + case goes && (x < simStatusGone || (r.doors.reads == 1 && x < 0.25)): |
| + goneAt, goneSent = r.doors.reads, r.doors.sent |
| + return gone[rng.IntN(len(gone))], true |
| + case x < simStatusGone+simStatusPasses: |
| + statusFaults++ |
| + return passes[rng.IntN(len(passes))], true |
| + } |
| + return offlinerun.Exchange{}, false |
| + } |
| done := r.run(3000) |
| var tally offlineRunSimTally |
| @@ -2729,8 +2840,12 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally { |
| tally.pressStop++ |
| } |
| } |
| + tally.unread = watch.unread |
| var trail []string |
| for _, p := range r.doors.posts { |
| + if p.limited { |
| + tally.limited++ |
| + } |
| who := "run" |
| if p.hand { |
| who = "hand" |
| @@ -2752,6 +2867,36 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally { |
| t.Fatalf("seed %d: %s\nended %+v after %d ticks\n%s", seed, fmt.Sprintf(format, args...), done, r.ticks, strings.Join(trail, "\n")) |
| } |
| + // Invariant C: an abort was promised only on the run's own move's |
| + // view, in a state abort applies to. |
| + if len(watch.bad) > 0 { |
| + fail("%s", strings.Join(watch.bad, "; ")) |
| + } |
| + // Invariant B: a status read that won't pass ended the run at that |
| + // read: the loop's error before any view (nothing was sent at all), |
| + // exit 1 after one, and no request of any kind after it. One that may |
| + // pass never ends a run. |
| + if goneAt != 0 { |
| + if r.doors.sent != goneSent { |
| + fail("the run made %d requests after status read %d was refused for good", r.doors.sent-goneSent, goneAt) |
| + } |
| + tally.gone++ |
| + switch { |
| + case errors.Is(r.err, offlinerun.ErrStatusRefused): |
| + tally.goneFirst++ |
| + if len(r.doors.posts) != 0 { |
| + fail("the first status reads never answered, yet POSTs were made") |
| + } |
| + case r.err != nil || done != (offlinerun.Done{Exit: offlinerun.ExitError, Reason: offlinerun.ReasonStatusRefused}): |
| + fail("status read %d was refused for good; the run ended %+v, err %v", goneAt, done, r.err) |
| + } |
| + t.Logf("seed %d: status read %d refused for good; err %v, %+v; run %s", seed, goneAt, r.err, done, strings.Join(r.doors.runVerbs(), ",")) |
| + return tally |
| + } |
| + if r.err != nil || done.Exit == offlinerun.ExitError { |
| + fail("the run ended %+v, err %v, with no status read refused for good (%d failed in ways that pass)", done, r.err, statusFaults) |
| + } |
| + |
| // The run's own move: its first POST is the create-only stage. When |
| // it created a move, that is the run's; when it was refused (someone |
| // staged between the run's read and its POST) it wrote nothing, and |
| @@ -2763,6 +2908,12 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally { |
| for i, p := range r.doors.posts { |
| switch { |
| case p.hand: |
| + case p.limited: |
| + // The rate limit answered: no door was reached, nothing was |
| + // written, and the gate's checks below still hold for it. |
| + if p.before.raw != p.after.raw { |
| + fail("a POST the rate limit answered wrote the record") |
| + } |
| case first < 0: |
| first = i |
| if p.verb != offlinerun.VerbStage || p.id != "" { |
| @@ -2787,6 +2938,12 @@ func offlineRunSim(t *testing.T, seed uint64) offlineRunSimTally { |
| if !p.hand && p.pending { |
| fail("the run dispatched %s with a Ctrl-C pending", p.verb) |
| } |
| + // One thing a read: every POST was decided by the loop from a |
| + // status read made since the last one. A door that sent a POST |
| + // again by itself (after a 429, say) fails here. |
| + if !p.hand && p.stale { |
| + fail("the run posted %s with no status read since its last POST", p.verb) |
| + } |
| if !p.hand && p.afterAbort { |
| switch p.verb { |
| case offlinerun.VerbStage, offlinerun.VerbStart, offlinerun.VerbSeal, offlinerun.VerbFlip, offlinerun.VerbOpen: |
diff --git a/internal/moves/offlinerun/construction_test.go b/internal/moves/offlinerun/construction_test.go| new file mode 100644 |
| index 000000000..8caec3a8c |
| --- /dev/null |
| +++ b/internal/moves/offlinerun/construction_test.go |
| @@ -0,0 +1,704 @@ |
| +package offlinerun |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "os" |
| + "reflect" |
| + "sort" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The run's shape after the third Astra round (the right course): the |
| +// invariants hold by how the code is built, and these tests hold the |
| +// build. The Doors make one request a call; the Runner's loop makes every |
| +// wait; the gate makes every POST; one function classifies a status |
| +// answer; one function, which takes a view, promises an abort. |
| + |
| +// fakeWire is a Transport: answer says what each request gets; log keeps |
| +// each as "<METHOD> <tail>". |
| +type fakeWire struct { |
| + answer func(method, tail string, body any) Exchange |
| + log []string |
| + bodies []any |
| +} |
| + |
| +func (w *fakeWire) Do(_ context.Context, method, tail string, body any) Exchange { |
| + w.log = append(w.log, method+" "+tail) |
| + w.bodies = append(w.bodies, body) |
| + return w.answer(method, tail, body) |
| +} |
| + |
| +func viewJSON(state, next string) string { |
| + s := `{"state":"` + state + `","id":"` + tID + `","to":"uk"` |
| + if next != "" { |
| + s += `,"next":"` + next + `"` |
| + } |
| + return s + "}" |
| +} |
| + |
| +func ok(body string) Exchange { return Exchange{Status: 200, Body: []byte(body)} } |
| + |
| +// wireRun is a Runner over HTTPDoors over w, on fake time, with Ctrl-Cs. |
| +// waits keeps every wait the loop made. |
| +func wireRun(w Transport) (*Runner, *nopWatch, *[]time.Duration) { |
| + r, watch := testRunner(nil, func() int { return 200 }) |
| + r.Interrupts = NewInterrupts() |
| + r.Doors = &HTTPDoors{Wire: w, Region: "uk", Interrupts: r.Interrupts} |
| + waits := &[]time.Duration{} |
| + after := r.After |
| + r.After = func(d time.Duration) <-chan time.Time { |
| + *waits = append(*waits, d) |
| + return after(d) |
| + } |
| + return r, watch, waits |
| +} |
| + |
| +// landedWire answers status from where the move stands: landed with next |
| +// open until an abort is posted, then reverting, then gone as aborted (a |
| +// model that never ends a move as done: a test that opens one stops at |
| +// open, or fails). open answers 429 the first limit times. |
| +type landedWire struct { |
| + fakeWire |
| + state string |
| + limit int |
| +} |
| + |
| +func newLandedWire(limit int) *landedWire { |
| + w := &landedWire{state: StateLanded, limit: limit} |
| + w.answer = func(method, tail string, _ any) Exchange { |
| + switch { |
| + case method == "GET" && w.state == StateNone: |
| + return ok(`{"state":"none","last":{"id":"` + tID + `","outcome":"aborted"}}`) |
| + case method == "GET" && w.state == StateLanded: |
| + return ok(viewJSON(w.state, VerbOpen)) |
| + case method == "GET" && w.state == StateReverting: |
| + return ok(viewJSON(w.state, VerbFinish)) |
| + case method == "GET": |
| + return ok(viewJSON(w.state, VerbFinish)) // open, finishing |
| + case tail == "/open" && w.limit > 0: |
| + w.limit-- |
| + return Exchange{Status: 429, Body: []byte(`{"error":"too many requests"}`)} |
| + case tail == "/open": |
| + w.state = StateOpen |
| + case tail == "/abort": |
| + w.state = StateReverting |
| + case tail == "/finish" && w.state == StateOpen: |
| + w.state = StateFinishing |
| + case tail == "/finish": |
| + w.state = StateNone |
| + } |
| + return Exchange{Status: 202, Body: []byte(viewJSON(w.state, ""))} |
| + } |
| + return w |
| +} |
| + |
| +// TestLimitedPostReturnsThroughTheGate is the witness the third round asked |
| +// for (P1): open is answered 429, and at the back-off's end the timer and a |
| +// Ctrl-C are ready together. Whichever the loop takes first, no second |
| +// open leaves: the next thing sent is the abort. The Doors sent the open |
| +// once; the loop, not the Doors, made the wait. |
| +func TestLimitedPostReturnsThroughTheGate(t *testing.T) { |
| + // Run it enough times that select has picked each ready case. |
| + for i := 0; i < 200; i++ { |
| + w := newLandedWire(1) |
| + r, watch, waits := wireRun(w) |
| + after := r.After |
| + r.After = func(d time.Duration) <-chan time.Time { |
| + if d == r.backoff() { |
| + r.Interrupts.Add() // the Ctrl-C and the timer coincide |
| + } |
| + return after(d) |
| + } |
| + done, _, err := r.Run(context.Background(), offline(StateLanded, 0)) |
| + if err != nil || done.Exit != ExitAborted { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| + var posts []string |
| + for _, l := range w.log { |
| + if strings.HasPrefix(l, "POST ") { |
| + posts = append(posts, strings.TrimPrefix(l, "POST ")) |
| + } |
| + } |
| + if got := strings.Join(posts, ","); got != "/open,/abort,/finish" { |
| + t.Fatalf("POSTs %s (requests %q)", got, w.log) |
| + } |
| + if !reflect.DeepEqual(watch.interrupts, []Interrupt{InterruptAbort}) { |
| + t.Fatalf("interrupts %v", watch.interrupts) |
| + } |
| + if (*waits)[0] != DefaultBackoff { |
| + t.Fatalf("waits %v: the first is not the back-off", *waits) |
| + } |
| + } |
| +} |
| + |
| +// TestLimitedPostIsDecidedAgain: with no Ctrl-C, a POST the rate limit |
| +// answered is sent again only after the back-off and a fresh status read, |
| +// decided anew through the gate; and it leaves nothing in the memory (a |
| +// limited restage is not one of the run's tries). |
| +func TestLimitedPostIsDecidedAgain(t *testing.T) { |
| + w := newLandedWire(2) |
| + r, _, waits := wireRun(w) |
| + r.Policy.NoFinish = true |
| + done, _, err := r.Run(context.Background(), offline(StateLanded, 0)) |
| + if err != nil || done.Exit != ExitDone { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| + if got := strings.Join(w.log[:6], ","); got != "GET ,POST /open,GET ,POST /open,GET ,POST /open" { |
| + t.Fatalf("requests %q", w.log) |
| + } |
| + if !reflect.DeepEqual((*waits)[:3], []time.Duration{DefaultBackoff, DefaultBackoff, DefaultPoll}) { |
| + t.Fatalf("waits %v", *waits) |
| + } |
| + |
| + // The memory after a limited POST is the memory before it was decided. |
| + d := &fakeDoors{views: []View{staging(5, true, 2*mib)}, answer: func(string) Answer { return Answer{Limited: true} }} |
| + rr, _ := testRunner(d, func() int { return 200 }) |
| + before := bound(StateStaging, 0) |
| + after, stop, err := rr.Step(context.Background(), before) |
| + if stop != nil || err != nil || !reflect.DeepEqual(after, before) { |
| + t.Fatalf("stop %v, err %v, memory changed: %+v, was %+v", stop, err, after, before) |
| + } |
| +} |
| + |
| +// TestLimitedStatusBacksOff: a status read the rate limit answered is |
| +// asked again after the back-off, and the Watcher is told. |
| +func TestLimitedStatusBacksOff(t *testing.T) { |
| + n := 0 |
| + w := &fakeWire{} |
| + w.answer = func(string, string, any) Exchange { |
| + n++ |
| + switch n { |
| + case 2: |
| + return Exchange{Status: 429} |
| + case 3: |
| + return Exchange{Status: 502} |
| + case 4: |
| + return ok(`{"state":"none","last":{"id":"` + tID + `","outcome":"done"}}`) |
| + } |
| + return ok(viewJSON(StateSealing, "")) |
| + } |
| + r, watch, waits := wireRun(w) |
| + done, _, err := r.Run(context.Background(), offline(StateSealing, 0)) |
| + if err != nil || done.Exit != ExitDone { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| + if !reflect.DeepEqual(*waits, []time.Duration{DefaultPoll, DefaultBackoff, DefaultPoll}) { |
| + t.Fatalf("waits %v", *waits) |
| + } |
| + if !reflect.DeepEqual(watch.unread, []string{"true 0s", "false 10s"}) { |
| + t.Fatalf("unread %v", watch.unread) |
| + } |
| +} |
| + |
| +// TestFirstReads: before any view, DefaultFirstReads failures in a row end |
| +// the run with the last error and nothing sent; the rate limit's answers |
| +// do not count; a refusal for good ends it at once. |
| +func TestFirstReads(t *testing.T) { |
| + n := 0 |
| + w := &fakeWire{} |
| + w.answer = func(string, string, any) Exchange { |
| + n++ |
| + if n <= 8 { |
| + return Exchange{Status: 429} |
| + } |
| + return Exchange{Status: 503} |
| + } |
| + r, _, waits := wireRun(w) |
| + _, _, err := r.Run(context.Background(), NewMemory("")) |
| + if !errors.Is(err, ErrNoStatus) || len(w.log) != 8+DefaultFirstReads { |
| + t.Fatalf("err %v after %d requests", err, len(w.log)) |
| + } |
| + if (*waits)[0] != DefaultBackoff || (*waits)[len(*waits)-1] != DefaultPoll { |
| + t.Fatalf("waits %v", *waits) |
| + } |
| + w = &fakeWire{answer: func(string, string, any) Exchange { return Exchange{Status: 401} }} |
| + r, _, _ = wireRun(w) |
| + if _, _, err := r.Run(context.Background(), NewMemory(tID)); !errors.Is(err, ErrStatusRefused) || len(w.log) != 1 { |
| + t.Fatalf("err %v after %q", err, w.log) |
| + } |
| +} |
| + |
| +// TestLoopNeverSpins: the loop goes round again without a wait only when |
| +// it took a Ctrl-C. Doors that say a read was interrupted when no Ctrl-C |
| +// is pending get the ordinary wait, and the first reads' cap. |
| +func TestLoopNeverSpins(t *testing.T) { |
| + d := &alwaysInterrupted{} |
| + r, _ := testRunner(d, func() int { return 200 }) |
| + r.Interrupts = NewInterrupts() |
| + waits := 0 |
| + after := r.After |
| + r.After = func(dd time.Duration) <-chan time.Time { |
| + waits++ |
| + return after(dd) |
| + } |
| + _, _, err := r.Run(context.Background(), NewMemory(tID)) |
| + if !errors.Is(err, ErrInterrupted) || d.reads != DefaultFirstReads || waits != DefaultFirstReads-1 { |
| + t.Fatalf("err %v after %d reads and %d waits", err, d.reads, waits) |
| + } |
| +} |
| + |
| +type alwaysInterrupted struct { |
| + fakeDoors |
| + reads int |
| +} |
| + |
| +func (d *alwaysInterrupted) Status(context.Context) (View, error) { |
| + if d.reads++; d.reads > 1000 { |
| + panic("the loop read status 1000 times without a wait") |
| + } |
| + return View{}, fmt.Errorf("status: %w", ErrInterrupted) |
| +} |
| + |
| +// TestClassifyStatus is the one status classifier's table (invariant B: a |
| +// status failure that won't pass stops run). The third round's case is |
| +// here: a 200 that is JSON but not a view ("next" a number). |
| +func TestClassifyStatus(t *testing.T) { |
| + view := viewJSON(StateLanded, VerbOpen) |
| + type also struct { |
| + Boxes []string `json:"boxes"` |
| + } |
| + for _, c := range []struct { |
| + name string |
| + x Exchange |
| + also bool |
| + want StatusClass |
| + }{ |
| + {"200 view", ok(view), false, StatusAnswered}, |
| + {"200 view, read both ways", ok(view), true, StatusAnswered}, |
| + {"no answer", Exchange{}, false, StatusPasses}, |
| + {"500", Exchange{Status: 500}, false, StatusPasses}, |
| + {"502 with a body", Exchange{Status: 502, Body: []byte(`{"error":"x"}`)}, false, StatusPasses}, |
| + {"599", Exchange{Status: 599}, false, StatusPasses}, |
| + {"429", Exchange{Status: 429}, false, StatusLimited}, |
| + {"429 cut", Exchange{Status: 429, Cut: true}, false, StatusLimited}, |
| + {"200 cut short", Exchange{Status: 200, Cut: true}, false, StatusPasses}, |
| + {"200 not JSON", ok("<html>"), false, StatusRefused}, |
| + {"200 empty", Exchange{Status: 200}, false, StatusRefused}, |
| + {"200 next is a number", ok(`{"state":"offline-landed","id":"` + tID + `","next":123}`), false, StatusRefused}, |
| + {"200 stage is a string", ok(`{"state":"offline-staging","id":"` + tID + `","stage":"x"}`), false, StatusRefused}, |
| + {"200 a view, but not the caller's", ok(`{"state":"offline-landed","id":"` + tID + `","boxes":7}`), true, StatusRefused}, |
| + {"204", Exchange{Status: 204}, false, StatusRefused}, |
| + {"202 view", Exchange{Status: 202, Body: []byte(view)}, false, StatusRefused}, |
| + {"301", Exchange{Status: 301}, false, StatusRefused}, |
| + {"302", Exchange{Status: 302}, false, StatusRefused}, |
| + {"307", Exchange{Status: 307}, false, StatusRefused}, |
| + {"400", Exchange{Status: 400}, false, StatusRefused}, |
| + {"401", Exchange{Status: 401}, false, StatusRefused}, |
| + {"401 cut short", Exchange{Status: 401, Cut: true}, false, StatusRefused}, |
| + {"403", Exchange{Status: 403}, false, StatusRefused}, |
| + {"404", Exchange{Status: 404}, false, StatusRefused}, |
| + {"409", Exchange{Status: 409}, false, StatusRefused}, |
| + {"418", Exchange{Status: 418}, false, StatusRefused}, |
| + {"600", Exchange{Status: 600}, false, StatusRefused}, |
| + } { |
| + var target any |
| + if c.also { |
| + target = &also{} |
| + } |
| + got, v := ClassifyStatus(c.x, target) |
| + if got != c.want { |
| + t.Errorf("%s: class %d, want %d", c.name, got, c.want) |
| + } |
| + if (got == StatusAnswered) != (v.ID == tID) { |
| + t.Errorf("%s: view %+v for class %d", c.name, v, got) |
| + } |
| + } |
| +} |
| + |
| +// TestStatusNotAViewStopsTheRun: the third round's case through the loop. |
| +// A 200 whose JSON is not a view ends the run: on the first read with the |
| +// error and nothing sent, on a later one with exit 1 and nothing more |
| +// sent. Before, a second classification outside the classifier held this. |
| +func TestStatusNotAViewStopsTheRun(t *testing.T) { |
| + bad := ok(`{"state":"offline-landed","id":"` + tID + `","next":123}`) |
| + w := &fakeWire{answer: func(string, string, any) Exchange { return bad }} |
| + r, _, _ := wireRun(w) |
| + if _, _, err := r.Run(context.Background(), NewMemory(tID)); !errors.Is(err, ErrStatusRefused) || len(w.log) != 1 { |
| + t.Fatalf("first read: err %v after %q", err, w.log) |
| + } |
| + n := 0 |
| + w = &fakeWire{} |
| + w.answer = func(string, string, any) Exchange { |
| + if n++; n == 1 { |
| + return ok(viewJSON(StateSealing, "")) |
| + } |
| + return bad |
| + } |
| + r, _, _ = wireRun(w) |
| + done, _, err := r.Run(context.Background(), offline(StateSealing, 0)) |
| + if err != nil || done != (Done{Exit: ExitError, Reason: ReasonStatusRefused}) || len(w.log) != 2 { |
| + t.Fatalf("later read: done %#v, err %v after %q", done, err, w.log) |
| + } |
| +} |
| + |
| +// TestCtrlCWithNoViewPromisesNothing is invariant C's witness (round 3, P2 |
| +// 3): a Ctrl-C that cuts the first read of a resumed run short is judged |
| +// by the next view, not before it. If someone opened the move meanwhile |
| +// the run says it is served and stops; if the host now has another move it |
| +// promises nothing and stops on that; only for its own move, before open, |
| +// does it say it is moving it back, and then it does. |
| +func TestCtrlCWithNoViewPromisesNothing(t *testing.T) { |
| + other := `{"state":"offline-landed","id":"mv-someone-elses","to":"us","next":"open"}` |
| + for _, c := range []struct { |
| + name string |
| + view string |
| + interrupts []Interrupt |
| + done Done |
| + posts string |
| + }{ |
| + {"opened by someone else", viewJSON(StateOpen, ""), []Interrupt{InterruptAfterOpen}, Done{Exit: ExitStopped, Reason: ReasonStoppedWatching}, ""}, |
| + {"finishing", viewJSON(StateFinishing, ""), []Interrupt{InterruptAfterOpen}, Done{Exit: ExitStopped, Reason: ReasonStoppedWatching}, ""}, |
| + {"replaced by another move", other, nil, Done{Exit: ExitStopped, Reason: ReasonOtherMove}, ""}, |
| + {"gone", `{"state":"none"}`, nil, Done{Exit: ExitStopped, Reason: ReasonMoveGone}, ""}, |
| + {"ended done", `{"state":"none","last":{"id":"` + tID + `","outcome":"done"}}`, nil, Done{Exit: ExitDone, Reason: ReasonDone}, ""}, |
| + {"its own, landed", "", []Interrupt{InterruptAbort}, Done{Exit: ExitAborted, Reason: ReasonAborted}, "/abort,/finish"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + w := newLandedWire(0) |
| + r, watch, _ := wireRun(w) |
| + model, first := w.answer, true |
| + w.answer = func(method, tail string, body any) Exchange { |
| + if method == "GET" && first { |
| + first = false |
| + r.Interrupts.Add() // cuts the read short |
| + return Exchange{} |
| + } |
| + if method == "GET" && c.view != "" { |
| + return ok(c.view) |
| + } |
| + return model(method, tail, body) |
| + } |
| + // The read is on a context the Ctrl-C ends, as the CLI's is. |
| + wire := r.Doors.(*HTTPDoors).Wire |
| + r.Doors.(*HTTPDoors).Wire = cutWire{wire} |
| + done, _, err := r.Run(context.Background(), NewMemory(tID)) |
| + if err != nil || done != c.done { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| + if !reflect.DeepEqual(watch.interrupts, c.interrupts) { |
| + t.Fatalf("interrupts %v, want %v", watch.interrupts, c.interrupts) |
| + } |
| + var posts []string |
| + for _, l := range w.log { |
| + if strings.HasPrefix(l, "POST ") { |
| + posts = append(posts, strings.TrimPrefix(l, "POST ")) |
| + } |
| + } |
| + if got := strings.Join(posts, ","); got != c.posts { |
| + t.Fatalf("POSTs %s", got) |
| + } |
| + }) |
| + } |
| + |
| + // A second Ctrl-C before any view stops watching: nothing was |
| + // promised, nothing is sent. |
| + w := &fakeWire{} |
| + r, watch, _ := wireRun(w) |
| + w.answer = func(string, string, any) Exchange { |
| + r.Interrupts.Add() |
| + return Exchange{} |
| + } |
| + r.Doors.(*HTTPDoors).Wire = cutWire{w} |
| + done, _, err := r.Run(context.Background(), NewMemory(tID)) |
| + if err != nil || done != (Done{Exit: ExitStopped, Reason: ReasonStoppedWatching}) { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| + if !reflect.DeepEqual(watch.interrupts, []Interrupt{InterruptStop}) || len(w.log) != 2 { |
| + t.Fatalf("interrupts %v, requests %q", watch.interrupts, w.log) |
| + } |
| +} |
| + |
| +// cutWire fails a request whose context has ended, as an HTTP client does. |
| +type cutWire struct{ Transport } |
| + |
| +func (c cutWire) Do(ctx context.Context, method, tail string, body any) Exchange { |
| + x := c.Transport.Do(ctx, method, tail, body) |
| + if ctx.Err() != nil { |
| + return Exchange{} |
| + } |
| + return x |
| +} |
| + |
| +// TestHTTPDoorsBodies: what the doors send, and how they read an answer. |
| +func TestHTTPDoorsBodies(t *testing.T) { |
| + w := &fakeWire{answer: func(method, tail string, _ any) Exchange { |
| + if method == "GET" { |
| + return ok(`{"state":"offline-staging","id":"` + tID + `","to":"us"}`) |
| + } |
| + return Exchange{Status: 202, Body: []byte(`{"state":"offline-staging","id":"` + tID + `","new":true}`)} |
| + }} |
| + d := &HTTPDoors{Wire: w, Region: "uk"} |
| + ctx := context.Background() |
| + if a := d.Post(ctx, VerbStage, ""); a != (Answer{Accepted: true, ID: tID}) { |
| + t.Fatalf("first stage: %+v", a) |
| + } |
| + if _, err := d.Status(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + d.Post(ctx, VerbStart, tID) |
| + d.Post(ctx, VerbSeal, tID) |
| + d.Nudge(ctx, tID) |
| + if got := strings.Join(w.log, ","); got != "POST /stage,GET ,POST ,POST /seal,POST /nudge" { |
| + t.Fatalf("requests %s", got) |
| + } |
| + want := []any{ |
| + map[string]any{"new": true, "region": "uk"}, |
| + nil, |
| + map[string]any{"id": tID, "region": "us"}, // the bound move's own region, once a view named it |
| + map[string]any{"id": tID}, |
| + map[string]any{"id": tID}, |
| + } |
| + if !reflect.DeepEqual(w.bodies, want) { |
| + t.Fatalf("bodies %#v", w.bodies) |
| + } |
| + for _, c := range []struct { |
| + name string |
| + x Exchange |
| + createOnly bool |
| + want Answer |
| + }{ |
| + {"202", Exchange{Status: 202, Body: []byte(viewJSON(StateSealing, ""))}, false, Answer{Accepted: true, ID: tID}}, |
| + {"create-only, not new", Exchange{Status: 202, Body: []byte(viewJSON(StateStaging, ""))}, true, Answer{Accepted: true}}, |
| + {"202 unread", Exchange{Status: 202, Body: []byte("<html>")}, false, Answer{}}, |
| + {"202 cut", Exchange{Status: 202, Cut: true}, false, Answer{}}, |
| + {"409", Exchange{Status: 409}, false, Answer{Refused: true}}, |
| + {"409 cut", Exchange{Status: 409, Cut: true}, false, Answer{}}, |
| + {"429", Exchange{Status: 429}, false, Answer{Limited: true}}, |
| + {"302", Exchange{Status: 302}, false, Answer{}}, |
| + {"502", Exchange{Status: 502}, false, Answer{}}, |
| + {"no answer", Exchange{}, false, Answer{}}, |
| + } { |
| + if got := answerOf(c.x, c.createOnly); got != c.want { |
| + t.Errorf("%s: %+v, want %+v", c.name, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +// ---- structural guards ---- |
| + |
| +// pkgFuncs parses the package's own files (not tests) and calls each for |
| +// every function, named "<Recv>.<name>" or "<name>". |
| +func pkgFuncs(t *testing.T, each func(file, name string, fn *ast.FuncDecl)) map[string]*ast.File { |
| + t.Helper() |
| + entries, err := os.ReadDir(".") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + files := map[string]*ast.File{} |
| + for _, e := range entries { |
| + name := e.Name() |
| + if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { |
| + continue |
| + } |
| + f, err := parser.ParseFile(token.NewFileSet(), name, nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + files[name] = f |
| + for _, decl := range f.Decls { |
| + fn, ok := decl.(*ast.FuncDecl) |
| + if !ok || fn.Body == nil { |
| + continue |
| + } |
| + full := fn.Name.Name |
| + if fn.Recv != nil && len(fn.Recv.List) == 1 { |
| + typ := fn.Recv.List[0].Type |
| + if st, ok := typ.(*ast.StarExpr); ok { |
| + typ = st.X |
| + } |
| + if id, ok := typ.(*ast.Ident); ok { |
| + full = id.Name + "." + full |
| + } |
| + } |
| + each(name, full, fn) |
| + } |
| + } |
| + return files |
| +} |
| + |
| +// TestDoorsAreSingleShot (invariant A, by construction): doors.go cannot |
| +// send a request twice or wait. It has no loop, no goto, no goroutine, no |
| +// select and no channel operation; it does not import time; and the |
| +// Transport is called in exactly three places, once in each of Status, |
| +// Post and Nudge. A retry added to the doors fails here. |
| +func TestDoorsAreSingleShot(t *testing.T) { |
| + calls := map[string]int{} |
| + files := pkgFuncs(t, func(file, name string, fn *ast.FuncDecl) { |
| + if file != "doors.go" { |
| + return |
| + } |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.ForStmt, *ast.RangeStmt, *ast.GoStmt, *ast.SelectStmt, *ast.SendStmt, *ast.DeferStmt: |
| + t.Errorf("doors.go: %s has a %T: the doors make one request a call and never wait", name, n) |
| + case *ast.BranchStmt: |
| + if n.Tok == token.GOTO { |
| + t.Errorf("doors.go: %s has a goto", name) |
| + } |
| + case *ast.UnaryExpr: |
| + if n.Op == token.ARROW { |
| + t.Errorf("doors.go: %s receives from a channel", name) |
| + } |
| + case *ast.CallExpr: |
| + if sel, ok := n.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "Do" { |
| + calls[name]++ |
| + } |
| + // No door calls another door, or itself. |
| + if sel, ok := n.Fun.(*ast.SelectorExpr); ok { |
| + switch sel.Sel.Name { |
| + case "Post", "Nudge", "Status": |
| + t.Errorf("doors.go: %s calls .%s", name, sel.Sel.Name) |
| + } |
| + } |
| + } |
| + return true |
| + }) |
| + }) |
| + want := map[string]int{"HTTPDoors.Status": 1, "HTTPDoors.Post": 1, "HTTPDoors.Nudge": 1} |
| + if !reflect.DeepEqual(calls, want) { |
| + t.Errorf("Transport.Do is called in %v, want once each in %v", calls, want) |
| + } |
| + for _, imp := range files["doors.go"].Imports { |
| + if imp.Path.Value == `"time"` { |
| + t.Error("doors.go imports time: the doors never wait") |
| + } |
| + } |
| +} |
| + |
| +// TestLoopOwnsEveryWait (invariants A and B, by construction): the package |
| +// has one loop that waits, Runner.Run. The loop's timer (After) is called |
| +// there and nowhere else; nothing calls time's own waits; a select or a |
| +// channel receive is in Run only; and the only other loops are the gate's |
| +// (it goes round on a withdrawn action, through its own check) and the |
| +// taking of pending Ctrl-Cs. |
| +func TestLoopOwnsEveryWait(t *testing.T) { |
| + loops := map[string]bool{} |
| + pkgFuncs(t, func(file, name string, fn *ast.FuncDecl) { |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.ForStmt: |
| + loops[name] = true |
| + case *ast.RangeStmt: |
| + if name != "Interrupts.Add" { |
| + t.Errorf("%s: %s ranges", file, name) |
| + } |
| + case *ast.SelectStmt: |
| + if name != "Runner.Run" && name != "Interrupts.Add" { |
| + t.Errorf("%s: %s selects: only Run waits", file, name) |
| + } |
| + case *ast.UnaryExpr: |
| + if n.Op == token.ARROW && name != "Runner.Run" { |
| + t.Errorf("%s: %s receives from a channel: only Run waits", file, name) |
| + } |
| + case *ast.CallExpr: |
| + sel, ok := n.Fun.(*ast.SelectorExpr) |
| + if !ok { |
| + return true |
| + } |
| + if sel.Sel.Name == "After" && name != "Runner.Run" { |
| + t.Errorf("%s: %s calls After: only Run waits", file, name) |
| + } |
| + if id, ok := sel.X.(*ast.Ident); ok && id.Name == "time" { |
| + switch sel.Sel.Name { |
| + case "Sleep", "After", "NewTimer", "NewTicker", "Tick", "AfterFunc": |
| + t.Errorf("%s: %s calls time.%s", file, name, sel.Sel.Name) |
| + } |
| + } |
| + } |
| + return true |
| + }) |
| + }) |
| + var got []string |
| + for name := range loops { |
| + got = append(got, name) |
| + } |
| + sort.Strings(got) |
| + if want := []string{"Runner.Run", "Runner.dispatch", "Runner.takeInterrupts"}; !reflect.DeepEqual(got, want) { |
| + t.Errorf("loops in %v, want only %v", got, want) |
| + } |
| +} |
| + |
| +// TestOneStatusClassifier (invariant B, by construction): HTTPDoors.Status |
| +// is the only caller of ClassifyStatus, the status errors are made there |
| +// and nowhere else, and nothing else in the package decodes JSON but the |
| +// classifier and the reading of a POST's answer. A second place that |
| +// judged a status body fails here. |
| +func TestOneStatusClassifier(t *testing.T) { |
| + classify, decodes := map[string]int{}, map[string]int{} |
| + pkgFuncs(t, func(file, name string, fn *ast.FuncDecl) { |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.CallExpr: |
| + if id, ok := n.Fun.(*ast.Ident); ok && id.Name == "ClassifyStatus" { |
| + classify[name]++ |
| + } |
| + if sel, ok := n.Fun.(*ast.SelectorExpr); ok { |
| + if id, ok := sel.X.(*ast.Ident); ok && id.Name == "json" { |
| + decodes[name]++ |
| + } |
| + } |
| + case *ast.Ident: |
| + switch n.Name { |
| + case "ErrStatusRefused", "ErrStatusLimited", "ErrNoStatus": |
| + if name != "HTTPDoors.Status" && name != "Runner.Run" { |
| + t.Errorf("%s: %s names %s", file, name, n.Name) |
| + } |
| + case "StatusAnswered", "StatusPasses", "StatusLimited", "StatusRefused": |
| + if name != "HTTPDoors.Status" && name != "ClassifyStatus" { |
| + t.Errorf("%s: %s names %s", file, name, n.Name) |
| + } |
| + } |
| + } |
| + return true |
| + }) |
| + }) |
| + if want := map[string]int{"HTTPDoors.Status": 1}; !reflect.DeepEqual(classify, want) { |
| + t.Errorf("ClassifyStatus is called in %v, want %v", classify, want) |
| + } |
| + if want := map[string]int{"ClassifyStatus": 2, "answerOf": 1}; !reflect.DeepEqual(decodes, want) { |
| + t.Errorf("JSON is decoded in %v, want %v", decodes, want) |
| + } |
| +} |
| + |
| +// TestAbortIsPromisedOnlyWithAView (invariant C, by construction): |
| +// InterruptAbort is said in judge and nowhere else, judge takes the view |
| +// by value (so it cannot be called without one), and only takeInterrupts |
| +// calls it. |
| +func TestAbortIsPromisedOnlyWithAView(t *testing.T) { |
| + said, callers := map[string]int{}, map[string]int{} |
| + pkgFuncs(t, func(file, name string, fn *ast.FuncDecl) { |
| + if name == "Runner.judge" { |
| + params := fn.Type.Params.List |
| + last := params[len(params)-1].Type |
| + if id, ok := last.(*ast.Ident); !ok || id.Name != "View" { |
| + t.Errorf("judge's last parameter is %s, want a View by value", fmt.Sprint(last)) |
| + } |
| + } |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.Ident: |
| + if n.Name == "InterruptAbort" { |
| + said[name]++ |
| + } |
| + case *ast.CallExpr: |
| + if sel, ok := n.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "judge" { |
| + callers[name]++ |
| + } |
| + } |
| + return true |
| + }) |
| + }) |
| + if want := map[string]int{"Runner.judge": 1}; !reflect.DeepEqual(said, want) { |
| + t.Errorf("InterruptAbort is said in %v, want %v", said, want) |
| + } |
| + if want := map[string]int{"Runner.takeInterrupts": 1}; !reflect.DeepEqual(callers, want) { |
| + t.Errorf("judge is called in %v, want %v", callers, want) |
| + } |
| +} |
diff --git a/internal/moves/offlinerun/decide.go b/internal/moves/offlinerun/decide.go| index 3aae7254e..6d444e9c1 100644 |
| --- a/internal/moves/offlinerun/decide.go |
| +++ b/internal/moves/offlinerun/decide.go |
| @@ -92,10 +92,13 @@ const ( |
| // reads. Field names and tags are the console's; unknown fields are |
| // ignored, so it decodes the full answer. |
| type View struct { |
| - State string `json:"state"` |
| - ID string `json:"id,omitempty"` |
| - Next string `json:"next,omitempty"` |
| - Waiting string `json:"waiting,omitempty"` |
| + State string `json:"state"` |
| + ID string `json:"id,omitempty"` |
| + Next string `json:"next,omitempty"` |
| + Waiting string `json:"waiting,omitempty"` |
| + // To is the region the move goes to: what the doors' stage and start |
| + // name for the bound move (HTTPDoors). Decide does not read it. |
| + To string `json:"to,omitempty"` |
| Failed bool `json:"failed,omitempty"` |
| StagedAt int64 `json:"staged_at,omitempty"` // Unix nanoseconds |
| RequestedAt int64 `json:"requested_at,omitempty"` |
diff --git a/internal/moves/offlinerun/doors.go b/internal/moves/offlinerun/doors.go| new file mode 100644 |
| index 000000000..56f7c44db |
| --- /dev/null |
| +++ b/internal/moves/offlinerun/doors.go |
| @@ -0,0 +1,211 @@ |
| +package offlinerun |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| +) |
| + |
| +// The console's offline doors over HTTP, as `carlos move offline run` |
| +// reaches them, and the one classifier of what a status read's answer |
| +// means. Nothing in this file waits, retries or prints: a call here is |
| +// exactly one request (TestDoorsAreSingleShot). Every wait, every retry |
| +// and every Ctrl-C belongs to the Runner's loop, so a request sent again |
| +// has been decided again from a fresh view and has passed the dispatch |
| +// gate again. |
| + |
| +// Exchange is one HTTP exchange with the console. |
| +type Exchange struct { |
| + // Status is the answer's status, 0 when none arrived (a network |
| + // error, or the context ended). |
| + Status int |
| + // Body is the answer's body, when all of it was read. |
| + Body []byte |
| + // Cut: an answer arrived and its body was cut short on the way. |
| + Cut bool |
| +} |
| + |
| +// Transport makes one request to the offline door (tail "") or a door |
| +// under it ("/seal", "/nudge") and reads its answer. An implementation |
| +// sends exactly one request a call: it never follows a redirect, never |
| +// sends again, never waits. body is nil for a read. |
| +type Transport interface { |
| + Do(ctx context.Context, method, tail string, body any) Exchange |
| +} |
| + |
| +// StatusClass is what a status read's answer means for the run. |
| +type StatusClass int |
| + |
| +const ( |
| + // StatusAnswered: a 200 whose body is a status view. |
| + StatusAnswered StatusClass = iota |
| + // StatusPasses: asking again may answer. |
| + StatusPasses |
| + // StatusLimited: the rate limit answered (a 429). It passes; the run |
| + // asks again after its back-off. |
| + StatusLimited |
| + // StatusRefused: asking again will not answer. |
| + StatusRefused |
| +) |
| + |
| +// ClassifyStatus is the one classifier of a status read's answer, for the |
| +// first read and every later one. Invariant (Astra branch review round 2, |
| +// R2-3; round 3, P2 2): a status failure that won't pass stops run, and |
| +// this function alone says which those are. |
| +// |
| +// What may pass: no answer at all, a 5xx, the rate limit's 429, and a 200 |
| +// whose body was cut short on the way. A 200 whose whole body decodes as a |
| +// status view is the answer. Everything else is refused for good: every |
| +// redirect (a console that moved, a proxy sending to /login), every other |
| +// 4xx whether or not its body read, any other 2xx, and a 200 that is not a |
| +// status view (not JSON, or JSON whose fields are not a view's). |
| +// |
| +// also, when not nil, is a second target the same body must decode into: |
| +// the caller's fuller reading of the view (the CLI's lines need more of it |
| +// than Decide does). A body that does not is not a status view either. |
| +func ClassifyStatus(x Exchange, also any) (StatusClass, View) { |
| + switch { |
| + case x.Status == 0: |
| + return StatusPasses, View{} |
| + case x.Status == 429: |
| + return StatusLimited, View{} |
| + case x.Status >= 500 && x.Status <= 599: |
| + return StatusPasses, View{} |
| + case x.Status == 200 && x.Cut: |
| + return StatusPasses, View{} |
| + case x.Status == 200: |
| + var v View |
| + if json.Unmarshal(x.Body, &v) != nil { |
| + break |
| + } |
| + if also != nil && json.Unmarshal(x.Body, also) != nil { |
| + break |
| + } |
| + return StatusAnswered, v |
| + } |
| + return StatusRefused, View{} |
| +} |
| + |
| +// HTTPDoors are Doors over a Transport: the production doors of `carlos |
| +// move offline run`, and the ones the two-box simulation drives. |
| +type HTTPDoors struct { |
| + Wire Transport |
| + // Region is the region a stage or start names (--to), until a view of |
| + // the bound move names its own. |
| + Region string |
| + // Interrupts are the run's Ctrl-Cs: one ends a status read on the |
| + // wire (the Runner then takes it). A POST is never sent on a context |
| + // a Ctrl-C ends, so one never makes a write's outcome unknown. |
| + Interrupts *Interrupts |
| + // Also, when set, makes the second target each status body must |
| + // decode into (ClassifyStatus's also); Viewed is handed each view that |
| + // answered, with it. |
| + Also func() any |
| + Viewed func(v View, also any) |
| + |
| + last View // the latest view that answered |
| +} |
| + |
| +// Status is one status read: one GET, classified by ClassifyStatus. The |
| +// error says which class did not answer: ErrStatusRefused, ErrStatusLimited |
| +// or (anything else that may pass) ErrNoStatus; ErrInterrupted when a |
| +// Ctrl-C ended the read before any answer. |
| +func (d *HTTPDoors) Status(ctx context.Context) (View, error) { |
| + rctx, release := d.Interrupts.Bind(ctx) |
| + x := d.Wire.Do(rctx, "GET", "", nil) |
| + interrupted := x.Status == 0 && rctx.Err() != nil && ctx.Err() == nil |
| + release() |
| + if interrupted { |
| + return View{}, fmt.Errorf("%w", ErrInterrupted) |
| + } |
| + var also any |
| + if d.Also != nil { |
| + also = d.Also() |
| + } |
| + class, v := ClassifyStatus(x, also) |
| + switch class { |
| + case StatusRefused: |
| + return View{}, fmt.Errorf("%w: %d", ErrStatusRefused, x.Status) |
| + case StatusLimited: |
| + return View{}, fmt.Errorf("%w: %d", ErrStatusLimited, x.Status) |
| + case StatusPasses: |
| + return View{}, fmt.Errorf("%w: %d", ErrNoStatus, x.Status) |
| + } |
| + d.last = v |
| + if d.Viewed != nil { |
| + d.Viewed(v, also) |
| + } |
| + return v, nil |
| +} |
| + |
| +// body is a door's request: the move's id once bound, and the region for |
| +// stage and start (the bound move's own, once a view of it named one). The |
| +// first stage, sent before anything is bound, is create-only ("new"): the |
| +// door refuses it if the host already has a move, rather than restaging |
| +// someone else's (Astra branch round 1, finding 1). |
| +func (d *HTTPDoors) body(verb, id string) map[string]any { |
| + b := map[string]any{} |
| + if id != "" { |
| + b["id"] = id |
| + } |
| + if verb == VerbStage && id == "" { |
| + b["new"] = true |
| + } |
| + if verb == VerbStage || verb == VerbStart { |
| + region := d.Region |
| + if v := d.last; id != "" && v.ID == id && v.To != "" { |
| + region = v.To |
| + } |
| + b["region"] = region |
| + } |
| + return b |
| +} |
| + |
| +// Post is one POST of a door. It is sent once, whatever answers: a rate |
| +// limit's 429 comes back as Answer.Limited, and the Runner's loop, not |
| +// this, decides what is sent next (Astra branch review round 3, P1). |
| +func (d *HTTPDoors) Post(ctx context.Context, verb, id string) Answer { |
| + tail := "/" + verb |
| + if verb == VerbStart { |
| + tail = "" // start is the offline door itself |
| + } |
| + b := d.body(verb, id) |
| + return answerOf(d.Wire.Do(ctx, "POST", tail, b), b["new"] == true) |
| +} |
| + |
| +// Nudge is one POST of the nudge door, sent once as Post is. |
| +func (d *HTTPDoors) Nudge(ctx context.Context, id string) Answer { |
| + return answerOf(d.Wire.Do(ctx, "POST", "/nudge", d.body("nudge", id)), false) |
| +} |
| + |
| +// answerOf reads a POST's answer. The rate limit's 429 comes before any |
| +// door, so nothing was written (Limited). A 2xx whose body read is |
| +// accepted; a 4xx is a refusal (the doors write nothing before they answer |
| +// one); anything else (no answer, a redirect, a body cut short or not a |
| +// view, a 5xx) says nothing about the write, and the next status read |
| +// decides. A create-only stage's answer names the move only when it says |
| +// this request created it ("new"), so the run is never bound to a move it |
| +// did not make. |
| +func answerOf(x Exchange, createOnly bool) Answer { |
| + switch { |
| + case x.Status == 429: |
| + return Answer{Limited: true} |
| + case x.Status == 0 || x.Cut: |
| + return Answer{} |
| + case x.Status >= 200 && x.Status <= 299: |
| + var v struct { |
| + View |
| + New bool `json:"new"` |
| + } |
| + if json.Unmarshal(x.Body, &v) != nil { |
| + return Answer{} |
| + } |
| + if createOnly && !v.New { |
| + return Answer{Accepted: true} |
| + } |
| + return Answer{Accepted: true, ID: v.ID} |
| + case x.Status >= 400 && x.Status <= 499: |
| + return Answer{Refused: true} |
| + } |
| + return Answer{} |
| +} |
diff --git a/internal/moves/offlinerun/gate_test.go b/internal/moves/offlinerun/gate_test.go| index 36b1936b2..42ba101e3 100644 |
| --- a/internal/moves/offlinerun/gate_test.go |
| +++ b/internal/moves/offlinerun/gate_test.go |
| @@ -125,9 +125,9 @@ func TestGateAfterOutput(t *testing.T) { |
| } |
| } |
| -// TestGateDuringBackoff: a Ctrl-C during a POST's rate-limit back-off (the |
| -// Doors give the POST up: NotSent) is taken before anything else is |
| -// posted: abort, never the open again. |
| +// TestGateDuringBackoff: a Ctrl-C after the rate limit answered a POST |
| +// (Limited: the Doors sent it once and no door took it) is taken before |
| +// anything else is posted: abort, never the open again. |
| func TestGateDuringBackoff(t *testing.T) { |
| d := &fakeDoors{views: landedToAbort()} |
| r, _ := gateRun(d) |
| @@ -136,7 +136,7 @@ func TestGateDuringBackoff(t *testing.T) { |
| if verb == VerbOpen && first { |
| first = false |
| r.Interrupts.Add() |
| - return Answer{NotSent: true} |
| + return Answer{Limited: true} |
| } |
| return Answer{Accepted: true} |
| } |
| @@ -169,7 +169,7 @@ func TestGateResumedFirstRead(t *testing.T) { |
| t.Fatalf("interrupts %v", w.interrupts) |
| } |
| // A first read that fails for any other reason still ends the run. |
| - d = &fakeDoors{views: []View{none(nil)}, errs: map[int]bool{0: true}} |
| + d = &fakeDoors{views: []View{none(nil)}, errs: map[int]bool{0: true, 1: true, 2: true, 3: true, 4: true}} |
| r, _ = gateRun(d) |
| if _, _, err := r.Run(context.Background(), NewMemory(tID)); err == nil || errors.Is(err, ErrInterrupted) { |
| t.Fatalf("err %v", err) |
diff --git a/internal/moves/offlinerun/run.go b/internal/moves/offlinerun/run.go| index 6d26bed4b..7ad61c143 100644 |
| --- a/internal/moves/offlinerun/run.go |
| +++ b/internal/moves/offlinerun/run.go |
| @@ -14,6 +14,14 @@ import ( |
| // DefaultPoll is the gap between ticks. |
| const DefaultPoll = 2 * time.Second |
| +// DefaultBackoff is the gap after the rate limit answered (a 429), on a |
| +// status read or a POST. |
| +const DefaultBackoff = 5 * DefaultPoll |
| + |
| +// DefaultFirstReads is how many status reads in a row may fail, before any |
| +// view was read, until the run gives up (the rate limit's do not count). |
| +const DefaultFirstReads = 5 |
| + |
| // ReasonStoppedWatching ends a run the operator stopped with Ctrl-C (the |
| // second before open, the first after it). The move itself goes on. |
| const ReasonStoppedWatching = "stopped-watching" |
| @@ -24,6 +32,15 @@ const ReasonStoppedWatching = "stopped-watching" |
| // and ReasonStatusRefused, since nothing can be decided without a view. |
| var ErrStatusRefused = errors.New("the console refused the status read") |
| +// ErrNoStatus is a status read that got no view and may yet: Run asks |
| +// again after the poll. ErrStatusLimited is one the rate limit answered: |
| +// Run asks again after the back-off. Doors wrap them; any other error a |
| +// Doors' Status returns is taken as ErrNoStatus. |
| +var ( |
| + ErrNoStatus = errors.New("no status view") |
| + ErrStatusLimited = errors.New("the rate limit answered the status read") |
| +) |
| + |
| // ErrInterrupted is a status read a Ctrl-C ended (the Doors read on a |
| // context from Interrupts.Bind). Doors wrap it; Run reads again. |
| var ErrInterrupted = errors.New("a Ctrl-C ended the status read") |
| @@ -45,10 +62,11 @@ type Answer struct { |
| // not have happened, and the next status read says which. Neither case |
| // is ever sent again blindly. |
| Refused bool |
| - // NotSent: no door took the POST. A rate limit answered it (before |
| - // any handler) and the run was interrupted during the back-off, so the |
| - // Doors gave up; nothing was written. Step undoes its count. |
| - NotSent bool |
| + // Limited: the rate limit answered the POST (a 429, before any door), |
| + // so nothing was written and no door took it. The Doors never send it |
| + // again themselves: the gate forgets it was decided, and after the |
| + // back-off the loop reads status and decides afresh. |
| + Limited bool |
| // Sentence is the console's own sentence for a refusal, when the |
| // Doors can carry it; "" otherwise. |
| Sentence string |
| @@ -192,7 +210,8 @@ func (i *Interrupts) take() bool { |
| } |
| // Watcher sees the run: each view read, each action before it is performed |
| -// (or withdrawn) and its result after, and each Ctrl-C. |
| +// (or withdrawn) and its result after, each Ctrl-C, and each status read |
| +// that got no view. |
| type Watcher interface { |
| Saw(v View) |
| // Acting says an action before the gate dispatches it; Withdrawn that |
| @@ -202,11 +221,20 @@ type Watcher interface { |
| Withdrawn(a Action) |
| Acted(a Action, r Result, m Memory) |
| Interrupted(i Interrupt, m Memory) |
| + // Unread: a status read got no view and may yet. limited says the |
| + // rate limit answered it; down is how long reads have gone without a |
| + // view since the last one that had one (0 before the first view). |
| + Unread(limited bool, down time.Duration) |
| } |
| // Runner runs one move. Clock is the terminal's monotonic clock; After is |
| -// the poll timer (time.After); both are seams for tests. Interrupts are the |
| -// operator's Ctrl-Cs (nil for none). |
| +// the loop's timer (time.After); both are seams for tests. Interrupts are |
| +// the operator's Ctrl-Cs (nil for none). |
| +// |
| +// The Runner's loop is the only thing in a run that waits, and its gate |
| +// the only thing that posts: the Doors make one request a call and never |
| +// wait or send again (doors.go). So nothing is sent that was not decided |
| +// from the latest view and passed the gate. |
| type Runner struct { |
| Doors Doors |
| Probe func(ctx context.Context) int |
| @@ -214,6 +242,8 @@ type Runner struct { |
| Clock func() time.Duration |
| After func(d time.Duration) <-chan time.Time |
| Poll time.Duration |
| + Backoff time.Duration // after a rate limit's answer; 5 polls when 0 |
| + FirstReads int // DefaultFirstReads when 0 |
| Watch Watcher |
| Interrupts *Interrupts |
| @@ -222,27 +252,29 @@ type Runner struct { |
| // aborts. |
| openAccepted, openUncertain bool |
| stops int |
| + // owed: the first Ctrl-C before open was taken with no view in hand. |
| + // What it means waits for the next view (judge). |
| + owed bool |
| + // limited: the rate limit answered the POST just dispatched; the next |
| + // wait is the back-off. |
| + limited bool |
| } |
| // Step reads status once, decides, and performs at most one action through |
| // the dispatch gate. done is set when the run ends; err when the status |
| -// could not be read (nothing was decided or sent). A Ctrl-C that arrived by |
| -// the end of the read is taken before anything is said or decided. |
| +// could not be read (nothing was decided or sent). A Ctrl-C that arrived |
| +// by then is taken; one that needs a view to be understood waits for it. |
| func (r *Runner) Step(ctx context.Context, m Memory) (Memory, *Done, error) { |
| v, err := r.Doors.Status(ctx) |
| - var read *View |
| - if err == nil { |
| - read = &v |
| - } |
| - var stop *Done |
| - if m, stop = r.takeInterrupts(m, read); stop != nil { |
| - return m, stop, nil |
| - } |
| if err != nil { |
| + m, stop := r.takeInterrupts(m, nil) |
| + if stop != nil { |
| + return m, stop, nil |
| + } |
| return m, nil, err |
| } |
| r.Watch.Saw(v) |
| - m, stop = r.dispatch(ctx, v, m) |
| + m, stop := r.dispatch(ctx, v, m) |
| return m, stop, nil |
| } |
| @@ -250,9 +282,9 @@ func (r *Runner) Step(ctx context.Context, m Memory) (Memory, *Done, error) { |
| // reaches the doors (TestGateIsTheOnlyWayToPost holds that nothing else in |
| // this package calls Doors.Post or Doors.Nudge). |
| // |
| -// Invariant (Astra branch review round 2, R2-1 and R2-2): a pending |
| -// pre-open interrupt prevents forward mutation, and the first pre-open |
| -// interrupt on a bound move follows abort through completion. |
| +// Invariant A (Astra branch review round 2, R2-1 and R2-2; round 3, P1): a |
| +// pending pre-open interrupt prevents forward mutation, and the first |
| +// pre-open interrupt on a bound move follows abort through completion. |
| // |
| // The gate holds it in one place. It takes every pending Ctrl-C, then |
| // decides; it says what the action will do (Watch.Acting: every piece of |
| @@ -263,6 +295,12 @@ func (r *Runner) Step(ctx context.Context, m Memory) (Memory, *Done, error) { |
| // so the same view now decides abort; a second stops watching), and the |
| // view is decided anew. So no forward POST leaves after a Ctrl-C was |
| // pending, and an abort once decided is posted until the move reverts. |
| +// |
| +// A dispatch is one request. The Doors do not send it again: when the rate |
| +// limit answers (Answer.Limited) the gate forgets the action was decided |
| +// (the memory stays as it was before Decide), and the loop waits, reads |
| +// status and comes back here, where a Ctrl-C that arrived meanwhile is |
| +// taken first like any other. |
| func (r *Runner) dispatch(ctx context.Context, v View, m Memory) (Memory, *Done) { |
| for { |
| var stop *Done |
| @@ -281,13 +319,15 @@ func (r *Runner) dispatch(ctx context.Context, v View, m Memory) (Memory, *Done) |
| r.Watch.Withdrawn(a) |
| continue |
| } |
| - m = next |
| switch a := a.(type) { |
| case Post: |
| - ans := r.Doors.Post(ctx, a.Verb, m.Bound()) |
| - if ans.NotSent { |
| - m = m.notSent(a.Verb) |
| + ans := r.Doors.Post(ctx, a.Verb, next.Bound()) |
| + if ans.Limited { |
| + r.limited = true |
| + r.Watch.Acted(a, Result{Answer: ans}, m) |
| + return m, nil |
| } |
| + m = next |
| if !ans.Accepted && ans.Refused { |
| m = m.Refused(ans.Sentence) |
| } |
| @@ -299,14 +339,21 @@ func (r *Runner) dispatch(ctx context.Context, v View, m Memory) (Memory, *Done) |
| } |
| if a.Verb == VerbOpen && ans.Accepted { |
| r.openAccepted = true |
| - } else if a.Verb == VerbOpen && !ans.Refused && !ans.NotSent { |
| + } else if a.Verb == VerbOpen && !ans.Refused { |
| r.openUncertain = true |
| } |
| r.Watch.Acted(a, Result{Answer: ans}, m) |
| case Nudge: |
| - ans := r.Doors.Nudge(ctx, m.Bound()) |
| + ans := r.Doors.Nudge(ctx, next.Bound()) |
| + if ans.Limited { |
| + r.limited = true |
| + r.Watch.Acted(a, Result{Answer: ans}, m) |
| + return m, nil |
| + } |
| + m = next |
| r.Watch.Acted(a, Result{Answer: ans}, m) |
| case Probe: |
| + m = next |
| code := r.Probe(ctx) |
| m = m.Probed(code >= 200 && code <= 299) |
| r.Watch.Acted(a, Result{Status: code}, m) |
| @@ -315,32 +362,64 @@ func (r *Runner) dispatch(ctx context.Context, v View, m Memory) (Memory, *Done) |
| } |
| } |
| -// Run steps until the run ends, sleeping Poll between ticks. A status read |
| -// that fails before any view was read ends it with that error, unless a |
| -// Ctrl-C ended it (ErrInterrupted): Step has taken that Ctrl-C, and the |
| -// read is tried again, so a --resume run whose first read was cut short |
| -// still follows the abort it promised (R2-2). Later failures are ridden |
| -// out (the move is under way, and only a view decides). A Ctrl-C |
| -// (Interrupts) is taken as soon as it arrives between ticks, and otherwise |
| -// by Step. |
| +// Run steps until the run ends. It is the run's only loop and makes its |
| +// only waits (TestLoopOwnsEveryWait): Poll between ticks, Backoff after |
| +// the rate limit answered a status read or a POST. |
| +// |
| +// A status read that got no view is asked again. Before any view was read, |
| +// FirstReads failures in a row (the rate limit's aside) end the run with |
| +// the last one's error, and so does a read refused for good |
| +// (ErrStatusRefused); nothing was sent. Once a view was read, failures |
| +// that may pass are ridden out (the move is under way, and only a view |
| +// decides), and a refusal for good ends the run with ExitError. A read a |
| +// Ctrl-C ended (ErrInterrupted) is made again at once: Step has taken that |
| +// Ctrl-C, so a --resume run whose first read was cut short still follows |
| +// the abort (R2-2). A Ctrl-C between ticks ends the wait. |
| func (r *Runner) Run(ctx context.Context, m Memory) (Done, Memory, error) { |
| - read := false |
| + read, failures := false, 0 |
| + down := time.Duration(-1) // when later reads began to fail; -1 while they answer |
| for { |
| + taken := r.stops |
| next, done, err := r.Step(ctx, m) |
| m = next |
| + if done != nil { |
| + return *done, m, nil |
| + } |
| + wait := r.Poll |
| + limited := r.limited || errors.Is(err, ErrStatusLimited) |
| + r.limited = false |
| switch { |
| - case errors.Is(err, ErrInterrupted): |
| - // Read again on a fresh context; the Ctrl-C was taken. |
| - case err != nil && !read: |
| - return Done{}, m, err |
| - case errors.Is(err, ErrStatusRefused): |
| - // Later failures are ridden out; this one never ends. |
| - return Done{Exit: ExitError, Reason: ReasonStatusRefused}, m, nil |
| case err == nil: |
| - read = true |
| + read, failures, down = true, 0, -1 |
| + case errors.Is(err, ErrInterrupted) && r.stops > taken: |
| + // Step took the Ctrl-C that ended the read: read again now. |
| + // (With none taken it is a failed read like any other, and |
| + // waits: the loop never goes round without a wait or a |
| + // Ctrl-C taken.) |
| + continue |
| + case errors.Is(err, ErrStatusRefused) && read: |
| + return Done{Exit: ExitError, Reason: ReasonStatusRefused}, m, nil |
| + case errors.Is(err, ErrStatusRefused): |
| + return Done{}, m, err |
| + case ctx.Err() != nil: |
| + return Done{}, m, ctx.Err() |
| + default: |
| + if !read && !limited { |
| + if failures++; failures >= r.firstReads() { |
| + return Done{}, m, err |
| + } |
| + } |
| + var gone time.Duration |
| + if read { |
| + if down < 0 { |
| + down = r.Clock() |
| + } |
| + gone = r.Clock() - down |
| + } |
| + r.Watch.Unread(limited, gone) |
| } |
| - if done != nil { |
| - return *done, m, nil |
| + if limited { |
| + wait = r.backoff() |
| } |
| select { |
| case <-ctx.Done(): |
| @@ -350,14 +429,28 @@ func (r *Runner) Run(ctx context.Context, m Memory) (Done, Memory, error) { |
| if m, stop = r.takeInterrupts(m, nil); stop != nil { |
| return *stop, m, nil |
| } |
| - case <-r.After(r.Poll): |
| + case <-r.After(wait): |
| } |
| } |
| } |
| +func (r *Runner) backoff() time.Duration { |
| + if r.Backoff > 0 { |
| + return r.Backoff |
| + } |
| + return 5 * r.Poll |
| +} |
| + |
| +func (r *Runner) firstReads() int { |
| + if r.FirstReads > 0 { |
| + return r.FirstReads |
| + } |
| + return DefaultFirstReads |
| +} |
| + |
| // takeInterrupts takes every pending Ctrl-C, in order, until one ends the |
| -// run. v is the view just read, if any: it says whether the move is open |
| -// before Decide has folded it in. |
| +// run. v is the view just read, nil when there is none: a first Ctrl-C |
| +// before open is judged only with one (judge), so with none it stays owed. |
| func (r *Runner) takeInterrupts(m Memory, v *View) (Memory, *Done) { |
| for r.Interrupts.take() { |
| var stop *Done |
| @@ -365,14 +458,19 @@ func (r *Runner) takeInterrupts(m Memory, v *View) (Memory, *Done) { |
| return m, stop |
| } |
| } |
| + if r.owed && v != nil { |
| + return r.judge(m, *v) |
| + } |
| return m, nil |
| } |
| -// interrupt is one Ctrl-C (plan §7, decision 3). |
| +// interrupt is one Ctrl-C (plan §7, decision 3), as far as the run's own |
| +// memory says what it means. The first one before open on a bound move is |
| +// only noted (owed): what it does depends on where the move is now, which |
| +// only a view says. |
| func (r *Runner) interrupt(m Memory, v *View) (Memory, *Done) { |
| r.stops++ |
| stop := &Done{Exit: ExitStopped, Reason: ReasonStoppedWatching} |
| - opened := m.Opened() || (v != nil && v.ID != "" && v.ID == m.Bound() && (v.State == StateOpen || v.State == StateFinishing)) |
| switch { |
| case m.Bound() == "" && !m.Staged(): |
| r.Watch.Interrupted(InterruptNothingSent, m) |
| @@ -386,21 +484,52 @@ func (r *Runner) interrupt(m Memory, v *View) (Memory, *Done) { |
| // cannot tell whose. It stops watching (status says). |
| r.Watch.Interrupted(InterruptStop, m) |
| return m, stop |
| - case opened || r.openAccepted: |
| + case m.Opened() || r.openAccepted || (v != nil && opened(m, *v)): |
| r.Watch.Interrupted(InterruptAfterOpen, m) |
| return m, stop |
| case r.openUncertain: |
| r.Watch.Interrupted(InterruptOpenUncertain, m) |
| return m, stop |
| case r.stops == 1: |
| - m = m.Abort(ReasonInterrupted) |
| - r.Watch.Interrupted(InterruptAbort, m) |
| + r.owed = true |
| return m, nil |
| } |
| r.Watch.Interrupted(InterruptStop, m) |
| return m, stop |
| } |
| +// opened says v shows the run's own move open (or finishing). |
| +func opened(m Memory, v View) bool { |
| + return v.ID != "" && v.ID == m.Bound() && (v.State == StateOpen || v.State == StateFinishing) |
| +} |
| + |
| +// judge is the one place the first Ctrl-C before open is given its |
| +// meaning, and it takes the view that meaning is about: it cannot be |
| +// called without one. |
| +// |
| +// Invariant C (Astra branch review round 3, P2 3): what the run says it |
| +// will do about a Ctrl-C describes the bound move and an action still open |
| +// to it. InterruptAbort (the CLI's "Moving <host> back") is said here and |
| +// nowhere else (TestAbortIsPromisedOnlyWithAView), only when v is the |
| +// run's own move in a state abort still applies to (or already reverting), |
| +// and the sticky abort is set by the same lines, so the gate decides the |
| +// abort from this same view. A move someone opened meanwhile is not |
| +// undone: the run says so and stops watching. A move that is gone or is |
| +// another's gets no promise: Decide ends the run in its own words. |
| +func (r *Runner) judge(m Memory, v View) (Memory, *Done) { |
| + r.owed = false |
| + mine := v.ID != "" && v.ID == m.Bound() |
| + switch { |
| + case opened(m, v): |
| + r.Watch.Interrupted(InterruptAfterOpen, m) |
| + return m, &Done{Exit: ExitStopped, Reason: ReasonStoppedWatching} |
| + case mine && (preOpen(v.State) || v.State == StateReverting): |
| + m = m.Abort(ReasonInterrupted) |
| + r.Watch.Interrupted(InterruptAbort, m) |
| + } |
| + return m, nil |
| +} |
| + |
| // Opened says the run read the move open (or finishing): nothing aborts it. |
| func (m Memory) Opened() bool { return m.opened } |
| @@ -408,14 +537,5 @@ func (m Memory) Opened() bool { return m.opened } |
| // may have). |
| func (m Memory) Staged() bool { return m.stagePosts > 0 } |
| -// notSent undoes the count of a POST no door took (Answer.NotSent). |
| -func (m Memory) notSent(verb string) Memory { |
| - if verb == VerbStage && m.stagePosts > 0 { |
| - m.stagePosts-- |
| - m.stageSent = false |
| - } |
| - return m |
| -} |
| - |
| // QuietFor is how long the view has gone without a change, at now. |
| func (m Memory) QuietFor(now time.Duration) time.Duration { return now - m.lastChange } |
diff --git a/internal/moves/offlinerun/run_test.go b/internal/moves/offlinerun/run_test.go| index 7e333590a..f8b752bf9 100644 |
| --- a/internal/moves/offlinerun/run_test.go |
| +++ b/internal/moves/offlinerun/run_test.go |
| @@ -54,7 +54,10 @@ func (f *fakeDoors) Nudge(_ context.Context, id string) Answer { |
| } |
| // nopWatch records the interrupts it saw. |
| -type nopWatch struct{ interrupts []Interrupt } |
| +type nopWatch struct { |
| + interrupts []Interrupt |
| + unread []string // each Unread as "<limited> <down>" |
| +} |
| func (*nopWatch) Saw(View) {} |
| func (*nopWatch) Acting(Action, Memory) {} |
| @@ -63,11 +66,15 @@ func (*nopWatch) Acted(Action, Result, Memory) {} |
| func (w *nopWatch) Interrupted(i Interrupt, _ Memory) { |
| w.interrupts = append(w.interrupts, i) |
| } |
| +func (w *nopWatch) Unread(limited bool, down time.Duration) { |
| + w.unread = append(w.unread, fmt.Sprintf("%v %s", limited, down)) |
| +} |
| // testRunner is a Runner on fake time: each poll advances the clock by Poll |
| // and fires at once. |
| func testRunner(d Doors, probe func() int) (*Runner, *nopWatch) { |
| var now time.Duration |
| + waits := 0 |
| w := &nopWatch{} |
| r := &Runner{ |
| Doors: d, |
| @@ -75,6 +82,11 @@ func testRunner(d Doors, probe func() int) (*Runner, *nopWatch) { |
| Policy: DefaultPolicy(), |
| Clock: func() time.Duration { return now }, |
| After: func(d time.Duration) <-chan time.Time { |
| + // Fake time never runs out: a run that does not end fails |
| + // here instead of spinning. |
| + if waits++; waits > 20000 { |
| + panic("the run made 20000 waits and did not end") |
| + } |
| now += d |
| c := make(chan time.Time, 1) |
| c <- time.Time{} |
| @@ -127,15 +139,21 @@ func TestRunRefusedFirstStageExits5(t *testing.T) { |
| } |
| func TestRunStatusErrors(t *testing.T) { |
| - // Before any view: the error ends the run, nothing sent. |
| - d := &fakeDoors{views: []View{none(nil)}, errs: map[int]bool{0: true}} |
| + // Before any view: DefaultFirstReads failures in a row end the run |
| + // with the error, nothing sent; fewer are ridden out. |
| + d := &fakeDoors{views: []View{none(nil)}, errs: map[int]bool{0: true, 1: true, 2: true, 3: true, 4: true}} |
| r, _ := testRunner(d, func() int { return 200 }) |
| if _, _, err := r.Run(context.Background(), NewMemory("")); err == nil { |
| - t.Fatal("a first status read that failed did not end the run") |
| + t.Fatal("first status reads that failed did not end the run") |
| } |
| - if len(d.log) != 1 { |
| + if len(d.log) != DefaultFirstReads { |
| t.Fatalf("calls %q", d.log) |
| } |
| + d = &fakeDoors{views: []View{none(&Outcome{ID: tID, Outcome: OutcomeDone})}, errs: map[int]bool{0: true, 1: true, 2: true, 3: true}} |
| + r, _ = testRunner(d, func() int { return 200 }) |
| + if done, _, err := r.Run(context.Background(), NewMemory(tID)); err != nil || done.Exit != ExitDone { |
| + t.Fatalf("done %#v, err %v", done, err) |
| + } |
| // After one: ridden out. |
| d = &fakeDoors{ |
| views: []View{tv(StateSealing), tv(StateSealing), tv(StateSealing), none(&Outcome{ID: tID, Outcome: OutcomeDone})}, |
| @@ -316,16 +334,16 @@ func TestRunCtrlCBeforeAnythingSent(t *testing.T) { |
| } |
| } |
| -// TestRunNotSentPostIsNotCounted: a POST the doors gave up on before any |
| -// door took it (interrupted in a rate limit's back-off) is not a stage the |
| -// run made: a Ctrl-C then ends a run that has sent nothing. |
| -func TestRunNotSentPostIsNotCounted(t *testing.T) { |
| +// TestRunLimitedPostIsNotCounted: a POST the rate limit answered (no door |
| +// took it) is not a stage the run made: a Ctrl-C then ends a run that has |
| +// sent nothing. |
| +func TestRunLimitedPostIsNotCounted(t *testing.T) { |
| d := &fakeDoors{views: []View{none(nil)}} |
| r, w := testRunner(d, func() int { return 200 }) |
| r.Interrupts = NewInterrupts() |
| d.answer = func(string) Answer { |
| r.Interrupts.Add() |
| - return Answer{NotSent: true} |
| + return Answer{Limited: true} |
| } |
| done, m, err := r.Run(context.Background(), NewMemory("")) |
| if err != nil || done != (Done{Exit: ExitStopped, Reason: ReasonNothingSent}) || m.Staged() { |
diff --git a/move_offline_run.go b/move_offline_run.go| index 90fd76ad2..bb3e7ada5 100644 |
| --- a/move_offline_run.go |
| +++ b/move_offline_run.go |
| @@ -20,7 +20,12 @@ import ( |
| // `carlos move offline run` (plan 2026-11-15-offline-move-run, Task 5): |
| // one offline move carried through from the operator's terminal. It is a |
| // loop over the same doors the hand verbs post (offlinerun.Runner): read |
| -// status, decide, do at most one thing, sleep 2 s. Before open any failure, |
| +// status, decide, do at most one thing, sleep 2 s. That loop is the only |
| +// one: it makes every wait and takes every Ctrl-C, its gate makes every |
| +// POST, and each request the run makes is one roundTrip (runWire) that the |
| +// loop decided from a fresh view. Nothing here sends a request again by |
| +// itself, not even after the rate limit's 429: the loop waits 10 s, reads |
| +// status and decides again. Before open any failure, |
| // limit or first Ctrl-C aborts and follows the move back through finish; |
| // after open nothing is undone. The only state is the console's record and |
| // this process's memory, so a dead terminal is picked up with status and |
| @@ -157,12 +162,21 @@ func (m *mover) offlineRun(ctx context.Context, a moveArgs, d moveDeps) int { |
| ints := offlinerun.NewInterrupts() |
| w := &offlineRun{m: m, said: map[string]bool{}} |
| - doors := &runDoors{w: w, region: a.to, code: -1, ints: ints, downSince: -1} |
| + wire := &runWire{m: m} |
| start := now() |
| - watch := &runWatcher{w: w, doors: doors, now: now, policy: policy, |
| + watch := &runWatcher{w: w, wire: wire, now: now, policy: policy, |
| resume: a.resume, bound: a.resume, url: "https://" + m.host + path} |
| watch.clock = func() time.Duration { return now().Sub(start) } |
| - doors.clock = watch.clock |
| + doors := &offlinerun.HTTPDoors{ |
| + Wire: wire, |
| + Region: a.to, |
| + Interrupts: ints, |
| + // The run's lines read more of a status view than Decide does: |
| + // the classifier decodes both, and a body that is not both is |
| + // not a status view. |
| + Also: func() any { return &offlineView{} }, |
| + Viewed: func(_ offlinerun.View, also any) { watch.read(*also.(*offlineView)) }, |
| + } |
| r := &offlinerun.Runner{ |
| Doors: doors, |
| Probe: func(ctx context.Context) int { return probe(ctx, watch.url) }, |
| @@ -170,6 +184,8 @@ func (m *mover) offlineRun(ctx context.Context, a moveArgs, d moveDeps) int { |
| Clock: watch.clock, |
| After: after, |
| Poll: offlinerun.DefaultPoll, |
| + Backoff: offlinerun.DefaultBackoff, |
| + FirstReads: moveTransient, |
| Watch: watch, |
| Interrupts: ints, |
| } |
| @@ -177,11 +193,7 @@ func (m *mover) offlineRun(ctx context.Context, a moveArgs, d moveDeps) int { |
| defer stop() |
| done, _, err := r.Run(ctx, offlinerun.NewMemory(a.resume)) |
| if err != nil { |
| - if doors.code >= 0 { |
| - return doors.code // the first status read said why |
| - } |
| - moveSay(m.out, moveStopped) |
| - return moveExitError |
| + return watch.unread(err) |
| } |
| return watch.end(done) |
| } |
| @@ -227,312 +239,60 @@ func probeOnce(ctx context.Context, url string) int { |
| return res.StatusCode |
| } |
| -// errRunStatus is a status read that got no view. |
| -var errRunStatus = errors.New("no status view") |
| +// runWire is the run's offlinerun.Transport: the mover's door, one |
| +// roundTrip a call. It never sends a request again, never waits and never |
| +// prints (TestRunDoorsWireIsSingleShot): the doors over it (offlinerun.HTTPDoors) |
| +// and the Runner's loop own what is sent and when. It keeps the latest |
| +// reply of each kind for the run's lines, which say the console's own |
| +// sentences (server text, said by saySpoken). |
| +type runWire struct { |
| + m *mover |
| + get moveReply // the latest status read's reply |
| + post moveReply // the latest POST's |
| +} |
| -// runDoors are the offline doors over HTTP, for offlinerun.Runner. They |
| -// keep the full view last read (the run's lines need more of it than |
| -// Decide does) and the last POST's reply (its refusal is server text, |
| -// said by saySpoken; Answer.Sentence stays empty). |
| -type runDoors struct { |
| - w *offlineRun |
| - ints *offlinerun.Interrupts // the run's Ctrl-Cs: they end a wait or a status read |
| - region string // the region stage and start are sent: --to, then the bound move's |
| - seen bool // a status view was read |
| - code int // the exit code the first status read ended with, -1 for none |
| - last offlineReply // the latest status view |
| - reply moveReply // the latest POST's reply |
| - |
| - // A later status read's trouble (finding 6 of the branch review): gone |
| - // is the reply the console refused it with for good; downSince is when |
| - // the reads that may pass began failing (run's clock, -1 while they |
| - // answer), downSaid that the notice was said for this outage. |
| - clock func() time.Duration |
| - gone moveReply |
| - downSince time.Duration |
| - downSaid bool |
| +func (w *runWire) Do(ctx context.Context, method, tail string, body any) offlinerun.Exchange { |
| + r := w.m.roundTrip(ctx, method, w.m.path+tail, body) |
| + if method == http.MethodGet { |
| + w.get = r |
| + } else { |
| + w.post = r |
| + } |
| + x := offlinerun.Exchange{Status: r.status} |
| + switch { |
| + case !r.failed: |
| + x.Body = r.body |
| + case r.unread: |
| + // A 2xx whose body is not JSON: no body to hand on. |
| + case r.status != 0: |
| + x.Cut = true // the answer came; its body did not read |
| + } |
| + return x |
| } |
| // runStatusNotice is how long later status reads may fail before run says |
| // so (once an outage). |
| const runStatusNotice = 2 * time.Minute |
| -// runStatusClass is what a status read's reply means for run. |
| -type runStatusClass int |
| - |
| -const ( |
| - statusAnswered runStatusClass = iota // a 200 whose body read |
| - statusPasses // asking again may answer |
| - statusRefused // asking again will not |
| -) |
| - |
| -// classifyStatus is the one classifier of a status read's reply, for the |
| -// first read and every later one. Invariant (Astra branch review round 2, |
| -// R2-3): a status failure that won't pass stops run. What may pass: no |
| -// response at all (a network error, or the context ended), a 5xx, the |
| -// rate limit's 429, and a 200 whose body was cut short in transit. |
| -// Everything else is refused for good, by its status alone: every redirect |
| -// (a console that moved, a proxy sending to /login), every other 4xx |
| -// whether or not its body read, and any other 2xx or a 200 that is not |
| -// JSON. TestRunStatusClasses holds the table. |
| -func classifyStatus(r moveReply) runStatusClass { |
| - switch { |
| - case r.status == 0: |
| - return statusPasses |
| - case r.status == http.StatusTooManyRequests, r.status >= 500 && r.status <= 599: |
| - return statusPasses |
| - case r.status == http.StatusOK && !r.failed: |
| - return statusAnswered |
| - case r.status == http.StatusOK && !r.unread: |
| - return statusPasses |
| - } |
| - return statusRefused |
| -} |
| - |
| -// sayStatusRefused says a status read classifyStatus refused, in the |
| -// mover's own sentences (sayReply): the console's sentence when it gave |
| -// one; else for a reply judged by its status, that status, whether or not |
| -// a body came with it. |
| +// sayStatusRefused says a status read the classifier refused for good |
| +// (offlinerun.ClassifyStatus), in the mover's own sentences (sayReply): |
| +// the console's sentence when it gave one; for a reply judged by its |
| +// status, that status, whether or not a body came with it; for a 2xx that |
| +// is not a status view, that its answer could not be read. |
| func sayStatusRefused(m *mover, r moveReply) { |
| if r.status/100 != 2 { |
| r.failed, r.unread = false, false |
| - } |
| - m.sayReply(r) |
| -} |
| - |
| -// outage notes a later status read that may pass, and says the notice once |
| -// it has gone on for runStatusNotice. |
| -func (d *runDoors) outage() { |
| - now := d.clock() |
| - if d.downSince < 0 { |
| - d.downSince = now |
| - } |
| - if now-d.downSince >= runStatusNotice && !d.downSaid { |
| - d.downSaid = true |
| - out := d.w.m.out |
| - moveSay(out, fmt.Sprintf("No status from the console for %s. run keeps asking. To see where the move is, run:", runDuration(runStatusNotice))) |
| - sayRunCommand(out, "status", d.w.m.host) |
| - } |
| -} |
| - |
| -// wait is one interval between calls (the mover's, 10 s once limited), |
| -// false when ctx ended or a Ctrl-C came first (finding 2 of the branch |
| -// review: a back-off never holds a Ctrl-C up). |
| -func (d *runDoors) wait(ctx context.Context) bool { |
| - wctx, release := d.ints.Bind(ctx) |
| - defer release() |
| - t := time.NewTimer(d.w.m.interval()) |
| - defer t.Stop() |
| - select { |
| - case <-wctx.Done(): |
| - return false |
| - case <-t.C: |
| - return true |
| - } |
| -} |
| - |
| -// get is one status read, which a Ctrl-C ends (the run then takes it). |
| -// interrupted says that is what ended it. |
| -func (d *runDoors) get(ctx context.Context) (r moveReply, interrupted bool) { |
| - rctx, release := d.ints.Bind(ctx) |
| - defer release() |
| - r = d.w.m.roundTrip(rctx, http.MethodGet, d.w.m.path, nil) |
| - return r, r.failed && rctx.Err() != nil && ctx.Err() == nil |
| -} |
| - |
| -// firstRead is the first status read: as the hand verbs' getReply, it |
| -// rides out a rate limit and a few failures and says why it gave up (code |
| -// >= 0), but a Ctrl-C ends it, and its waits, at once (interrupted). |
| -func (d *runDoors) firstRead(ctx context.Context) (r moveReply, code int, interrupted bool) { |
| - m := d.w.m |
| - failures := 0 |
| - for { |
| - r, interrupted = d.get(ctx) |
| - if interrupted { |
| - return moveReply{}, -1, true |
| - } |
| - switch classifyStatus(r) { |
| - case statusAnswered: |
| - return r, -1, false |
| - case statusRefused: |
| - // A 4xx is the console refusing this run before it wrote |
| - // anything (exit 5); any other refusal is an error (exit 1). |
| - sayStatusRefused(m, r) |
| - if r.status >= 400 && r.status <= 499 { |
| - return moveReply{}, moveExitRefused, false |
| - } |
| - return moveReply{}, moveExitError, false |
| - } |
| - switch { |
| - case r.stopped: |
| - m.sayReply(r) |
| - return moveReply{}, moveExitError, false |
| - case r.status == http.StatusTooManyRequests: |
| - m.limit() |
| - default: |
| - failures++ |
| - if failures >= moveTransient { |
| - m.sayReply(r) |
| - return moveReply{}, moveExitError, false |
| - } |
| - } |
| - if !d.wait(ctx) { |
| - if ctx.Err() != nil { |
| - moveSay(m.out, moveStopped) |
| - return moveReply{}, moveExitError, false |
| - } |
| - return moveReply{}, -1, true |
| - } |
| - } |
| -} |
| - |
| -func (d *runDoors) Status(ctx context.Context) (offlinerun.View, error) { |
| - var r moveReply |
| - if !d.seen { |
| - // The first read rides out a rate limit and a few failures, and |
| - // says why it gave up. |
| - var code int |
| - var interrupted bool |
| - if r, code, interrupted = d.firstRead(ctx); interrupted { |
| - return offlinerun.View{}, fmt.Errorf("%w", offlinerun.ErrInterrupted) |
| - } else if code >= 0 { |
| - d.code = code |
| - return offlinerun.View{}, errRunStatus |
| - } |
| } else { |
| - // Later ones are ridden out by the loop: the move is under way |
| - // and only a view decides anything. One the console refuses for |
| - // good ends the run; the rest are silent, until they have gone on |
| - // long enough to say so once. |
| - var interrupted bool |
| - r, interrupted = d.get(ctx) |
| - if interrupted { |
| - return offlinerun.View{}, fmt.Errorf("%w", offlinerun.ErrInterrupted) |
| - } |
| - switch classifyStatus(r) { |
| - case statusRefused: |
| - d.gone = r |
| - return offlinerun.View{}, fmt.Errorf("%w: %d", offlinerun.ErrStatusRefused, r.status) |
| - case statusPasses: |
| - d.outage() |
| - return offlinerun.View{}, errRunStatus |
| - } |
| - d.downSince, d.downSaid = -1, false |
| - } |
| - var full offlineView |
| - var v offlinerun.View |
| - if json.Unmarshal(r.body, &full) != nil || json.Unmarshal(r.body, &v) != nil { |
| - // A 200 that is not a status view is refused for good too. |
| r.failed, r.unread = true, true |
| - if !d.seen { |
| - sayStatusRefused(d.w.m, r) |
| - d.code = moveExitError |
| - return offlinerun.View{}, errRunStatus |
| - } |
| - d.gone = r |
| - return offlinerun.View{}, fmt.Errorf("%w: not a status view", offlinerun.ErrStatusRefused) |
| - } |
| - d.seen = true |
| - d.w.learn(full) |
| - d.last = offlineReply{v: full, waiting: r.answer.waiting, hasWaiting: r.answer.hasWaiting} |
| - return v, nil |
| -} |
| - |
| -// body is a door's request: the move's id once bound, and the region for |
| -// stage and start (the bound move's own, once a view of it named one). The |
| -// first stage, sent before anything is bound, is create-only ("new"): the |
| -// door refuses it if the host already has a move, rather than restaging |
| -// someone else's (Astra branch round 1, finding 1). |
| -func (d *runDoors) body(verb, id string) map[string]any { |
| - b := map[string]any{} |
| - if id != "" { |
| - b["id"] = id |
| - } |
| - if verb == offlinerun.VerbStage && id == "" { |
| - b["new"] = true |
| - } |
| - if verb == offlinerun.VerbStage || verb == offlinerun.VerbStart { |
| - region := d.region |
| - if v := d.last.v; id != "" && v.ID == id && v.To != "" { |
| - region = v.To |
| - } |
| - b["region"] = region |
| } |
| - return b |
| -} |
| - |
| -// send sends one POST, again after the back-off while the rate limit |
| -// answers 429 (it answers before any door, so nothing was done). The POST |
| -// itself is never cut short by a Ctrl-C, so its outcome is never made |
| -// unknown by one; the back-off is. sent is false when no door took it. |
| -func (d *runDoors) send(ctx context.Context, tail string, body any) (r moveReply, sent bool) { |
| - m := d.w.m |
| - for { |
| - r = m.roundTrip(ctx, http.MethodPost, m.path+tail, body) |
| - if r.failed || r.moved != "" || r.status != http.StatusTooManyRequests { |
| - return r, true |
| - } |
| - m.limit() |
| - if !d.wait(ctx) { |
| - return r, false |
| - } |
| - } |
| -} |
| - |
| -func (d *runDoors) Post(ctx context.Context, verb, id string) offlinerun.Answer { |
| - tail := "/" + verb |
| - if verb == offlinerun.VerbStart { |
| - tail = "" // start is the offline door itself |
| - } |
| - b := d.body(verb, id) |
| - r, sent := d.send(ctx, tail, b) |
| - if !sent { |
| - d.reply = moveReply{} |
| - return offlinerun.Answer{NotSent: true} |
| - } |
| - return d.answer(r, b["new"] == true) |
| -} |
| - |
| -func (d *runDoors) Nudge(ctx context.Context, id string) offlinerun.Answer { |
| - r, sent := d.send(ctx, "/nudge", d.body("nudge", id)) |
| - if !sent { |
| - d.reply = moveReply{} |
| - return offlinerun.Answer{NotSent: true} |
| - } |
| - return d.answer(r, false) |
| -} |
| - |
| -// answer reads a POST's reply. A 2xx is accepted (and its view teaches the |
| -// move's id and regions); a 4xx is a refusal (the doors write nothing |
| -// before they answer one); anything else (no reply, a redirect, an |
| -// unreadable body, a 5xx with or without a sentence) says nothing about the |
| -// write, and the next status read decides. A create-only stage's reply |
| -// names the move only when it says this request created it ("new"), so the |
| -// run is never bound to a move it did not make. |
| -func (d *runDoors) answer(r moveReply, createOnly bool) offlinerun.Answer { |
| - d.reply = r |
| - switch { |
| - case r.failed || r.moved != "": |
| - return offlinerun.Answer{} |
| - case r.status >= 200 && r.status <= 299: |
| - var v offlineView |
| - if json.Unmarshal(r.body, &v) == nil { |
| - d.w.learn(v) |
| - } |
| - if createOnly && !v.New { |
| - return offlinerun.Answer{Accepted: true} |
| - } |
| - return offlinerun.Answer{Accepted: true, ID: v.ID} |
| - case r.status >= 400 && r.status <= 499: |
| - return offlinerun.Answer{Refused: true} |
| - } |
| - return offlinerun.Answer{} |
| + m.sayReply(r) |
| } |
| // runWatcher prints the run (offlinerun.Watcher). |
| type runWatcher struct { |
| w *offlineRun |
| - doors *runDoors |
| + wire *runWire |
| + last offlineReply // the latest status view |
| now func() time.Time |
| clock func() time.Duration |
| policy offlinerun.Policy |
| @@ -544,7 +304,7 @@ type runWatcher struct { |
| id string // the move this run carries, once the header named it |
| stageSaid int64 // the staged_at whose round was said |
| abortSaid bool // why the run aborts was said |
| - abortOwed bool // OR28 waits for a view that names the region |
| + downSaid bool // the outage notice was said for this outage |
| } |
| func (rw *runWatcher) out() io.Writer { return rw.w.m.out } |
| @@ -566,14 +326,54 @@ func (rw *runWatcher) sayHeader(v offlineView) { |
| moveSay(rw.out(), fmt.Sprintf("Move %s.", v.ID)) |
| } |
| +// read keeps a status view that answered (the doors' Viewed), before Saw. |
| +func (rw *runWatcher) read(v offlineView) { |
| + rw.w.learn(v) |
| + a := rw.wire.get.answer |
| + rw.last = offlineReply{v: v, waiting: a.waiting, hasWaiting: a.hasWaiting} |
| + rw.downSaid = false |
| +} |
| + |
| +// Unread is a status read that got no view and may yet (finding 6 of the |
| +// branch review). The rate limit's is said once (the mover's sentence); |
| +// the rest are silent until they have gone on for runStatusNotice, said |
| +// once an outage. |
| +func (rw *runWatcher) Unread(limited bool, down time.Duration) { |
| + if limited { |
| + rw.w.m.limit() |
| + } |
| + if down >= runStatusNotice && !rw.downSaid { |
| + rw.downSaid = true |
| + moveSay(rw.out(), fmt.Sprintf("No status from the console for %s. run keeps asking. To see where the move is, run:", runDuration(runStatusNotice))) |
| + sayRunCommand(rw.out(), "status", rw.w.m.host) |
| + } |
| +} |
| + |
| +// unread ends a run whose status reads never gave a view (the Runner's |
| +// error): refused for good, or failed moveTransient times in a row. A 4xx |
| +// is the console refusing this run before it wrote anything (exit 5); any |
| +// other is an error (exit 1). The class is the classifier's |
| +// (offlinerun.ClassifyStatus); this only says it. |
| +func (rw *runWatcher) unread(err error) int { |
| + m, r := rw.w.m, rw.wire.get |
| + switch { |
| + case errors.Is(err, offlinerun.ErrStatusRefused): |
| + sayStatusRefused(m, r) |
| + if r.status >= 400 && r.status <= 499 { |
| + return moveExitRefused |
| + } |
| + case errors.Is(err, offlinerun.ErrNoStatus): |
| + m.sayReply(r) |
| + default: |
| + moveSay(m.out, moveStopped) |
| + } |
| + return moveExitError |
| +} |
| + |
| func (rw *runWatcher) Saw(offlinerun.View) { |
| - r := rw.doors.last |
| + r := rw.last |
| v := r.v |
| rw.sayHeader(v) |
| - if rw.abortOwed && rw.from(v) != "" { |
| - rw.abortOwed = false |
| - rw.sayMovingBack(v) |
| - } |
| if v.ID == "" || v.ID != rw.id { |
| return // another move's view, or none: Decide says what it means |
| } |
| @@ -612,7 +412,7 @@ func (rw *runWatcher) sayWhy(reason string) { |
| return |
| } |
| rw.abortSaid = true |
| - v, host := rw.doors.last.v, rw.w.m.host |
| + v, host := rw.last.v, rw.w.m.host |
| from := v.fromPlace() |
| p := rw.policy |
| switch reason { |
| @@ -685,7 +485,7 @@ func (rw *runWatcher) Withdrawn(a offlinerun.Action) { |
| func (rw *runWatcher) sayAnswer(verb string, ans offlinerun.Answer) { |
| out := rw.out() |
| runSep(out, ", ") |
| - r := rw.doors.reply |
| + r := rw.wire.post |
| switch { |
| case ans.Accepted: |
| runPiece(out, "accepted") |
| @@ -699,7 +499,7 @@ func (rw *runWatcher) sayAnswer(verb string, ans offlinerun.Answer) { |
| // (whose write the next status read decides). |
| runPiece(out, "refused: ") |
| saySpoken(out, r.refusal) |
| - case ans.Refused: |
| + case ans.Refused || ans.Limited: |
| runPiece(out, "refused: ") |
| moveSay(out, fmt.Sprintf("The console answered %d and gave no reason.", r.status)) |
| default: |
| @@ -711,18 +511,24 @@ func (rw *runWatcher) Acted(a offlinerun.Action, res offlinerun.Result, m offlin |
| rw.bound = m.Bound() |
| switch a := a.(type) { |
| case offlinerun.Post: |
| - rw.posted = true |
| + // A POST the rate limit answered reached no door: the line says |
| + // the console's answer, and the run has still posted nothing. |
| + rw.posted = rw.posted || !res.Limited |
| runPiece(rw.out(), "sent") |
| rw.sayAnswer(a.Verb, res.Answer) |
| + rw.w.learn(rw.lastPostView()) |
| rw.sayHeader(rw.lastPostView()) |
| + rw.sayLimited(res.Answer) |
| case offlinerun.Nudge: |
| rw.column("waiting") |
| + rw.w.learn(rw.lastPostView()) |
| if res.Accepted { |
| moveSay(rw.out(), fmt.Sprintf("no change for %s, woke the boxes", runDuration(m.QuietFor(rw.clock())))) |
| return |
| } |
| runPiece(rw.out(), "sent") |
| rw.sayAnswer("nudge", res.Answer) |
| + rw.sayLimited(res.Answer) |
| case offlinerun.Probe: |
| if res.Status >= 200 && res.Status <= 299 { |
| rw.column("check") |
| @@ -731,31 +537,35 @@ func (rw *runWatcher) Acted(a offlinerun.Action, res offlinerun.Result, m offlin |
| } |
| } |
| +// sayLimited says, once, that the rate limit answered a POST (the mover's |
| +// sentence): the loop waits its back-off, reads status and decides again. |
| +func (rw *runWatcher) sayLimited(ans offlinerun.Answer) { |
| + if ans.Limited { |
| + rw.w.m.limit() |
| + } |
| +} |
| + |
| // lastPostView is the view the last accepted POST answered with. |
| func (rw *runWatcher) lastPostView() offlineView { |
| var v offlineView |
| - if r := rw.doors.reply; !r.failed && r.status >= 200 && r.status <= 299 { |
| + if r := rw.wire.post; !r.failed && r.status >= 200 && r.status <= 299 { |
| _ = json.Unmarshal(r.body, &v) |
| } |
| return v |
| } |
| -// sayMovingBack is OR28. |
| -func (rw *runWatcher) sayMovingBack(v offlineView) { |
| - moveSay(rw.out(), fmt.Sprintf("Moving %s back to %s. Press Ctrl-C again to stop watching.", rw.w.m.host, rw.from(v))) |
| -} |
| - |
| +// Interrupted says what a Ctrl-C did. InterruptAbort is OR28, and the |
| +// Runner says it only with the bound move's own view in hand, in a state |
| +// abort still applies to (offlinerun's judge, invariant C): rw.last is that |
| +// view, so the region is that move's. It is never put off to a later view, |
| +// which might be an opened move or someone else's (Astra round 3, P2 3). |
| func (rw *runWatcher) Interrupted(i offlinerun.Interrupt, _ offlinerun.Memory) { |
| - host, v := rw.w.m.host, rw.doors.last.v |
| + host, v := rw.w.m.host, rw.last.v |
| switch i { |
| case offlinerun.InterruptAbort: |
| - if rw.from(v) == "" { |
| - // No view has named the region yet (a resumed run's first |
| - // read was cut short): said once one does (Saw). |
| - rw.abortOwed = true |
| - return |
| + if from := v.fromPlace(); v.ID == rw.bound && from != "" { |
| + moveSay(rw.out(), fmt.Sprintf("Moving %s back to %s. Press Ctrl-C again to stop watching.", host, from)) |
| } |
| - rw.sayMovingBack(v) |
| case offlinerun.InterruptStop: |
| moveSay(rw.out(), "Stopped watching. The move is still running. To see where it is, run:") |
| sayRunCommand(rw.out(), "status", host) |
| @@ -789,7 +599,7 @@ func (rw *runWatcher) to(v offlineView) string { |
| // end says how the run ended and answers its exit code. |
| func (rw *runWatcher) end(d offlinerun.Done) int { |
| - host, r := rw.w.m.host, rw.doors.last |
| + host, r := rw.w.m.host, rw.last |
| v := r.v |
| switch d.Reason { |
| case offlinerun.ReasonDone, offlinerun.ReasonAborted: |
| @@ -827,7 +637,7 @@ func (rw *runWatcher) end(d offlinerun.Done) int { |
| // said at the Ctrl-C |
| case offlinerun.ReasonStatusRefused: |
| // The console's own sentence for it, then where to look. |
| - sayStatusRefused(rw.w.m, rw.doors.gone) |
| + sayStatusRefused(rw.w.m, rw.wire.get) |
| moveSay(rw.out(), "Stopped watching. The move is still running. To see where it is, run:") |
| sayRunCommand(rw.out(), "status", host) |
| } |
diff --git a/move_offline_run_test.go b/move_offline_run_test.go| index ab7bc8a39..53293b284 100644 |
| --- a/move_offline_run_test.go |
| +++ b/move_offline_run_test.go |
| @@ -17,6 +17,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/awsinv" |
| + "github.com/carlosframework/platform/internal/moves/offlinerun" |
| ) |
| // offlineSim is a model of one offline move behind the doors, for |
| @@ -894,11 +895,10 @@ func TestMoveOfflineRunCtrlCDuringStatusRead(t *testing.T) { |
| wantLines(t, out, "Moving acme.shop.example.com back to ie. Press Ctrl-C again to stop watching.", orBack) |
| } |
| -// TestMoveOfflineRunCtrlCDuringRateLimit (finding 2): the rate limit's |
| -// back-off ends at a Ctrl-C. On a POST: no door took it, so nothing was |
| -// written; the first Ctrl-C aborts. On the first status read, a Ctrl-C as |
| -// the limit answers ends the read itself: nothing was sent at all, and the |
| -// run stops there. |
| +// TestMoveOfflineRunCtrlCDuringRateLimit (finding 2): a Ctrl-C as the rate |
| +// limit answers. On a POST: no door took it, so nothing was written, and |
| +// it is not sent again; the first Ctrl-C aborts. On the first status read, |
| +// a Ctrl-C as the limit answers ends the run: nothing was sent at all. |
| func TestMoveOfflineRunCtrlCDuringRateLimit(t *testing.T) { |
| var press func() |
| sim := &offlineSim{limit: map[string]int{"seal": 1}, onLimit: func() { press() }} |
| @@ -924,8 +924,7 @@ func TestMoveOfflineRunCtrlCDuringRateLimit(t *testing.T) { |
| if posts := c.postsSent(); len(posts) != 0 { |
| t.Fatalf("posted %q", posts) |
| } |
| - // The 429 is said when it was read before the Ctrl-C ended the read. |
| - if out != "Stopped. Nothing was sent.\n" && out != "The console is limiting requests. Checking every 10 seconds.\nStopped. Nothing was sent.\n" { |
| + if out != "Stopped. Nothing was sent.\n" { |
| t.Fatalf("output:\n%s", out) |
| } |
| } |
| @@ -1110,54 +1109,64 @@ func TestMoveOfflineRunStagingCaps(t *testing.T) { |
| } |
| // TestRunStatusClasses is the one status classifier's table (Astra branch |
| -// review round 2, R2-3; invariant: a status failure that won't pass stops |
| -// run). Every reply comes off a real HTTP exchange through roundTrip, as |
| -// run reads one. Network errors, 5xx and 429 pass; everything else, every |
| -// redirect and every other 4xx (a body that does not read included), is |
| +// review round 2, R2-3; invariant B: a status failure that won't pass |
| +// stops run), as run meets it: every reply comes off a real HTTP exchange |
| +// through the run's own wire (runWire over roundTrip) into |
| +// offlinerun.ClassifyStatus, decoding as the run does. Network errors, 5xx |
| +// and 429 pass; everything else, every redirect, every other 4xx (a body |
| +// that does not read included) and a 200 that is not a status view, is |
| // refused for good. |
| func TestRunStatusClasses(t *testing.T) { |
| view := `{"host":"` + oHost + `","state":"offline-sealing","id":"` + tMoveID + `"}` |
| for _, c := range []struct { |
| name string |
| serve func(w http.ResponseWriter) |
| - want runStatusClass |
| + want offlinerun.StatusClass |
| failed bool // roundTrip marks the reply failed (its body did not read, or is not JSON) |
| wantFirst string |
| }{ |
| - {"200 view", func(w http.ResponseWriter) { w.WriteHeader(200); io.WriteString(w, view) }, statusAnswered, false, ""}, |
| - {"no response", nil, statusPasses, false, ""}, |
| - {"500", func(w http.ResponseWriter) { w.WriteHeader(500) }, statusPasses, false, ""}, |
| + {"200 view", func(w http.ResponseWriter) { w.WriteHeader(200); io.WriteString(w, view) }, offlinerun.StatusAnswered, false, ""}, |
| + {"no response", nil, offlinerun.StatusPasses, false, ""}, |
| + {"500", func(w http.ResponseWriter) { w.WriteHeader(500) }, offlinerun.StatusPasses, false, ""}, |
| {"502 with a sentence", func(w http.ResponseWriter) { |
| w.WriteHeader(502) |
| io.WriteString(w, `{"error":"could not read the instance"}`) |
| - }, statusPasses, false, ""}, |
| - {"503", func(w http.ResponseWriter) { w.WriteHeader(503) }, statusPasses, false, ""}, |
| - {"429", func(w http.ResponseWriter) { w.WriteHeader(429); io.WriteString(w, `{"error":"slow down"}`) }, statusPasses, false, ""}, |
| + }, offlinerun.StatusPasses, false, ""}, |
| + {"503", func(w http.ResponseWriter) { w.WriteHeader(503) }, offlinerun.StatusPasses, false, ""}, |
| + {"429", func(w http.ResponseWriter) { w.WriteHeader(429); io.WriteString(w, `{"error":"slow down"}`) }, offlinerun.StatusLimited, false, ""}, |
| {"200 cut short", func(w http.ResponseWriter) { |
| w.Header().Set("Content-Length", "500") |
| w.WriteHeader(200) |
| io.WriteString(w, view[:20]) |
| - }, statusPasses, true, ""}, |
| - {"200 not a view", func(w http.ResponseWriter) { w.WriteHeader(200); io.WriteString(w, "<html>") }, statusRefused, true, "The console's answer could not be read."}, |
| - {"204", func(w http.ResponseWriter) { w.WriteHeader(204) }, statusRefused, true, "The console's answer could not be read."}, |
| + }, offlinerun.StatusPasses, true, ""}, |
| + {"200 not a view", func(w http.ResponseWriter) { w.WriteHeader(200); io.WriteString(w, "<html>") }, offlinerun.StatusRefused, true, "The console's answer could not be read."}, |
| + {"200 next is a number", func(w http.ResponseWriter) { |
| + w.WriteHeader(200) |
| + io.WriteString(w, `{"host":"`+oHost+`","state":"offline-landed","id":"`+tMoveID+`","next":123}`) |
| + }, offlinerun.StatusRefused, false, "The console's answer could not be read."}, |
| + {"200 a view Decide reads, not one run's lines do", func(w http.ResponseWriter) { |
| + w.WriteHeader(200) |
| + io.WriteString(w, `{"host":"`+oHost+`","state":"offline-landed","id":"`+tMoveID+`","boxes":7}`) |
| + }, offlinerun.StatusRefused, false, "The console's answer could not be read."}, |
| + {"204", func(w http.ResponseWriter) { w.WriteHeader(204) }, offlinerun.StatusRefused, true, "The console's answer could not be read."}, |
| {"301 the console moved", func(w http.ResponseWriter) { |
| w.Header().Set("Location", "https://console.example.net/api/cli/x") |
| w.WriteHeader(301) |
| - }, statusRefused, false, ""}, |
| - {"302 to /login", func(w http.ResponseWriter) { w.Header().Set("Location", "/login"); w.WriteHeader(302) }, statusRefused, false, "The console answered 302 and gave no reason."}, |
| - {"307", func(w http.ResponseWriter) { w.Header().Set("Location", "/elsewhere"); w.WriteHeader(307) }, statusRefused, false, "The console answered 307 and gave no reason."}, |
| - {"400", func(w http.ResponseWriter) { w.WriteHeader(400); io.WriteString(w, `{"error":"bad request"}`) }, statusRefused, false, "bad request"}, |
| - {"401", func(w http.ResponseWriter) { w.WriteHeader(401); io.WriteString(w, `{"error":"sign in again"}`) }, statusRefused, false, "sign in again"}, |
| + }, offlinerun.StatusRefused, false, ""}, |
| + {"302 to /login", func(w http.ResponseWriter) { w.Header().Set("Location", "/login"); w.WriteHeader(302) }, offlinerun.StatusRefused, false, "The console answered 302 and gave no reason."}, |
| + {"307", func(w http.ResponseWriter) { w.Header().Set("Location", "/elsewhere"); w.WriteHeader(307) }, offlinerun.StatusRefused, false, "The console answered 307 and gave no reason."}, |
| + {"400", func(w http.ResponseWriter) { w.WriteHeader(400); io.WriteString(w, `{"error":"bad request"}`) }, offlinerun.StatusRefused, false, "bad request"}, |
| + {"401", func(w http.ResponseWriter) { w.WriteHeader(401); io.WriteString(w, `{"error":"sign in again"}`) }, offlinerun.StatusRefused, false, "sign in again"}, |
| {"401 cut short", func(w http.ResponseWriter) { |
| w.Header().Set("Content-Length", "500") |
| w.WriteHeader(401) |
| io.WriteString(w, `{"error":"sign`) |
| - }, statusRefused, true, "The console answered 401 and gave no reason."}, |
| - {"403", func(w http.ResponseWriter) { w.WriteHeader(403) }, statusRefused, false, "The console answered 403 and gave no reason."}, |
| - {"404", func(w http.ResponseWriter) { w.WriteHeader(404) }, statusRefused, false, "Not found. Check --account and --app, and that you are a member of the instance's account."}, |
| - {"409", func(w http.ResponseWriter) { w.WriteHeader(409); io.WriteString(w, `{"error":"no"}`) }, statusRefused, false, "no"}, |
| - {"410", func(w http.ResponseWriter) { w.WriteHeader(410) }, statusRefused, false, "The console answered 410 and gave no reason."}, |
| - {"418", func(w http.ResponseWriter) { w.WriteHeader(418) }, statusRefused, false, "The console answered 418 and gave no reason."}, |
| + }, offlinerun.StatusRefused, true, "The console answered 401 and gave no reason."}, |
| + {"403", func(w http.ResponseWriter) { w.WriteHeader(403) }, offlinerun.StatusRefused, false, "The console answered 403 and gave no reason."}, |
| + {"404", func(w http.ResponseWriter) { w.WriteHeader(404) }, offlinerun.StatusRefused, false, "Not found. Check --account and --app, and that you are a member of the instance's account."}, |
| + {"409", func(w http.ResponseWriter) { w.WriteHeader(409); io.WriteString(w, `{"error":"no"}`) }, offlinerun.StatusRefused, false, "no"}, |
| + {"410", func(w http.ResponseWriter) { w.WriteHeader(410) }, offlinerun.StatusRefused, false, "The console answered 410 and gave no reason."}, |
| + {"418", func(w http.ResponseWriter) { w.WriteHeader(418) }, offlinerun.StatusRefused, false, "The console answered 418 and gave no reason."}, |
| } { |
| t.Run(c.name, func(t *testing.T) { |
| ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| @@ -1172,14 +1181,16 @@ func TestRunStatusClasses(t *testing.T) { |
| defer ts.Close() |
| var out bytes.Buffer |
| m := &mover{sess: &apiSession{c: newConsoleClient(ts.URL, "t")}, out: &out, host: oHost, path: "/api/cli/x"} |
| - r := m.roundTrip(context.Background(), http.MethodGet, m.path, nil) |
| - if got := classifyStatus(r); got != c.want { |
| + wire := &runWire{m: m} |
| + x := wire.Do(context.Background(), http.MethodGet, "", nil) |
| + r := wire.get |
| + if got, _ := offlinerun.ClassifyStatus(x, &offlineView{}); got != c.want { |
| t.Fatalf("class %d, want %d (reply %+v)", got, c.want, r) |
| } |
| if c.failed != (r.failed && r.status != 0) { |
| t.Fatalf("reply failed %v (status %d), the case wants %v", r.failed, r.status, c.failed) |
| } |
| - if c.want != statusRefused { |
| + if c.want != offlinerun.StatusRefused { |
| return |
| } |
| sayStatusRefused(m, r) |
| @@ -1310,12 +1321,18 @@ func TestMoveOfflineRunGateBoundaries(t *testing.T) { |
| }) |
| } |
| -// TestRunDoorsPostOnlyThroughTheGate: the CLI's doors make their POSTs in |
| -// one function (runDoors.send), which only runDoors.Post and Nudge call, |
| -// and nothing in the package calls those: the only caller is the |
| -// offlinerun.Runner's dispatch gate, through the Doors interface |
| -// (TestGateIsTheOnlyWayToPost holds that side). |
| -func TestRunDoorsPostOnlyThroughTheGate(t *testing.T) { |
| +// TestRunDoorsWireIsSingleShot (invariant A, by construction, on the CLI's |
| +// side): `carlos move offline run` reaches the console through one |
| +// function, runWire.Do, which makes one roundTrip and has no loop; and |
| +// roundTrip makes one HTTP request and has no loop. move_offline_run.go |
| +// names no HTTP method but GET (the wire telling a read from a POST, and |
| +// the probe of the instance), calls none of the mover's own |
| +// retrying or waiting helpers, calls no door (only the Runner's gate |
| +// does, in offlinerun: TestGateIsTheOnlyWayToPost) and waits nowhere: its |
| +// one loop is the Ctrl-C source's. So a request the run makes was decided |
| +// by the Runner's loop from a fresh view, every time. A retry or a wait |
| +// added on this side fails here. |
| +func TestRunDoorsWireIsSingleShot(t *testing.T) { |
| fset := token.NewFileSet() |
| pkgs, err := parser.ParseDir(fset, ".", func(fi os.FileInfo) bool { return !strings.HasSuffix(fi.Name(), "_test.go") }, 0) |
| if err != nil { |
| @@ -1332,9 +1349,19 @@ func TestRunDoorsPostOnlyThroughTheGate(t *testing.T) { |
| } |
| return "" |
| } |
| - sends := 0 |
| + loop := func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.ForStmt, *ast.RangeStmt: |
| + return true |
| + case *ast.BranchStmt: |
| + return n.Tok == token.GOTO |
| + } |
| + return false |
| + } |
| + roundTrips, httpDos := map[string]int{}, 0 |
| for _, pkg := range pkgs { |
| for name, f := range pkg.Files { |
| + run := name == "move_offline_run.go" |
| for _, decl := range f.Decls { |
| fn, ok := decl.(*ast.FuncDecl) |
| if !ok || fn.Body == nil { |
| @@ -1342,32 +1369,51 @@ func TestRunDoorsPostOnlyThroughTheGate(t *testing.T) { |
| } |
| where := recv(fn) + "." + fn.Name.Name |
| ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + if n == nil { |
| + return true |
| + } |
| + if loop(n) && ((run && where != ".ctrlC") || where == "mover.roundTrip") { |
| + t.Errorf("%s: %s has a loop", name, where) |
| + } |
| switch n := n.(type) { |
| + case *ast.SelectStmt: |
| + if run && where != ".ctrlC" { |
| + t.Errorf("%s: %s selects: the run waits only in the Runner's loop", name, where) |
| + } |
| case *ast.SelectorExpr: |
| - if id, ok := n.X.(*ast.Ident); ok && id.Name == "http" && n.Sel.Name == "MethodPost" && name == "move_offline_run.go" && where != "runDoors.send" { |
| - t.Errorf("%s: %s sends a POST outside runDoors.send", name, where) |
| + if id, ok := n.X.(*ast.Ident); run && ok && id.Name == "http" && strings.HasPrefix(n.Sel.Name, "Method") && |
| + (n.Sel.Name != "MethodGet" || (where != "runWire.Do" && where != ".probeOnce")) { |
| + t.Errorf("%s: %s names http.%s: the doors choose what is sent", name, where, n.Sel.Name) |
| } |
| case *ast.CallExpr: |
| sel, ok := n.Fun.(*ast.SelectorExpr) |
| if !ok { |
| return true |
| } |
| + if where == "mover.roundTrip" && sel.Sel.Name == "Do" { |
| + httpDos++ |
| + } |
| + if !run { |
| + return true |
| + } |
| switch sel.Sel.Name { |
| - case "send": |
| - if recv(fn) == "runDoors" { |
| - sends++ |
| - if where != "runDoors.Post" && where != "runDoors.Nudge" { |
| - t.Errorf("%s: %s calls runDoors.send", name, where) |
| - } |
| + case "roundTrip": |
| + roundTrips[where]++ |
| + case "Post", "Nudge", "Status", "Do": |
| + if where == ".probeOnce" && sel.Sel.Name == "Do" { |
| + break // the probe's one GET of the instance, not a door |
| } |
| - case "Post", "Nudge": |
| - if name == "move_offline_run.go" { |
| - t.Errorf("%s: %s calls .%s: only the gate may", name, where, sel.Sel.Name) |
| + t.Errorf("%s: %s calls .%s: only the Runner's gate and the doors may", name, where, sel.Sel.Name) |
| + case "sleep", "interval", "get", "getReply", "send", "mutate", "poll", "post", "follow", "readFlat", "readDetail": |
| + t.Errorf("%s: %s calls the mover's .%s, which waits or sends again", name, where, sel.Sel.Name) |
| + case "Sleep", "After", "NewTimer", "NewTicker", "Tick", "AfterFunc": |
| + if id, ok := sel.X.(*ast.Ident); ok && id.Name == "time" { |
| + t.Errorf("%s: %s calls time.%s", name, where, sel.Sel.Name) |
| } |
| } |
| case *ast.Ident: |
| - if n.Name == "runDoors" && name != "move_offline_run.go" { |
| - t.Errorf("%s reaches runDoors", name) |
| + if n.Name == "runWire" && !run { |
| + t.Errorf("%s reaches runWire", name) |
| } |
| } |
| return true |
| @@ -1375,7 +1421,165 @@ func TestRunDoorsPostOnlyThroughTheGate(t *testing.T) { |
| } |
| } |
| } |
| - if sends != 2 { |
| - t.Fatalf("runDoors.send is called %d times, want twice (Post, Nudge)", sends) |
| + if len(roundTrips) != 1 || roundTrips["runWire.Do"] != 1 { |
| + t.Errorf("roundTrip is called in %v, want once in runWire.Do", roundTrips) |
| + } |
| + if httpDos != 1 { |
| + t.Errorf("roundTrip makes %d HTTP requests, want one", httpDos) |
| + } |
| +} |
| + |
| +// TestMoveOfflineRunLimitedPostGoesBackThroughTheGate is round 3's P1 as |
| +// the CLI meets it: the rate limit answers open, and a Ctrl-C lands with |
| +// the back-off's end. The open is not sent again; the run aborts. With no |
| +// Ctrl-C, the open goes out again only after the back-off and a fresh |
| +// status read. |
| +func TestMoveOfflineRunLimitedPostGoesBackThroughTheGate(t *testing.T) { |
| + var press func() |
| + limited := false |
| + sim := &offlineSim{limit: map[string]int{"open": 1}, onLimit: func() { limited = true }} |
| + c := &fakeOfflineConsole{sim: sim} |
| + code, out := runOfflineRun(t, c, runSeams{press: &press, ctrlC: func(int) bool { |
| + if limited { |
| + limited = false |
| + return true // during the back-off after the limited open |
| + } |
| + return false |
| + }}, "--to", "uk") |
| + if code != 3 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(c.postsSent()); got != "stage,start,seal,flip,open,abort,finish" { |
| + t.Fatalf("doors %s:\n%s", got, out) |
| + } |
| + if n := c.posted("/open"); n != 0 { |
| + t.Fatalf("a door took %d opens:\n%s", n, out) |
| + } |
| + wantLines(t, out, |
| + "open sent, refused: too many requests", |
| + "The console is limiting requests. Checking every 10 seconds.", |
| + "Moving acme.shop.example.com back to ie. Press Ctrl-C again to stop watching.", orBack) |
| + |
| + // No Ctrl-C: each limited POST is followed by a status read before |
| + // the door is posted again. |
| + c = &fakeOfflineConsole{sim: &offlineSim{limit: map[string]int{"seal": 2, "open": 1}}} |
| + code, out = runOfflineRun(t, c, runSeams{}, "--to", "uk") |
| + if code != 0 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(c.postsSent()); got != "stage,start,seal,seal,seal,flip,open,open,finish,finish" { |
| + t.Fatalf("doors %s:\n%s", got, out) |
| + } |
| + last := "" |
| + for _, r := range c.requests() { |
| + method, rest, _ := strings.Cut(r, " ") |
| + door, _, _ := strings.Cut(rest, " ") |
| + if method == "POST" && strings.HasPrefix(last, "POST "+door+" ") && (strings.HasSuffix(door, "/seal") || strings.HasSuffix(door, "/open")) { |
| + t.Fatalf("%s was posted twice with no status read between:\n%s", door, strings.Join(c.requests(), "\n")) |
| + } |
| + last = r |
| + } |
| + if strings.Count(out, "The console is limiting requests. Checking every 10 seconds.") != 1 { |
| + t.Fatalf("want the limit said once:\n%s", out) |
| + } |
| + wantLines(t, out, orMoved) |
| +} |
| + |
| +// TestMoveOfflineRunStatusNotAView is round 3's P2 2 as the CLI meets it: a |
| +// 200 whose JSON is not a status view ("next" a number, which the mover's |
| +// own reading of a reply lets through) is refused for good by the one |
| +// classifier: exit 1 on the first read, nothing sent; exit 1 mid-run with |
| +// OR29 and the status command, nothing more sent. |
| +func TestMoveOfflineRunStatusNotAView(t *testing.T) { |
| + bad := func(w http.ResponseWriter) { |
| + w.WriteHeader(200) |
| + io.WriteString(w, `{"host":"`+oHost+`","state":"offline-landed","id":"`+tMoveID+`","next":123}`) |
| + } |
| + sim := &offlineSim{getRaw: func(_ *offlineSim, w http.ResponseWriter) bool { bad(w); return true }} |
| + c := &fakeOfflineConsole{sim: sim} |
| + code, out := runOfflineRun(t, c, runSeams{}, "--to", "uk") |
| + if code != 1 || len(c.postsSent()) != 0 || out != "The console's answer could not be read.\n" { |
| + t.Fatalf("first read: exit %d, posts %q:\n%s", code, c.postsSent(), out) |
| + } |
| + if n := len(c.requests()); n != 1 { |
| + t.Fatalf("first read: %d requests, want one", n) |
| + } |
| + |
| + sim = &offlineSim{holdIn: "offline-sealing"} |
| + sim.getRaw = func(s *offlineSim, w http.ResponseWriter) bool { |
| + if s.state != "offline-sealing" { |
| + return false |
| + } |
| + bad(w) |
| + return true |
| + } |
| + c = &fakeOfflineConsole{sim: sim} |
| + code, out = runOfflineRun(t, c, runSeams{}, "--to", "uk") |
| + if code != 1 { |
| + t.Fatalf("exit %d:\n%s", code, out) |
| + } |
| + if got := doorsOf(c.postsSent()); got != "stage,start,seal" { |
| + t.Fatalf("doors %s:\n%s", got, out) |
| + } |
| + if !strings.HasSuffix(out, "The console's answer could not be read.\n"+ |
| + "Stopped watching. The move is still running. To see where it is, run:\n"+ |
| + " carlos move offline status --host acme.shop.example.com\n") { |
| + t.Fatalf("output:\n%s", out) |
| } |
| } |
| + |
| +// TestMoveOfflineRunCtrlCPromisesOnlyWhatItCanDo is round 3's P2 3 as the |
| +// CLI meets it. A Ctrl-C cuts the first read of a resumed run short; by |
| +// the next read someone else has opened the move, or the host has another |
| +// move. OR28 ("Moving ... back") is not said for either: the opened move |
| +// is said to be served and the run stops watching; the other move ends the |
| +// run on its own sentence. Nothing is posted. |
| +func TestMoveOfflineRunCtrlCPromisesOnlyWhatItCanDo(t *testing.T) { |
| + const or28 = "back to ie. Press Ctrl-C again to stop watching." |
| + t.Run("opened by someone else", func(t *testing.T) { |
| + var press func() |
| + sim := &offlineSim{} |
| + sim.enter("offline-landed") |
| + sim.getRaw = func(s *offlineSim, w http.ResponseWriter) bool { |
| + s.getRaw = nil |
| + press() // the read is on the wire: it is cut short, unanswered |
| + if conn, _, err := w.(http.Hijacker).Hijack(); err == nil { |
| + conn.Close() |
| + } |
| + s.enter("offline-open") // and a second operator opens the move |
| + return true |
| + } |
| + c := &fakeOfflineConsole{sim: sim} |
| + code, out := runOfflineRun(t, c, runSeams{press: &press}, "--resume", tMoveID) |
| + if code != 4 || len(c.postsSent()) != 0 { |
| + t.Fatalf("exit %d, posts %q:\n%s", code, c.postsSent(), out) |
| + } |
| + if strings.Contains(out, or28) { |
| + t.Fatalf("promised to move an opened move back:\n%s", out) |
| + } |
| + wantLines(t, out, "acme.shop.example.com is already served from uk, so the move is not undone. Stopped watching.") |
| + }) |
| + t.Run("replaced by another move", func(t *testing.T) { |
| + var press func() |
| + sim := &offlineSim{} |
| + sim.enter("offline-landed") |
| + sim.onGet = func(s *offlineSim) { |
| + s.onGet = nil |
| + press() |
| + } |
| + c := &fakeOfflineConsole{sim: sim} |
| + // The run resumes a move the host no longer has: the record's |
| + // (tMoveID) is someone else's, in ie to uk as it happens. |
| + const mine = "mv-20261115-0611-aaaa" |
| + code, out := runOfflineRun(t, c, runSeams{press: &press}, "--resume", mine) |
| + if code != 4 || len(c.postsSent()) != 0 { |
| + t.Fatalf("exit %d, posts %q:\n%s", code, c.postsSent(), out) |
| + } |
| + if strings.Contains(out, or28) || strings.Contains(out, "Moving acme.shop.example.com") { |
| + t.Fatalf("promised a rollback of someone else's move:\n%s", out) |
| + } |
| + if out != "acme.shop.example.com's move is "+tMoveID+", not "+mine+". Nothing was sent.\n" { |
| + t.Fatalf("output:\n%s", out) |
| + } |
| + }) |
| +} |