carlos / platform Public

edge: end the app dial hold on drain or outside stop (#511 R27)

Review round 2's P1: a gap request the activator still proxies waited in
dialGenUntil's 13 s hold, which watched neither the drain nor an outside
stop. Drill 3's box exited about 1.15 s after SIGTERM, so
refuseUnreachedApp never ran and a gap POST got 502.

dialGenUntil and waitServingGen now end their hold for a fleet tunnel
stream nothing was written to (tunnelclient.Refusable) at once when its
box's drain closes (they wait on tunnelclient.DrainSignal), or within a
dial step when the host's app is known stopped from outside the
activator (holdEnded). The request fails with no app byte written, and
refuseUnreachedApp refuses it with REFUSED_STREAM. Every other request
holds as before.

Fable minor: the gate no longer registers the id of a stream the hub has
already reset; the server drops that RST, so the id would have stayed
in the map until the connection ended.

Witnesses through the real genRoundTripper and dial path:
TestReplicaDialHoldEndsAndRefuses (app stops, a POST and a GET wait in
the hold, the drain or an outside stop ends it at once, both served by
the survivor; without the change both time out about 9.7 s later) and
TestReplicaDialWrittenIsNotRefused (a POST written to the app is
answered 502 and never repeated).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 649f0cd08a0561daaacd6fc159cbf1cfc24f4a51 parent 29ec028
3 files changed, +214 −8
  • internal/edge/genproxy.go +34 −1
  • internal/edge/replica_drain_e2e_test.go +156 −6
  • internal/tunnelclient/refuse.go +24 −1
diff --git a/internal/edge/genproxy.go b/internal/edge/genproxy.go
index 68e9dd688..395ec7e09 100644
--- a/internal/edge/genproxy.go
+++ b/internal/edge/genproxy.go
@@ -14,6 +14,7 @@ import (
"syscall"
"time"
+ "github.com/carlosframework/platform/internal/tunnelclient"
"github.com/carlosframework/platform/internal/unixdial"
)
@@ -82,6 +83,7 @@ func dialGen(ctx context.Context, d *net.Dialer, src GenSource, host string, own
// and each wait is min(100ms, time left); an attempt the deadline cut
// short gives errHoldExpired.
func dialGenUntil(ctx context.Context, deadline time.Time, d *net.Dialer, src GenSource, host string, own GenInfo) (net.Conn, error) {
+ drained := tunnelclient.DrainSignal(ctx)
for {
actx, cancel := context.WithDeadline(ctx, deadline)
conn, err := unixdial.Checked(actx, d, own.Socket)
@@ -121,9 +123,15 @@ func dialGenUntil(ctx context.Context, deadline time.Time, d *net.Dialer, src Ge
if cur, ok := src.ServingGen(host); ok && (cur.N != own.N || cur.Socket != own.Socket) {
return nil, &genMovedError{to: cur}
}
+ if holdEnded(ctx, src, host) {
+ return nil, err
+ }
select {
case <-ctx.Done():
return nil, ctx.Err()
+ case <-drained:
+ // The box began shutting down: the hold ends now (holdEnded).
+ return nil, err
case <-time.After(min(localDialStep, left)):
}
if !time.Now().Before(deadline) {
@@ -348,21 +356,46 @@ func (t *genRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
// host to have a current generation, asking every 100 ms.
func waitServingGen(ctx context.Context, src GenSource, host string) (GenInfo, bool) {
deadline := time.Now().Add(localDialHold)
+ drained := tunnelclient.DrainSignal(ctx)
for {
if g, ok := src.ServingGen(host); ok {
return g, true
}
- if time.Now().After(deadline) {
+ if time.Now().After(deadline) || holdEnded(ctx, src, host) {
return GenInfo{}, false
}
select {
case <-ctx.Done():
return GenInfo{}, false
+ case <-drained:
+ return GenInfo{}, false
case <-time.After(100 * time.Millisecond):
}
}
}
+// holdEnded reports whether a hold waiting for host's app (dialGenUntil's
+// dial retries, waitServingGen's wait for a generation) must end now
+// rather than at localDialHold (#511 R27, review round 2): ctx is a fleet
+// tunnel stream nothing has been written to, and its box's tunnel drain
+// has begun or host's app was stopped from outside the activator
+// (src's StoppedOutside). The hold ends at once on the drain (both holds
+// also wait on its signal) and within one step on an outside stop. The
+// request then fails with nothing written to the app, and
+// refuseUnreachedApp refuses it unprocessed, so the hub serves it from
+// another copy: drill 3's box exited about 1.15 s after its SIGTERM, well
+// inside the 13 s hold. Any other request holds as before.
+func holdEnded(ctx context.Context, src GenSource, host string) bool {
+ if !tunnelclient.Refusable(ctx) {
+ return false
+ }
+ if tunnelclient.Draining(ctx) {
+ return true
+ }
+ so, ok := src.(interface{ StoppedOutside(string) bool })
+ return ok && so.StoppedOutside(host)
+}
+
// heldBody is a request body the transport cannot consume or close before
// the request is on a connection. The transport reads a body only while it
// writes the request on a dialled connection, and closes it on any error,
diff --git a/internal/edge/replica_drain_e2e_test.go b/internal/edge/replica_drain_e2e_test.go
index dace05bff..f3af50a7b 100644
--- a/internal/edge/replica_drain_e2e_test.go
+++ b/internal/edge/replica_drain_e2e_test.go
@@ -46,10 +46,20 @@ type replicaDrainBox struct {
inflight chan string // /slow ids that reached the app
}
-func newReplicaDrainBox(t *testing.T, hubURL, label, token string, drains bool, act *replicaGapActivator) *replicaDrainBox {
+func newReplicaDrainBox(t *testing.T, hubURL, label, token string, drains bool, act *replicaGapActivator, genAct *replicaGenActivator) *replicaDrainBox {
t.Helper()
b := &replicaDrainBox{label: label, admission: &replicaDrainAdmission{}, done: make(chan struct{}), finish: make(chan struct{}), inflight: make(chan string, 8)}
appHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/written" && label == "box-00" {
+ // The app reads the request, then drops the connection
+ // without an answer (TestReplicaDialWrittenIsNotRefused).
+ io.ReadAll(r.Body)
+ b.backend.Add(1)
+ if conn, _, err := w.(http.Hijacker).Hijack(); err == nil {
+ conn.Close()
+ }
+ return
+ }
b.backend.Add(1)
body, _ := io.ReadAll(r.Body)
if r.URL.Path == "/slow" && label == "box-00" {
@@ -68,7 +78,17 @@ func newReplicaDrainBox(t *testing.T, hubURL, label, token string, drains bool,
reg := openReg(t)
var e *Edge
var err error
- if act == nil {
+ if genAct != nil {
+ // An instance with generations on: the edge reaches it through
+ // appSocketProxy, the real genRoundTripper and dial hold.
+ sock := filepath.Join(genSockDir(t), "g1.sock")
+ genAct.app = startGenApp(t, sock, appHandler)
+ genAct.switchTo("shop.example.com", GenInfo{Socket: sock, N: 1, Build: "v1"})
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "instance", Status: "ready", Account: "bab", App: "shop", Stateless: true, Socket: sock}); err != nil {
+ t.Fatal(err)
+ }
+ e, err = New(reg, genAct)
+ } else if act == nil {
app := httptest.NewServer(appHandler)
t.Cleanup(app.Close)
if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Status: "ready", Addr: strings.TrimPrefix(app.URL, "http://")}); err != nil {
@@ -142,6 +162,7 @@ func replicaDrainRig(t *testing.T, drains bool) (srvURL string, hub *TunnelHub,
type drainRigOpts struct {
drains, holdGoAway bool
act *replicaGapActivator
+ genAct *replicaGenActivator
}
type drainRig struct {
@@ -214,10 +235,11 @@ func newReplicaDrainRig(t *testing.T, opts drainRigOpts) *drainRig {
}
for i, label := range []string{"box-00", "box-01"} {
var act *replicaGapActivator
+ var genAct *replicaGenActivator
if i == 0 {
- act = opts.act
+ act, genAct = opts.act, opts.genAct
}
- rig.boxes[i] = newReplicaDrainBox(t, srv.URL, label, "tok-"+label, opts.drains, act)
+ rig.boxes[i] = newReplicaDrainBox(t, srv.URL, label, "tok-"+label, opts.drains, act, genAct)
waitForTunnelState(t, hub, "pi/"+label, "connected", 10*time.Second)
}
// The jobs started before the boxes connected; let each find its
@@ -548,8 +570,26 @@ type drainResult struct {
func drainAsync(t *testing.T, srvURL, method, path, body string) <-chan drainResult {
ch := make(chan drainResult, 1)
go func() {
- code, got := drainDo(t, srvURL, method, path, body)
- ch <- drainResult{method, body, code, got}
+ // No t.Fatal off the test's goroutine: a failed request is a
+ // result with code 0 and the error as its text.
+ var rd io.Reader
+ if body != "" {
+ rd = strings.NewReader(body)
+ }
+ req, err := http.NewRequest(method, srvURL+path, rd)
+ if err != nil {
+ ch <- drainResult{method, body, 0, err.Error()}
+ return
+ }
+ req.Host = "shop.example.com"
+ resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req)
+ if err != nil {
+ ch <- drainResult{method, body, 0, err.Error()}
+ return
+ }
+ b, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ ch <- drainResult{method, body, resp.StatusCode, string(b)}
}()
return ch
}
@@ -685,3 +725,113 @@ func TestReplicaGapRequestsServedBySurvivor(t *testing.T) {
t.Fatalf("box-00 refused %d, answered %d, its app saw %d gap requests; want 3, 0, 0", act.refused.Load(), act.answered.Load(), b0.backend.Load()-appBefore)
}
}
+
+// replicaGenActivator stands in for a box's activator while it still
+// proxies (#511 R27, review round 2): it passes every request to the
+// edge's proxy, which for an instance with generations on is the real
+// appSocketProxy, genRoundTripper and dial hold, over the fake generation
+// source it embeds; and it answers StoppedOutside as the test says.
+type replicaGenActivator struct {
+ *fakeGens
+ app *genApp
+ outside atomic.Bool
+}
+
+func newReplicaGenActivator() *replicaGenActivator {
+ return &replicaGenActivator{fakeGens: newFakeGens(true)}
+}
+
+func (a *replicaGenActivator) ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) bool {
+ proxy.ServeHTTP(w, r)
+ return true
+}
+func (a *replicaGenActivator) RetireExcept(map[string]bool) {}
+func (a *replicaGenActivator) AdmitHeldLeg(context.Context, registry.Route) (HeldLeg, error) {
+ return nil, io.EOF
+}
+func (a *replicaGenActivator) HeldAdmissible(string) bool { return false }
+func (a *replicaGenActivator) SetHeldWakeHook(func(string)) {}
+func (a *replicaGenActivator) StoppedOutside(string) bool { return a.outside.Load() }
+
+// TestReplicaDialHoldEndsAndRefuses is R27's app-proxy witness (review
+// round 2) through the real genRoundTripper and dial path on box-00:
+// systemd stops box-00's app, while the activator still has its
+// generation current, so a gap POST and a gap GET wait in dialGenUntil's
+// 13 s hold. The hold ends at once when the box's drain closes (or, in the
+// second case, as soon as the app is known stopped from outside), the
+// requests are refused with REFUSED_STREAM (refuseUnreachedApp: no app
+// byte written), and the hub serves both from box-01: zero failures, well
+// inside the hold.
+func TestReplicaDialHoldEndsAndRefuses(t *testing.T) {
+ for _, trigger := range []string{"drain", "stopped outside"} {
+ t.Run(trigger, func(t *testing.T) {
+ genAct := newReplicaGenActivator()
+ r := newReplicaDrainRig(t, drainRigOpts{drains: true, genAct: genAct})
+ b0 := r.boxes[0]
+ served := map[string]int{}
+ for i := 0; i < 4; i++ {
+ code, body := drainDo(t, r.url, "GET", "/", "")
+ if code != 200 {
+ t.Fatalf("before the stop: %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)
+ }
+ appBefore := b0.backend.Load()
+ genAct.app.stop()
+ base := b0.reached.Load()
+ gap := []<-chan drainResult{
+ parkOn(t, r.url, "POST", "/", "order", func() bool { return b0.reached.Load() >= base+1 }),
+ parkOn(t, r.url, "GET", "/", "", func() bool { return b0.reached.Load() >= base+2 }),
+ }
+ // Both are in box-00's dial hold now.
+ time.Sleep(300 * time.Millisecond)
+ start := time.Now()
+ switch trigger {
+ case "drain":
+ b0.edge.beginShutdown()
+ case "stopped outside":
+ genAct.outside.Store(true)
+ }
+ for _, ch := range gap {
+ res := <-ch
+ // TestReplicaDialHoldEndsAndRefuses
+ if res.code != 200 || res.got != "box-01 "+res.method+" "+res.body {
+ t.Errorf("%s: a gap request: %s %d %q, want box-01's answer", trigger, res.method, res.code, res.got)
+ }
+ }
+ if took := time.Since(start); took > 2*time.Second {
+ t.Fatalf("%s: the hold ended %s after the trigger, want at once (the hold is %s)", trigger, took, localDialHold)
+ }
+ if b0.backend.Load() != appBefore {
+ t.Fatal("box-00's app saw a gap request")
+ }
+ })
+ }
+}
+
+// TestReplicaDialWrittenIsNotRefused is the negative: once the request was
+// written to the app (here the app reads it and drops the connection
+// without an answer), box-00 answers its 502 and nothing is refused or
+// repeated, even with its app stopped from outside.
+func TestReplicaDialWrittenIsNotRefused(t *testing.T) {
+ genAct := newReplicaGenActivator()
+ r := newReplicaDrainRig(t, drainRigOpts{drains: true, genAct: genAct})
+ b0, b1 := r.boxes[0], r.boxes[1]
+ genAct.outside.Store(true)
+ for i := 0; i < 10; i++ {
+ b1Before := b1.backend.Load()
+ code, got := drainDo(t, r.url, "POST", "/written", "x")
+ if strings.HasPrefix(got, "box-01 ") {
+ continue
+ }
+ // TestReplicaDialWrittenIsNotRefused
+ if code != http.StatusBadGateway || b1.backend.Load() != b1Before || b0.backend.Load() == 0 {
+ t.Fatalf("a POST written to box-00's app: %d %q, box-01 saw %d, box-00's app saw %d", code, got, b1.backend.Load()-b1Before, b0.backend.Load())
+ }
+ return
+ }
+ t.Fatal("no POST reached box-00")
+}
diff --git a/internal/tunnelclient/refuse.go b/internal/tunnelclient/refuse.go
index d55911bfd..3a1d26371 100644
--- a/internal/tunnelclient/refuse.go
+++ b/internal/tunnelclient/refuse.go
@@ -138,6 +138,24 @@ func Draining(ctx context.Context) bool {
return ref != nil && closed(ref.drain)
}
+// Refusable reports whether ctx is a fleet tunnel stream's request that
+// Refuse could still refuse: nothing has been written to it.
+func Refusable(ctx context.Context) bool {
+ ref, _ := ctx.Value(refusalKey{}).(*refusal)
+ return ref != nil && !ref.w.wrote.Load()
+}
+
+// DrainSignal is the drain of ctx's fleet tunnel stream: it closes when
+// the box's tunnel drain begins. nil, which never closes, off a fleet
+// tunnel stream.
+func DrainSignal(ctx context.Context) <-chan struct{} {
+ ref, _ := ctx.Value(refusalKey{}).(*refusal)
+ if ref == nil {
+ return nil
+ }
+ return ref.drain
+}
+
// streamGate is the outermost handler of a fleet tunnel's streams. Once
// the drain has begun, a stream whose handler starts is refused before
// the wrapped handler (the upgrade shim, the box's edge, its activator,
@@ -165,7 +183,12 @@ func (g streamGate) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ref := &refusal{drain: g.drain, w: tw}
g.h.ServeHTTP(tw, r.WithContext(context.WithValue(r.Context(), refusalKey{}, ref)))
if ref.refused.Load() && !tw.wrote.Load() {
- g.conn.refuse(id)
+ // A stream the hub has already reset is closed on the server,
+ // which then drops this handler's RST: registering its id would
+ // only leave it in the map until the connection ends.
+ if r.Context().Err() == nil {
+ g.conn.refuse(id)
+ }
panic(http.ErrAbortHandler)
}
}