edge: ingress drain step 1 and step 3, guarded against the HA drain
BeginIngressDrain turns on Connection: close without the barrier. CloseIngress closes edge-held streams, shuts both public servers down within the connection wait, then cuts, counts and joins what is still running, as DrainConnections does at its bound. Each drain refuses while the other is on. Tests use real servers on loopback over HTTP/1 and HTTP/2, including the partial-headers refusal of spec section 3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/edge/edge.go+2 −2internal/edge/hadrainconns.go+28 −8internal/edge/heldstream.go+8 −3internal/edge/ingressdrain.go+140 −0internal/edge/ingressdrain_test.go+511 −0
Intent
<task-notification> <task-id>a0ed24bdf33bcf76f</task-id> <tool-use-id>toolu_01CkiogbFSNSkp2cMFqqFrkz</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a373aecd-faa9-4b83-8736-ff726fb2d3af/tasks/a0ed24bdf33bcf76f.output</output-file> <status>completed</status> <summary>Agent "Implement W6 Tasks 1+2" 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: - c36f69e5 ingresshealth: a self entry with no health is unknown, not dropped (fix round 1) - 180c57dd ingresshealth: target-health reader and AWS adapter for the ingress drain - 7329d323 lbhealth: ingress-drain condition, listed last Fix: the adapter now keeps a registration of this box that has no health data as a new `StateUnknown`, which never counts as withdrawn. Before, it dropped that registration, so self:80 unhealthy plus self:443 with no health plus a healthy peer read as withdrawn. A peer with no health data still does not count as a healthy peer. Tests: a new fake-client test, `TestWithdrawnSelfWithMissingHealthIsUnknown`, sends exactly that mixed response, once with no health and once with an empty state. It failed before the fix and passes now. Both `internal/ingresshealth` packages pass in full, and `go vet` and gofmt are clean. I did not touch `internal/edge`. Concerns: none new. The ones from the first round still stand: the AWS code is in the subpackage `awstg`, a target group with no entry for this box reads as `absent`, and the report is not committed because `.superpowers/` is gitignored. Report (fix round 1 section added): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/w6-build/.superpowers/sdd/2026-11-10-fixed-edge-ingress-drain/task-1-2-report.md</result> <usage><subagent_tokens>108743</subagent_tokens><tool_uses>7</tool_uses><duration_ms>43049</duration_ms></usage> </task-notification>
<task-notification> <task-id>a1a34d61307c3ca38</task-id> <tool-use-id>toolu_01JYJT15FU3tFS9mUZrzQQG5</tool-use-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)" is waiting on its own background work</summary> <note>This agent stopped with background work of its own still running. It may resume on its own when that work completes or reports, and the same task-id notifies again if it does; the result below may be interim.</note> <result>I'll wait for the completion notification.</result> <usage><subagent_tokens>101070</subagent_tokens><tool_uses>22</tool_uses><duration_ms>985853</duration_ms></usage> </task-notification>
<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)" is waiting on its own background work</summary> <note>This agent stopped with background work of its own still running. It may resume on its own when that work completes or reports, and the same task-id notifies again if it does; the result below may be interim.</note> <result>Waiting for that run.</result> <usage><subagent_tokens>103270</subagent_tokens><tool_uses>26</tool_uses><duration_ms>1291591</duration_ms></usage> </task-notification>
<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)" is waiting on its own background work</summary> <note>This agent stopped with background work of its own still running. It may resume on its own when that work completes or reports, and the same task-id notifies again if it does; the result below may be interim.</note> <result>Waiting.</result> <usage><subagent_tokens>104359</subagent_tokens><tool_uses>28</tool_uses><duration_ms>1903700</duration_ms></usage> </task-notification>
Attributed to this commit: 12.3 g CO₂e (1,484,968 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 e247f30db..857590ec6 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -4954,14 +4954,14 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun |
| // :80 serves the ACME HTTP-01 challenge and redirects everything else. |
| go func() { |
| - if err := httpSrv.Serve(httpLn); err != nil && err != http.ErrServerClosed { |
| + if err := httpSrv.Serve(httpLn); listenerFailed(err) { |
| log.Fatalf("edge: http listener %s: %v", *httpAddr, err) |
| } |
| }() |
| go func() { |
| log.Printf("edge: serving %d route(s) on %s (registry %s, acme cache %s)", |
| len(e.current()), *httpsAddr, *registryPath, *acmeCache) |
| - if err := httpsSrv.ServeTLS(httpsLn, "", ""); err != nil && err != http.ErrServerClosed { |
| + if err := httpsSrv.ServeTLS(httpsLn, "", ""); listenerFailed(err) { |
| log.Fatalf("edge: https listener %s: %v", *httpsAddr, err) |
| } |
| }() |
diff --git a/internal/edge/hadrainconns.go b/internal/edge/hadrainconns.go| index e290c3681..4afd4dc91 100644 |
| --- a/internal/edge/hadrainconns.go |
| +++ b/internal/edge/hadrainconns.go |
| @@ -79,10 +79,16 @@ type connDrain struct { |
| draining atomic.Bool |
| mu sync.Mutex |
| // barrier: closed under mu by DrainConnections; a request arriving |
| - // after it is refused, never counted or forwarded. |
| + // after it is refused, never counted or forwarded. It also marks |
| + // §25's drain as on until EndConnectionDrain, for the guard. |
| barrier bool |
| + // ingress: the fixed box's ingress drain is on (W6, ingressdrain.go). |
| + // Set once under mu and never cleared: the stop it is for follows. |
| + ingress bool |
| next uint64 |
| - active map[uint64]trackedRequest |
| + // ended counts the requests that have finished, for step 3's report. |
| + ended uint64 |
| + active map[uint64]trackedRequest |
| // changed is closed and replaced whenever a request ends. |
| changed chan struct{} |
| servers []*http.Server |
| @@ -130,6 +136,7 @@ func (d *connDrain) track(w http.ResponseWriter, r *http.Request) (*http.Request |
| return r.WithContext(ctx), func() { |
| d.mu.Lock() |
| delete(d.active, id) |
| + d.ended++ |
| if d.changed != nil { |
| close(d.changed) |
| d.changed = nil |
| @@ -199,10 +206,15 @@ var ErrDrainNotIdle = errors.New("connection drain: requests are still in flight |
| // the drain fails with ErrDrainNotIdle. |
| // |
| // On success nothing is in flight and nothing new is admitted until |
| -// EndConnectionDrain. |
| +// EndConnectionDrain. It refuses with ErrIngressDrainOn, changing nothing, |
| +// while the ingress drain is on (W6 §4.3). |
| func (e *Edge) DrainConnections(ctx context.Context, bound time.Duration) (int, error) { |
| d := &e.conns |
| d.mu.Lock() |
| + if d.ingress { |
| + d.mu.Unlock() |
| + return 0, ErrIngressDrainOn |
| + } |
| d.barrier = true |
| srvs := append([]*http.Server(nil), d.servers...) |
| d.mu.Unlock() |
| @@ -235,10 +247,16 @@ func (e *Edge) DrainConnections(ctx context.Context, bound time.Duration) (int, |
| // EndConnectionDrain undoes DrainConnections (drain --cancel): the barrier |
| // opens, keep-alives come back and responses no longer close their |
| -// connections. |
| +// connections. While the ingress drain is on it does nothing: the |
| +// guard refused DrainConnections, so there is nothing of §25's to undo, |
| +// and Connection: close and the servers belong to the ingress drain. |
| func (e *Edge) EndConnectionDrain() { |
| d := &e.conns |
| d.mu.Lock() |
| + if d.ingress { |
| + d.mu.Unlock() |
| + return |
| + } |
| d.barrier = false |
| srvs := append([]*http.Server(nil), d.servers...) |
| d.mu.Unlock() |
| @@ -266,12 +284,14 @@ func (e *Edge) CloseHeldHost(host string) { |
| } |
| // closeAllHeld closes every edge-held stream on this edge the same way |
| -// (§25.4 step 4). |
| -func (e *Edge) closeAllHeld() { |
| +// (§25.4 step 4), and returns how many it closed. |
| +func (e *Edge) closeAllHeld() int { |
| if e.held == nil { |
| - return |
| + return 0 |
| } |
| + n := 0 |
| for _, h := range e.held.hosts() { |
| - e.held.closeHost(h) |
| + n += e.held.closeHost(h) |
| } |
| + return n |
| } |
diff --git a/internal/edge/heldstream.go b/internal/edge/heldstream.go| index 9dc9e70fe..213c229dc 100644 |
| --- a/internal/edge/heldstream.go |
| +++ b/internal/edge/heldstream.go |
| @@ -239,13 +239,18 @@ func (s *heldSet) wake(host string) { |
| } |
| // closeHost closes every stream held for host: this edge no longer manages |
| -// it (reload). |
| -func (s *heldSet) closeHost(host string) { |
| +// it (reload). It returns how many it closed that were not closing yet. |
| +func (s *heldSet) closeHost(host string) int { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| + n := 0 |
| for st := range s.byHost[host] { |
| - st.closeOnce.Do(func() { close(st.closeC) }) |
| + st.closeOnce.Do(func() { |
| + close(st.closeC) |
| + n++ |
| + }) |
| } |
| + return n |
| } |
| // hosts lists the hosts with at least one held stream. |
diff --git a/internal/edge/ingressdrain.go b/internal/edge/ingressdrain.go| new file mode 100644 |
| index 000000000..bea155b1c |
| --- /dev/null |
| +++ b/internal/edge/ingressdrain.go |
| @@ -0,0 +1,140 @@ |
| +package edge |
| + |
| +// The fixed box's ingress drain, the edge's half (W6 spec §4.2 steps 1 |
| +// and 3, §4.3): keep serving with Connection: close while the load |
| +// balancer withdraws the box, then close the public listeners gracefully. |
| +// The driver is internal/host's ingress drain; nothing here runs unless |
| +// it asks. It shares connDrain with §25's connection drain (its |
| +// Connection: close switch, its request tracking and bound) but never its |
| +// barrier, and the two refuse each other. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// ErrConnectionDrainOn refuses the ingress drain while §25's connection |
| +// drain is on. |
| +var ErrConnectionDrainOn = errors.New("ingress drain: a region HA connection drain is on") |
| + |
| +// ErrIngressDrainOn refuses §25's connection drain while the ingress |
| +// drain is on. |
| +var ErrIngressDrainOn = errors.New("connection drain: an ingress drain is on") |
| + |
| +// IngressClose is what step 3 did, for the drain's report. |
| +type IngressClose struct { |
| + // HeldClosed: edge-held streams closed at the start of the wait. |
| + HeldClosed int |
| + // Finished: requests that finished during the wait. |
| + Finished int |
| + // Closed: requests still running at the bound, whose contexts were |
| + // cancelled and connections closed. |
| + 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. |
| +func (e *Edge) BeginIngressDrain() error { |
| + d := &e.conns |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + if d.barrier { |
| + return ErrConnectionDrainOn |
| + } |
| + d.ingress = true |
| + d.draining.Store(true) |
| + return nil |
| +} |
| + |
| +// CloseIngress is step 3's edge half: close the public listeners |
| +// gracefully, waiting up to wait (the connection wait). |
| +// |
| +// 1. The edge-held streams still open here are closed at an event |
| +// boundary, so they do not hold the wait. |
| +// 2. Both registered servers are shut down together (http.Server.Shutdown |
| +// with the wait's context): no new connections, idle ones closed, |
| +// 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. |
| +// |
| +// 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 { |
| + 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) |
| + defer wcancel() |
| + var wg sync.WaitGroup |
| + for _, s := range srvs { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + _ = s.Shutdown(wctx) |
| + }() |
| + } |
| + wg.Wait() |
| + idle := d.waitIdle(wctx.Done()) |
| + |
| + 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() |
| + } |
| + } |
| + } |
| + 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. |
| + for _, s := range srvs { |
| + _ = s.Close() |
| + } |
| + if idle { |
| + return out, nil |
| + } |
| + jctx, jcancel := context.WithTimeout(context.Background(), drainJoinBound) |
| + defer jcancel() |
| + if !d.waitIdle(jctx.Done()) { |
| + return out, ErrDrainNotIdle |
| + } |
| + return out, nil |
| +} |
| + |
| +// listenerFailed is whether a public serve loop ended in error. Shutdown |
| +// and Close (step 3, SIGTERM) end it with http.ErrServerClosed, a normal |
| +// exit. |
| +func listenerFailed(err error) bool { |
| + return err != nil && !errors.Is(err, http.ErrServerClosed) |
| +} |
diff --git a/internal/edge/ingressdrain_test.go b/internal/edge/ingressdrain_test.go| new file mode 100644 |
| index 000000000..8ebf4cc7b |
| --- /dev/null |
| +++ b/internal/edge/ingressdrain_test.go |
| @@ -0,0 +1,511 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "crypto/ecdsa" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "crypto/x509/pkix" |
| + "errors" |
| + "io" |
| + "math/big" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/http/httptrace" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// loopbackCert is a self-signed certificate for 127.0.0.1 and the pool |
| +// that trusts it. |
| +func loopbackCert(t *testing.T) (tls.Certificate, *x509.CertPool) { |
| + t.Helper() |
| + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tmpl := &x509.Certificate{ |
| + SerialNumber: big.NewInt(1), |
| + Subject: pkix.Name{CommonName: "127.0.0.1"}, |
| + IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)}, |
| + NotBefore: time.Now().Add(-time.Hour), |
| + NotAfter: time.Now().Add(time.Hour), |
| + KeyUsage: x509.KeyUsageDigitalSignature, |
| + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, |
| + BasicConstraintsValid: true, |
| + IsCA: true, |
| + } |
| + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + leaf, err := x509.ParseCertificate(der) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pool := x509.NewCertPool() |
| + pool.AddCert(leaf) |
| + 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. |
| +type ingressEdge struct { |
| + e *Edge |
| + https, http *http.Server |
| + httpsAddr string |
| + httpAddr string |
| + pool *x509.CertPool |
| + httpsErr, httpErr chan error |
| +} |
| + |
| +func newIngressEdge(t *testing.T, e *Edge, h http.HandlerFunc) *ingressEdge { |
| + t.Helper() |
| + cert, pool := loopbackCert(t) |
| + tracked := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + r, done, ok := e.conns.track(w, r) |
| + if !ok { |
| + handoverExit(w, r, answerHolderUnreachable) |
| + return |
| + } |
| + defer done() |
| + h(w, r) |
| + }) |
| + 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}, |
| + pool: pool, |
| + httpsErr: make(chan error, 1), |
| + httpErr: make(chan error, 1), |
| + } |
| + httpsLn, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + httpLn, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ie.httpsAddr, ie.httpAddr = httpsLn.Addr().String(), httpLn.Addr().String() |
| + e.conns.serve(ie.https, ie.http) |
| + go func() { ie.httpErr <- ie.http.Serve(httpLn) }() |
| + go func() { ie.httpsErr <- ie.https.ServeTLS(httpsLn, "", "") }() |
| + t.Cleanup(func() { |
| + _ = ie.https.Close() |
| + _ = ie.http.Close() |
| + }) |
| + return ie |
| +} |
| + |
| +// client is an HTTPS client speaking HTTP/2 (h2) or only HTTP/1.1. |
| +func (ie *ingressEdge) client(t *testing.T, h2 bool) *http.Client { |
| + t.Helper() |
| + tr := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: ie.pool}, ForceAttemptHTTP2: h2} |
| + if !h2 { |
| + tr.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{} |
| + } |
| + t.Cleanup(tr.CloseIdleConnections) |
| + return &http.Client{Transport: tr} |
| +} |
| + |
| +func (ie *ingressEdge) get(t *testing.T, c *http.Client, path string) *http.Response { |
| + t.Helper() |
| + resp, err := c.Get("https://" + ie.httpsAddr + path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return resp |
| +} |
| + |
| +type closeResult struct { |
| + out IngressClose |
| + err error |
| + in time.Duration |
| +} |
| + |
| +func (ie *ingressEdge) closeIngress(wait time.Duration) chan closeResult { |
| + done := make(chan closeResult, 1) |
| + go func() { |
| + start := time.Now() |
| + out, err := ie.e.CloseIngress(context.Background(), wait) |
| + done <- closeResult{out, err, time.Since(start)} |
| + }() |
| + return done |
| +} |
| + |
| +// listenersClosed waits until a new connection to :443 is refused: step 3 |
| +// has begun. |
| +func (ie *ingressEdge) listenersClosed(t *testing.T) { |
| + t.Helper() |
| + waitFor(t, 2*time.Second, "the listener to close", func() bool { |
| + c, err := net.DialTimeout("tcp", ie.httpsAddr, 100*time.Millisecond) |
| + if err != nil { |
| + return true |
| + } |
| + c.Close() |
| + return false |
| + }) |
| +} |
| + |
| +// Step 1: the health check fails elsewhere; here every response says |
| +// Connection: close and nothing is refused (no barrier), on HTTP/1 and |
| +// HTTP/2 alike. |
| +func TestBeginIngressDrainServesWithConnectionClose(t *testing.T) { |
| + e := &Edge{} |
| + var served atomic.Int32 |
| + ie := newIngressEdge(t, e, func(w http.ResponseWriter, r *http.Request) { |
| + served.Add(1) |
| + io.WriteString(w, "ok") |
| + }) |
| + h1, h2 := ie.client(t, false), ie.client(t, true) |
| + resp := ie.get(t, h1, "/") |
| + resp.Body.Close() |
| + if resp.StatusCode != 200 || resp.Close { |
| + t.Fatalf("before the drain: %d, close %v", resp.StatusCode, resp.Close) |
| + } |
| + if err := e.BeginIngressDrain(); err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < 2; i++ { |
| + resp = ie.get(t, h1, "/") |
| + body, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if resp.StatusCode != 200 || !resp.Close || string(body) != "ok" { |
| + t.Fatalf("HTTP/1 during step 1: %d %q, close %v", resp.StatusCode, body, resp.Close) |
| + } |
| + resp = ie.get(t, h2, "/") |
| + body, _ = io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if resp.StatusCode != 200 || resp.ProtoMajor != 2 || string(body) != "ok" { |
| + t.Fatalf("HTTP/2 during step 1: %d %s %q", resp.StatusCode, resp.Proto, body) |
| + } |
| + } |
| + e.conns.mu.Lock() |
| + barrier := e.conns.barrier |
| + e.conns.mu.Unlock() |
| + if barrier || served.Load() != 5 { |
| + t.Fatalf("barrier %v, served %d of 5", barrier, served.Load()) |
| + } |
| + if err := e.BeginIngressDrain(); err != nil { |
| + t.Fatalf("a second step 1: %v", err) |
| + } |
| +} |
| + |
| +// The guard (§4.3): neither drain starts while the other is on. |
| +func TestIngressDrainAndConnectionDrainRefuseEachOther(t *testing.T) { |
| + e := &Edge{} |
| + ie := newIngressEdge(t, e, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok") }) |
| + h1 := ie.client(t, false) |
| + |
| + if _, err := e.DrainConnections(context.Background(), time.Second); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.BeginIngressDrain(); !errors.Is(err, ErrConnectionDrainOn) { |
| + t.Fatalf("step 1 during a connection drain: %v", err) |
| + } |
| + if _, err := e.CloseIngress(context.Background(), time.Second); !errors.Is(err, ErrConnectionDrainOn) { |
| + t.Fatalf("step 3 during a connection drain: %v", err) |
| + } |
| + e.EndConnectionDrain() |
| + resp := ie.get(t, h1, "/") |
| + resp.Body.Close() |
| + if resp.StatusCode != 200 || resp.Close { |
| + t.Fatalf("after the connection drain: %d, close %v", resp.StatusCode, resp.Close) |
| + } |
| + |
| + if err := e.BeginIngressDrain(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n, err := e.DrainConnections(context.Background(), time.Second); n != 0 || !errors.Is(err, ErrIngressDrainOn) { |
| + t.Fatalf("a connection drain during an ingress drain: %d %v", n, err) |
| + } |
| + // The refused drain set nothing, and undoing it (a cancelled §25 |
| + // drain) does not undo the ingress drain's Connection: close. |
| + e.EndConnectionDrain() |
| + resp = ie.get(t, h1, "/") |
| + resp.Body.Close() |
| + if resp.StatusCode != 200 || !resp.Close { |
| + t.Fatalf("after the refusal: %d, close %v", resp.StatusCode, resp.Close) |
| + } |
| +} |
| + |
| +// Step 3: an HTTP/1 request in flight and an HTTP/2 stream already open |
| +// both complete; the HTTP/2 client gets GOAWAY and its next request opens |
| +// a new connection (refused here: the listener is closed); nothing is |
| +// cut; the serve loops end with http.ErrServerClosed, which edge.go's |
| +// loops treat as a normal exit; and the SIGTERM shutdown that follows |
| +// returns at once. |
| +func TestCloseIngressFinishesWhatIsInFlight(t *testing.T) { |
| + e := &Edge{} |
| + release := make(chan struct{}) |
| + ie := newIngressEdge(t, e, func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path == "/slow" { |
| + <-release |
| + } |
| + io.WriteString(w, "done "+r.Proto) |
| + }) |
| + h1, h2 := ie.client(t, false), ie.client(t, true) |
| + type got struct { |
| + body string |
| + err error |
| + } |
| + start := func(c *http.Client) chan got { |
| + ch := make(chan got, 1) |
| + go func() { |
| + resp, err := c.Get("https://" + ie.httpsAddr + "/slow") |
| + 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 |
| + } |
| + r1, r2 := start(h1), start(h2) |
| + waitInFlight(t, e, 2) |
| + if err := e.BeginIngressDrain(); err != nil { |
| + t.Fatal(err) |
| + } |
| + done := ie.closeIngress(10 * time.Second) |
| + ie.listenersClosed(t) |
| + |
| + // GOAWAY: the HTTP/2 client stops using its connection, so a new |
| + // request dials (and is refused) rather than riding the old one. |
| + waitFor(t, 2*time.Second, "an HTTP/2 request on a new connection", func() bool { |
| + var dialed atomic.Bool |
| + ctx := httptrace.WithClientTrace(context.Background(), &httptrace.ClientTrace{ |
| + ConnectStart: func(string, string) { dialed.Store(true) }, |
| + }) |
| + req, _ := http.NewRequestWithContext(ctx, "GET", "https://"+ie.httpsAddr+"/quick", nil) |
| + if resp, err := h2.Do(req); err == nil { |
| + resp.Body.Close() |
| + } |
| + return dialed.Load() |
| + }) |
| + |
| + select { |
| + case r := <-done: |
| + t.Fatalf("step 3 returned with requests in flight: %+v", r) |
| + case <-time.After(100 * time.Millisecond): |
| + } |
| + close(release) |
| + if g := <-r1; g.err != nil || g.body != "done HTTP/1.1" { |
| + t.Fatalf("HTTP/1 in flight: %+v", g) |
| + } |
| + if g := <-r2; g.err != nil || g.body != "done HTTP/2.0" { |
| + t.Fatalf("HTTP/2 in flight: %+v", g) |
| + } |
| + r := <-done |
| + if r.err != nil || r.out.Closed != 0 || r.out.Finished < 2 || r.in > 5*time.Second { |
| + t.Fatalf("step 3: %+v", r) |
| + } |
| + for name, ch := range map[string]chan error{"https": ie.httpsErr, "http": ie.httpErr} { |
| + select { |
| + case err := <-ch: |
| + if !errors.Is(err, http.ErrServerClosed) || listenerFailed(err) { |
| + t.Fatalf("%s serve loop ended with %v", name, err) |
| + } |
| + case <-time.After(time.Second): |
| + t.Fatalf("%s serve loop still running", name) |
| + } |
| + } |
| + |
| + // The SIGTERM path in edge.go, unchanged: its 10 s Shutdown finds the |
| + // servers already shut. |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + sigterm := time.Now() |
| + if err := ie.https.Shutdown(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := ie.http.Shutdown(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if d := time.Since(sigterm); d > 500*time.Millisecond { |
| + t.Fatalf("the SIGTERM shutdown took %s", d) |
| + } |
| +} |
| + |
| +// listenerFailed is the serve loops' fatal test; any other error is. |
| +func TestListenerFailed(t *testing.T) { |
| + if listenerFailed(nil) || listenerFailed(http.ErrServerClosed) || !listenerFailed(errors.New("accept: boom")) { |
| + t.Fatal("listenerFailed") |
| + } |
| +} |
| + |
| +// The refusal in §3, pinned: a connection accepted before step 3 whose |
| +// request headers have not all arrived is closed by Go's Shutdown without |
| +// an answer (net/http treats it as idle 5 s after it was accepted), before |
| +// the bound and without being counted. A Go upgrade that changes this |
| +// fails here. |
| +func TestCloseIngressClosesPartialHeadersWithoutAnAnswer(t *testing.T) { |
| + if testing.Short() { |
| + t.Skip("waits for net/http's 5 s new-connection rule") |
| + } |
| + e := &Edge{} |
| + var served atomic.Int32 |
| + ie := newIngressEdge(t, e, func(w http.ResponseWriter, r *http.Request) { |
| + served.Add(1) |
| + io.WriteString(w, "ok") |
| + }) |
| + c, err := tls.Dial("tcp", ie.httpsAddr, &tls.Config{RootCAs: ie.pool, NextProtos: []string{"http/1.1"}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer c.Close() |
| + if _, err := io.WriteString(c, "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n"); err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(50 * time.Millisecond) // the server reads the partial headers |
| + if err := e.BeginIngressDrain(); err != nil { |
| + t.Fatal(err) |
| + } |
| + done := ie.closeIngress(20 * time.Second) |
| + ie.listenersClosed(t) |
| + _ = c.SetReadDeadline(time.Now().Add(15 * time.Second)) |
| + got, err := io.ReadAll(c) |
| + if err != nil || len(got) != 0 { |
| + t.Fatalf("the client read %q, %v; want the connection closed without an answer", got, err) |
| + } |
| + r := <-done |
| + if r.err != nil || r.out.Closed != 0 || r.in > 15*time.Second || served.Load() != 0 { |
| + t.Fatalf("step 3: %+v, served %d", r, served.Load()) |
| + } |
| +} |
| + |
| +// At the bound: a streaming response (a proxied SSE stream) and a |
| +// hijacked connection (a WebSocket) are not singled out early; they run |
| +// until the bound, then are cancelled, their connections closed, counted |
| +// and joined. |
| +func TestCloseIngressCutsLongResponsesAtTheBound(t *testing.T) { |
| + e := &Edge{} |
| + cancelled := make(chan struct{}, 1) |
| + ie := newIngressEdge(t, e, func(w http.ResponseWriter, r *http.Request) { |
| + switch r.URL.Path { |
| + case "/sse": |
| + w.Header().Set("Content-Type", "text/event-stream") |
| + w.WriteHeader(200) |
| + io.WriteString(w, "data: one\n\n") |
| + w.(http.Flusher).Flush() |
| + <-r.Context().Done() |
| + cancelled <- struct{}{} |
| + case "/ws": |
| + conn, brw, err := http.NewResponseController(w).Hijack() |
| + if err != nil { |
| + t.Errorf("hijack: %v", err) |
| + return |
| + } |
| + defer conn.Close() |
| + brw.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") |
| + brw.Flush() |
| + _, _ = io.Copy(io.Discard, conn) // ends when the drain closes the connection |
| + } |
| + }) |
| + sse := ie.get(t, ie.client(t, true), "/sse") |
| + defer sse.Body.Close() |
| + ws, err := tls.Dial("tcp", ie.httpsAddr, &tls.Config{RootCAs: ie.pool, NextProtos: []string{"http/1.1"}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ws.Close() |
| + io.WriteString(ws, "GET /ws HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n") |
| + waitInFlight(t, e, 2) |
| + |
| + const wait = 400 * time.Millisecond |
| + r := <-ie.closeIngress(wait) |
| + if r.err != nil || r.out.Closed != 2 || r.out.Finished != 0 { |
| + t.Fatalf("step 3: %+v; want 2 cut and joined", r) |
| + } |
| + if r.in < wait { |
| + t.Fatalf("step 3 cut them after %s, before the %s bound", r.in, wait) |
| + } |
| + select { |
| + case <-cancelled: |
| + case <-time.After(time.Second): |
| + t.Fatal("the streaming handler's context was not cancelled") |
| + } |
| + if _, err := readFor(sse.Body, time.Second); err == nil { |
| + t.Fatal("the stream did not end") |
| + } |
| + _ = ws.SetReadDeadline(time.Now().Add(time.Second)) |
| + if _, err := io.ReadAll(ws); err != nil { |
| + t.Fatalf("the hijacked connection: %v", err) |
| + } |
| + if e.InFlight() != 0 { |
| + t.Fatal("step 3 returned with a request in flight") |
| + } |
| +} |
| + |
| +// A handler that ignores its context and its connection cannot be joined: |
| +// step 3 reports it, it never reports zero. |
| +func TestCloseIngressFailsWhenZeroIsNotReached(t *testing.T) { |
| + prev := drainJoinBound |
| + drainJoinBound = 100 * time.Millisecond |
| + defer func() { drainJoinBound = prev }() |
| + e := &Edge{} |
| + stuck := make(chan struct{}) |
| + defer close(stuck) |
| + ie := newIngressEdge(t, e, func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(200) |
| + w.(http.Flusher).Flush() |
| + <-stuck |
| + }) |
| + resp := ie.get(t, ie.client(t, false), "/stuck") |
| + defer resp.Body.Close() |
| + waitInFlight(t, e, 1) |
| + r := <-ie.closeIngress(50 * time.Millisecond) |
| + if r.out.Closed != 1 || !errors.Is(r.err, ErrDrainNotIdle) { |
| + t.Fatalf("step 3: %+v; want ErrDrainNotIdle", r) |
| + } |
| +} |
| + |
| +// Edge-held SSE streams are closed at the start of the wait, at an event |
| +// boundary, so they do not hold step 3 to its bound. |
| +func TestCloseIngressClosesHeldStreams(t *testing.T) { |
| + h := newHeldHarness(t, heldTestConfig(), func(int, http.ResponseWriter, *http.Request) {}) |
| + h.act.asleep.Store(true) |
| + rt := registry.Route{Host: heldTestHost} |
| + h.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + r, done, ok := h.e.conns.track(w, r) |
| + if !ok { |
| + handoverExit(w, r, answerHolderUnreachable) |
| + return |
| + } |
| + defer done() |
| + h.e.serveHeld(w, r, rt, h.proxy) |
| + })) |
| + h.e.conns.serve(h.srv.Config) |
| + h.start(t) |
| + resp := h.get(t, "/live?carlos_hold=1", nil) |
| + waitFor(t, time.Second, "held", func() bool { return len(h.e.held.hosts()) == 1 }) |
| + start := time.Now() |
| + out, err := h.e.CloseIngress(context.Background(), 10*time.Second) |
| + if err != nil || out.HeldClosed != 1 || out.Closed != 0 || out.Finished != 1 || time.Since(start) > 5*time.Second { |
| + t.Fatalf("step 3: %+v %v after %s", out, err, time.Since(start)) |
| + } |
| + if _, err := readFor(resp.Body, time.Second); err != io.EOF && !strings.Contains(errString(err), "closed") { |
| + t.Fatalf("held stream did not end: %v", err) |
| + } |
| + if r := <-h.ends; r != heldCloseUnmanaged { |
| + t.Fatalf("close reason %v", r) |
| + } |
| +} |
| + |
| +func errString(err error) string { |
| + if err == nil { |
| + return "" |
| + } |
| + return err.Error() |
| +} |