carlos / platform Public

edge-roll-blip: D10, loopback TCP routes hold the dial

A route whose upstream is a loopback TCP addr (or localhost) now retries a
refused dial for up to 13s (localDialHold) instead of answering 502 at once,
so a restarting local process is waited for. Settings live per Edge
(localHold, newEdge); hold.dial <= 0 keeps today's transport. Non-local
addrs keep the instant 502.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 0d6dc49381b8e5fa997e551ecc152a5eb3ad06fa parent e6ad40a
7 files changed, +527 −25
  • internal/edge/answered.go +6 −4
  • internal/edge/edge.go +36 −9
  • internal/edge/edge_test.go +12 −6
  • internal/edge/edgeerrors_test.go +1 −1
  • internal/edge/localhold.go +95 −0
  • internal/edge/localhold_test.go +365 −0
  • internal/host/applessroute_test.go +12 −5
diff --git a/internal/edge/answered.go b/internal/edge/answered.go
index 8a6c6ee8b..bba7ec852 100644
--- a/internal/edge/answered.go
+++ b/internal/edge/answered.go
@@ -58,10 +58,12 @@ const causeClientGone = "client_gone"
// clientGoneGrace is how long a client may wait before its leaving stops
// being its own business. Past it the wait is the finding: a dead unix
-// socket is redialled for 13s (dialUnixWithRetry) and a wedged instance is
-// never timed out at all, so a monitor or a visitor that gives up first is
-// the only way those outages end — and filing nothing for them would hide
-// exactly the worst ones (apperr.CauseAbandoned).
+// socket, a refused loopback TCP upstream and a probed route with a local
+// upstream are all held for 13s or more (dialUnixWithRetry, retryLocalDial)
+// and a wedged instance is never timed out at all, so a monitor or a
+// visitor that gives up first is the only way those outages end — and
+// filing nothing for them would hide exactly the worst ones
+// (apperr.CauseAbandoned).
var clientGoneGrace = 5 * time.Second // a var only so a test can shorten it
// withOutcome returns r carrying a fresh outcome and the outcome itself.
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 28a421f0c..2c0e65445 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -97,7 +97,10 @@ type Activator interface {
// its backend. The host→backend map is swapped atomically, so reloads and
// zero-downtime deploys never drop a live connection.
type Edge struct {
- reg *registry.Registry
+ reg *registry.Registry
+ // hold is this Edge's local-upstream hold settings (localhold.go), set
+ // before the startup Reload and read by it.
+ hold localHold
upstreams atomic.Pointer[map[string]upstream]
// act, when non-nil, is the hibernation activator: hibernate-flagged
// instance routes stop being always-on backends and become on-demand
@@ -455,7 +458,13 @@ type upstream struct {
// New builds an Edge over reg and performs the startup reload. act may be nil
// (no hibernation).
func New(reg *registry.Registry, act Activator) (*Edge, error) {
- e := &Edge{reg: reg, act: act, gate: gate.New(), probers: newProberSet(), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(),
+ return newEdge(reg, act, defaultLocalHold())
+}
+
+// newEdge is New with the local-upstream hold settings given, so a test can
+// shorten or turn off a hold on its own Edge without touching a global.
+func newEdge(reg *registry.Registry, act Activator, hold localHold) (*Edge, error) {
+ e := &Edge{reg: reg, act: act, hold: hold, gate: gate.New(), probers: newProberSet(), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(),
lbHealth: lbHealthFromEnv(os.Getenv, act), rateMode: rateModeFromEnv(), rateLimiter: ratelimit.NewLimiter(time.Now, 100_000),
planLimiter: ratelimit.NewLimiter(time.Now, 100_000)}
e.geo = geo.NewSwappable()
@@ -848,7 +857,7 @@ func (e *Edge) Reload() error {
var p *httputil.ReverseProxy
switch {
case t.Health == "":
- p = tcpProxy(addrs[0])
+ p = tcpProxy(addrs[0], e.hold)
default:
var h provision.Health
if err := json.Unmarshal([]byte(t.Health), &h); err != nil {
@@ -861,7 +870,7 @@ func (e *Edge) Reload() error {
// as long as it exists.
e.logThrottled("health-parse "+t.Host, fmt.Sprintf(
"route %s: unparseable health config (%v) — serving %s unprobed", t.Host, err, addrs[0]))
- p = tcpProxy(addrs[0])
+ p = tcpProxy(addrs[0], e.hold)
break
}
// Raw parse, deliberately un-normalized: Sync runs every spec
@@ -2733,7 +2742,28 @@ func unixProxy(socketPath string) *httputil.ReverseProxy {
// tcpProxy reverse-proxies to a TCP upstream at http://addr with the same
// Host preservation and idle bounds as unixProxy — this is what lets
// whole-app tenants sit behind the edge without unix-socket support.
-func tcpProxy(addr string) *httputil.ReverseProxy {
+//
+// A loopback upstream is this box's own process, so a refused dial there is
+// a restart in progress: the dial is retried for hold.dial (one deadline
+// fixed per dial) instead of 502ing at once. hold.dial <= 0, or a remote
+// addr, keeps the stock dialer (hold.dialer is nil in production).
+func tcpProxy(addr string, hold localHold) *httputil.ReverseProxy {
+ tr := &http.Transport{
+ MaxIdleConns: 32,
+ IdleConnTimeout: 90 * time.Second,
+ DialContext: hold.dialer,
+ }
+ if hold.dial > 0 && isLocalUpstream(addr) {
+ dial := hold.dialer
+ if dial == nil {
+ dial = (&net.Dialer{}).DialContext
+ }
+ tr.DialContext = func(ctx context.Context, network, a string) (net.Conn, error) {
+ return retryLocalDial(ctx, time.Now().Add(hold.dial), func(actx context.Context) (net.Conn, error) {
+ return dial(actx, network, a)
+ })
+ }
+ }
return &httputil.ReverseProxy{
Rewrite: func(pr *httputil.ProxyRequest) {
setForwarded(pr)
@@ -2743,10 +2773,7 @@ func tcpProxy(addr string) *httputil.ReverseProxy {
pr.Out.Host = pr.In.Host // backend sees the real hostname
scrubInboundPurgeHeader(pr)
},
- Transport: &http.Transport{
- MaxIdleConns: 32,
- IdleConnTimeout: 90 * time.Second,
- },
+ Transport: tr,
ErrorHandler: defaultProxyError(proxyCause),
}
}
diff --git a/internal/edge/edge_test.go b/internal/edge/edge_test.go
index 89c2f5278..5e1b50b8f 100644
--- a/internal/edge/edge_test.go
+++ b/internal/edge/edge_test.go
@@ -1919,7 +1919,7 @@ func TestLegacySingleAddrRouteUnchanged(t *testing.T) {
t.Fatalf("upsert: %v", err)
}
- e, err := New(reg, nil)
+ e, err := newEdge(reg, nil, noHold())
if err != nil {
t.Fatalf("New: %v", err)
}
@@ -1990,7 +1990,15 @@ func TestReloadSwapsUpstreamSet(t *testing.T) {
// whatever it reads with tag so a test can tell WHICH upstream served it.
func upgradeEchoBackend(t *testing.T, tag string) string {
t.Helper()
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ ts := httptest.NewServer(upgradeEchoHandler(tag))
+ t.Cleanup(ts.Close)
+ return ts.Listener.Addr().String()
+}
+
+// upgradeEchoHandler is upgradeEchoBackend's handler, for a test that
+// starts its own listener.
+func upgradeEchoHandler(tag string) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == testProbePath {
w.WriteHeader(http.StatusOK)
return
@@ -2015,9 +2023,7 @@ func upgradeEchoBackend(t *testing.T, tag string) string {
}
buf.WriteString(tag + ":" + line)
buf.Flush()
- }))
- t.Cleanup(ts.Close)
- return ts.Listener.Addr().String()
+ })
}
// TestMultiUpstreamServesWebSocketUpgrade guards the one thing multiProxy's
@@ -2151,7 +2157,7 @@ func TestMultiAddrWithoutHealthServesFirstUnprobed(t *testing.T) {
t.Fatalf("upsert: %v", err)
}
- e, err := New(reg, nil)
+ e, err := newEdge(reg, nil, noHold())
if err != nil {
t.Fatalf("New: %v", err)
}
diff --git a/internal/edge/edgeerrors_test.go b/internal/edge/edgeerrors_test.go
index 2f98961e1..59a51b261 100644
--- a/internal/edge/edgeerrors_test.go
+++ b/internal/edge/edgeerrors_test.go
@@ -198,7 +198,7 @@ func TestEdgeFilesUnavailableByCause(t *testing.T) {
t.Fatal(err)
}
}
- e, err := New(reg, nil)
+ e, err := newEdge(reg, nil, noHold())
if err != nil {
t.Fatal(err)
}
diff --git a/internal/edge/localhold.go b/internal/edge/localhold.go
new file mode 100644
index 000000000..af647dea6
--- /dev/null
+++ b/internal/edge/localhold.go
@@ -0,0 +1,95 @@
+package edge
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "net/netip"
+ "time"
+)
+
+// localDialHold is how long a request waits for a local upstream that is
+// restarting: the unix-socket redial window (it exceeds a deploy's
+// socket-absent gap), now shared by loopback TCP routes.
+const localDialHold = 13 * time.Second
+
+// localHoldCap bounds the whole hold of a probed route with a local
+// upstream (dial plus readmission). It equals the ordinary wake wait.
+const localHoldCap = 30 * time.Second
+
+// localHold is one Edge's hold settings. They live on the Edge, not in
+// package globals, so tests that shorten them cannot see each other.
+type localHold struct {
+ dial, cap, probe time.Duration
+ // dialer is a test seam; nil means a plain net.Dialer.
+ dialer func(ctx context.Context, network, addr string) (net.Conn, error)
+}
+
+// defaultLocalHold is what New gives every Edge.
+func defaultLocalHold() localHold {
+ return localHold{dial: localDialHold, cap: localHoldCap, probe: probeTimeout}
+}
+
+// isLocalUpstream reports whether addr (host:port) names this box's own
+// loopback: a loopback IP literal or "localhost". A refused dial there is
+// a restart in progress; a refused remote box is an outage.
+func isLocalUpstream(addr string) bool {
+ host, _, err := net.SplitHostPort(addr)
+ if err != nil {
+ return false
+ }
+ if host == "localhost" {
+ return true
+ }
+ ip, err := netip.ParseAddr(host)
+ return err == nil && ip.IsLoopback()
+}
+
+// errHoldExpired is what retryLocalDial returns when the deadline cut an
+// attempt that had not failed on its own. It wraps DeadlineExceeded so
+// proxyCause files it as a timeout.
+var errHoldExpired = fmt.Errorf("edge: local upstream hold expired: %w", context.DeadlineExceeded)
+
+// localDialStep is the pause between attempts.
+const localDialStep = 100 * time.Millisecond
+
+// retryLocalDial calls attempt until it connects, fails in a way that
+// cannot heal (not isRetryableDialErr), or deadline passes. The caller
+// fixes deadline once, before the first attempt. Each attempt runs on a
+// context that ends at deadline and each wait is min(100ms, time left), so
+// nothing outlives the hold. It always makes the first attempt. At the
+// deadline it returns the last retryable error; an attempt the deadline cut
+// short gives errHoldExpired. A cancelled ctx returns ctx's error.
+func retryLocalDial(ctx context.Context, deadline time.Time, attempt func(context.Context) (net.Conn, error)) (net.Conn, error) {
+ for {
+ actx, cancel := context.WithDeadline(ctx, deadline)
+ conn, err := attempt(actx)
+ cut := actx.Err() != nil // read before cancel, which would also set it
+ cancel()
+ if err == nil {
+ return conn, nil
+ }
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ retryable := isRetryableDialErr(err)
+ if cut && !retryable {
+ return nil, errHoldExpired
+ }
+ if !retryable {
+ return nil, err
+ }
+ left := time.Until(deadline)
+ if left <= 0 {
+ return nil, err
+ }
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-time.After(min(localDialStep, left)):
+ }
+ if !time.Now().Before(deadline) {
+ return nil, err
+ }
+ }
+}
diff --git a/internal/edge/localhold_test.go b/internal/edge/localhold_test.go
new file mode 100644
index 000000000..09fb5378d
--- /dev/null
+++ b/internal/edge/localhold_test.go
@@ -0,0 +1,365 @@
+package edge
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "runtime"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/apperr"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// noHold is D10 off: today's transport, an instant 502 on a refused loopback
+// dial. Tests whose point is the failure itself build their Edge on it.
+func noHold() localHold { return localHold{probe: probeTimeout} }
+
+// refusedErr is what a dial to a port nobody listens on returns.
+func refusedErr() error {
+ return &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
+}
+
+func TestIsLocalUpstream(t *testing.T) {
+ for _, a := range []string{"127.0.0.1:80", "127.9.9.9:80", "[::1]:80", "localhost:80"} {
+ if !isLocalUpstream(a) {
+ t.Errorf("isLocalUpstream(%q) = false, want true", a)
+ }
+ }
+ for _, a := range []string{"10.0.0.5:80", "example.com:80", "nonsense"} {
+ if isLocalUpstream(a) {
+ t.Errorf("isLocalUpstream(%q) = true, want false", a)
+ }
+ }
+}
+
+func TestRetryLocalDialServesWhenUpstreamReturns(t *testing.T) {
+ a, b := net.Pipe()
+ defer a.Close()
+ defer b.Close()
+ var calls int
+ conn, err := retryLocalDial(context.Background(), time.Now().Add(5*time.Second),
+ func(context.Context) (net.Conn, error) {
+ calls++
+ if calls <= 2 {
+ return nil, refusedErr()
+ }
+ return a, nil
+ })
+ if err != nil {
+ t.Fatalf("retryLocalDial: %v", err)
+ }
+ if conn != a || calls != 3 {
+ t.Fatalf("conn ok = %v, calls = %d, want the pipe end after 3 attempts", conn == a, calls)
+ }
+}
+
+func TestRetryLocalDialReturnsLastRefusalAtDeadline(t *testing.T) {
+ start := time.Now()
+ _, err := retryLocalDial(context.Background(), start.Add(300*time.Millisecond),
+ func(context.Context) (net.Conn, error) { return nil, refusedErr() })
+ el := time.Since(start)
+ if !errors.Is(err, syscall.ECONNREFUSED) {
+ t.Fatalf("err = %v, want the last refusal", err)
+ }
+ if errors.Is(err, errHoldExpired) {
+ t.Fatalf("err = %v, a refusal at the deadline is not errHoldExpired", err)
+ }
+ if el < 300*time.Millisecond || el >= 450*time.Millisecond {
+ t.Fatalf("elapsed = %v, want in [300ms, 450ms)", el)
+ }
+}
+
+func TestRetryLocalDialBlockingAttemptEndsAtDeadline(t *testing.T) {
+ start := time.Now()
+ _, err := retryLocalDial(context.Background(), start.Add(200*time.Millisecond),
+ func(actx context.Context) (net.Conn, error) {
+ <-actx.Done()
+ return nil, actx.Err()
+ })
+ el := time.Since(start)
+ if !errors.Is(err, errHoldExpired) || !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("err = %v, want errHoldExpired wrapping DeadlineExceeded", err)
+ }
+ if el >= 300*time.Millisecond {
+ t.Fatalf("elapsed = %v, want < 300ms", el)
+ }
+}
+
+func TestRetryLocalDialNonRetryableFailsAtOnce(t *testing.T) {
+ var calls int
+ boom := errors.New("boom")
+ _, err := retryLocalDial(context.Background(), time.Now().Add(5*time.Second),
+ func(context.Context) (net.Conn, error) { calls++; return nil, boom })
+ if !errors.Is(err, boom) || calls != 1 {
+ t.Fatalf("err = %v, calls = %d, want boom after exactly one attempt", err, calls)
+ }
+}
+
+// holdEdge is an Edge over one ready service route at addr, with the dial
+// hold d and nothing else changed.
+func holdEdge(t *testing.T, addr string, hold localHold) (*Edge, *httptest.Server) {
+ t.Helper()
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Status: "ready", Addr: addr}); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ e, err := newEdge(reg, nil, hold)
+ if err != nil {
+ t.Fatalf("newEdge: %v", err)
+ }
+ t.Cleanup(e.probers.Stop)
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ return e, srv
+}
+
+func holdGet(t *testing.T, url string) (int, string) {
+ t.Helper()
+ req, _ := http.NewRequest(http.MethodGet, url, nil)
+ req.Host = "shop.example.com"
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("GET: %v", err)
+ }
+ defer resp.Body.Close()
+ b, _ := io.ReadAll(resp.Body)
+ return resp.StatusCode, string(b)
+}
+
+// listenLater starts handler on addr after delay, reusing a port deadAddr
+// reserved. The server is closed with the test.
+func listenLater(t *testing.T, addr string, delay time.Duration, h http.Handler) {
+ t.Helper()
+ var (
+ mu sync.Mutex
+ ts *httptest.Server
+ )
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ time.Sleep(delay)
+ ln, err := net.Listen("tcp", addr)
+ if err != nil {
+ t.Errorf("listen %s: %v", addr, err)
+ return
+ }
+ s := httptest.NewUnstartedServer(h)
+ s.Listener.Close()
+ s.Listener = ln
+ s.Start()
+ mu.Lock()
+ ts = s
+ mu.Unlock()
+ }()
+ t.Cleanup(func() {
+ <-done
+ mu.Lock()
+ defer mu.Unlock()
+ if ts != nil {
+ ts.Close()
+ }
+ })
+}
+
+func TestLoopbackAddrRouteHolds(t *testing.T) {
+ for _, host := range []string{"127.0.0.1", "localhost"} {
+ t.Run(host, func(t *testing.T) {
+ a := deadAddr(t)
+ listenAddr := a
+ if host == "localhost" {
+ _, port, _ := net.SplitHostPort(a)
+ a = net.JoinHostPort("localhost", port)
+ }
+ listenLater(t, listenAddr, 300*time.Millisecond, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, "back")
+ }))
+ _, srv := holdEdge(t, a, localHold{dial: 2 * time.Second, probe: probeTimeout})
+ start := time.Now()
+ code, body := holdGet(t, srv.URL)
+ if code != http.StatusOK || body != "back" {
+ t.Fatalf("got %d %q after %v, want 200 back", code, body, time.Since(start))
+ }
+ })
+ }
+}
+
+func TestLoopbackAddrRouteRefusedPastHold(t *testing.T) {
+ e, srv := holdEdge(t, deadAddr(t), localHold{dial: 200 * time.Millisecond, probe: probeTimeout})
+ sink := &memErrSink{}
+ e.EnableErrors(sink)
+ start := time.Now()
+ code, _ := holdGet(t, srv.URL)
+ if code != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502", code)
+ }
+ if el := time.Since(start); el < 200*time.Millisecond {
+ t.Fatalf("502 after %v, before the hold ended", el)
+ }
+ recs := sink.snap()
+ if len(recs) != 1 || recs[0].Cause != apperr.CauseRefused {
+ t.Fatalf("records = %+v, want one with cause %q", recs, apperr.CauseRefused)
+ }
+}
+
+func TestNonLoopbackAddrRouteFailsAtOnce(t *testing.T) {
+ var calls atomic.Int32
+ hold := localHold{dial: 2 * time.Second, probe: probeTimeout,
+ dialer: func(context.Context, string, string) (net.Conn, error) {
+ calls.Add(1)
+ return nil, refusedErr()
+ }}
+ _, srv := holdEdge(t, "10.0.0.5:80", hold)
+ start := time.Now()
+ code, _ := holdGet(t, srv.URL)
+ if code != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502", code)
+ }
+ if el := time.Since(start); el > 100*time.Millisecond {
+ t.Fatalf("502 after %v, want within 100ms", el)
+ }
+ if n := calls.Load(); n != 1 {
+ t.Fatalf("dialer calls = %d, want exactly 1", n)
+ }
+}
+
+func TestHeldDialClientCancelReturnsAtOnce(t *testing.T) {
+ _, srv := holdEdge(t, deadAddr(t), localHold{dial: 2 * time.Second, probe: probeTimeout})
+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer cancel()
+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
+ req.Host = "shop.example.com"
+ start := time.Now()
+ resp, err := http.DefaultClient.Do(req)
+ if err == nil {
+ resp.Body.Close()
+ }
+ if el := time.Since(start); el > 300*time.Millisecond {
+ t.Fatalf("Do returned after %v, want within 300ms of the client giving up", el)
+ }
+}
+
+func TestHeldDialPOSTBodyArrives(t *testing.T) {
+ a := deadAddr(t)
+ listenLater(t, a, 300*time.Millisecond, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // Read it all before the first write: HTTP/1 does not let a handler
+ // stream a response while the request body is still arriving.
+ b, _ := io.ReadAll(r.Body)
+ w.Write(b)
+ }))
+ _, srv := holdEdge(t, a, localHold{dial: 2 * time.Second, probe: probeTimeout})
+ body := strings.Repeat("0123456789abcdef", 4096) // 64 KiB
+ req, _ := http.NewRequest(http.MethodPost, srv.URL, strings.NewReader(body))
+ req.Host = "shop.example.com"
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("POST: %v", err)
+ }
+ defer resp.Body.Close()
+ got, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK || string(got) != body {
+ t.Fatalf("status %d, echoed %d bytes, want 200 and %d identical bytes", resp.StatusCode, len(got), len(body))
+ }
+}
+
+func TestHeldDialWebSocketUpgrade(t *testing.T) {
+ a := deadAddr(t)
+ listenLater(t, a, 300*time.Millisecond, upgradeEchoHandler("ws"))
+ _, srv := holdEdge(t, a, localHold{dial: 2 * time.Second, probe: probeTimeout})
+
+ c, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://"))
+ if err != nil {
+ t.Fatalf("dial edge: %v", err)
+ }
+ defer c.Close()
+ c.SetDeadline(time.Now().Add(5 * time.Second))
+ fmt.Fprint(c, "GET /ws HTTP/1.1\r\nHost: shop.example.com\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n")
+ buf := make([]byte, 0, 512)
+ tmp := make([]byte, 256)
+ for !strings.Contains(string(buf), "\r\n\r\n") {
+ n, err := c.Read(tmp)
+ if err != nil {
+ t.Fatalf("read handshake: %v (got %q)", err, buf)
+ }
+ buf = append(buf, tmp[:n]...)
+ }
+ if !strings.HasPrefix(string(buf), "HTTP/1.1 101") {
+ t.Fatalf("handshake = %q, want 101", buf)
+ }
+ fmt.Fprint(c, "hello\n")
+ rest := string(buf[strings.Index(string(buf), "\r\n\r\n")+4:])
+ for !strings.Contains(rest, "\n") {
+ n, err := c.Read(tmp)
+ if err != nil {
+ t.Fatalf("read echo: %v (got %q)", err, rest)
+ }
+ rest += string(tmp[:n])
+ }
+ if rest != "ws:hello\n" {
+ t.Fatalf("echo = %q, want %q", rest, "ws:hello\n")
+ }
+}
+
+func TestHeldDialsReleaseAfterHold(t *testing.T) {
+ _, srv := holdEdge(t, deadAddr(t), localHold{dial: 300 * time.Millisecond, probe: probeTimeout})
+ http.DefaultClient.CloseIdleConnections()
+ base := runtime.NumGoroutine()
+
+ var wg sync.WaitGroup
+ codes := make(chan int, 50)
+ start := time.Now()
+ for i := 0; i < 50; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ req, _ := http.NewRequest(http.MethodGet, srv.URL, nil)
+ req.Host = "shop.example.com"
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ codes <- -1
+ return
+ }
+ resp.Body.Close()
+ codes <- resp.StatusCode
+ }()
+ }
+ wg.Wait()
+ close(codes)
+ if el := time.Since(start); el > time.Second {
+ t.Fatalf("50 held GETs took %v, want within 1s", el)
+ }
+ for c := range codes {
+ if c != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502", c)
+ }
+ }
+ http.DefaultClient.CloseIdleConnections()
+ deadline := time.Now().Add(2 * time.Second)
+ for runtime.NumGoroutine() > base+10 {
+ if time.Now().After(deadline) {
+ t.Fatalf("goroutines = %d, baseline %d: held dials did not release", runtime.NumGoroutine(), base)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+func TestLocalHoldOffKeepsInstant502(t *testing.T) {
+ _, srv := holdEdge(t, deadAddr(t), noHold())
+ start := time.Now()
+ code, _ := holdGet(t, srv.URL)
+ if code != http.StatusBadGateway {
+ t.Fatalf("status = %d, want 502", code)
+ }
+ if el := time.Since(start); el > 100*time.Millisecond {
+ t.Fatalf("502 after %v, want within 100ms", el)
+ }
+}
diff --git a/internal/host/applessroute_test.go b/internal/host/applessroute_test.go
index 8bed6c30b..20c3ab63d 100644
--- a/internal/host/applessroute_test.go
+++ b/internal/host/applessroute_test.go
@@ -81,14 +81,21 @@ func captureShipLog(t *testing.T) *bytes.Buffer {
// TestErrshipAppLessRouteWritesNothing is the dev-bucket regression end to
// end. The route is the shape found on leo-climbing: an instance row with
-// an account, no app, and a TCP upstream nobody listens on. Every request
-// is a refused 502 that the edge files under (bab, ""). The errors shipper
+// an account, no app, and a TCP upstream that fails every request. Every
+// request is a 502 that the edge files under (bab, ""). The errors shipper
// must write nothing for it (it once wrote apps/bab//errors/...), prune
// nothing, keep shipping the app beside it, and say so once.
func TestErrshipAppLessRouteWritesNothing(t *testing.T) {
- dead := httptest.NewServer(http.NotFoundHandler())
+ // An upstream that hangs up on every request: still a 502 the edge files,
+ // but not a refused dial, which a loopback route now holds for 13s
+ // (edge.localDialHold) waiting for a restarting process to come back.
+ dead := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if c, _, err := w.(http.Hijacker).Hijack(); err == nil {
+ c.Close()
+ }
+ }))
+ t.Cleanup(dead.Close)
deadAddr := dead.Listener.Addr().String()
- dead.Close() // nothing listens here now: every dial is refused
reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
if err != nil {
@@ -120,7 +127,7 @@ func TestErrshipAppLessRouteWritesNothing(t *testing.T) {
}
resp.Body.Close()
if resp.StatusCode != http.StatusBadGateway {
- t.Fatalf("%s answered %d, want a refused 502", host, resp.StatusCode)
+ t.Fatalf("%s answered %d, want a 502", host, resp.StatusCode)
}
}