Files
magpie/internal/gui/backend.go
T
yetone a39e675d2a gui: magpie web beside a busy gateway waits for the port instead of failing to bind it (K.Liu)
K.Liu on Discord: `magpie web` next to the systemd `magpie daemon` logged
"gateway: listen tcp 0.0.0.0:3425: bind: address already in use".

Cause: before listening, serveGatewayLocked asks the gateway's address
whether a magpie serves it (ServedBy, one GET with a 700ms timeout). A
magpie that holds the port but doesn't answer in time (busy on a small
server, or still starting) reads as "nobody", so the page's process
listened itself and the bind failed. With the service answering, no
second gateway was started and the page's state matched.

Now, after ServedBy says no, gateway.Taken() dials the address (500ms).
When something accepts, this magpie doesn't listen; it logs once that the
port is taken and leaves it to the 15s watch, which serves the gateway
once the port is free.

Run:
- Sandbox HOME, settings {"port":3461,"lan":true}: `magpie serve`, then
  `kill -STOP` it, then `magpie web --no-open --addr 127.0.0.1:3462`. The
  old binary printed the exact bind error. The new one logs "is taken but
  doesn't answer as magpie yet" and doesn't bind. After SIGCONT,
  /v1/models and the page's /api/state show the same 3 models. With the
  serve killed, the page's process took 3461 over in about 16s.
- TestGatewayNotServedBesideASlowOne (a listener whose handler blocks):
  it goes red with the Taken check reverted by hand.
- gofmt -l; go vet (gui), and go vet -tags nogui for darwin, linux and
  windows, on cli, daemon, gui and gateway; go test -tags nogui ./... in a
  sandbox HOME.
2026-10-14 08:32:40 +08:00

154 lines
4.9 KiB
Go

package gui
import (
"context"
"log"
"sync"
"sync/atomic"
"time"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/update"
)
// served is the gateway this process serves, nil while another magpie
// has it.
var served atomic.Pointer[gateway.Server]
// backendCtx ends the gateway this process serves (stopServing).
var backendCtx, endBackend = context.WithCancel(context.Background())
// serving is the gateway this process serves, until it has finished.
var serving sync.WaitGroup
// stopServing stops this process's gateway taking requests and returns
// once those in flight have finished.
func stopServing() {
endBackend()
serving.Wait()
}
// startBackend starts what serves the page and the agents: the gateway,
// unless another magpie has it (then that one serves and this one only
// shows its status, and gw is nil — until that one is gone: a magpie left
// running from before an update, a magpie serve in a terminal), and the
// model lists kept warm.
func startBackend() (gw *gateway.Server) {
gateway.Window = true // the routing this process serves is shown on its page
gw = serveGateway()
go watchGateway(backendCtx, gatewayWatch)
// Codex's background app-server, restarted when it has the list from
// before a change and no codex session is on it (luci)
go agent.KeepCodexDaemonCurrent(backendCtx)
// Model lists are fetched, never compiled in: whatever the agents can see
// comes from the models.dev catalog plus each vendor's own /models answer.
// Keep both halves warm without making the user click anything.
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
if catalog.Stale() {
if err := catalog.Sync(ctx); err != nil {
log.Println("catalog:", err)
}
}
cancel()
// A signed-in agent's list exists only at the vendor; fill it in the
// first time so the picker never shows a stale snapshot.
provider.FetchNew(20 * time.Second)
// lists an older magpie wrote into agents' files, without what
// it has learnt since (context windows, providers added)
agent.SyncCatalog()
// and fetched again each day it stays open, for new models' prices
catalog.KeepFresh()
}()
return gw
}
// gatewayWatch is how often a magpie without the gateway looks for it gone.
const gatewayWatch = 15 * time.Second
// watchGateway takes the gateway up once the magpie that had it is gone,
// looking every so often until ctx ends: a watch that outlived it would
// start a gateway after this one has stopped serving.
func watchGateway(ctx context.Context, every time.Duration) {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
gatewayMu.Lock()
if ctx.Err() == nil && served.Load() == nil && !gateway.Running() {
serveGatewayLocked()
}
gatewayMu.Unlock()
}
}
// takenSaid: the log has said the gateway's port is taken by one that
// doesn't answer, said once until it is free again.
var takenSaid atomic.Bool
// gatewayMu keeps one start of the gateway here at a time: the watch's,
// a restart's, a take-over's (takeover.go).
var gatewayMu sync.Mutex
// servedRun ends the gateway this process serves, and is closed once it
// has, for a restart; under gatewayMu.
var servedRun struct {
stop context.CancelFunc
done chan struct{}
}
// serveGateway starts the gateway here when no magpie has it: the one
// started, or nil.
func serveGateway() *gateway.Server {
gatewayMu.Lock()
defer gatewayMu.Unlock()
return serveGatewayLocked()
}
func serveGatewayLocked() *gateway.Server {
// handing over, the one there is this one's predecessor, which lets go
// once this one listens beside it
if !gateway.Handover {
if o := gateway.ServedBy(); o.Running {
if update.Newer(gateway.Version, o.Version) {
log.Printf("gateway: magpie %s serves %s, older than this one (%s); agents' requests go through it until it quits", o.Version, gateway.URL(), gateway.Version)
}
return nil
}
// a magpie too busy to answer the question in time (a small
// server, one starting), or another program, has the port: a
// second listen only fails (K.Liu on Discord: magpie web beside
// the service logged "bind: address already in use")
if gateway.Taken() {
if !takenSaid.Swap(true) {
log.Printf("gateway: %s is taken but doesn't answer as magpie yet; this magpie serves the gateway once it is free", gateway.URL())
}
return nil
}
}
takenSaid.Store(false)
gw := gateway.New()
served.Store(gw)
serving.Add(1)
ctx, stop := context.WithCancel(backendCtx)
done := make(chan struct{})
servedRun.stop, servedRun.done = stop, done
go func() {
defer serving.Done()
defer close(done)
defer stop()
if err := gw.ListenAndServe(ctx); err != nil {
log.Println("gateway:", err)
served.CompareAndSwap(gw, nil) // another took the port first
}
}()
return gw
}