carlos / platform Public

edge: :80 joins the ingress drain; HA drain transitions under one lock

Port 80's handler (ACME challenge and redirect) is now tracked in its own
connDrain, which only the ingress drain uses: Connection: close in step
1, counted, cut and joined in step 3, never under the HA barrier. Both
public servers come from publicServers, which the tests share.
EndConnectionDrain and DrainConnections now change their state under the
mutex that ingress start holds, so a cancellation cannot undo a new
ingress drain.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f37152dec9b12c995c86256292203c59e2da5af8 parent fd382cd
4 files changed, +246 −67
  • internal/edge/edge.go +5 −5
  • internal/edge/hadrainconns.go +31 −15
  • internal/edge/ingressdrain.go +81 −41
  • internal/edge/ingressdrain_test.go +129 −6

Intent

Human

<task-notification> <task-id>a1a34d61307c3ca38</task-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a373aecd-faa9-4b83-8736-ff726fb2d3af/tasks/a1a34d61307c3ca38.output</output-file> <status>completed</status> <summary>Agent "Implement W6 Task 3 (edge)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE **Commits:** `fd382cd8` edge: ingress drain step 1 and step 3, guarded against the HA drain **Tests:** All 8 new tests pass (including a `-race` run over the drain tests), along with the full `internal/edge` package (850 s), `internal/host -run Drain`, the darwin and windows builds, and gofmt. I did not run the full `internal/host` package to completion: it hit go test's 10-minute default timeout. Host code is unchanged. **Concerns:** - The `:80` handler doesn't go through `connDrain.track`, so step 1's `Connection: close` only reaches `:443`, while spec §4.2 says "every response". I left it, because routing it through would also put `:80` under §25's barrier. Step 3 still shuts `:80` down gracefully. The reviewer should decide if "every" is meant literally. - A connection with partial headers holds `Shutdown` for about 5 s. That is Go's rule for connections that haven't sent a full first request. It is then closed without an answer, as §3 says, and the pinned test takes about 5.8 s (skipped under `-short`). - I made `EndConnectionDrain` do nothing while an ingress drain is on, so cancelling a refused §25 drain can't turn off `Connection: close`. There is no way to end an ingress drain, since the spec doesn't define a cancel. - `.superpowers/` is gitignored, so the report is written but not committed. **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/w6-build/.superpowers/sdd/2026-11-10-fixed-edge-ingress-drain/task-3-report.md</result> <usage><subagent_tokens>107912</subagent_tokens><tool_uses>33</tool_uses><duration_ms>2790303</duration_ms></usage> </task-notification>

