box: refuse a stream no app has read while stopping (#511 R27)
Once a fleet box's shutdown has begun (its tunnel drain), or its app's run unit ended without the activator asking it to (systemd's shutdown, a hand stop, a crash: ExecBackend.StoppedOutside, set by the unit watcher, cleared by the host's next run unit), a fleet tunnel request that fails before any app read is refused with REFUSED_STREAM instead of answered 502/503, and the hub retries it on a survivor (R26). Unit ordering is unchanged. "Before any app read" is exactly three places, all through one rule, edge.RefuseBeforeApp: - the edge's admission refusal (closed at shutdown); - the activator's four refusals in serve before its proxy runs (the HA lease, awaitStartup, the near-startup recheck, begin), now serveWakeErrorBeforeApp; the duty wrapper's call, which may follow a proxied request, never refuses; - the app socket proxy's error for a request it never got onto a connection to the app: no current generation, a moved generation, or a failed dial, with net/http's WroteHeaders unfired on every attempt and no body byte read. A client that has gone, or a stream something was written to, is never refused. Witnesses: TestServeRefusesBeforeAppRead drives the real Service behind the production tunnel loop (refused once draining or stopped outside, 503 otherwise and off a tunnel); TestStoppedOutsideFollowsTheRunUnit; TestReplicaGapRequestsServedBySurvivor (app stop, gap GETs and POSTs, edge shutdown: all served by the survivor, zero failures) and TestReplicaRequestsCrossingDrainServedBySurvivor (R26: POSTs cross the drain before the hub reads the GOAWAY) through the real hub and box.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+777
−24
internal/activator/activator.go+35 −4internal/activator/backend_exec.go+6 −0internal/activator/tunnel_refuse_test.go+214 −0internal/activator/unitproc.go+15 −0internal/edge/genproxy.go+68 −5internal/edge/group_admission.go+9 −1internal/edge/replica_drain_e2e_test.go+397 −14internal/edge/tunnelrefuse.go+33 −0
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 07f0b571b..5c3dad3d3 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -6539,7 +6539,7 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| a.mu.Unlock() |
| if refusal != nil { |
| a.retryHALostHost(rt) |
| - return a.serveWakeError(w, r, rt, refusal) |
| + return a.serveWakeErrorBeforeApp(w, r, rt, refusal) |
| } |
| } |
| @@ -6548,7 +6548,7 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| err := a.awaitStartup(r.Context(), deadline.C) |
| deadline.Stop() |
| if err != nil { |
| - return a.serveWakeError(w, r, rt, err) |
| + return a.serveWakeErrorBeforeApp(w, r, rt, err) |
| } |
| // The edge may have chosen rt and its proxy before startup recovery |
| // ran, whether this request waited here or arrived just as Startup |
| @@ -6560,7 +6560,7 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| if a.nearStartup() && a.Routes != nil { |
| if fresh, ferr := a.Routes.Get(rt.Host); ferr == nil && fresh != nil && |
| (fresh.Socket != rt.Socket || fresh.Addr != rt.Addr) { |
| - return a.serveWakeError(w, r, rt, errWakeTimeout) |
| + return a.serveWakeErrorBeforeApp(w, r, rt, errWakeTimeout) |
| } |
| } |
| } |
| @@ -6625,7 +6625,7 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| release, err := a.begin(r.Context(), rt, stamp, r) |
| if err != nil { |
| - return a.serveWakeError(w, r, rt, err) |
| + return a.serveWakeErrorBeforeApp(w, r, rt, err) |
| } |
| defer release() |
| // A move of the host ends it early if its response is a stream |
| @@ -6639,6 +6639,37 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout |
| return true |
| } |
| +// serveWakeErrorBeforeApp is serveWakeError for a failure in serve before |
| +// its proxy runs, so before any app has read the request (#511 R27). On a |
| +// fleet tunnel stream (tunnelclient.Refuse) of a box whose tunnel drain has |
| +// begun (its shutdown has started), or for a host whose app last ended |
| +// without the activator asking it to (StoppedOutside: systemd's shutdown, |
| +// a hand stop, a crash), the stream is refused unprocessed instead of |
| +// answered, and the hub sends the request to another copy whatever its |
| +// method (R26). A client that went away is never refused; every other |
| +// request is answered as before. |
| +// |
| +// "Before any app read" is exactly these call sites: the HA lease refusal, |
| +// awaitStartup's refusal (errStartupStopped, errWakeTimeout, a cancelled |
| +// wait), the near-startup route recheck and begin's refusal, all of which |
| +// return before serve calls proxy.ServeHTTP, the only place the request is |
| +// written to the app. serveWakeError's other caller, ServeHTTP's duty |
| +// wrapper, may follow a serve that already proxied, so it never refuses. |
| +func (a *Service) serveWakeErrorBeforeApp(w http.ResponseWriter, r *http.Request, rt registry.Route, err error) bool { |
| + if !errors.Is(err, context.Canceled) && edge.RefuseBeforeApp(r, a.StoppedOutside(rt.Host)) { |
| + return true |
| + } |
| + return a.serveWakeError(w, r, rt, err) |
| +} |
| + |
| +// StoppedOutside reports whether host's app last ended without the |
| +// activator asking it to, when the backend can tell (ExecBackend); false |
| +// otherwise (#511 R27). |
| +func (a *Service) StoppedOutside(host string) bool { |
| + so, ok := a.backend.(interface{ StoppedOutside(string) bool }) |
| + return ok && so.StoppedOutside(host) |
| +} |
| + |
| func (a *Service) serveWakeError(w http.ResponseWriter, r *http.Request, rt registry.Route, err error) bool { |
| if errors.Is(err, ErrHALeaseUnavailable) { |
| edge.HAUnavailableResponse(w, r) |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index 2b52023e0..2959a2e4f 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -81,6 +81,12 @@ type ExecBackend struct { |
| SandboxEffective execsandbox.Effective |
| SandboxConfigErr error |
| + // stoppedOutside: hosts whose app (the run role's unit) last ended |
| + // without the activator asking it to stop (a system shutdown, a hand |
| + // `systemctl stop`, a crash), until the host's next run unit starts |
| + // (#511 R27, StoppedOutside). |
| + stoppedOutside sync.Map |
| + |
| ServedPools func() edgesfile.PoolEvidence |
| TenantStartAllowed func(registry.Route) bool |
| workerAPI http.Handler |
diff --git a/internal/activator/tunnel_refuse_test.go b/internal/activator/tunnel_refuse_test.go| new file mode 100644 |
| index 000000000..4b4d6f6bc |
| --- /dev/null |
| +++ b/internal/activator/tunnel_refuse_test.go |
| @@ -0,0 +1,214 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/net/http2" |
| + |
| + "github.com/carlosframework/platform/internal/execsandbox" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| +) |
| + |
| +// stoppedOutsideBackend is the fake backend with ExecBackend's |
| +// StoppedOutside answer under the test's control. |
| +type stoppedOutsideBackend struct { |
| + *fakeBackend |
| + stopped atomic.Bool |
| +} |
| + |
| +func (b *stoppedOutsideBackend) StoppedOutside(string) bool { return b.stopped.Load() } |
| + |
| +// refuseBox is a real Service behind the production tunnel loop, its |
| +// streams arriving from a fake hub's ClientConn (cc). Its instance waits in |
| +// awaitStartup (a.Startup open) until the test stops the activator. |
| +type refuseBox struct { |
| + a *Service |
| + b *stoppedOutsideBackend |
| + cc *http2.ClientConn |
| + drain chan struct{} |
| + entered chan struct{} |
| + appReads atomic.Int32 |
| +} |
| + |
| +func newRefuseBox(t *testing.T) *refuseBox { |
| + t.Helper() |
| + x := &refuseBox{b: &stoppedOutsideBackend{fakeBackend: &fakeBackend{}}, drain: make(chan struct{}), entered: make(chan struct{}, 4)} |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + x.a = New(Config{Bucket: "test-bucket", Idle: time.Hour}, x.b, reg) |
| + x.a.Startup = make(chan struct{}) |
| + conns := make(chan *http2.ClientConn, 1) |
| + hub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + conn, bufrw, err := w.(http.Hijacker).Hijack() |
| + if err != nil { |
| + t.Errorf("hijack: %v", err) |
| + return |
| + } |
| + fmt.Fprintf(bufrw, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: carlos-tunnel/1\r\nConnection: Upgrade\r\n\r\n") |
| + bufrw.Flush() |
| + cc, err := (&http2.Transport{}).NewClientConn(conn) |
| + if err != nil { |
| + t.Errorf("h2 client: %v", err) |
| + return |
| + } |
| + conns <- cc |
| + })) |
| + t.Cleanup(hub.Close) |
| + rt := testRoute("shop.example.com") |
| + app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { x.appReads.Add(1); io.WriteString(w, "app") }) |
| + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + x.entered <- struct{}{} |
| + if !x.a.ServeHTTP(w, r, rt, app) { |
| + app.ServeHTTP(w, r) |
| + } |
| + }) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + tunnelclient.Loop(ctx, tunnelclient.Config{URL: hub.URL, Name: "pi/box-1", Token: "t", Handler: handler, Drain: x.drain, Logf: func(string, ...any) {}}) |
| + }() |
| + t.Cleanup(func() { cancel(); <-done }) |
| + select { |
| + case x.cc = <-conns: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the box never connected") |
| + } |
| + return x |
| +} |
| + |
| +// TestServeRefusesBeforeAppRead (#511 R27) drives the real activator's |
| +// serve: a fleet tunnel stream waits in awaitStartup, then the activator |
| +// stops, so serve fails before its proxy runs (errStartupStopped, drill 3's |
| +// box-2 answer). Once the box's tunnel drain has begun, or when the app |
| +// last ended outside the activator, the stream is refused with |
| +// REFUSED_STREAM and the app never read it; otherwise, and off a tunnel, |
| +// it is answered 503 as before. |
| +func TestServeRefusesBeforeAppRead(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + drain, outside bool |
| + wantRefusedCode bool |
| + }{ |
| + {"shutdown begun", true, false, true}, |
| + {"app stopped outside the activator", false, true, true}, |
| + {"neither", false, false, false}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + x := newRefuseBox(t) |
| + x.b.stopped.Store(c.outside) |
| + type result struct { |
| + resp *http.Response |
| + err error |
| + } |
| + res := make(chan result, 1) |
| + go func() { |
| + req, _ := http.NewRequest("POST", "https://shop.example.com/", strings.NewReader("order")) |
| + resp, err := x.cc.RoundTrip(req) |
| + res <- result{resp, err} |
| + }() |
| + <-x.entered |
| + if c.drain { |
| + close(x.drain) |
| + } |
| + x.a.lifeStop() |
| + r := <-res |
| + var se http2.StreamError |
| + refused := errors.As(r.err, &se) && se.Code == http2.ErrCodeRefusedStream |
| + // TestServeRefusesBeforeAppRead |
| + if refused != c.wantRefusedCode || x.appReads.Load() != 0 { |
| + t.Fatalf("%s: refused %v (%v), app reads %d", c.name, refused, r.err, x.appReads.Load()) |
| + } |
| + if !c.wantRefusedCode && (r.err != nil || r.resp.StatusCode != http.StatusServiceUnavailable) { |
| + t.Fatalf("%s: want the 503 answer, got %v %v", c.name, r.resp, r.err) |
| + } |
| + if r.resp != nil { |
| + r.resp.Body.Close() |
| + } |
| + }) |
| + } |
| + t.Run("off a tunnel", func(t *testing.T) { |
| + b := &stoppedOutsideBackend{fakeBackend: &fakeBackend{}} |
| + b.stopped.Store(true) |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg) |
| + a.Startup = make(chan struct{}) |
| + a.lifeStop() |
| + w := httptest.NewRecorder() |
| + a.ServeHTTP(w, httptest.NewRequest("POST", "https://shop.example.com/", strings.NewReader("x")), testRoute("shop.example.com"), http.NotFoundHandler()) |
| + if w.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("off a tunnel: %d, want the 503 answer", w.Code) |
| + } |
| + }) |
| +} |
| + |
| +// TestStoppedOutsideFollowsTheRunUnit (#511 R27): the unit watcher records |
| +// a run unit that ended without the activator asking it to stop, not one |
| +// it stopped, and the host's next run unit clears it. |
| +func TestStoppedOutsideFollowsTheRunUnit(t *testing.T) { |
| + const host = "shop.example.com" |
| + var running atomic.Bool |
| + b := &ExecBackend{ |
| + UnitState: func(context.Context, string) (string, string, error) { |
| + if running.Load() { |
| + return "active", "inv", nil |
| + } |
| + return "inactive", "inv", nil |
| + }, |
| + CgroupEvents: func(string, string) (bool, bool, error) { return running.Load(), running.Load(), nil }, |
| + ObservePoll: time.Millisecond, |
| + } |
| + unit, err := unitName(instancectl.RoleRun, host, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rt := registry.Route{Host: host, Kind: "instance"} |
| + exit := func(requested bool) { |
| + t.Helper() |
| + p := &unitProc{b: b, rt: rt, role: instancectl.RoleRun, unit: unit, slice: instancectl.SliceName(host), invocation: "inv", runDir: t.TempDir(), done: make(chan struct{})} |
| + p.stopRequested.Store(requested) |
| + go b.observe(p) |
| + select { |
| + case <-p.done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the watcher never saw the exit") |
| + } |
| + } |
| + exit(true) |
| + if b.StoppedOutside(host) { |
| + t.Fatal("a stop the activator asked for counted as outside") |
| + } |
| + exit(false) |
| + // TestStoppedOutsideFollowsTheRunUnit |
| + if !b.StoppedOutside(host) { |
| + t.Fatal("an exit the activator did not ask for was not recorded") |
| + } |
| + running.Store(true) |
| + p, err := b.newUnitProcFor(rt, instancectl.RoleRun, 0, instancePaths{runDir: t.TempDir()}, instancectl.StartResponse{Unit: unit, InvocationID: "inv", Sandbox: execsandbox.EffectiveSystemd}, nil, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if b.StoppedOutside(host) { |
| + t.Fatal("the host's next run unit did not clear the record") |
| + } |
| + p.stopRequested.Store(true) |
| + running.Store(false) |
| + <-p.done |
| +} |
diff --git a/internal/activator/unitproc.go b/internal/activator/unitproc.go| index a76ab7ce5..632fc5e0d 100644 |
| --- a/internal/activator/unitproc.go |
| +++ b/internal/activator/unitproc.go |
| @@ -154,10 +154,22 @@ func (b *ExecBackend) newUnitProcFor(rt registry.Route, role instancectl.Role, g |
| unit := started.Unit |
| up := &unitProc{b: b, rt: rt, role: role, gen: gen, unit: unit, slice: instancectl.SliceName(rt.Host), |
| invocation: started.InvocationID, sandbox: started.Sandbox, runDir: p.runDir, dataDir: p.dataDir, ctl: ctl, logs: logs, extraListeners: extra, done: make(chan struct{})} |
| + if role == instancectl.RoleRun { |
| + b.stoppedOutside.Delete(rt.Host) |
| + } |
| go b.observe(up) |
| return up, nil |
| } |
| +// StoppedOutside reports whether host's app last ended without the |
| +// activator asking it to (#511 R27): its run unit was stopped by systemd |
| +// (a shutdown), by hand, or crashed, and no run unit of host has started |
| +// since. |
| +func (b *ExecBackend) StoppedOutside(host string) bool { |
| + _, ok := b.stoppedOutside.Load(host) |
| + return ok |
| +} |
| + |
| // unitName is the unit a role of host runs as: the original template's, or |
| // generation gen's (zero-downtime spec §7.6). A role with no binary unit |
| // (RoleWorker) is an error, never "". |
| @@ -529,6 +541,9 @@ func (b *ExecBackend) observe(p *unitProc) { |
| } else if p.worker == "" { |
| emitEvent(b.Logs, p.rt, "warn", "instance exited (status unknown: restarted outside the activator)") |
| } |
| + if p.role == instancectl.RoleRun && p.worker == "" && !p.stopRequested.Load() { |
| + b.stoppedOutside.Store(p.rt.Host, true) |
| + } |
| p.finaliseGen() |
| p.exited.Store(true) |
| // Stop closes the listeners when it observes done; a crash |
diff --git a/internal/edge/genproxy.go b/internal/edge/genproxy.go| index eb29f0f4b..68e9dd688 100644 |
| --- a/internal/edge/genproxy.go |
| +++ b/internal/edge/genproxy.go |
| @@ -7,8 +7,10 @@ import ( |
| "io" |
| "net" |
| "net/http" |
| + "net/http/httptrace" |
| "net/http/httputil" |
| "sync" |
| + "sync/atomic" |
| "syscall" |
| "time" |
| @@ -218,6 +220,14 @@ func genTransportFor(host string, src GenSource, own *GenInfo) *http.Transport { |
| return dialGen(ctx, dialer, src, host, g) |
| } |
| } |
| + undialled := dial |
| + dial = func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + conn, err := undialled(ctx, network, addr) |
| + if err != nil { |
| + return nil, &appDialError{err} |
| + } |
| + return conn, nil |
| + } |
| return &http.Transport{ |
| DialContext: dial, |
| MaxIdleConns: 32, |
| @@ -261,6 +271,17 @@ func (t *genRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { |
| hb = &heldBody{rc: req.Body} |
| req.Body = hb |
| } |
| + // wrote: some attempt's request headers went into a connection's |
| + // write buffer (net/http fires WroteHeaders right after writing them), |
| + // across every connection the transport tried, a reused one included. |
| + var wrote atomic.Bool |
| + req = req.WithContext(httptrace.WithClientTrace(req.Context(), &httptrace.ClientTrace{WroteHeaders: func() { wrote.Store(true) }})) |
| + notReached := func(err error) error { |
| + if !wrote.Load() && (hb == nil || !hb.wasRead()) { |
| + return &appNotReachedError{err} |
| + } |
| + return err |
| + } |
| for attempt, stale := 0, 0; ; { |
| g, ok := t.src.ServingGen(t.host) |
| if !ok { |
| @@ -273,7 +294,7 @@ func (t *genRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { |
| if hb != nil { |
| hb.release() |
| } |
| - return nil, errNoGeneration |
| + return nil, notReached(errNoGeneration) |
| } |
| } |
| gp, ok := t.pools.pool(t.host, g, t.src) |
| @@ -284,9 +305,9 @@ func (t *genRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { |
| hb.release() |
| } |
| if cur, ok := t.src.ServingGen(t.host); ok { |
| - return nil, &genMovedError{to: cur} |
| + return nil, notReached(&genMovedError{to: cur}) |
| } |
| - return nil, errNoGeneration |
| + return nil, notReached(errNoGeneration) |
| } |
| continue |
| } |
| @@ -303,6 +324,13 @@ func (t *genRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { |
| if hb != nil { |
| hb.release() |
| } |
| + var dialErr *appDialError |
| + if errors.As(err, &dialErr) { |
| + // The last connection was never made; notReached also |
| + // requires that no earlier one (a reused idle connection |
| + // net/http tried first) had the request written to it. |
| + return nil, notReached(err) |
| + } |
| return nil, err |
| } |
| // X-Carlos-Version names the build of the generation that served the |
| @@ -385,9 +413,44 @@ func appSocketProxy(host string, src GenSource, pools *GenPools) *httputil.Rever |
| pr.Out.Host = pr.In.Host // backend sees the real hostname |
| scrubInboundPurgeHeader(pr) |
| }, |
| - Transport: &genRoundTripper{host: host, src: src, pools: pools}, |
| - ErrorHandler: defaultProxyError(proxyCause), |
| + Transport: &genRoundTripper{host: host, src: src, pools: pools}, |
| + ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) { |
| + if refuseUnreachedApp(r, host, src, err) { |
| + return |
| + } |
| + defaultProxyError(proxyCause)(w, r, err) |
| + }, |
| + } |
| +} |
| + |
| +// appDialError is a failure to connect to an app's socket: nothing of the |
| +// request was written on that connection. |
| +type appDialError struct{ error } |
| + |
| +func (e *appDialError) Unwrap() error { return e.error } |
| + |
| +// appNotReachedError is a generation round trip that failed before any of |
| +// the request reached the app (#511 R27): no current generation, a |
| +// generation that moved, or a dial that failed, with no request headers |
| +// written to any connection (net/http's WroteHeaders never fired, on any |
| +// attempt) and no byte of the body read. |
| +type appNotReachedError struct{ error } |
| + |
| +func (e *appNotReachedError) Unwrap() error { return e.error } |
| + |
| +// refuseUnreachedApp refuses r's fleet tunnel stream unprocessed (#511 |
| +// R27), instead of the proxy's 502, when the app never got the request |
| +// (appNotReachedError) and either the box's shutdown has begun (its |
| +// tunnel drain) or the host's app last ended without the activator asking |
| +// it to (src's StoppedOutside). The hub then sends the request to another |
| +// copy. Anything else is answered as before. |
| +func refuseUnreachedApp(r *http.Request, host string, src GenSource, err error) bool { |
| + var nr *appNotReachedError |
| + if !errors.As(err, &nr) { |
| + return false |
| } |
| + so, _ := src.(interface{ StoppedOutside(string) bool }) |
| + return RefuseBeforeApp(r, so != nil && so.StoppedOutside(host)) |
| } |
| // AppSocketProxy is appSocketProxy for callers outside this package: the |
diff --git a/internal/edge/group_admission.go b/internal/edge/group_admission.go| index e25c805ea..d0c2359e7 100644 |
| --- a/internal/edge/group_admission.go |
| +++ b/internal/edge/group_admission.go |
| @@ -1,8 +1,9 @@ |
| package edge |
| import ( |
| - "github.com/carlosframework/platform/internal/registry" |
| "net/http" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| ) |
| type HAAdmission interface{ TenantAdmitted() bool } |
| @@ -15,6 +16,13 @@ func (e *Edge) admissionRefuses(w http.ResponseWriter, r *http.Request, rt regis |
| if scope, ok := a.(interface{ TenantAdmissionExempt(registry.Route) bool }); ok && scope.TenantAdmissionExempt(rt) { |
| return false |
| } |
| + // #511 R27: a fleet tunnel stream on a box whose shutdown has begun |
| + // (its tunnel drain) is refused unprocessed rather than answered: no |
| + // app has read it, and the hub sends it to another copy. Off a fleet |
| + // tunnel, or before the drain, the answer is as ever. |
| + if RefuseBeforeApp(r, false) { |
| + return true |
| + } |
| if phase, ok := a.(interface{ TenantAdmissionStarting() bool }); ok && !phase.TenantAdmissionStarting() { |
| AdmissionUnavailableResponse(w, r) |
| } else { |
diff --git a/internal/edge/replica_drain_e2e_test.go b/internal/edge/replica_drain_e2e_test.go| index 26e3e9a7e..dace05bff 100644 |
| --- a/internal/edge/replica_drain_e2e_test.go |
| +++ b/internal/edge/replica_drain_e2e_test.go |
| @@ -3,9 +3,12 @@ package edge |
| import ( |
| "context" |
| "io" |
| + "net" |
| "net/http" |
| "net/http/httptest" |
| "net/url" |
| + "os" |
| + "path/filepath" |
| "strings" |
| "sync" |
| "sync/atomic" |
| @@ -43,10 +46,10 @@ type replicaDrainBox struct { |
| inflight chan string // /slow ids that reached the app |
| } |
| -func newReplicaDrainBox(t *testing.T, hubURL, label, token string, drains bool) *replicaDrainBox { |
| +func newReplicaDrainBox(t *testing.T, hubURL, label, token string, drains bool, act *replicaGapActivator) *replicaDrainBox { |
| t.Helper() |
| b := &replicaDrainBox{label: label, admission: &replicaDrainAdmission{}, done: make(chan struct{}), finish: make(chan struct{}), inflight: make(chan string, 8)} |
| - app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + appHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| b.backend.Add(1) |
| body, _ := io.ReadAll(r.Body) |
| if r.URL.Path == "/slow" && label == "box-00" { |
| @@ -61,22 +64,49 @@ func newReplicaDrainBox(t *testing.T, hubURL, label, token string, drains bool) |
| } |
| } |
| io.WriteString(w, label+" "+r.Method+" "+string(body)) |
| - })) |
| - t.Cleanup(app.Close) |
| - // Before the app closes (cleanups run last first): a failed run must |
| - // not leave the parked request holding it open. |
| - t.Cleanup(b.releaseFinish) |
| + }) |
| reg := openReg(t) |
| - if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Status: "ready", Addr: strings.TrimPrefix(app.URL, "http://")}); err != nil { |
| - t.Fatal(err) |
| + var e *Edge |
| + var err error |
| + if act == nil { |
| + app := httptest.NewServer(appHandler) |
| + t.Cleanup(app.Close) |
| + if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Status: "ready", Addr: strings.TrimPrefix(app.URL, "http://")}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err = New(reg, nil) |
| + if err == nil { |
| + WithHAAdmission(b.admission)(e) |
| + } |
| + } else { |
| + // An activator-owned instance on a unix socket, as a fleet box |
| + // runs one; act stands in for the activator (replicaGapActivator). |
| + dir, derr := os.MkdirTemp("", "app") |
| + if derr != nil { |
| + t.Fatal(derr) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(dir) }) |
| + ln, lerr := net.Listen("unix", filepath.Join(dir, "app.sock")) |
| + if lerr != nil { |
| + t.Fatal(lerr) |
| + } |
| + app := &http.Server{Handler: appHandler} |
| + go app.Serve(ln) |
| + act.app = app |
| + t.Cleanup(func() { app.Close() }) |
| + if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "instance", Status: "ready", Account: "bab", App: "shop", Stateless: true, Socket: filepath.Join(dir, "app.sock")}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err = New(reg, act) |
| } |
| - e, err := New(reg, nil) |
| if err != nil { |
| t.Fatal(err) |
| } |
| + // Before the app closes (cleanups run last first): a failed run must |
| + // not leave the parked request holding it open. |
| + t.Cleanup(b.releaseFinish) |
| t.Cleanup(e.probers.Stop) |
| b.edge = e |
| - WithHAAdmission(b.admission)(e) |
| drain := make(chan struct{}) |
| var once sync.Once |
| WithShutdownStarted(func(time.Time) { once.Do(func() { close(drain) }) })(e) |
| @@ -101,6 +131,31 @@ func newReplicaDrainBox(t *testing.T, hubURL, label, token string, drains bool) |
| // pi, and its two boxes, registered with real fleet credentials. |
| func replicaDrainRig(t *testing.T, drains bool) (srvURL string, hub *TunnelHub, boxes [2]*replicaDrainBox) { |
| t.Helper() |
| + r := newReplicaDrainRig(t, drainRigOpts{drains: drains}) |
| + return r.url, r.hub, r.boxes |
| +} |
| + |
| +// drainRigOpts: drains wires each box's tunnel drain (R24); holdGoAway |
| +// holds back, at the hub, every GOAWAY box-00 sends until hold.release |
| +// (R26: streams cross the drain before the hub knows of it); act serves |
| +// box-00's instance through that activator stand-in (R27). |
| +type drainRigOpts struct { |
| + drains, holdGoAway bool |
| + act *replicaGapActivator |
| +} |
| + |
| +type drainRig struct { |
| + url string |
| + hub *TunnelHub |
| + edge *Edge |
| + clock *replicaTestClock |
| + boxes [2]*replicaDrainBox |
| + hold *goAwayHold |
| +} |
| + |
| +func newReplicaDrainRig(t *testing.T, opts drainRigOpts) *drainRig { |
| + t.Helper() |
| + rig := &drainRig{} |
| reg := openReg(t) |
| if err := reg.UpsertFleet(registry.Fleet{Name: "pi", Account: "bab", Bucket: "pi-data"}); err != nil { |
| t.Fatal(err) |
| @@ -128,7 +183,16 @@ func replicaDrainRig(t *testing.T, drains bool) (srvURL string, hub *TunnelHub, |
| } |
| t.Setenv("CARLOS_TUNNEL_HOST", u.Hostname()) |
| t.Setenv("CARLOS_FLEET", "") |
| - hub = NewTunnelHub(u.Hostname(), nil) |
| + hub := NewTunnelHub(u.Hostname(), nil) |
| + if opts.holdGoAway { |
| + hub.wrapConn = func(name string, c net.Conn) net.Conn { |
| + if name != "pi/box-00" { |
| + return c |
| + } |
| + rig.hold = newGoAwayHold(c) |
| + return rig.hold |
| + } |
| + } |
| e.EnableTunnels(hub) |
| clock := newReplicaTestClock() |
| // The copies' health, without a box-side probe endpoint: a copy is |
| @@ -149,7 +213,11 @@ func replicaDrainRig(t *testing.T, drains bool) (srvURL string, hub *TunnelHub, |
| t.Fatal(err) |
| } |
| for i, label := range []string{"box-00", "box-01"} { |
| - boxes[i] = newReplicaDrainBox(t, srv.URL, label, "tok-"+label, drains) |
| + var act *replicaGapActivator |
| + if i == 0 { |
| + act = opts.act |
| + } |
| + rig.boxes[i] = newReplicaDrainBox(t, srv.URL, label, "tok-"+label, opts.drains, act) |
| waitForTunnelState(t, hub, "pi/"+label, "connected", 10*time.Second) |
| } |
| // The jobs started before the boxes connected; let each find its |
| @@ -158,7 +226,172 @@ func replicaDrainRig(t *testing.T, drains bool) (srvURL string, hub *TunnelHub, |
| clock.advance(time.Second) |
| } |
| replicaAwait(t, "both copies live", func() bool { return len(e.replicaProbes.Live("shop.example.com")) == 2 }) |
| - return srv.URL, hub, boxes |
| + rig.url, rig.hub, rig.edge, rig.clock = srv.URL, hub, e, clock |
| + return rig |
| +} |
| + |
| +// relive brings every copy whose channel can take a stream back into the |
| +// live set after a refusal ejected it: two passing probes. |
| +func (r *drainRig) relive(t *testing.T) { |
| + t.Helper() |
| + r.clock.advance(time.Second) |
| + r.clock.advance(time.Second) |
| + r.clock.advance(time.Second) |
| + replicaAwait(t, "both copies live again", func() bool { return len(r.edge.replicaProbes.Live("shop.example.com")) == 2 }) |
| +} |
| + |
| +// goAwayHold is the hub's view of a box's tunnel with every GOAWAY frame |
| +// held back until release, and every other frame delivered as it comes: |
| +// the hub keeps sending new streams that cross the box's drain (R26). |
| +type goAwayHold struct { |
| + net.Conn |
| + frames chan []byte |
| + cur []byte |
| + err error |
| + held atomic.Int32 |
| + release chan struct{} |
| + once sync.Once |
| +} |
| + |
| +func newGoAwayHold(c net.Conn) *goAwayHold { |
| + h := &goAwayHold{Conn: c, frames: make(chan []byte, 256), release: make(chan struct{})} |
| + // mu orders every send on frames, and its close, so a release after the |
| + // wire ended sends nothing. |
| + var mu sync.Mutex |
| + var stash [][]byte |
| + ended := false |
| + go func() { |
| + <-h.release |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if !ended { |
| + for _, f := range stash { |
| + h.frames <- f |
| + } |
| + } |
| + stash = nil |
| + }() |
| + go func() { |
| + defer func() { |
| + mu.Lock() |
| + ended = true |
| + close(h.frames) |
| + mu.Unlock() |
| + }() |
| + for { |
| + hdr := make([]byte, 9) |
| + if _, err := io.ReadFull(c, hdr); err != nil { |
| + h.err = err |
| + return |
| + } |
| + f := make([]byte, 9+(int(hdr[0])<<16|int(hdr[1])<<8|int(hdr[2]))) |
| + copy(f, hdr) |
| + if _, err := io.ReadFull(c, f[9:]); err != nil { |
| + h.err = err |
| + return |
| + } |
| + mu.Lock() |
| + held := false |
| + if f[3] == 0x7 { |
| + select { |
| + case <-h.release: |
| + default: |
| + stash = append(stash, f) |
| + h.held.Add(1) |
| + held = true |
| + } |
| + } |
| + if !held { |
| + h.frames <- f |
| + } |
| + mu.Unlock() |
| + } |
| + }() |
| + return h |
| +} |
| + |
| +func (h *goAwayHold) Read(p []byte) (int, error) { |
| + if len(h.cur) == 0 { |
| + f, ok := <-h.frames |
| + if !ok { |
| + if h.err == nil { |
| + return 0, io.EOF |
| + } |
| + return 0, h.err |
| + } |
| + h.cur = f |
| + } |
| + n := copy(p, h.cur) |
| + h.cur = h.cur[n:] |
| + return n, nil |
| +} |
| + |
| +func (h *goAwayHold) releaseGoAway() { h.once.Do(func() { close(h.release) }) } |
| + |
| +// replicaGapActivator stands in for a fleet box's activator around a |
| +// graceful stop, as drill 3's box-2 behaved: systemd stops the app's unit |
| +// first (stopped: a stop the activator did not ask for), and the edge gets |
| +// its SIGTERM a moment later. A request in that gap starts a wake that |
| +// systemd will not run: it fails at once (failFast of them) or waits until |
| +// the edge's shutdown closes admission. Either way it then fails before its |
| +// proxy runs, and is refused through the one rule the real activator's |
| +// serveWakeErrorBeforeApp calls, RefuseBeforeApp (StoppedOutside true). |
| +// Before the stop it proxies straight to the app. |
| +type replicaGapActivator struct { |
| + app *http.Server |
| + stopped atomic.Bool |
| + failFast atomic.Int32 |
| + parked atomic.Int32 |
| + refused atomic.Int32 |
| + answered atomic.Int32 |
| + closed atomic.Bool |
| + closing chan struct{} |
| + closeOnce sync.Once |
| +} |
| + |
| +func newReplicaGapActivator() *replicaGapActivator { |
| + return &replicaGapActivator{closing: make(chan struct{})} |
| +} |
| + |
| +// stopApp is systemd stopping the app's unit. |
| +func (a *replicaGapActivator) stopApp() { |
| + a.stopped.Store(true) |
| + a.app.Close() |
| +} |
| + |
| +func (a *replicaGapActivator) ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) bool { |
| + if !a.stopped.Load() { |
| + proxy.ServeHTTP(w, r) |
| + return true |
| + } |
| + if a.failFast.Add(-1) < 0 { |
| + a.failFast.Add(1) |
| + a.parked.Add(1) |
| + select { |
| + case <-a.closing: |
| + case <-r.Context().Done(): |
| + return true |
| + } |
| + } |
| + if RefuseBeforeApp(r, true) { |
| + a.refused.Add(1) |
| + return true |
| + } |
| + a.answered.Add(1) |
| + Unavailable(w, "wake-failed", "instance failed to wake", 5) |
| + return true |
| +} |
| +func (a *replicaGapActivator) RetireExcept(map[string]bool) {} |
| +func (a *replicaGapActivator) AdmitHeldLeg(context.Context, registry.Route) (HeldLeg, error) { |
| + return nil, io.EOF |
| +} |
| +func (a *replicaGapActivator) HeldAdmissible(string) bool { return false } |
| +func (a *replicaGapActivator) SetHeldWakeHook(func(string)) {} |
| +func (a *replicaGapActivator) TenantAdmitted() bool { return !a.closed.Load() } |
| +func (a *replicaGapActivator) TenantAdmissionStarting() bool { return false } |
| +func (a *replicaGapActivator) CloseTenantAdmission() { |
| + a.closed.Store(true) |
| + a.closeOnce.Do(func() { close(a.closing) }) |
| } |
| // drainDo sends one request for shop.example.com to the hub. |
| @@ -302,3 +535,153 @@ func TestReplicaBoxShutdownWithoutDrain(t *testing.T) { |
| } |
| func (b *replicaDrainBox) releaseFinish() { b.release.Do(func() { close(b.finish) }) } |
| + |
| +// drainResult is one request's answer. |
| +type drainResult struct { |
| + method, body string |
| + code int |
| + got string |
| +} |
| + |
| +// drainAsync sends method with body for shop.example.com in the |
| +// background, its answer on the returned channel. |
| +func drainAsync(t *testing.T, srvURL, method, path, body string) <-chan drainResult { |
| + ch := make(chan drainResult, 1) |
| + go func() { |
| + code, got := drainDo(t, srvURL, method, path, body) |
| + ch <- drainResult{method, body, code, got} |
| + }() |
| + return ch |
| +} |
| + |
| +// parkOn sends method until one lands where landed reports it did (the |
| +// hub picks copies in turn, and the other copy answers at once), and |
| +// returns that request's channel. |
| +func parkOn(t *testing.T, srvURL, method, path, body string, landed func() bool) <-chan drainResult { |
| + t.Helper() |
| + for range 20 { |
| + ch := drainAsync(t, srvURL, method, path, body) |
| + deadline := time.After(5 * time.Second) |
| + for { |
| + if landed() { |
| + return ch |
| + } |
| + select { |
| + case r := <-ch: |
| + if r.code != 200 || !strings.HasPrefix(r.got, "box-01 ") { |
| + t.Fatalf("%s %s on the other copy: %d %q", method, path, r.code, r.got) |
| + } |
| + case <-deadline: |
| + t.Fatalf("%s %s never landed", method, path) |
| + case <-time.After(5 * time.Millisecond): |
| + continue |
| + } |
| + break |
| + } |
| + } |
| + t.Fatalf("%s %s never landed in 20 tries", method, path) |
| + return nil |
| +} |
| + |
| +// TestReplicaRequestsCrossingDrainServedBySurvivor is R26's witness through |
| +// the real hub and box wiring: box-00 begins its shutdown, and the hub, |
| +// which has not yet read box-00's GOAWAY (held back at the hub), keeps |
| +// sending it new streams, POSTs with bodies among them. box-00's server |
| +// drops every one unprocessed (above the GOAWAY's last stream); once the |
| +// hub reads the GOAWAY it knows they were never processed, and serves |
| +// them all from box-01: zero failures, none reaching box-00's edge. A |
| +// request box-00 accepted before the drain keeps the connection open and |
| +// finishes there. |
| +func TestReplicaRequestsCrossingDrainServedBySurvivor(t *testing.T) { |
| + r := newReplicaDrainRig(t, drainRigOpts{drains: true, holdGoAway: true}) |
| + b0, b1 := r.boxes[0], r.boxes[1] |
| + accepted := parkOn(t, r.url, "POST", "/slow?id=finish", "f", func() bool { return len(b0.inflight) > 0 }) |
| + <-b0.inflight |
| + |
| + b0.edge.beginShutdown() |
| + replicaAwait(t, "box-00's GOAWAY to be held at the hub", func() bool { return r.hold.held.Load() >= 1 }) |
| + if r.hub.channel("pi/box-00").cc.State().Closing { |
| + t.Fatal("the hub read the GOAWAY it was meant not to see yet") |
| + } |
| + reachedBefore, b1Before := b0.reached.Load(), b1.backend.Load() |
| + var crossing []<-chan drainResult |
| + for i := 0; i < 12; i++ { |
| + method, body := "POST", strings.Repeat("p", 1000+i) |
| + if i%2 == 1 { |
| + method, body = "GET", "" |
| + } |
| + crossing = append(crossing, drainAsync(t, r.url, method, "/", body)) |
| + } |
| + // box-01's share answers at once; box-00's waits on a box that dropped |
| + // it, until the hub reads the GOAWAY. |
| + replicaAwait(t, "box-01's share of the requests", func() bool { return b1.backend.Load()-b1Before >= 6 }) |
| + time.Sleep(100 * time.Millisecond) |
| + waiting := 12 - int(b1.backend.Load()-b1Before) |
| + r.hold.releaseGoAway() |
| + for _, ch := range crossing { |
| + res := <-ch |
| + // TestReplicaRequestsCrossingDrainServedBySurvivor |
| + if res.code != 200 || res.got != "box-01 "+res.method+" "+res.body { |
| + t.Errorf("a request crossing the drain: %s %d %q, want box-01's answer", res.method, res.code, res.got) |
| + } |
| + } |
| + if waiting == 0 || b0.reached.Load() != reachedBefore || b1.backend.Load()-b1Before != 12 { |
| + t.Fatalf("crossing: %d waited on box-00, %d reached box-00's edge, box-01 served %d of 12", waiting, b0.reached.Load()-reachedBefore, b1.backend.Load()-b1Before) |
| + } |
| + b0.releaseFinish() |
| + if res := <-accepted; res.code != 200 || res.got != "box-00 POST f" { |
| + t.Fatalf("the request accepted before the drain: %d %q", res.code, res.got) |
| + } |
| +} |
| + |
| +// TestReplicaGapRequestsServedBySurvivor is R27's witness through the real |
| +// hub and box wiring, in drill 3's order: systemd stops box-00's app (a |
| +// stop the activator did not ask for), requests arrive in the gap, then |
| +// box-00's edge begins its shutdown. Every gap request, GETs and POSTs, is |
| +// served by box-01 with zero failures: |
| +// - one whose wake fails at once in the gap is refused (the app stopped |
| +// outside the activator) before the edge's shutdown; |
| +// - ones waiting on the wake are refused when the shutdown begins. |
| +// |
| +// None reached box-00's app; box-00 answered none. |
| +func TestReplicaGapRequestsServedBySurvivor(t *testing.T) { |
| + act := newReplicaGapActivator() |
| + act.failFast.Store(1) |
| + r := newReplicaDrainRig(t, drainRigOpts{drains: true, act: act}) |
| + b0 := r.boxes[0] |
| + served := map[string]int{} |
| + for i := 0; i < 4; i++ { |
| + code, body := drainDo(t, r.url, "GET", "/", "") |
| + if code != 200 { |
| + t.Fatalf("before the stop: %d %q", code, body) |
| + } |
| + served[strings.Fields(body)[0]]++ |
| + } |
| + if served["box-00"] == 0 || served["box-01"] == 0 { |
| + t.Fatalf("both copies did not serve: %v", served) |
| + } |
| + appBefore := b0.backend.Load() |
| + |
| + act.stopApp() |
| + // A gap request whose wake fails at once. |
| + fast := parkOn(t, r.url, "POST", "/", "fast", func() bool { return act.refused.Load() >= 1 }) |
| + var gap []<-chan drainResult |
| + gap = append(gap, fast) |
| + // The refusal took box-00 out of the live set; it is still up, so it |
| + // comes back, and the next gap requests wait on its wake. |
| + r.relive(t) |
| + gap = append(gap, parkOn(t, r.url, "POST", "/", "waits", func() bool { return act.parked.Load() >= 1 })) |
| + gap = append(gap, parkOn(t, r.url, "GET", "/", "", func() bool { return act.parked.Load() >= 2 })) |
| + |
| + b0.edge.beginShutdown() |
| + for _, ch := range gap { |
| + res := <-ch |
| + // TestReplicaGapRequestsServedBySurvivor |
| + if res.code != 200 || res.got != "box-01 "+res.method+" "+res.body { |
| + t.Errorf("a gap request: %s %d %q, want box-01's answer", res.method, res.code, res.got) |
| + } |
| + } |
| + if act.refused.Load() != 3 || act.answered.Load() != 0 || b0.backend.Load() != appBefore { |
| + t.Fatalf("box-00 refused %d, answered %d, its app saw %d gap requests; want 3, 0, 0", act.refused.Load(), act.answered.Load(), b0.backend.Load()-appBefore) |
| + } |
| +} |
diff --git a/internal/edge/tunnelrefuse.go b/internal/edge/tunnelrefuse.go| new file mode 100644 |
| index 000000000..78d51bd79 |
| --- /dev/null |
| +++ b/internal/edge/tunnelrefuse.go |
| @@ -0,0 +1,33 @@ |
| +package edge |
| + |
| +import ( |
| + "net/http" |
| + |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| +) |
| + |
| +// RefuseBeforeApp is #511 R27's one rule. It refuses r's fleet tunnel |
| +// stream unprocessed (RST_STREAM REFUSED_STREAM, tunnelclient.Refuse), |
| +// instead of answering it, when the box's shutdown has begun (its tunnel |
| +// drain) or stoppedOutside (the host's app last ended without the |
| +// activator asking it to: systemd's shutdown, a hand stop, a crash). The |
| +// hub then sends the request to another copy whatever its method (R26). |
| +// |
| +// A caller calls it only for a request no app has read: one that failed |
| +// before it was written to the app's socket. Exactly three places do: the |
| +// edge's admission refusal (admissionRefuses), the activator's refusals in |
| +// serve before its proxy runs (serveWakeErrorBeforeApp), and the app |
| +// socket proxy's error for a request it never got onto a connection to |
| +// the app (refuseUnreachedApp). After a true answer the caller writes |
| +// nothing and returns. It answers false, and the caller answers as before, |
| +// for a client that has gone, off a fleet tunnel stream, when something |
| +// was already written, or when neither condition holds. |
| +func RefuseBeforeApp(r *http.Request, stoppedOutside bool) bool { |
| + if r.Context().Err() != nil { |
| + return false |
| + } |
| + if !tunnelclient.Draining(r.Context()) && !stoppedOutside { |
| + return false |
| + } |
| + return tunnelclient.Refuse(r) |
| +} |