carlos / platform Public

devbox mode (#474): a timed-out drain closes and reports

When the 10s Shutdown deadline passes, ServeDevbox now calls srv.Close and
returns an error wrapping Shutdown's, instead of returning nil with
connections still active. serveDevbox's test hooks become devboxSeams
(bound address, server error log, drain timeout).

The end-to-end test holds a proxied request across cancellation and checks
ServeDevbox waits for it; a new test runs the drain out of time and checks
the error and the forced close. Handshake refusals go to a captured error
log the test asserts on, so passing runs stay quiet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 09f08bbeb9a89897a8eac39dd50c108c16e2183a parent 6f376ce
2 files changed, +244 −45
  • internal/edge/devbox.go +40 −12
  • internal/edge/devbox_test.go +204 −33

Intent

Attributed to this commit: 16.3 g CO₂e (2,033,529 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-devbox-mode, 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/devbox.go b/internal/edge/devbox.go
index 3d76badc1..f6b6eda52 100644
--- a/internal/edge/devbox.go
+++ b/internal/edge/devbox.go
@@ -44,17 +44,31 @@ type DevboxConfig struct {
// ServeDevbox serves the registry's routes over HTTPS on cfg.ListenAddr with
// the wildcard as the only certificate, until ctx is done; then it drains
-// in-flight requests for up to 10s, as Run does, and returns nil. Every
-// refusal and bind failure is returned, never fatal: a caller may run this
-// beside another server in one process.
+// in-flight requests for up to 10s, as Run does, and returns nil. A drain
+// that runs out of time closes what is left and returns an error, so a
+// caller never tears down what a handler may still be using on the word of
+// a clean shutdown. Every refusal and bind failure is returned, never fatal:
+// a caller may run this beside another server in one process.
func ServeDevbox(ctx context.Context, cfg DevboxConfig) error {
- return serveDevbox(ctx, cfg, nil)
+ return serveDevbox(ctx, cfg, devboxSeams{})
}
-// serveDevbox is ServeDevbox with a hook that is handed the bound address
-// once the listener exists, so a test can listen on port 0 and dial what it
-// got instead of reusing a port it closed. nil in production.
-func serveDevbox(ctx context.Context, cfg DevboxConfig, bound func(net.Addr)) error {
+// devboxDrainTimeout bounds the drain, as Run's does.
+const devboxDrainTimeout = 10 * time.Second
+
+// devboxSeams are the test hooks serveDevbox takes; the zero value is
+// production. bound is handed the listener's address once it exists, so a
+// test can listen on port 0 and dial what it got. errorLog replaces the
+// server's default logger (the standard one), so a test can read the
+// handshake refusals it causes. drainTimeout, when set, replaces
+// devboxDrainTimeout so a test can run a drain out of time quickly.
+type devboxSeams struct {
+ bound func(net.Addr)
+ errorLog *log.Logger
+ drainTimeout time.Duration
+}
+
+func serveDevbox(ctx context.Context, cfg DevboxConfig, seams devboxSeams) error {
// The address first, before anything is built: a devbox is reachable
// only on its tailnet address, and an empty or wildcard host would put
// every route on the office LAN too.
@@ -112,8 +126,8 @@ func serveDevbox(ctx context.Context, cfg DevboxConfig, bound func(net.Addr)) er
if err != nil {
return err
}
- if bound != nil {
- bound(ln.Addr())
+ if seams.bound != nil {
+ seams.bound(ln.Addr())
}
stop := make(chan struct{})
@@ -136,6 +150,7 @@ func serveDevbox(ctx context.Context, cfg DevboxConfig, bound func(net.Addr)) er
MinVersion: tls.VersionTLS12,
},
ReadHeaderTimeout: 10 * time.Second,
+ ErrorLog: seams.errorLog,
}
served := make(chan error, 1)
go func() { served <- srv.ServeTLS(ln, "", "") }()
@@ -148,9 +163,22 @@ func serveDevbox(ctx context.Context, cfg DevboxConfig, bound func(net.Addr)) er
return fmt.Errorf("edge: https listener %s: %w", cfg.ListenAddr, err)
}
log.Printf("edge: devbox: draining and shutting down")
- sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ drain := devboxDrainTimeout
+ if seams.drainTimeout > 0 {
+ drain = seams.drainTimeout
+ }
+ sctx, cancel := context.WithTimeout(context.Background(), drain)
defer cancel()
- _ = srv.Shutdown(sctx)
+ if err := srv.Shutdown(sctx); err != nil {
+ // Shutdown gives up at the deadline without touching the connections
+ // still active. Close them, so no handler outlives the return, and
+ // say the drain failed. Close does not reach hijacked connections
+ // (proxied WebSockets); as in Run, those are not drained either.
+ if cerr := srv.Close(); cerr != nil {
+ err = errors.Join(err, cerr)
+ }
+ return fmt.Errorf("edge: devbox: drain did not finish within %s; closed the remaining connections: %w", drain, err)
+ }
return nil
}
diff --git a/internal/edge/devbox_test.go b/internal/edge/devbox_test.go
index 60867d404..9f26e8695 100644
--- a/internal/edge/devbox_test.go
+++ b/internal/edge/devbox_test.go
@@ -1,17 +1,27 @@
package edge
import (
+ "bytes"
"context"
"crypto/tls"
"crypto/x509"
+ "errors"
+ "fmt"
+ "io"
+ "log"
"net"
+ "net/http"
+ "net/http/httptest"
"os"
"strings"
+ "sync"
"sync/atomic"
"testing"
"time"
"golang.org/x/crypto/acme/autocert"
+
+ "github.com/carlosframework/platform/internal/registry"
)
// devboxParent is the one wildcard parent these tests run under.
@@ -187,14 +197,61 @@ func TestDevboxEdgeSwitchesOff(t *testing.T) {
}
}
-// End to end: with the wildcard already in the cert cache (so the manager's
-// run loop loads it and orders nothing), ServeDevbox serves it for a covered
-// name, fails the handshake for any other, and drains and returns nil when
-// its context ends, leaving the port free.
-func TestDevboxServesTheWildcardAndDrains(t *testing.T) {
- ca, requests := countingCA(t)
- devboxEnv(t, ca.URL)
+// lockedBuffer is a bytes.Buffer safe for the server's goroutines to write
+// while the test reads it.
+type lockedBuffer struct {
+ mu sync.Mutex
+ buf bytes.Buffer
+}
+
+func (b *lockedBuffer) Write(p []byte) (int, error) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.buf.Write(p)
+}
+
+func (b *lockedBuffer) String() string {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.buf.String()
+}
+
+// heldBackend is an upstream whose handler signals entered and then holds
+// the request until release is called (or the test ends).
+func heldBackend(t *testing.T) (addr string, entered <-chan struct{}, release func()) {
+ t.Helper()
+ in := make(chan struct{}, 8)
+ gate := make(chan struct{})
+ var once sync.Once
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ in <- struct{}{}
+ <-gate
+ io.WriteString(w, "held reply")
+ }))
+ rel := func() { once.Do(func() { close(gate) }) }
+ // Release before the server's Close, which waits for its handlers.
+ t.Cleanup(ts.Close)
+ t.Cleanup(rel)
+ return ts.Listener.Addr().String(), in, rel
+}
+// devboxRun is one ServeDevbox under test: the address it bound, its result,
+// the cancel that ends it, the server's error log, and a client that trusts
+// the seeded wildcard and dials the bound address whatever the URL's host.
+type devboxRun struct {
+ addr string
+ done <-chan error
+ cancel context.CancelFunc
+ errLog *lockedBuffer
+ roots *x509.CertPool
+ client *http.Client
+}
+
+// startDevbox seeds the wildcard into a fresh cert cache (so the manager's
+// run loop loads it and orders nothing), adds a service route
+// slow.<parent> to heldAddr when it is set, and serves on 127.0.0.1:0.
+func startDevbox(t *testing.T, heldAddr string, drainTimeout time.Duration) *devboxRun {
+ t.Helper()
certDir := t.TempDir()
cert, key := selfSignedWildcard(t, devboxParent, time.Now().Add(60*24*time.Hour))
raw, err := encodeWildcardPEM(cert, key)
@@ -204,35 +261,47 @@ func TestDevboxServesTheWildcardAndDrains(t *testing.T) {
if err := autocert.DirCache(certDir).Put(context.Background(), wildcardPEMKey(devboxParent), raw); err != nil {
t.Fatal(err)
}
+ reg := openReg(t)
+ if heldAddr != "" {
+ if err := reg.Upsert(registry.Route{Host: "slow." + devboxParent, Kind: "service", Addr: heldAddr, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ }
ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- cfg := DevboxConfig{Registry: openReg(t), ListenAddr: "127.0.0.1:0", CertDir: certDir, SpoolRoot: t.TempDir()}
+ t.Cleanup(cancel)
+ errLog := &lockedBuffer{}
boundAddr := make(chan string, 1)
done := make(chan error, 1)
- go func() { done <- serveDevbox(ctx, cfg, func(a net.Addr) { boundAddr <- a.String() }) }()
- var addr string
+ cfg := DevboxConfig{Registry: reg, ListenAddr: "127.0.0.1:0", CertDir: certDir, SpoolRoot: t.TempDir()}
+ seams := devboxSeams{
+ bound: func(a net.Addr) { boundAddr <- a.String() },
+ errorLog: log.New(errLog, "", 0),
+ drainTimeout: drainTimeout,
+ }
+ go func() { done <- serveDevbox(ctx, cfg, seams) }()
+ run := &devboxRun{done: done, cancel: cancel, errLog: errLog, roots: x509.NewCertPool()}
select {
- case addr = <-boundAddr:
+ case run.addr = <-boundAddr:
case err := <-done:
t.Fatalf("ServeDevbox returned before binding: %v", err)
case <-time.After(10 * time.Second):
t.Fatal("ServeDevbox never bound its listener")
}
-
- roots := x509.NewCertPool()
- roots.AddCert(cert.Leaf)
- dial := func(sni string) error {
- d := &net.Dialer{Timeout: time.Second}
- conn, err := tls.DialWithDialer(d, "tcp", addr, &tls.Config{ServerName: sni, RootCAs: roots})
- if err == nil {
- conn.Close()
- }
- return err
+ run.roots.AddCert(cert.Leaf)
+ tr := &http.Transport{
+ TLSClientConfig: &tls.Config{RootCAs: run.roots},
+ DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, network, run.addr)
+ },
}
+ t.Cleanup(tr.CloseIdleConnections)
+ run.client = &http.Client{Transport: tr}
+
+ // The wildcard is served once the run loop's first pass has loaded it.
deadline := time.Now().Add(10 * time.Second)
for {
- err := dial("app." + devboxParent)
+ err := run.dial("app." + devboxParent)
if err == nil {
break
}
@@ -246,23 +315,92 @@ func TestDevboxServesTheWildcardAndDrains(t *testing.T) {
}
time.Sleep(50 * time.Millisecond)
}
- if err := dial("other.example.net"); err == nil {
- t.Fatal("uncovered name completed a handshake")
- }
- if err := dial(devboxParent); err == nil {
- t.Fatal("the parent apex completed a handshake")
+ return run
+}
+
+// dial completes (or fails) one TLS handshake with sni, verifying against
+// the seeded wildcard.
+func (r *devboxRun) dial(sni string) error {
+ d := &net.Dialer{Timeout: time.Second}
+ conn, err := tls.DialWithDialer(d, "tcp", r.addr, &tls.Config{ServerName: sni, RootCAs: r.roots})
+ if err == nil {
+ conn.Close()
+ }
+ return err
+}
+
+// heldGet starts GET https://slow.<parent>/ and returns its outcome on a
+// channel: the body, or the error.
+func (r *devboxRun) heldGet() <-chan string {
+ out := make(chan string, 1)
+ go func() {
+ resp, err := r.client.Get("https://slow." + devboxParent + "/")
+ if err != nil {
+ out <- "error: " + err.Error()
+ return
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ out <- "error: " + err.Error()
+ return
+ }
+ out <- fmt.Sprintf("%d %s", resp.StatusCode, b)
+ }()
+ return out
+}
+
+// End to end: ServeDevbox serves the cached wildcard for a covered name,
+// fails the handshake for any other (saying so in its error log), and on
+// cancel waits for an in-flight request to finish before it returns nil,
+// leaving the port free. The CA is never asked for anything.
+func TestDevboxServesTheWildcardAndDrains(t *testing.T) {
+ ca, requests := countingCA(t)
+ devboxEnv(t, ca.URL)
+ heldAddr, entered, release := heldBackend(t)
+ run := startDevbox(t, heldAddr, 0)
+
+ for _, sni := range []string{"other.example.net", devboxParent} {
+ if err := run.dial(sni); err == nil {
+ t.Fatalf("%q completed a handshake", sni)
+ }
+ want := fmt.Sprintf("edge: devbox: no certificate for %q", sni)
+ deadline := time.Now().Add(5 * time.Second)
+ for !strings.Contains(run.errLog.String(), want) {
+ if time.Now().After(deadline) {
+ t.Fatalf("error log %q lacks %q", run.errLog.String(), want)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
}
- cancel()
+ reply := run.heldGet()
select {
- case err := <-done:
+ case <-entered:
+ case got := <-reply:
+ t.Fatalf("held request finished before the backend saw it: %s", got)
+ case <-time.After(10 * time.Second):
+ t.Fatal("held request never reached the backend")
+ }
+ run.cancel()
+ select {
+ case err := <-run.done:
+ t.Fatalf("ServeDevbox returned (%v) with a request still in flight", err)
+ case <-time.After(300 * time.Millisecond):
+ }
+ release()
+ if got := <-reply; got != "200 held reply" {
+ t.Fatalf("in-flight request across the drain = %q, want 200 held reply", got)
+ }
+ select {
+ case err := <-run.done:
if err != nil {
- t.Fatalf("ServeDevbox after cancel = %v, want nil", err)
+ t.Fatalf("ServeDevbox after the drain = %v, want nil", err)
}
case <-time.After(15 * time.Second):
- t.Fatal("ServeDevbox did not return after its context ended")
+ t.Fatal("ServeDevbox did not return after the drain")
}
- ln, err := net.Listen("tcp", addr)
+ ln, err := net.Listen("tcp", run.addr)
if err != nil {
t.Fatalf("port still held after ServeDevbox returned: %v", err)
}
@@ -272,6 +410,39 @@ func TestDevboxServesTheWildcardAndDrains(t *testing.T) {
}
}
+// A drain that runs out of time is not a clean shutdown: ServeDevbox closes
+// the connection still in flight and returns an error wrapping Shutdown's.
+func TestDevboxDrainTimeoutClosesAndReports(t *testing.T) {
+ ca, _ := countingCA(t)
+ devboxEnv(t, ca.URL)
+ heldAddr, entered, _ := heldBackend(t) // never released: the drain must give up
+ run := startDevbox(t, heldAddr, 200*time.Millisecond)
+
+ reply := run.heldGet()
+ select {
+ case <-entered:
+ case <-time.After(10 * time.Second):
+ t.Fatal("held request never reached the backend")
+ }
+ run.cancel()
+ select {
+ case err := <-run.done:
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("ServeDevbox after a timed-out drain = %v, want an error wrapping %v", err, context.DeadlineExceeded)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("ServeDevbox did not return after its drain timed out")
+ }
+ select {
+ case got := <-reply:
+ if !strings.HasPrefix(got, "error: ") {
+ t.Fatalf("held request after the forced close = %q, want a connection error", got)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("held connection was not closed")
+ }
+}
+
// Devbox certificates come only from CARLOS_WILDCARD_DOMAINS: either
// variable that would add another parent is refused, even alongside it.
func TestDevboxRefusesExtraParents(t *testing.T) {