Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
netproxy: a hung system proxy read holds no request; a failed one keeps the last proxy (#3421)
JoeyWu-tech4725c772bba2
diff --git a/internal/netproxy/boot_test.go b/internal/netproxy/boot_test.goindex 376f59e7e..7e217b1df 100644--- a/internal/netproxy/boot_test.go+++ b/internal/netproxy/boot_test.go@@ -17,7 +17,7 @@ func TestSystemProxySetAfterStartIsTakenSoon(t *testing.T) {var p atomic.Valuep.Store(Proxy{})oldRead, oldNone := readSystem, noneKeep- readSystem = func() Proxy { return p.Load().(Proxy) }+ readSystem = func() (Proxy, bool) { return p.Load().(Proxy), true }noneKeep = 50 * time.MillisecondsysCache.Lock()sysCache.at, sysCache.p = time.Time{}, Proxy{}diff --git a/internal/netproxy/netproxy.go b/internal/netproxy/netproxy.goindex 5c9989cb5..07da998e9 100644--- a/internal/netproxy/netproxy.go+++ b/internal/netproxy/netproxy.go@@ -453,35 +453,80 @@ type Proxy struct {var sysCache struct {sync.Mutex- at time.Time- p Proxy+ at time.Time // when the last read ended; zero: nothing read yet+ p Proxy+ failed bool // the last read failed, so p is from one before it+ // reading is closed when the read under way, begun at since, ends;+ // nil while none is+ reading chan struct{}+ since time.Time}// How long a system proxy read stands: a proxy that is set, 15 seconds;// none, 2. magpie started at login comes up before the proxy app does// (#1518), and its requests went direct for up to 15 seconds after the-// proxy app had set the system's proxy.+// proxy app had set the system's proxy. A request waits for a read until+// readWait after the read began, then takes what was read before: a+// scutil that never answered held every request that asked for the+// system's proxy for as long as it hung (#3421).var (systemKeep = 15 * time.SecondnoneKeep = 2 * time.Second+ readWait = 2 * time.SecondreadSystem = system)// System reads the system proxy, at most every 15 seconds while one is-// set and every 2 while none is.+// set and every 2 while none is. One read runs at a time, outside the+// lock. A read that fails keeps what was read before, and the one after+// it holds nobody.func System() Proxy {sysCache.Lock()- defer sysCache.Unlock()keep := systemKeepif sysCache.p.URL == "" {keep = noneKeep}- if sysCache.at.IsZero() || time.Since(sysCache.at) > keep {- sysCache.p, sysCache.at = readSystem(), time.Now()+ if !sysCache.at.IsZero() && time.Since(sysCache.at) <= keep {+ p := sysCache.p+ sysCache.Unlock()+ return p+ }+ if sysCache.reading == nil {+ sysCache.reading, sysCache.since = make(chan struct{}), time.Now()+ go refreshSystem(sysCache.reading)+ }+ var wait time.Duration+ if sysCache.at.IsZero() || !sysCache.failed {+ wait = time.Until(sysCache.since.Add(readWait))+ }+ done := sysCache.reading+ sysCache.Unlock()+ if wait > 0 {+ t := time.NewTimer(wait)+ select {+ case <-done:+ case <-t.C:+ }+ t.Stop()}+ sysCache.Lock()+ defer sysCache.Unlock()return sysCache.p}+// refreshSystem reads the system proxy into sysCache, then closes done.+// A read that fails keeps what was read before, if anything was.+func refreshSystem(done chan struct{}) {+ p, ok := readSystem()+ sysCache.Lock()+ if ok || sysCache.at.IsZero() {+ sysCache.p = p+ }+ sysCache.at, sysCache.failed, sysCache.reading = time.Now(), !ok, nil+ sysCache.Unlock()+ close(done)+}+func loopback(host string) bool {if host == "localhost" || strings.HasSuffix(host, ".localhost") {return truediff --git a/internal/netproxy/scutil.go b/internal/netproxy/scutil.goindex 699f50375..929e08212 100644--- a/internal/netproxy/scutil.go+++ b/internal/netproxy/scutil.go@@ -1,10 +1,31 @@package netproxyimport (+ "context""net""strings"+ "time"++ "github.com/yetone/magpie/internal/proc")+// toolWait is how long a tool that reads the system's proxy gets. scutil+// answers in milliseconds; one that never did held every request that+// asked for the system's proxy (#3421).+var toolWait = 10 * time.Second++// readTool runs a tool that prints the system's proxy and parses what it+// prints. A run that fails, or is ended at toolWait, is a failed read.+func readTool(parse func(string) Proxy, name string, args ...string) (Proxy, bool) {+ ctx, cancel := context.WithTimeout(context.Background(), toolWait)+ defer cancel()+ out, err := proc.CommandContext(ctx, name, args...).Output()+ if err != nil {+ return Proxy{}, false+ }+ return parse(string(out)), true+}+// parseScutil reads `scutil --proxy`. HTTPS wins over HTTP over SOCKS for// URL; HTTP and SOCKS are each entry alone.func parseScutil(out string) Proxy {diff --git a/internal/netproxy/stuckread_test.go b/internal/netproxy/stuckread_test.gonew file mode 100644index 000000000..0c9e4a179--- /dev/null+++ b/internal/netproxy/stuckread_test.go@@ -0,0 +1,190 @@+package netproxy++import (+ "runtime"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++type readAnswer struct {+ p Proxy+ ok bool+}++// holdReads makes each read of the system proxy wait for the test's+// answer. The cache starts as p, read at at (zero: nothing read yet), and+// a request waits for a read until wait after it began. It returns how+// many reads began and where to answer them.+func holdReads(t *testing.T, p Proxy, at time.Time, wait time.Duration) (*atomic.Int32, chan<- readAnswer) {+ t.Helper()+ var reads atomic.Int32+ answers, stop := make(chan readAnswer), make(chan struct{})+ oldRead, oldWait := readSystem, readWait+ readSystem = func() (Proxy, bool) {+ reads.Add(1)+ select {+ case a := <-answers:+ return a.p, a.ok+ case <-stop:+ return Proxy{}, false+ }+ }+ readWait = wait+ sysCache.Lock()+ sysCache.at, sysCache.p, sysCache.failed = at, p, false+ sysCache.Unlock()+ t.Cleanup(func() {+ // the read still under way ends before the next test reads+ close(stop)+ readEnds(t, underWay())+ readSystem, readWait = oldRead, oldWait+ sysCache.Lock()+ sysCache.at, sysCache.p, sysCache.failed = time.Time{}, Proxy{}, false+ sysCache.Unlock()+ })+ return &reads, answers+}++// underWay is the read of the system proxy under way, nil when none is.+func underWay() chan struct{} {+ sysCache.Lock()+ defer sysCache.Unlock()+ return sysCache.reading+}++func readEnds(t *testing.T, done chan struct{}) {+ t.Helper()+ if done == nil {+ return+ }+ select {+ case <-done:+ case <-time.After(10 * time.Second):+ t.Fatal("the read of the system proxy never ended")+ }+}++// ask is System() for a test that fails when no answer comes in 10s.+func ask(t *testing.T) Proxy {+ t.Helper()+ got := make(chan Proxy, 1)+ go func() { got <- System() }()+ select {+ case p := <-got:+ return p+ case <-time.After(10 * time.Second):+ t.Fatal("a request still waits on a read of the system proxy that never ends")+ return Proxy{}+ }+}++// #3421: a scutil --proxy that never answered held System's lock, and+// with it every request that asked for the system's proxy, for as long as+// it hung. A request now waits for a read until readWait after the read+// began, then goes on with what was read before (here nothing yet, so+// direct), and one read runs at a time.+func TestStuckSystemProxyReadHoldsNoRequest(t *testing.T) {+ const wait = time.Second+ reads, answers := holdReads(t, Proxy{}, time.Time{}, wait)++ got := make(chan Proxy, 8)+ for range 8 {+ go func() { got <- System() }()+ }+ for i := range 8 {+ select {+ case p := <-got:+ if p.URL != "" {+ t.Fatalf("nothing read yet, but a request went through %+v", p)+ }+ case <-time.After(10 * time.Second):+ t.Fatalf("%d of 8 requests still wait on a read of the system proxy that never ends", 8-i)+ }+ }+ if n := reads.Load(); n != 1 {+ t.Fatalf("%d reads of the system proxy at once, want 1", n)+ }++ // The read is past readWait: a request doesn't wait for it again.+ start := time.Now()+ ask(t)+ if took := time.Since(start); took >= wait {+ t.Fatalf("a request waited %v for a read already past readWait (%v)", took, wait)+ }++ // It answers at last, and what it read is taken.+ done := underWay()+ answers <- readAnswer{Proxy{URL: "http://127.0.0.1:7890"}, true}+ readEnds(t, done)+ if p := ask(t); p.URL != "http://127.0.0.1:7890" {+ t.Fatalf("the read answered, but requests take %+v", p)+ }+ if n := reads.Load(); n != 1 {+ t.Fatalf("%d reads of the system proxy, want 1", n)+ }+}++// A read that fails, or hasn't answered by readWait, leaves the proxy+// read before in place, so requests keep going through it. The read after+// a failed one holds nobody.+func TestFailedSystemProxyReadKeepsTheProxy(t *testing.T) {+ const wait = time.Second+ set := Proxy{URL: "http://127.0.0.1:7890"}+ reads, answers := holdReads(t, set, time.Now().Add(-time.Hour), wait)++ if p := ask(t); p.URL != set.URL {+ t.Fatalf("while a read hangs, requests lost the proxy read before: %+v", p)+ }+ done := underWay()+ answers <- readAnswer{Proxy{}, false}+ readEnds(t, done)+ if p := ask(t); p.URL != set.URL {+ t.Fatalf("a failed read dropped the proxy read before: %+v", p)+ }+ if n := reads.Load(); n != 1 {+ t.Fatalf("%d reads: a failed one was tried again before its keep was up", n)+ }++ // Its keep is up: the next read is tried, and no request waits for it.+ sysCache.Lock()+ sysCache.at = time.Now().Add(-time.Hour)+ sysCache.Unlock()+ start := time.Now()+ if p := ask(t); p.URL != set.URL {+ t.Fatalf("after a failed read, requests lost the proxy read before: %+v", p)+ }+ if took := time.Since(start); took >= wait {+ t.Fatalf("a request waited %v for the read after a failed one", took)+ }+ done = underWay()+ answers <- readAnswer{Proxy{URL: "http://127.0.0.1:7891"}, true}+ readEnds(t, done)+ if p := ask(t); p.URL != "http://127.0.0.1:7891" {+ t.Fatalf("the read after a failed one answered, but requests take %+v", p)+ }+}++// The tool that reads the system's proxy (scutil on macOS) is ended at+// toolWait, and its read fails; what a tool that answers prints is parsed.+func TestSystemProxyToolThatHangsIsEnded(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("no echo or sleep program on Windows")+ }+ parse := func(out string) Proxy { return Proxy{URL: strings.TrimSpace(out)} }+ if p, ok := readTool(parse, "echo", "http://127.0.0.1:7890"); !ok || p.URL != "http://127.0.0.1:7890" {+ t.Fatalf("a tool that answered read as %+v, %v", p, ok)+ }++ old := toolWait+ toolWait = 100 * time.Millisecond+ t.Cleanup(func() { toolWait = old })+ start := time.Now()+ if p, ok := readTool(parse, "sleep", "30"); ok || p.URL != "" {+ t.Fatalf("a tool that never answered read as %+v, %v", p, ok)+ }+ if took := time.Since(start); took > 10*time.Second {+ t.Fatalf("a tool that never answered held the read %v", took)+ }+}diff --git a/internal/netproxy/system_darwin.go b/internal/netproxy/system_darwin.goindex fa31d2548..62ee38e45 100644--- a/internal/netproxy/system_darwin.go+++ b/internal/netproxy/system_darwin.go@@ -1,13 +1,5 @@package netproxy-import "github.com/yetone/magpie/internal/proc"-// system reads what System Settings → Network → Proxies says, through// scutil (the same dictionary CFNetwork uses).-func system() Proxy {- out, err := proc.Command("scutil", "--proxy").Output()- if err != nil {- return Proxy{}- }- return parseScutil(string(out))-}+func system() (Proxy, bool) { return readTool(parseScutil, "scutil", "--proxy") }diff --git a/internal/netproxy/system_other.go b/internal/netproxy/system_other.goindex 55628d5c1..524b86d5d 100644--- a/internal/netproxy/system_other.go+++ b/internal/netproxy/system_other.go@@ -3,4 +3,4 @@package netproxy// system: elsewhere the desktop's proxy reaches apps as *_PROXY variables.-func system() Proxy { return Proxy{} }+func system() (Proxy, bool) { return Proxy{}, true }diff --git a/internal/netproxy/system_windows.go b/internal/netproxy/system_windows.goindex 4525adee4..9cec4b946 100644--- a/internal/netproxy/system_windows.go+++ b/internal/netproxy/system_windows.go@@ -1,21 +1,27 @@package netproxy-import "golang.org/x/sys/windows/registry"+import (+ "errors"++ "golang.org/x/sys/windows/registry"+)// system reads Internet Options' manual proxy (what most proxy clients set).-func system() Proxy {+// A key or value that isn't there is no proxy; any other error is a+// failed read.+func system() (Proxy, bool) {k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.QUERY_VALUE)if err != nil {- return Proxy{}+ return Proxy{}, errors.Is(err, registry.ErrNotExist)}defer k.Close()if on, _, err := k.GetIntegerValue("ProxyEnable"); err != nil || on == 0 {- return Proxy{}+ return Proxy{}, err == nil || errors.Is(err, registry.ErrNotExist)}server, _, err := k.GetStringValue("ProxyServer")if err != nil {- return Proxy{}+ return Proxy{}, errors.Is(err, registry.ErrNotExist)}override, _, _ := k.GetStringValue("ProxyOverride")- return parseWindows(server, override)+ return parseWindows(server, override), true}