Attributed to this commit: 7.09 g CO₂e (905,466 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on w6-ingress-drain, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 857590ec6..b903800c1 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -382,6 +382,9 @@ type Edge struct {
// conns is the planned-handover connection drain (hadrainconns.go,
// region HA §25.4 step 4): every request ServeHTTP serves, counted.
conns connDrain
+ // plain tracks :80's requests for the fixed box's ingress drain only
+ // (ingressdrain.go); §25's connection drain never touches it.
+ plain connDrain
// certs is the certificate mirror newCertMirror built, which control
// requests choose their TLS name from (hadrain.go).
certs atomic.Pointer[certMirror]
@@ -4924,11 +4927,8 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
acmeAndFallback = mirror.challengeHandler(acmeAndFallback)
}
- // ReadHeaderTimeout guards the public front door against Slowloris-style
- // slow-header connection exhaustion. No ReadTimeout/WriteTimeout — those
- // would break long-lived proxied WebSockets.
- httpSrv := &http.Server{Addr: *httpAddr, Handler: acmeAndFallback, ReadHeaderTimeout: 10 * time.Second}
- httpsSrv := &http.Server{Addr: *httpsAddr, Handler: e, TLSConfig: tlsCfg, ReadHeaderTimeout: 10 * time.Second}
+ // :80 is tracked for the ingress drain (publicServers, ingressdrain.go).
+ httpsSrv, httpSrv := e.publicServers(e, acmeAndFallback, tlsCfg, *httpAddr, *httpsAddr)
// Bind both before serving either, on this goroutine, as ListenAndServe
// and ListenAndServeTLS do internally (empty flags become :http and
diff --git a/internal/edge/hadrainconns.go b/internal/edge/hadrainconns.go
index 4afd4dc91..4b1cb0548 100644
--- a/internal/edge/hadrainconns.go
+++ b/internal/edge/hadrainconns.go
@@ -185,6 +185,20 @@ func (d *connDrain) waitIdle(done <-chan struct{}) bool {
}
}
+// cut ends every request still in flight: its context is cancelled and
+// its connection closed (a hijacked one included). It returns how many.
+func (d *connDrain) cut() int {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ for _, t := range d.active {
+ t.cancel()
+ if t.conn != nil {
+ _ = t.conn.Close()
+ }
+ }
+ return len(d.active)
+}
+
// ErrDrainNotIdle is a connection drain that could not establish zero
// requests in flight: handlers still running after their contexts were
// cancelled and their connections closed.
@@ -215,28 +229,21 @@ func (e *Edge) DrainConnections(ctx context.Context, bound time.Duration) (int,
d.mu.Unlock()
return 0, ErrIngressDrainOn
}
+ // Under mu, as EndConnectionDrain's transition is: a cancellation
+ // cannot interleave with it.
d.barrier = true
- srvs := append([]*http.Server(nil), d.servers...)
- d.mu.Unlock()
d.draining.Store(true)
- for _, s := range srvs {
+ for _, s := range d.servers {
s.SetKeepAlivesEnabled(false)
}
+ d.mu.Unlock()
e.closeAllHeld()
wctx, wcancel := context.WithTimeout(ctx, bound)
defer wcancel()
if d.waitIdle(wctx.Done()) {
return 0, nil
}
- d.mu.Lock()
- n := len(d.active)
- for _, t := range d.active {
- t.cancel()
- if t.conn != nil {
- _ = t.conn.Close()
- }
- }
- d.mu.Unlock()
+ n := d.cut()
jctx, jcancel := context.WithTimeout(context.Background(), drainJoinBound)
defer jcancel()
if !d.waitIdle(jctx.Done()) {
@@ -257,15 +264,24 @@ func (e *Edge) EndConnectionDrain() {
d.mu.Unlock()
return
}
+ // The whole transition happens under mu, so an ingress drain cannot
+ // start between the barrier opening and Connection: close turning
+ // off, and then have its Connection: close undone.
d.barrier = false
- srvs := append([]*http.Server(nil), d.servers...)
- d.mu.Unlock()
+ if endConnectionDrainGap != nil {
+ endConnectionDrainGap()
+ }
d.draining.Store(false)
- for _, s := range srvs {
+ for _, s := range d.servers {
s.SetKeepAlivesEnabled(true)
}
+ d.mu.Unlock()
}
+// endConnectionDrainGap is a test seam inside EndConnectionDrain's
+// transition.
+var endConnectionDrainGap func()
+
// InFlight is the requests ServeHTTP is serving now.
func (e *Edge) InFlight() int {
e.conns.mu.Lock()
diff --git a/internal/edge/ingressdrain.go b/internal/edge/ingressdrain.go
index bea155b1c..319eed315 100644
--- a/internal/edge/ingressdrain.go
+++ b/internal/edge/ingressdrain.go
@@ -10,6 +10,7 @@ package edge
import (
"context"
+ "crypto/tls"
"errors"
"net/http"
"sync"
@@ -35,24 +36,58 @@ type IngressClose struct {
Closed int
}
-// BeginIngressDrain is step 1's edge half: from now every response says
-// Connection: close, so each HTTP/1 connection carries at most one more
-// request and HTTP/2 connections get a graceful GOAWAY. Nothing is
-// refused (no barrier) and keep-alives are left alone (§25 owns them).
-// The health answer is failed elsewhere (lbhealth). Calling it again does
-// nothing more.
+// BeginIngressDrain is step 1's edge half: from now every response on
+// both public listeners says Connection: close, so each HTTP/1 connection
+// carries at most one more request and HTTP/2 connections get a graceful
+// GOAWAY. Nothing is refused (no barrier) and keep-alives are left alone
+// (§25 owns them). The health answer is failed elsewhere (lbhealth).
+// Calling it again does nothing more.
func (e *Edge) BeginIngressDrain() error {
d := &e.conns
d.mu.Lock()
defer d.mu.Unlock()
- if d.barrier {
+ return e.startIngressLocked()
+}
+
+// startIngressLocked turns the ingress drain on, under e.conns.mu: the
+// same lock §25's transitions hold, so neither interleaves with the other.
+func (e *Edge) startIngressLocked() error {
+ if e.conns.barrier {
return ErrConnectionDrainOn
}
- d.ingress = true
- d.draining.Store(true)
+ e.conns.ingress = true
+ e.conns.draining.Store(true)
+ e.plain.draining.Store(true)
return nil
}
+// plainTracked wraps :80's handler (the ACME HTTP-01 challenge and the
+// redirect) in e.plain, so its requests take part in the ingress drain:
+// Connection: close in step 1, counted, cut and joined in step 3. e.plain
+// is never §25's: its barrier is never closed, so nothing is refused here
+// and DrainConnections neither waits for nor counts :80.
+func (e *Edge) plainTracked(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ r, done, _ := e.plain.track(w, r)
+ defer done()
+ h.ServeHTTP(w, r)
+ })
+}
+
+// publicServers builds the edge's two public servers: :443 serving
+// https (the edge itself in production) and :80 serving challenge
+// through plainTracked. The caller registers both with e.conns.serve
+// after any other ConnContext (the hairpin) is set.
+//
+// ReadHeaderTimeout guards the public front door against Slowloris-style
+// slow-header connection exhaustion. No ReadTimeout/WriteTimeout: those
+// would break long-lived proxied WebSockets.
+func (e *Edge) publicServers(https, challenge http.Handler, tlsCfg *tls.Config, httpAddr, httpsAddr string) (httpsSrv, httpSrv *http.Server) {
+ httpSrv = &http.Server{Addr: httpAddr, Handler: e.plainTracked(challenge), ReadHeaderTimeout: 10 * time.Second}
+ httpsSrv = &http.Server{Addr: httpsAddr, Handler: https, TLSConfig: tlsCfg, ReadHeaderTimeout: 10 * time.Second}
+ return httpsSrv, httpSrv
+}
+
// CloseIngress is step 3's edge half: close the public listeners
// gracefully, waiting up to wait (the connection wait).
//
@@ -63,30 +98,33 @@ func (e *Edge) BeginIngressDrain() error {
// GOAWAY on HTTP/2, dispatched requests waited for. A connection whose
// request headers are incomplete is closed without an answer (§3's
// refusal, Go's behaviour).
-// 3. It then waits, within the same bound, for the tracked requests
-// Shutdown does not wait for (hijacked connections such as WebSockets).
-// Long responses are not singled out early.
-// 4. At the bound, or when ctx ends, what is still running is cancelled
-// and its connection closed, as DrainConnections does, and both
-// servers are closed; then the cut requests are joined within
-// drainJoinBound, or it fails with ErrDrainNotIdle.
+// 3. It then waits, within the same bound, for the tracked requests on
+// both listeners that Shutdown does not wait for (hijacked connections
+// such as WebSockets). Long responses are not singled out early.
+// 4. At the bound, or when ctx ends, what is still running on either
+// listener is cancelled and its connection closed, as DrainConnections
+// does, and both servers are closed; then the cut requests are joined
+// within drainJoinBound, or it fails with ErrDrainNotIdle.
//
// It starts the ingress drain if BeginIngressDrain has not, and refuses
// with ErrConnectionDrainOn while §25's drain is on. The SIGTERM shutdown
// that follows finds both servers shut and returns at once.
func (e *Edge) CloseIngress(ctx context.Context, wait time.Duration) (IngressClose, error) {
var out IngressClose
- d := &e.conns
- d.mu.Lock()
- if d.barrier {
+ e.conns.mu.Lock()
+ if err := e.startIngressLocked(); err != nil {
+ e.conns.mu.Unlock()
+ return out, err
+ }
+ srvs := append([]*http.Server(nil), e.conns.servers...)
+ e.conns.mu.Unlock()
+ listeners := []*connDrain{&e.conns, &e.plain}
+ endedBefore := make([]uint64, len(listeners))
+ for i, d := range listeners {
+ d.mu.Lock()
+ endedBefore[i] = d.ended
d.mu.Unlock()
- return out, ErrConnectionDrainOn
}
- d.ingress = true
- d.draining.Store(true)
- srvs := append([]*http.Server(nil), d.servers...)
- endedBefore := d.ended
- d.mu.Unlock()
out.HeldClosed = e.closeAllHeld()
wctx, wcancel := context.WithTimeout(ctx, wait)
@@ -100,24 +138,24 @@ func (e *Edge) CloseIngress(ctx context.Context, wait time.Duration) (IngressClo
}()
}
wg.Wait()
- idle := d.waitIdle(wctx.Done())
+ idle := true
+ for _, d := range listeners {
+ if !d.waitIdle(wctx.Done()) {
+ idle = false
+ }
+ }
- d.mu.Lock()
- out.Finished = int(d.ended - endedBefore)
- if !idle {
- out.Closed = len(d.active)
- for _, t := range d.active {
- t.cancel()
- if t.conn != nil {
- _ = t.conn.Close()
- }
+ for i, d := range listeners {
+ d.mu.Lock()
+ out.Finished += int(d.ended - endedBefore[i])
+ d.mu.Unlock()
+ if !idle {
+ out.Closed += d.cut()
}
}
- d.mu.Unlock()
// Connections Shutdown was still waiting for at the bound that carry
- // no tracked request (headers still arriving, :80's challenge and
- // redirect handler) close here. After a Shutdown that finished this
- // closes nothing.
+ // no tracked request (headers still arriving) close here. After a
+ // Shutdown that finished this closes nothing.
for _, s := range srvs {
_ = s.Close()
}
@@ -126,8 +164,10 @@ func (e *Edge) CloseIngress(ctx context.Context, wait time.Duration) (IngressClo
}
jctx, jcancel := context.WithTimeout(context.Background(), drainJoinBound)
defer jcancel()
- if !d.waitIdle(jctx.Done()) {
- return out, ErrDrainNotIdle
+ for _, d := range listeners {
+ if !d.waitIdle(jctx.Done()) {
+ return out, ErrDrainNotIdle
+ }
}
return out, nil
}
diff --git a/internal/edge/ingressdrain_test.go b/internal/edge/ingressdrain_test.go
index 8ebf4cc7b..8304ee6e1 100644
--- a/internal/edge/ingressdrain_test.go
+++ b/internal/edge/ingressdrain_test.go
@@ -55,10 +55,12 @@ func loopbackCert(t *testing.T) (tls.Certificate, *x509.CertPool) {
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: leaf}, pool
}
-// ingressEdge is the edge's two public servers as edge.go runs them: real
-// http.Servers on loopback listeners, :443 over TLS with HTTP/2, each
-// handler going through the connection drain as ServeHTTP does, both
-// registered with connDrain.serve, and each serve loop's error kept.
+// ingressEdge is the edge's two public servers as edge.go builds them
+// (publicServers): real http.Servers on loopback listeners, :443 over TLS
+// with HTTP/2 and its handler going through the connection drain as
+// ServeHTTP does, :80 serving the challenge handler through the
+// production wrapper, both registered with connDrain.serve, and each
+// serve loop's error kept.
type ingressEdge struct {
e *Edge
https, http *http.Server
@@ -69,6 +71,13 @@ type ingressEdge struct {
}
func newIngressEdge(t *testing.T, e *Edge, h http.HandlerFunc) *ingressEdge {
+ t.Helper()
+ return newIngressEdgeWith(t, e, h, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "redirect")
+ }))
+}
+
+func newIngressEdgeWith(t *testing.T, e *Edge, h http.HandlerFunc, challenge http.Handler) *ingressEdge {
t.Helper()
cert, pool := loopbackCert(t)
tracked := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -80,10 +89,11 @@ func newIngressEdge(t *testing.T, e *Edge, h http.HandlerFunc) *ingressEdge {
defer done()
h(w, r)
})
+ httpsSrv, httpSrv := e.publicServers(tracked, challenge, &tls.Config{Certificates: []tls.Certificate{cert}}, "", "")
ie := &ingressEdge{
e: e,
- https: &http.Server{Handler: tracked, TLSConfig: &tls.Config{Certificates: []tls.Certificate{cert}}, ReadHeaderTimeout: 10 * time.Second},
- http: &http.Server{Handler: tracked, ReadHeaderTimeout: 10 * time.Second},
+ https: httpsSrv,
+ http: httpSrv,
pool: pool,
httpsErr: make(chan error, 1),
httpErr: make(chan error, 1),
@@ -509,3 +519,116 @@ func errString(err error) string {
}
return err.Error()
}
+
+// A §25 cancellation racing a new ingress drain cannot undo it: once
+// BeginIngressDrain succeeds, Connection: close stays on. The seam opens
+// EndConnectionDrain's transition and starts the ingress drain inside it.
+func TestEndConnectionDrainCannotUndoANewIngressDrain(t *testing.T) {
+ e := &Edge{}
+ if _, err := e.DrainConnections(context.Background(), time.Second); err != nil {
+ t.Fatal(err)
+ }
+ began := make(chan error, 1)
+ endConnectionDrainGap = func() {
+ go func() { began <- e.BeginIngressDrain() }()
+ time.Sleep(50 * time.Millisecond)
+ }
+ defer func() { endConnectionDrainGap = nil }()
+ e.EndConnectionDrain()
+ if err := <-began; err != nil {
+ t.Fatalf("the ingress drain after the cancellation: %v", err)
+ }
+ if !e.conns.draining.Load() {
+ t.Fatal("the cancellation undid the ingress drain's Connection: close")
+ }
+}
+
+// :80 takes part in the ingress drain through the production wiring
+// (publicServers), and never in §25's barrier: during a §25 drain it is
+// not refused; during step 1 its answers say Connection: close;
+// at step 3 a challenge still running at the bound is cut, counted and
+// joined, and one that finishes in the wait is counted as finished.
+func TestPlainListenerTakesPartInTheIngressDrainOnly(t *testing.T) {
+ e := &Edge{}
+ entered := make(chan struct{}, 2)
+ release := make(chan struct{})
+ ie := newIngressEdgeWith(t, e, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok") },
+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/.well-known/acme-challenge/stuck":
+ entered <- struct{}{}
+ <-r.Context().Done()
+ case "/.well-known/acme-challenge/slow":
+ entered <- struct{}{}
+ <-release
+ }
+ io.WriteString(w, "challenge")
+ }))
+ get := func(path string) (*http.Response, error) {
+ return (&http.Client{Transport: &http.Transport{}}).Get("http://" + ie.httpAddr + path)
+ }
+
+ // §25's drain leaves :80 alone.
+ if _, err := e.DrainConnections(context.Background(), time.Second); err != nil {
+ t.Fatal(err)
+ }
+ resp, err := get("/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ // Not refused (its keep-alives are off, as they have been since §25:
+ // that is not the barrier).
+ if resp.StatusCode != 200 {
+ t.Fatalf(":80 during a connection drain: %d", resp.StatusCode)
+ }
+ e.EndConnectionDrain()
+
+ if err := e.BeginIngressDrain(); err != nil {
+ t.Fatal(err)
+ }
+ resp, err = get("/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != 200 || !resp.Close {
+ t.Fatalf(":80 during step 1: %d, close %v", resp.StatusCode, resp.Close)
+ }
+
+ type got struct {
+ body string
+ err error
+ }
+ start := func(path string) chan got {
+ ch := make(chan got, 1)
+ go func() {
+ resp, err := get(path)
+ if err != nil {
+ ch <- got{err: err}
+ return
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(resp.Body)
+ ch <- got{string(b), err}
+ }()
+ return ch
+ }
+ stuck, slow := start("/.well-known/acme-challenge/stuck"), start("/.well-known/acme-challenge/slow")
+ <-entered
+ <-entered
+ const wait = 400 * time.Millisecond
+ done := ie.closeIngress(wait)
+ ie.listenersClosed(t)
+ close(release)
+ if g := <-slow; g.err != nil || g.body != "challenge" {
+ t.Fatalf("the challenge that finished in the wait: %+v", g)
+ }
+ r := <-done
+ if r.err != nil || r.out.Closed != 1 || r.out.Finished != 1 || r.in < wait {
+ t.Fatalf("step 3: %+v; want the stuck challenge cut and joined at the bound", r)
+ }
+ if g := <-stuck; g.err == nil && g.body == "challenge" {
+ t.Fatalf("the stuck challenge was answered: %+v", g)
+ }
+}