| new file mode 100644 |
| index 000000000..26e3e9a7e |
| --- /dev/null |
| +++ b/internal/edge/replica_drain_e2e_test.go |
| @@ -0,0 +1,304 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/replicas" |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| +) |
| + |
| +// replicaDrainAdmission is a box's tenant admission that its shutdown closes, as |
| +// the activator's is: from then on the box's edge answers every tenant |
| +// request 503 (AdmissionUnavailableResponse). Drill 3's box-2 answered its |
| +// 9 the same way, with the activator's stopped-wake 503. |
| +type replicaDrainAdmission struct{ closed atomic.Bool } |
| + |
| +func (a *replicaDrainAdmission) TenantAdmitted() bool { return !a.closed.Load() } |
| +func (a *replicaDrainAdmission) TenantAdmissionStarting() bool { return false } |
| +func (a *replicaDrainAdmission) CloseTenantAdmission() { a.closed.Store(true) } |
| + |
| +// replicaDrainBox is one fleet box: a real Edge serving shop.example.com from a |
| +// local backend, behind the production tunnel loop with its drain wired |
| +// to the edge's shutdown start, as the agent wires it. |
| +type replicaDrainBox struct { |
| + label string |
| + edge *Edge |
| + admission *replicaDrainAdmission |
| + reached atomic.Int32 // requests that reached the box's edge over the tunnel |
| + backend atomic.Int32 // requests that reached the app |
| + cancel context.CancelFunc |
| + done chan struct{} |
| + finish chan struct{} // releases /slow?id=finish |
| + release sync.Once |
| + inflight chan string // /slow ids that reached the app |
| +} |
| + |
| +func newReplicaDrainBox(t *testing.T, hubURL, label, token string, drains bool) *replicaDrainBox { |
| + t.Helper() |
| + b := &replicaDrainBox{label: label, admission: &replicaDrainAdmission{}, done: make(chan struct{}), finish: make(chan struct{}), inflight: make(chan string, 8)} |
| + app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + b.backend.Add(1) |
| + body, _ := io.ReadAll(r.Body) |
| + if r.URL.Path == "/slow" && label == "box-00" { |
| + id := r.URL.Query().Get("id") |
| + b.inflight <- id |
| + switch id { |
| + case "finish": |
| + <-b.finish |
| + default: |
| + <-r.Context().Done() |
| + return |
| + } |
| + } |
| + io.WriteString(w, label+" "+r.Method+" "+string(body)) |
| + })) |
| + t.Cleanup(app.Close) |
| + // Before the app closes (cleanups run last first): a failed run must |
| + // not leave the parked request holding it open. |
| + t.Cleanup(b.releaseFinish) |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Status: "ready", Addr: strings.TrimPrefix(app.URL, "http://")}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + b.edge = e |
| + WithHAAdmission(b.admission)(e) |
| + drain := make(chan struct{}) |
| + var once sync.Once |
| + WithShutdownStarted(func(time.Time) { once.Do(func() { close(drain) }) })(e) |
| + var loopDrain <-chan struct{} |
| + if drains { |
| + loopDrain = drain |
| + } |
| + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { b.reached.Add(1); e.ServeHTTP(w, r) }) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + b.cancel = cancel |
| + go func() { |
| + defer close(b.done) |
| + tunnelclient.Loop(ctx, tunnelclient.Config{URL: hubURL, Name: "pi/" + label, Token: token, Handler: handler, Drain: loopDrain, |
| + Logf: func(string, ...any) {}}) |
| + }() |
| + t.Cleanup(func() { cancel(); <-b.done }) |
| + return b |
| +} |
| + |
| +// replicaDrainRig is a hub (a real Edge with its tunnel hub on one |
| +// loopback listener) serving a two-copy set of shop.example.com on fleet |
| +// pi, and its two boxes, registered with real fleet credentials. |
| +func replicaDrainRig(t *testing.T, drains bool) (srvURL string, hub *TunnelHub, boxes [2]*replicaDrainBox) { |
| + t.Helper() |
| + reg := openReg(t) |
| + if err := reg.UpsertFleet(registry.Fleet{Name: "pi", Account: "bab", Bucket: "pi-data"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, b := range []string{"box-00", "box-01"} { |
| + if err := reg.AddFleetBox(registry.FleetBox{Fleet: "pi", Label: b, TokenHash: sha256Hex("tok-" + b), Status: "active"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + set := registry.Route{Host: "shop.example.com", Kind: registry.KindForward, Region: "fleet/pi", Account: "bab", App: "shop", Stateless: true, |
| + FleetBoxes: `["box-00","box-01"]`, Copies: 2, ReplicaRevision: 1, ReplicaIncarnation: "life"} |
| + if err := reg.PutForward(set); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + srv := httptest.NewServer(e) |
| + t.Cleanup(srv.Close) |
| + u, err := url.Parse(srv.URL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Setenv("CARLOS_TUNNEL_HOST", u.Hostname()) |
| + t.Setenv("CARLOS_FLEET", "") |
| + hub = NewTunnelHub(u.Hostname(), nil) |
| + e.EnableTunnels(hub) |
| + clock := newReplicaTestClock() |
| + // The copies' health, without a box-side probe endpoint: a copy is |
| + // healthy while its channel can take a stream, as a real probe over |
| + // that channel would find. |
| + e.replicaProbes = newReplicaProber(hub, func(_ context.Context, channel, host string) (replicas.Copy, error) { |
| + if hub.replicaChannelLost(channel) { |
| + return replicas.Copy{}, io.ErrUnexpectedEOF |
| + } |
| + row, err := reg.Get(host) |
| + if err != nil { |
| + return replicas.Copy{}, err |
| + } |
| + return replicaTestCopy(*row, strings.TrimPrefix(channel, "pi/")), nil |
| + }, clock) |
| + t.Cleanup(e.stopReplicaProbes) |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + for i, label := range []string{"box-00", "box-01"} { |
| + boxes[i] = newReplicaDrainBox(t, srv.URL, label, "tok-"+label, drains) |
| + waitForTunnelState(t, hub, "pi/"+label, "connected", 10*time.Second) |
| + } |
| + // The jobs started before the boxes connected; let each find its |
| + // channel and pass twice. |
| + for n := 1; n <= 3; n++ { |
| + clock.advance(time.Second) |
| + } |
| + replicaAwait(t, "both copies live", func() bool { return len(e.replicaProbes.Live("shop.example.com")) == 2 }) |
| + return srv.URL, hub, boxes |
| +} |
| + |
| +// drainDo sends one request for shop.example.com to the hub. |
| +func drainDo(t *testing.T, srvURL, method, path, body string) (int, string) { |
| + t.Helper() |
| + var rd io.Reader |
| + if body != "" { |
| + rd = strings.NewReader(body) |
| + } |
| + req, err := http.NewRequest(method, srvURL+path, rd) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Host = "shop.example.com" |
| + resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req) |
| + if err != nil { |
| + t.Fatalf("%s %s: %v", method, path, err) |
| + } |
| + b, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + return resp.StatusCode, string(b) |
| +} |
| + |
| +// TestReplicaBoxDrainRefusedAtTunnel is R24's witness through the real |
| +// hub and box wiring (hub Edge and TunnelHub, fleet credentials from the |
| +// registry, the production tunnel loop, box Edges): box-00 begins its |
| +// graceful shutdown (edge.beginShutdown: the agent's drain hook, then |
| +// closed tenant admission), and every new request, POSTs included, is |
| +// served by box-01 with zero 503s; none of them reaches box-00's edge. |
| +// Requests box-00 accepted before the drain: one finishes there; one POST |
| +// cut by the box's exit is not repeated; one GET cut the same way is. |
| +// |
| +// Without the drain (drains=false, today's box) the same requests reach |
| +// box-00's closed admission and come back 503, as drill 3's 9 did. |
| +func TestReplicaBoxDrainRefusedAtTunnel(t *testing.T) { |
| + srvURL, hub, boxes := replicaDrainRig(t, true) |
| + b0, b1 := boxes[0], boxes[1] |
| + served := map[string]int{} |
| + for i := 0; i < 4; i++ { |
| + code, body := drainDo(t, srvURL, "GET", "/", "") |
| + if code != 200 { |
| + t.Fatalf("before the drain: %d %q", code, body) |
| + } |
| + served[strings.Fields(body)[0]]++ |
| + } |
| + if served["box-00"] == 0 || served["box-01"] == 0 { |
| + t.Fatalf("both copies did not serve: %v", served) |
| + } |
| + |
| + // Accepted before the drain: three requests parked in box-00's app. |
| + // The hub picks copies in turn, and box-01 answers /slow at once, so |
| + // each is sent until box-00's app has it. |
| + type result struct { |
| + code int |
| + body string |
| + } |
| + results := map[string]chan result{} |
| + for _, c := range []struct{ id, method, body string }{{"finish", "POST", "f"}, {"cut-post", "POST", "c"}, {"cut-get", "GET", ""}} { |
| + for { |
| + ch := make(chan result, 1) |
| + go func(c struct{ id, method, body string }) { |
| + code, body := drainDo(t, srvURL, c.method, "/slow?id="+c.id, c.body) |
| + ch <- result{code, body} |
| + }(c) |
| + select { |
| + case got := <-b0.inflight: |
| + if got != c.id { |
| + t.Fatalf("box-00 got %q, want %q", got, c.id) |
| + } |
| + results[c.id] = ch |
| + case r := <-ch: |
| + if r.code != 200 || !strings.HasPrefix(r.body, "box-01 ") { |
| + t.Fatalf("%s on box-01: %d %q", c.id, r.code, r.body) |
| + } |
| + continue |
| + } |
| + break |
| + } |
| + } |
| + |
| + // box-00 begins its graceful shutdown. |
| + b0.edge.beginShutdown() |
| + replicaAwait(t, "the hub to read box-00's GOAWAY", func() bool { |
| + c := hub.channel("pi/box-00") |
| + return c != nil && c.cc.State().Closing |
| + }) |
| + reachedBefore, b1Before := b0.reached.Load(), b1.backend.Load() |
| + var fives int |
| + for i := 0; i < 20; i++ { |
| + method, body := "POST", "drained" |
| + if i%2 == 1 { |
| + method, body = "GET", "" |
| + } |
| + code, got := drainDo(t, srvURL, method, "/", body) |
| + if code == http.StatusServiceUnavailable { |
| + fives++ |
| + } |
| + if code != 200 || got != "box-01 "+method+" "+body { |
| + t.Errorf("during the drain: %s %d %q, want box-01", method, code, got) |
| + } |
| + } |
| + // TestReplicaBoxDrainRefusedAtTunnel |
| + if fives != 0 || b0.reached.Load() != reachedBefore || b1.backend.Load()-b1Before != 20 { |
| + t.Fatalf("drain: %d 503s, %d new requests reached box-00's edge, box-01 served %d of 20", fives, b0.reached.Load()-reachedBefore, b1.backend.Load()-b1Before) |
| + } |
| + |
| + // The accepted ones: one finishes on box-00, unrepeated. |
| + b0.releaseFinish() |
| + if r := <-results["finish"]; r.code != 200 || r.body != "box-00 POST f" { |
| + t.Fatalf("the accepted request did not finish on box-00: %d %q", r.code, r.body) |
| + } |
| + // box-00's process exits under the other two. |
| + b0.cancel() |
| + <-b0.done |
| + if r := <-results["cut-post"]; r.code != http.StatusBadGateway { |
| + t.Fatalf("an accepted POST cut by the box's exit: %d %q, want 502 and no repeat", r.code, r.body) |
| + } |
| + if r := <-results["cut-get"]; r.code != 200 || r.body != "box-01 GET " { |
| + t.Fatalf("an accepted GET cut by the box's exit: %d %q, want it repeated on box-01", r.code, r.body) |
| + } |
| + if n := b1.backend.Load() - b1Before - 20; n != 1 { |
| + t.Fatalf("box-01's app saw %d repeated requests, want 1 (the GET)", n) |
| + } |
| +} |
| + |
| +// TestReplicaBoxShutdownWithoutDrain is the witness's control: the same |
| +// rig with today's box (no tunnel drain). New requests during box-00's |
| +// shutdown reach its edge and get its 503, which the hub may not retry. |
| +func TestReplicaBoxShutdownWithoutDrain(t *testing.T) { |
| + srvURL, _, boxes := replicaDrainRig(t, false) |
| + boxes[0].edge.beginShutdown() |
| + var fives int |
| + for i := 0; i < 10; i++ { |
| + if code, _ := drainDo(t, srvURL, "POST", "/", "x"); code == http.StatusServiceUnavailable { |
| + fives++ |
| + } |
| + } |
| + if fives == 0 { |
| + t.Fatal("a box shutting down without the drain answered no 503: the control no longer models drill 3") |
| + } |
| +} |
| + |
| +func (b *replicaDrainBox) releaseFinish() { b.release.Do(func() { close(b.finish) }) } |