On a restart to update the old magpie hands its listening socket to the new one (Inherit, then HandOff once the new one serves on it). HandOff only marked the drain, so the old one went on accepting from the shared socket beside the new one until its end's Shutdown closed its copy. net/http's conn.serve returns without an answer when it reads a request after Shutdown began (go1.26.8 net/http/server.go:1994), so a connection the old one took in the moment before its Shutdown, whose request it read a moment after, was closed unanswered. The agent got EOF on a fresh connection, which Go's client doesn't retry for a POST. That is CI's red at81a58d2f(run 40210740758, ubuntu-latest): handover_test.go:142: request 0 during the handover: Post "http://127.0.0.1:.../v1/chat/completions": EOF `make dev`'s handover (Handover) ends through the same drain and lost such a connection the same way. Now: - HandOff lets this process's copy of the socket go at once (stopAccepting). The new one's copy keeps the socket open, so every connection from then on waits in its queue for the new one, and none is refused. A `make dev` backend lets its own listener go as its end begins; the one started beside it has the port on a socket of its own. - Before Shutdown, a handover's end waits until Serve has returned and each connection it took has had its first request read (unreadConns, the server's ConnState), unreadWait (5s) at most: a connection that sends nothing for 5s is idle to Shutdown too. Serve returning counts because net/http notes a connection (StateNew) on the goroutine that took it, after Accept and before Serve can return; Shutdown marks the server shutting down before it waits for Serve, so one noted after that would have its request cut too. - Serve ending because its listener was let go waits for the drain, as an end through Shutdown does. An ordinary quit and a restart that waits are unchanged: no wait, the 2s drain. Documented in docs/subsystems/gui-shell.md (the handover's step 3) and gateway-routing.md. Not changed: - With TLS on, tlsListener has a connection from this computer wait for its first byte (sniff) before handing it to the server, and closes one still waiting when the listener closes (hand, tls.go:288). Such a connection is still closed unanswered, at HandOff now and at Shutdown before (#3647). - `make dev`'s own backend server (dev_on.go, dev builds only), which serves the page rather than agents, still calls Shutdown at once as its handover begins: the same drop for the page's requests (noted on #3568). - An idle keep-alive connection is closed by Shutdown, as HTTP/1.1 lets a server do; a client sending on it in that moment sees it closed. - What waits in `make dev`'s own SO_REUSEPORT queue when it closes is reset by the kernel, at its end's start now and at Shutdown before. What was run (tree e1968b96, on origin/main9fc382e6, go1.26.8; Linux, outside graftcp, umask 077; line numbers at this tree): TestHandedOverGatewayFinishesItsStream as it is, -count=200: 3 of 200 red at origin/main with CI's message (handover_test.go:142 there), 0 of 200 with this change with the drain injected 50ms late and a connection taken once handed off served 100ms late (scratch, env-gated), -count=20: 10 of 20 red at origin/main's gateway, handover_test.go:144: request 0 during the handover: Post "http://127.0.0.1:.../v1/chat/completions": EOF; 0 of 20 with this change. The drain 50ms late alone: 9 of 20 red there, handover_test.go:153: the new one answered 0 of the 5 requests after the handover; 0 of 20 with it the new tests on origin/main's gateway.go and handover.go, -count=20: TestHandedOffGatewayTakesNoNewConnection 20 of 20 red: handover_test.go:275: the old one answered 1 request(s) made once it had handed the gateway off TestHandedOffGatewayAnswersAConnectionItTook, both subtests 20 of 20 red: handover_test.go:335: a request on a connection the old one took, sent once its end began: "" unexpected EOF TestHandedOffGatewayAnswersAConnectionNotedLate, both subtests 20 of 20 red: handover_test.go:435: a request on a connection the old one took, noted once its end began: "" unexpected EOF with this change, -race -count=20 of those four, TestSameAddr, TestInheritedForAnotherAddressIsLetGo, TestToolCallOfTheMagpieBeforeGoesToIt, TestCallbacksSocketServesOnlyToolCalls and TestBridgeTurnsCount: ok, no race (load 94) broken by hand, with this change, -count=20 each: HandOff not letting its listener go: TestHandedOffGatewayTakesNoNewConnection 20 of 20 (:275), and TestHandedOverGatewayFinishesItsStream 1 of 20, handover_test.go:153: the new one answered 1 of the 5 requests after the handover Serve's end once its listener is let go not waiting for the drain: TestHandedOverGatewayFinishesItsStream 20 of 20, handover_test.go:159: the old one ended with a stream in flight: accept tcp 127.0.0.1:...: use of closed network connection; the four subtests above 20 of 20 with the same error (:342, :440) no wait before Shutdown: the four subtests 20 of 20 (:335, :435) the wait not waiting for Serve to return: both subtests of ...NotedLate 20 of 20 (:435) a `make dev` end keeping its listener: both make dev subtests 20 of 20, handover_test.go:345: the old one never ended once its connections were answered (it waits out unreadWait's 5s; the tests give it 3s, against the ~0.1s it takes) the end's steps for a handed-off gateway only: both make dev subtests 20 of 20 (:335, :435) internal/gui TestRestartHandsTheGatewayOver -count=20, the other gui handover tests -count=3 and internal/handoff -count=3: ok, as at origin/main -run TestTLS ./internal/gateway -count=3: ok gofmt -l: nothing. GOOS=linux and darwin go vet -tags nogui ./..., GOOS=windows go vet ./...: exit 0. GOOS=linux and darwin go build -tags nogui ., GOOS=windows go build .: exit 0 full suite, go test -tags nogui -count=1 -timeout 45m ./... (302 s, load 76 to 97): 64 packages ok, internal/gateway among them. 14 reds in 7 packages, none in a file this change touches: internal/agent TestCursorFolderFromTheEditorIsNotTheCLI, TestCopilotFolderFromAnIDEPluginIsNotTheCLI, TestQoderSettingsFromAnIDEPluginIsNotTheCLI and TestOmpDetectedWithPiDir: proc.Look keeps "not found" for a tool written in the tick of its folder's last change (#3141). internal/agent TestReasonixCLIRequiresSupportedNativeVersion and TestReasonixCLIRecoversAfterProbeTimeout: their fixture build under /tmp meets a /tmp/.git that isn't a repository of this user's ("error obtaining VCS status: exit status 128"). internal/davsync TestSync and TestSyncTeraCloudStillSeesOtherWrites: the local save lands in the push's clock tick (#3420). internal/edit TestWriteAtomicReadOnlyHardLink and internal/testenv TestProgram: umask 077 here; the fixtures' own modes go through it. internal/gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie: proc.ListeningOn reads every fd this user can, 19.7M on this machine (other projects' processes leak them), which takes 1m30s against the 30s the take-over gives it; both pass in a fresh pid namespace. internal/netproxy TestBunProxyLoginWithReservedCharacters: Bun 1.3.11 on PATH (#3397). internal/provider: fatal error: close of synctest channel from outside bubble, in TestUnreadLoginsWriteErrorsKeepCredentials (#3632). (A first suite run under systemd's own PATH, node v12 and no Bun, had four more in internal/plugin, "Cannot find module 'node:assert/strict'"; with the user's PATH, node v22, it is ok.) Not tried: a real restart to update on Linux or macOS (the tests hand the socket over within one process), and macOS at all; Windows, which doesn't hand over (vet and build only); a Relisten reaching the old one after HandOff, whose window is withdrawn by then. Ported from JoeyWu-tech's fix/3568-handoff-stops-accepting (56c67ad2, posted on #3568 on 10-25) after it went red on ubuntu CI again at0a7633136(run 40614167541, handover_test.go:142 EOF). Cherry-picked unchanged onto origin/main. Run again by the porter (mote-run, ata05b37353+ this; at the pushed head69626580b+ this, go build ./... and the handover set -count=10 ok;7bdefe212since then changes only the Routing page's JS, CSS and GUI tests): - the three new tests on the old gateway.go/handover.go, -count=5: 15 of 15 red; with this change, with TestHandedOverGatewayFinishesItsStream, TestSameAddr and TestInherited*, -count=20: ok. - the same set plus TestRestartHands*, -race -count=10: ok. - GOOS=windows and GOOS=linux go vet ./internal/gateway: ok. gofmt -l clean. - go test -timeout 45m ./internal/gateway: ok (510s). ./internal/gui/...: TestMainWindowCorners/macOS_26_SDK red on mote's macOS 27, #3949, not touched here. Not tried: a real update restart.
331 lines
9.9 KiB
Go
331 lines
9.9 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httputil"
|
|
"net/url"
|
|
"os"
|
|
"strconv"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// A restart to update hands the gateway over rather than ending it
|
|
// (internal/handoff): the magpie updating gives the new version the
|
|
// socket it listens on, the new one serves on it at once, and the old
|
|
// stops accepting and finishes the requests it has (handedOffDrain at
|
|
// most) before it quits. No connection is refused on the way: the socket
|
|
// is never closed, only accepted from by the other process.
|
|
|
|
// handedOffDrain is how long a magpie that handed the gateway over waits
|
|
// for its requests in flight to finish: the longest stream an agent has
|
|
// been seen to keep, as `make dev`'s handover waits.
|
|
var handedOffDrain = 15 * time.Minute
|
|
|
|
// shortDrain is how long the gateway's end waits for its requests when
|
|
// nothing serves the port after it: a quit, or a restart that waits.
|
|
var shortDrain = 2 * time.Second
|
|
|
|
// inherited is the listener the magpie before this one handed over, taken
|
|
// by the first Listen of its address; ack is called once this gateway
|
|
// serves on it, which tells the one before to stop accepting.
|
|
var inherited struct {
|
|
sync.Mutex
|
|
ln net.Listener
|
|
ack func()
|
|
}
|
|
|
|
// Inherit has this process's gateway serve on ln, the socket the magpie
|
|
// it replaces listened on, rather than listening itself; ack is called
|
|
// once it serves.
|
|
func Inherit(ln net.Listener, ack func()) {
|
|
inherited.Lock()
|
|
defer inherited.Unlock()
|
|
if inherited.ln != nil {
|
|
inherited.ln.Close()
|
|
}
|
|
inherited.ln, inherited.ack = ln, ack
|
|
}
|
|
|
|
// Inherited is whether a listener handed over is waiting to be served:
|
|
// the gateway's port is then held by the magpie that handed it over, and
|
|
// is this process's to serve all the same.
|
|
func Inherited() bool {
|
|
inherited.Lock()
|
|
defer inherited.Unlock()
|
|
return inherited.ln != nil
|
|
}
|
|
|
|
// takeInherited is the listener handed over when it listens on addr, and
|
|
// the ack to call once it serves. One on another address (the settings
|
|
// changed in between) is closed: the port is then listened on as usual.
|
|
func takeInherited(addr string) (net.Listener, func()) {
|
|
inherited.Lock()
|
|
defer inherited.Unlock()
|
|
ln, ack := inherited.ln, inherited.ack
|
|
if ln == nil {
|
|
return nil, nil
|
|
}
|
|
inherited.ln, inherited.ack = nil, nil
|
|
if !sameAddr(ln.Addr(), addr) {
|
|
log.Printf("gateway: the socket handed over listens on %s, not %s; listening anew", ln.Addr(), addr)
|
|
ln.Close()
|
|
return nil, nil
|
|
}
|
|
return ln, ack
|
|
}
|
|
|
|
// pendingAck is the ack of the socket handed over that Listen returned,
|
|
// for ListenAndServe to call once it serves on it.
|
|
var pendingAck struct {
|
|
sync.Mutex
|
|
ack func()
|
|
}
|
|
|
|
func setAck(ack func()) {
|
|
pendingAck.Lock()
|
|
pendingAck.ack = ack
|
|
pendingAck.Unlock()
|
|
}
|
|
|
|
// takeAck is the ack waiting, nil when the listener wasn't handed over.
|
|
func takeAck() func() {
|
|
pendingAck.Lock()
|
|
defer pendingAck.Unlock()
|
|
ack := pendingAck.ack
|
|
pendingAck.ack = nil
|
|
return ack
|
|
}
|
|
|
|
// sameAddr is whether a listens where addr names: the same port, on the
|
|
// same IP or both on every interface.
|
|
func sameAddr(a net.Addr, addr string) bool {
|
|
ta, ok := a.(*net.TCPAddr)
|
|
if !ok {
|
|
return false
|
|
}
|
|
host, port, err := net.SplitHostPort(addr)
|
|
if err != nil || port != strconv.Itoa(ta.Port) {
|
|
return false
|
|
}
|
|
if host == "" {
|
|
return ta.IP == nil || ta.IP.IsUnspecified()
|
|
}
|
|
ips := []net.IP{net.ParseIP(host)}
|
|
if ips[0] == nil {
|
|
// a name (localhost): any of its addresses
|
|
var err error
|
|
if ips, err = net.LookupIP(host); err != nil {
|
|
return false
|
|
}
|
|
}
|
|
for _, ip := range ips {
|
|
if ip.IsUnspecified() {
|
|
if ta.IP == nil || ta.IP.IsUnspecified() {
|
|
return true
|
|
}
|
|
} else if ip.Equal(ta.IP) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// ListenerFile is a copy of the socket the gateway listens on, to hand to
|
|
// the magpie that takes it over; the caller closes it once sent.
|
|
func (s *Server) ListenerFile() (*os.File, error) {
|
|
s.lnMu.Lock()
|
|
ln := s.ln
|
|
s.lnMu.Unlock()
|
|
if t, ok := ln.(*tlsListener); ok {
|
|
ln = t.Listener
|
|
}
|
|
tl, ok := ln.(*net.TCPListener)
|
|
if !ok {
|
|
return nil, errors.New("the gateway isn't listening on a TCP socket")
|
|
}
|
|
return tl.File()
|
|
}
|
|
|
|
// HandOff has the gateway stop accepting at once: the magpie it was
|
|
// handed to takes every connection from now on (one this one took as its
|
|
// end began was closed unanswered, #3568). Once its ctx ends, it waits
|
|
// for every request in flight to finish (handedOffDrain at most) rather
|
|
// than 2s.
|
|
func (s *Server) HandOff() {
|
|
s.handedOff.Store(true)
|
|
s.stopAccepting()
|
|
}
|
|
|
|
// stopAccepting has the gateway take no connection from here on, for the
|
|
// magpie serving the port after it: the copy of the socket handed to that
|
|
// one keeps the socket open, so a connection waits there rather than
|
|
// being refused. (`make dev`'s takes them on a socket of its own.)
|
|
func (s *Server) stopAccepting() {
|
|
s.lnMu.Lock()
|
|
defer s.lnMu.Unlock()
|
|
s.notAccepting.Store(true)
|
|
if s.ln != nil {
|
|
s.ln.Close()
|
|
}
|
|
}
|
|
|
|
// handingOver is whether another magpie serves the port once this
|
|
// gateway ends: it was handed off, or `make dev` started one beside it.
|
|
func (s *Server) handingOver() bool { return Handover || s.handedOff.Load() }
|
|
|
|
// drainFor is how long the gateway's end waits for the requests in flight.
|
|
func (s *Server) drainFor() time.Duration {
|
|
if s.handingOver() {
|
|
return handedOffDrain
|
|
}
|
|
return shortDrain
|
|
}
|
|
|
|
// unreadWait is how long a handover's end waits for a connection taken to
|
|
// send its first request: as for net/http's Shutdown, one that sent
|
|
// nothing for 5s is idle.
|
|
var unreadWait = 5 * time.Second
|
|
|
|
// unreadConns are the connections the gateway took whose first request it
|
|
// hasn't read yet. Shutdown closes such a connection unanswered when its
|
|
// request is read after it began, so a handover's end waits for them
|
|
// first: the agent's request is answered here, not cut.
|
|
type unreadConns struct {
|
|
mu sync.Mutex
|
|
conns map[net.Conn]bool
|
|
// stopped: the server takes none from here on, its Serve returned
|
|
stopped bool
|
|
}
|
|
|
|
// note is the server's ConnState: a connection is unread from StateNew to
|
|
// its next state, whichever it is.
|
|
func (u *unreadConns) note(c net.Conn, state http.ConnState) {
|
|
u.mu.Lock()
|
|
defer u.mu.Unlock()
|
|
if state != http.StateNew {
|
|
delete(u.conns, c)
|
|
return
|
|
}
|
|
if u.conns == nil {
|
|
u.conns = map[net.Conn]bool{}
|
|
}
|
|
u.conns[c] = true
|
|
}
|
|
|
|
// stop is called once the server's Serve has returned. net/http notes a
|
|
// connection (StateNew) on the goroutine that took it, before Serve can
|
|
// return, so every one it took is noted by then: one noted after Shutdown
|
|
// began would have its request closed unanswered too.
|
|
func (u *unreadConns) stop() {
|
|
u.mu.Lock()
|
|
u.stopped = true
|
|
u.mu.Unlock()
|
|
}
|
|
|
|
// wait returns once the server takes no more connections and none it took
|
|
// is unread, after unreadWait at most, or when ctx ends.
|
|
func (u *unreadConns) wait(ctx context.Context) {
|
|
for deadline := time.Now().Add(unreadWait); ; time.Sleep(10 * time.Millisecond) {
|
|
u.mu.Lock()
|
|
done := u.stopped && len(u.conns) == 0
|
|
u.mu.Unlock()
|
|
if done || time.Now().After(deadline) || ctx.Err() != nil {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// ServeCallbacks answers, on ln, the tool calls of the Claude Code runs
|
|
// this process started (claudeMCPPath): their MCP helper calls the
|
|
// gateway's port, which the magpie this one handed it to now serves, and
|
|
// that one passes on the calls of runs it doesn't have (ForwardCallbacks).
|
|
// It returns once ln is closed.
|
|
func (s *Server) ServeCallbacks(ln net.Listener) error {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("POST "+claudeMCPPath+"{token}", s.subscription.mcpCall)
|
|
err := (&http.Server{Handler: mux, ReadHeaderTimeout: 30 * time.Second}).Serve(ln)
|
|
if errors.Is(err, net.ErrClosed) || errors.Is(err, http.ErrServerClosed) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
// predecessorCallbacks is the unix socket of the magpie this one took the
|
|
// gateway over from, which answers its own runs' tool calls there; ""
|
|
// when there is none.
|
|
var predecessorCallbacks struct {
|
|
sync.Mutex
|
|
sock string
|
|
}
|
|
|
|
// ForwardCallbacks has a tool call for a Claude Code run this process
|
|
// doesn't know passed on to sock, where the magpie it took the gateway
|
|
// over from answers those of its own runs (ServeCallbacks): a turn under
|
|
// way there when the gateway changed hands still gets its tool results.
|
|
// "" stops it.
|
|
func ForwardCallbacks(sock string) {
|
|
predecessorCallbacks.Lock()
|
|
predecessorCallbacks.sock = sock
|
|
predecessorCallbacks.Unlock()
|
|
}
|
|
|
|
// forwardCallback passes the tool call r, for a run this process doesn't
|
|
// have, on to the magpie before this one; false when there is none to.
|
|
func forwardCallback(w http.ResponseWriter, r *http.Request) bool {
|
|
predecessorCallbacks.Lock()
|
|
sock := predecessorCallbacks.sock
|
|
predecessorCallbacks.Unlock()
|
|
if sock == "" {
|
|
return false
|
|
}
|
|
if _, err := os.Stat(sock); err != nil {
|
|
// that magpie has finished and gone
|
|
ForwardCallbacks("")
|
|
return false
|
|
}
|
|
p := &httputil.ReverseProxy{
|
|
Rewrite: func(pr *httputil.ProxyRequest) {
|
|
pr.SetURL(&url.URL{Scheme: "http", Host: "predecessor"})
|
|
pr.Out.URL.Path, pr.Out.URL.RawPath = r.URL.Path, r.URL.RawPath
|
|
},
|
|
Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
|
var d net.Dialer
|
|
return d.DialContext(ctx, "unix", sock)
|
|
}},
|
|
FlushInterval: -1,
|
|
ErrorHandler: func(w http.ResponseWriter, _ *http.Request, err error) {
|
|
if !errors.Is(err, io.EOF) {
|
|
log.Printf("claude: a tool call for the magpie before this one didn't reach it: %v", err)
|
|
}
|
|
http.Error(w, "unknown or expired Claude run", http.StatusNotFound)
|
|
},
|
|
}
|
|
p.ServeHTTP(w, r)
|
|
return true
|
|
}
|
|
|
|
// forwarding is whether tool calls this process doesn't know go on to the
|
|
// magpie it took the gateway over from.
|
|
func forwarding() bool {
|
|
predecessorCallbacks.Lock()
|
|
sock := predecessorCallbacks.sock
|
|
predecessorCallbacks.Unlock()
|
|
return sock != ""
|
|
}
|
|
|
|
// Addr is where the gateway listens, "" before it does.
|
|
func (s *Server) Addr() string {
|
|
s.lnMu.Lock()
|
|
defer s.lnMu.Unlock()
|
|
if s.ln == nil {
|
|
return ""
|
|
}
|
|
return s.ln.Addr().String()
|
|
}
|