diff --git a/internal/hosts/hosts.go b/internal/hosts/hosts.go new file mode 100644 index 0000000..05369b2 --- /dev/null +++ b/internal/hosts/hosts.go @@ -0,0 +1,106 @@ +// Package hosts finds Rex servers by what people call them: the local +// server, a host's label, as rex hosts lists them, or an address, the way +// the rex CLI's -S option takes them. It also lists and saves hosts, which +// the local server keeps. +package hosts + +import ( + "context" + "fmt" + "log" + "time" + + "100gex/internal/rex" +) + +// clientInfo is what this program tells servers about itself. +var clientInfo = rex.ClientInfo{Kind: "app", Name: "100gex"} + +// Dial opens a control connection to target: "" for the local server, a +// host's label, or an address. A label is looked up in the local server's +// hosts first, ignoring case; a value with a port is always an address. It +// returns the endpoint that answered, and the host's label if a label named +// it. +func Dial(ctx context.Context, target string) (*rex.Conn, rex.Endpoint, string, error) { + if target == "" { + ep, err := rex.DiscoverEndpoint() + if err != nil { + return nil, rex.Endpoint{}, "", err + } + c, err := rex.Dial(ctx, ep, clientInfo) + return c, ep, "", err + } + var candidates []rex.Endpoint + label := "" + if rex.LooksLikeLabel(target) { + if saved, err := Saved(ctx); err == nil { + if host, ok := rex.FindHost(saved, target); ok { + label = host.Label + for _, address := range host.Endpoints { + eps, err := rex.Candidates(address) + if err != nil { + log.Printf("host %s: %v", host.Label, err) + continue + } + candidates = append(candidates, eps...) + } + } + } + } + if label == "" { + eps, err := rex.Candidates(target) + if err != nil { + return nil, rex.Endpoint{}, "", err + } + candidates = eps + } + c, ep, err := rex.DialAny(ctx, candidates, clientInfo) + if err != nil { + return nil, rex.Endpoint{}, "", fmt.Errorf("connect to %s: %w", target, err) + } + return c, ep, label, nil +} + +// local opens a short-lived connection to the local server, which keeps +// the hosts. +func local(ctx context.Context) (*rex.Conn, error) { + ep, err := rex.DiscoverEndpoint() + if err != nil { + return nil, err + } + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + return rex.Dial(ctx, ep, clientInfo) +} + +// Saved returns the hosts the local server keeps, as rex hosts lists them. +func Saved(ctx context.Context) ([]rex.Host, error) { + c, err := local(ctx) + if err != nil { + return nil, err + } + defer c.Close() + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + return c.Hosts(ctx) +} + +// Save adds a host to the local server's hosts, or replaces the one with +// the same label, so that rex -S and other clients know it too. +func Save(ctx context.Context, label, address string) error { + c, err := local(ctx) + if err != nil { + return err + } + defer c.Close() + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + host := map[string]any{"label": label, "endpoints": []string{address}, "added_from": "100gex"} + if saved, err := c.Hosts(ctx); err == nil { + if h, ok := rex.FindHost(saved, label); ok { + host["id"] = h.ID + } + } + _, err = c.Call(ctx, "hosts.put", map[string]any{"host": host}, nil) + return err +} diff --git a/internal/hosts/hosts_test.go b/internal/hosts/hosts_test.go new file mode 100644 index 0000000..b20fd85 --- /dev/null +++ b/internal/hosts/hosts_test.go @@ -0,0 +1,49 @@ +package hosts + +import ( + "context" + "testing" + "time" + + "100gex/internal/rex" + "100gex/internal/rex/rextest" +) + +// TestDialLabel names a server by a host's label, which the local server +// (here, the one REX_SERVER names) keeps, as rex -S does. +func TestDialLabel(t *testing.T) { + local := rextest.Start(t) + studio := rextest.Start(t) + t.Setenv(rex.ServerEnv, local.Endpoint.String()) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + if err := Save(ctx, "studio", studio.Endpoint.String()); err != nil { + t.Fatal(err) + } + conn, ep, label, err := Dial(ctx, "Studio") // labels ignore case + if err != nil { + t.Fatal(err) + } + defer conn.Close() + if label != "studio" || ep != studio.Endpoint { + t.Errorf("Dial(Studio) = %v, label %q; want %v, studio", ep, label, studio.Endpoint) + } + + // Saving the label again replaces the host, rather than adding one. + if err := Save(ctx, "studio", "studio.tail1234.ts.net"); err != nil { + t.Fatal(err) + } + saved, err := Saved(ctx) + if err != nil { + t.Fatal(err) + } + if len(saved) != 1 || saved[0].Endpoints[0] != "studio.tail1234.ts.net" { + t.Errorf("hosts after saving twice = %+v, want one, at its new address", saved) + } + + // A name that isn't a label is an address. + if _, _, _, err := Dial(ctx, "nosuchhost.invalid"); err == nil { + t.Error("connected to an address that can't resolve") + } +} diff --git a/internal/rex/control.go b/internal/rex/control.go index 99d8e27..bbe060c 100644 --- a/internal/rex/control.go +++ b/internal/rex/control.go @@ -230,6 +230,13 @@ func (c *Conn) Close() error { return err } +// Drop ends the connection without closing it, as a network failure does: +// the server keeps the client for a while, for it to reconnect. +func (c *Conn) Drop() { + c.ws.CloseNow() + <-c.done +} + // Call calls method with args, which may be nil, and decodes its result into // result, which may also be nil. It returns the response's seq: events with a // higher seq happened after the server started the request. diff --git a/internal/ui/actions.go b/internal/ui/actions.go index 8d892a9..481512c 100644 --- a/internal/ui/actions.go +++ b/internal/ui/actions.go @@ -202,10 +202,11 @@ var actions = func() map[string]action { return nil }, true}, {info("client.config.reload", "Reload Config", "View"), func(u *UI, _ actionArgs) error { + conn := u.conn go func() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - if _, err := u.conn.Call(ctx, "server.config_reload", nil, nil); err != nil { + if _, err := conn.Call(ctx, "server.config_reload", nil, nil); err != nil { log.Printf("ui: reload config: %v", err) } }() @@ -331,10 +332,10 @@ func toModes(list []rex.KeymapMode) []keymap.Mode { // fetchKeymap asks the server for this client's keymap, and hands it to the // drawing goroutine. -func (u *UI) fetchKeymap() { +func (u *UI) fetchKeymap(conn *rex.Conn) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - result, err := u.conn.Keymap(ctx, rex.KeymapArgs{ + result, err := conn.Keymap(ctx, rex.KeymapArgs{ Actions: declaredActions(), Defaults: []rex.KeymapLayer{{Name: defaultsLayer, Bindings: defaultBindings()}}, }) @@ -352,6 +353,7 @@ func (u *UI) fetchKeymap() { km := keymap.New(toBindings(result.Bindings), toModes(result.Modes)) u.mu.Lock() u.newKeymap, u.newServerActions, u.newBindings, u.keymapHash = km, server, result.Bindings, result.Config.Hash + u.newKeymapConn = conn u.mu.Unlock() u.notify() } @@ -406,11 +408,13 @@ func (u *UI) queueClientActions(list []rex.ClientAction) { } // queuedAction is an action to perform on the drawing goroutine, from -// another goroutine. A callID means another client is waiting for it. +// another goroutine. A callID means another client is waiting for it, on +// conn. type queuedAction struct { name string args json.RawMessage callID string + conn *rex.Conn } // runQueued performs queued actions, answering any client waiting on one. @@ -431,22 +435,22 @@ func (u *UI) runQueued() { if err != nil { apiErr = &rex.Error{Code: "not_supported", Message: err.Error()} } - go u.reply(q.callID, apiErr) + go reply(q.conn, q.callID, apiErr) } } -func (u *UI) reply(callID string, err *rex.Error) { +func reply(conn *rex.Conn, callID string, err *rex.Error) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - if replyErr := u.conn.Reply(ctx, callID, nil, err); replyErr != nil { + if replyErr := conn.Reply(ctx, callID, nil, err); replyErr != nil { log.Printf("ui: reply: %v", replyErr) } } -// HandleEvent takes the events that concern this client rather than a -// session: keymap changes and requests from other clients. Call it from any -// goroutine with every event. -func (u *UI) HandleEvent(ev rex.Event) { +// handleEvent takes the events that concern this client rather than a +// session: keymap changes and requests from other clients. It runs on the +// goroutine that reads conn's events. +func (u *UI) handleEvent(conn *rex.Conn, ev rex.Event) { switch ev.Name { case "keymap_changed": var e struct { @@ -457,7 +461,7 @@ func (u *UI) HandleEvent(ev rex.Event) { same := e.Hash != "" && e.Hash == u.keymapHash u.mu.Unlock() if !same { - go u.fetchKeymap() + go u.fetchKeymap(conn) } case "client_perform_requested": var req rex.PerformRequest @@ -465,7 +469,7 @@ func (u *UI) HandleEvent(ev rex.Event) { return } u.mu.Lock() - u.queued = append(u.queued, queuedAction{name: req.Action, args: req.Args, callID: req.CallID}) + u.queued = append(u.queued, queuedAction{name: req.Action, args: req.Args, callID: req.CallID, conn: conn}) u.mu.Unlock() u.notify() case "client_prompt_requested": @@ -475,7 +479,7 @@ func (u *UI) HandleEvent(ev rex.Event) { CallID string `json:"call_id"` } if ev.Decode(&e) == nil && e.CallID != "" { - go u.reply(e.CallID, &rex.Error{Code: "not_supported", Message: "100gex can't show prompts yet"}) + go reply(conn, e.CallID, &rex.Error{Code: "not_supported", Message: "100gex can't show prompts yet"}) } } } diff --git a/internal/ui/keys_test.go b/internal/ui/keys_test.go index b9ebc24..379e038 100644 --- a/internal/ui/keys_test.go +++ b/internal/ui/keys_test.go @@ -63,13 +63,8 @@ func startUI(t *testing.T, srv *rextest.Server, c *rex.Conn, sessionID string) * t.Cleanup(ws.Close) h := &uiHarness{t: t} h.u = New(ws, c, theme.NewShaper(), func() {}) + h.u.SetTarget(srv.Endpoint.String(), "") t.Cleanup(h.u.Close) - go func() { - for ev := range c.Events() { - h.u.HandleEvent(ev) - ws.HandleEvent(ev) - } - }() return h } diff --git a/internal/ui/render_test.go b/internal/ui/render_test.go index 42c18b4..ec58d7c 100644 --- a/internal/ui/render_test.go +++ b/internal/ui/render_test.go @@ -39,12 +39,6 @@ func TestHeaderCentred(t *testing.T) { defer ws.Close() u := New(ws, c, theme.NewShaper(), func() {}) defer u.Close() - go func() { - for ev := range c.Events() { - u.HandleEvent(ev) - ws.HandleEvent(ev) - } - }() var ops op.Ops for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(20 * time.Millisecond) { @@ -135,12 +129,6 @@ func TestSessionRowsAligned(t *testing.T) { defer ws.Close() u := New(ws, c, theme.NewShaper(), func() {}) defer u.Close() - go func() { - for ev := range c.Events() { - u.HandleEvent(ev) - ws.HandleEvent(ev) - } - }() // starts renders the window once the session shown is want, and // returns where each row's name starts: the leftmost ink, right of the diff --git a/internal/ui/server.go b/internal/ui/server.go index c0e6ee6..4a56fd6 100644 --- a/internal/ui/server.go +++ b/internal/ui/server.go @@ -20,6 +20,7 @@ import ( "gioui.org/unit" "gioui.org/widget" + "100gex/internal/rex" "100gex/internal/theme" ) @@ -39,19 +40,22 @@ type serverChip struct { // fetchServerDetails asks the server for what the chip's card shows that // bootstrap didn't say. -func (u *UI) fetchServerDetails() { +func (u *UI) fetchServerDetails(conn *rex.Conn) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - v, verr := u.conn.ServerVersion(ctx) - who, werr := u.conn.ServerWhoami(ctx) + v, verr := conn.ServerVersion(ctx) + who, werr := conn.ServerWhoami(ctx) u.mu.Lock() + defer u.mu.Unlock() + if u.watched == nil || u.watched.conn != conn { + return // switched away meanwhile + } if verr == nil { u.server.version = v.RexVersion } if werr == nil { u.server.account = who.Account } - u.mu.Unlock() u.notify() } @@ -65,8 +69,8 @@ func (u *UI) serverName() (name, where string) { where = "local" } switch { - case u.ServerLabel != "": - name = u.ServerLabel + case u.srv.label != "": + name = u.srv.label case ep.Local(): name, _ = os.Hostname() case net.ParseIP(ep.Host) != nil: diff --git a/internal/ui/servers.go b/internal/ui/servers.go new file mode 100644 index 0000000..3aa9af1 --- /dev/null +++ b/internal/ui/servers.go @@ -0,0 +1,206 @@ +package ui + +import ( + "context" + "errors" + "time" + + "100gex/internal/hosts" + "100gex/internal/rex" + "100gex/internal/workspace" +) + +// server is the Rex server the window shows: the connection, the workspace +// on it, and what reaches it again. +type server struct { + conn *rex.Conn + ws *workspace.Workspace + label string // the host's label it was reached by, or "" + // target reaches it again: "" for the local server, a host's label, or + // an address. + target string +} + +// connecting is a switch to another server, or a reconnect, under way. +type connecting struct { + target string + reconnect bool + err error // why the last attempt failed +} + +// SetTarget says what reached the first server, so that a reconnect can +// reach it again, and the label to call it by. +func (u *UI) SetTarget(target, label string) { + u.srv.target, u.srv.label = target, label +} + +// setServer makes s the server the window shows. +func (u *UI) setServer(s *server) { + u.srv, u.conn, u.ws = s, s.conn, s.ws +} + +// watch passes a server's events to the UI and its workspace, until its +// connection ends, and then asks for a frame, so that the UI notices. +func (u *UI) watch(s *server) { + go func() { + for ev := range s.conn.Events() { + u.mu.Lock() + current := u.watched == s + u.mu.Unlock() + if !current { + continue // a server switched away from + } + u.handleEvent(s.conn, ev) + s.ws.HandleEvent(ev) + } + u.notify() + }() +} + +// Connect switches the window to another server: "" for the local one, a +// host's label, or an address. It connects in the background; the window +// keeps showing the current server until the new one is ready. +func (u *UI) Connect(target string) { + u.mu.Lock() + if u.connecting != nil && u.connecting.target == target && u.connecting.err == nil { + u.mu.Unlock() + return + } + c := &connecting{target: target} + u.connecting = c + u.mu.Unlock() + u.notify() + go u.dial(c, "") +} + +// dial connects to c.target and hands the server to the drawing goroutine. +// session, if set, is the session to show first. +func (u *UI) dial(c *connecting, session string) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + conn, ep, label, err := hosts.Dial(ctx, c.target) + var ws *workspace.Workspace + if err == nil { + ws, err = workspace.Start(ctx, conn, ep, session, u.TerminalTheme, u.notify) + if err != nil && session != "" { + // The session may be gone; show the one the server picks. + ws, err = workspace.Start(ctx, conn, ep, "", u.TerminalTheme, u.notify) + } + if err != nil { + conn.Close() + } + } + u.mu.Lock() + defer u.mu.Unlock() + if u.connecting != c { + // Superseded by another switch while connecting. + if err == nil { + go func() { ws.Close(); conn.Close() }() + } + return + } + if err != nil { + c.err = err + u.notify() + return + } + u.next = &server{conn: conn, ws: ws, label: label, target: c.target} + u.notify() +} + +// reconnectDelays are the waits between attempts to reach a server whose +// connection dropped. +var reconnectDelays = []time.Duration{0, time.Second, 2 * time.Second, 5 * time.Second, 10 * time.Second} + +// reconnect tries to reach the current server again, until it answers or +// the person switches away, showing the session shown before. +func (u *UI) reconnect(target, session string) { + c := &connecting{target: target, reconnect: true} + u.mu.Lock() + u.connecting = c + u.mu.Unlock() + u.notify() + go func() { + for i := 0; ; i++ { + time.Sleep(reconnectDelays[min(i, len(reconnectDelays)-1)]) + u.mu.Lock() + current := u.connecting == c + u.mu.Unlock() + if !current { + return + } + u.dial(c, session) + u.mu.Lock() + done := u.connecting != c || u.next != nil + u.mu.Unlock() + if done { + return + } + } + }() +} + +// syncServer runs on the drawing goroutine: it puts in place a server that +// has finished connecting, and starts reconnecting when the connection +// drops. +func (u *UI) syncServer() { + u.mu.Lock() + next := u.next + u.next = nil + if next != nil { + u.connecting = nil + } + reconnecting := u.connecting != nil && u.connecting.reconnect + u.mu.Unlock() + + if next != nil { + old := u.srv + u.setServer(next) + u.mu.Lock() + u.watched = next + u.serverActions, u.bindings = nil, defaultBindings() + u.server.version, u.server.account = "", "" + u.mu.Unlock() + u.palette.close() + u.watch(next) + conn := next.conn + go u.fetchKeymap(conn) + go u.fetchServerDetails(conn) + if old != nil { + // Its panes close here, on the drawing goroutine; the + // connection, in the background. + old.ws.Close() + go old.conn.Close() + } + return + } + + if err := u.conn.Err(); err != nil && !errors.Is(err, rex.ErrClosed) && !reconnecting { + session := "" + if u.session != nil { + session = u.session.ID() + } + u.reconnect(u.srv.target, session) + } +} + +// connectState describes a switch or reconnect under way, for the server +// chip, or returns "" when there is none. +func (u *UI) connectState() (state string, err error) { + u.mu.Lock() + defer u.mu.Unlock() + if u.connecting == nil { + return "", nil + } + if u.connecting.reconnect { + return "reconnecting", u.connecting.err + } + return "connecting to " + displayTarget(u.connecting.target), u.connecting.err +} + +func displayTarget(target string) string { + if target == "" { + return "this machine" + } + return target +} diff --git a/internal/ui/servers_test.go b/internal/ui/servers_test.go new file mode 100644 index 0000000..a743531 --- /dev/null +++ b/internal/ui/servers_test.go @@ -0,0 +1,63 @@ +package ui + +import ( + "errors" + "testing" + + "100gex/internal/rex" + "100gex/internal/rex/rextest" + "100gex/internal/rexsession" +) + +// TestSwitchServer switches the window to another server, which shows its +// own session, and closes the first connection. +func TestSwitchServer(t *testing.T) { + alpha := rextest.Start(t) + bravo := rextest.Start(t) + sidA, _ := rextest.NewSession(t, alpha.Dial(t, "setup"), rextest.RawCat...) + sidB, bidB := rextest.NewSession(t, bravo.Dial(t, "setup"), rextest.RawCat...) + + h := startUI(t, alpha, alpha.Dial(t, "100gex-test"), sidA) + h.until("the first server", func(f rexsession.Frame) bool { return f.Ready() && len(f.Visible) == 1 }) + first := h.u.conn + + h.u.Connect(bravo.Endpoint.String()) + h.until("the second server's session", func(f rexsession.Frame) bool { + return f.View.SessionID == sidB && f.Ready() && len(f.Visible) == 1 && f.Visible[0] == bidB + }) + // The first connection closes in the background. + h.until("the first connection to close", func(rexsession.Frame) bool { return errors.Is(first.Err(), rex.ErrClosed) }) + if state, _ := h.u.connectState(); state != "" { + t.Errorf("still %s after switching", state) + } + + // A server that isn't there leaves the window where it was, saying why. + h.u.Connect("unix:///nonexistent/rex.sock") + h.until("the failed switch", func(rexsession.Frame) bool { + _, err := h.u.connectState() + return err != nil + }) + if f := h.frame(); f.View.SessionID != sidB { + t.Errorf("after a failed switch, showing %s, want %s", f.View.SessionID, sidB) + } +} + +// TestReconnect drops the connection, as a network failure would, and +// checks the window reaches the server again and shows the same session. +func TestReconnect(t *testing.T) { + srv := rextest.Start(t) + other := srv.Dial(t, "setup") + rextest.NewSession(t, other, rextest.RawCat...) // a session the server might pick instead + sid, bid := rextest.NewSession(t, other, rextest.RawCat...) + h := startUI(t, srv, srv.Dial(t, "100gex-test"), sid) + h.until("the session", func(f rexsession.Frame) bool { return f.Ready() && f.View.SessionID == sid }) + first := h.u.conn + + first.Drop() + h.until("a new connection, showing the same session", func(f rexsession.Frame) bool { + return h.u.conn != first && f.View.SessionID == sid && f.Ready() && f.Visible[0] == bid + }) + if !h.u.connected() { + t.Error("not connected after reconnecting") + } +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index e4bff72..1f8c1db 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -65,9 +65,9 @@ type UI struct { // FontSize is the size of the terminals' text. FontSize unit.Sp - // ServerLabel, if set, is the label the server was reached by, as rex - // hosts lists it, to call it by. - ServerLabel string + // TerminalTheme, if set, is asked of every terminal shown, on every + // server switched to. + TerminalTheme *rex.TerminalTheme // Primary, if set, is the desktop's primary selection: selecting text // in a pane sets it, and a middle click pastes it. @@ -95,7 +95,13 @@ type UI struct { // Where things were drawn, for tests. tabRects map[string]image.Rectangle + srv *server // the server shown; conn and ws are its + mu sync.Mutex // guards what other goroutines hand over + watched *server // the server whose events count + next *server // connected, waiting to be shown + connecting *connecting + newKeymapConn *rex.Conn // the connection newKeymap came from newKeymap *keymap.Keymap newServerActions map[string]rex.ActionInfo newBindings []rex.KeyBinding @@ -128,17 +134,43 @@ func New(ws *workspace.Workspace, conn *rex.Conn, shaper *text.Shaper, notify fu } u.sessionList.Axis = layout.Vertical u.matcher = keymap.NewMatcher(localKeymap(), u.available) - go u.fetchKeymap() - go u.fetchServerDetails() + first := &server{conn: conn, ws: ws} + u.setServer(first) + u.watched = first + u.watch(first) + go u.fetchKeymap(conn) + go u.fetchServerDetails(conn) return u } -// Close frees the drawing state of every pane. +// Close frees the drawing state of every pane, and ends the connection to +// the server shown, and to one still being switched to. func (u *UI) Close() { for id, p := range u.panes { p.view.Close() delete(u.panes, id) } + u.mu.Lock() + next := u.next + u.next, u.connecting, u.watched = nil, nil, nil + u.mu.Unlock() + for _, s := range []*server{u.srv, next} { + if s != nil { + s.ws.Close() + s.conn.Close() + } + } +} + +// Conn returns the connection to the server shown. It is safe to call from +// any goroutine. +func (u *UI) Conn() *rex.Conn { + u.mu.Lock() + defer u.mu.Unlock() + if u.watched == nil { + return nil + } + return u.watched.conn } // Title is the window's title: the session's label. @@ -163,10 +195,15 @@ func (u *UI) report(err error) { // frame of the session it drew, and the actions the person asked of the // window, such as closing it, for the caller to perform. func (u *UI) Layout(gtx layout.Context) (rexsession.Frame, system.Action, error) { + u.syncServer() u.mu.Lock() if u.newKeymap != nil { - u.matcher.SetKeymap(u.newKeymap) - u.serverActions, u.bindings = u.newServerActions, u.newBindings + // A keymap fetched from a server since switched away from is + // dropped. + if u.newKeymapConn == u.conn { + u.matcher.SetKeymap(u.newKeymap) + u.serverActions, u.bindings = u.newServerActions, u.newBindings + } u.newKeymap = nil } u.mu.Unlock() diff --git a/main.go b/main.go index c955bc3..1715fdf 100644 --- a/main.go +++ b/main.go @@ -8,7 +8,6 @@ import ( "context" "errors" "flag" - "fmt" "log" "os" "os/signal" @@ -21,6 +20,7 @@ import ( "gioui.org/op" "gioui.org/unit" + "100gex/internal/hosts" "100gex/internal/primary" "100gex/internal/rex" "100gex/internal/theme" @@ -63,11 +63,22 @@ var terminalTheme = &rex.TerminalTheme{ func run(w *app.Window, server, sessionQuery string) error { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - conn, ep, label, err := connect(ctx, server) + conn, ep, label, err := hosts.Dial(ctx, server) if err != nil { return err } - defer conn.Close() + ws, err := workspace.Start(ctx, conn, ep, sessionQuery, terminalTheme, w.Invalidate) + if err != nil { + conn.Close() + return err + } + + // From here the UI owns the server: it follows its events, reconnects + // when the connection drops, switches to others, and closes it. + u := ui.New(ws, conn, theme.NewShaper(), w.Invalidate) + defer u.Close() + u.TerminalTheme = terminalTheme + u.SetTarget(server, label) // Ctrl+C or SIGTERM closes the window, so that the server sees this // client leave instead of losing its connection. Window.Perform isn't @@ -83,21 +94,12 @@ func run(w *app.Window, server, sessionQuery string) error { w.Invalidate() time.Sleep(2 * time.Second) log.Print("the window didn't close; leaving without it") - conn.Close() + if c := u.Conn(); c != nil { + c.Close() + } os.Exit(1) }() - ws, err := workspace.Start(ctx, conn, ep, sessionQuery, terminalTheme, w.Invalidate) - if err != nil { - return err - } - defer ws.Close() - - shaper := theme.NewShaper() - u := ui.New(ws, conn, shaper, w.Invalidate) - defer u.Close() - u.ServerLabel = label - // Gio offers no primary selection, so it gets a Wayland connection of // its own. Without one, selecting doesn't copy and middle click doesn't // paste. @@ -110,14 +112,6 @@ func run(w *app.Window, server, sessionQuery string) error { u.Primary = sel } - go func() { - for ev := range conn.Events() { - u.HandleEvent(ev) - ws.HandleEvent(ev) - } - w.Invalidate() // the connection ended - }() - var ops op.Ops title := "" for { @@ -143,77 +137,6 @@ func run(w *app.Window, server, sessionQuery string) error { title = t w.Option(app.Title(t)) } - switch err := conn.Err(); { - case errors.Is(err, rex.ErrClosed): - w.Perform(system.ActionClose) - case err != nil: - return err - } - } - } -} - -// connect opens a control connection to server, which is "" for the local -// server, a host's label, or an address, as the rex CLI's -S option takes -// them: a label is looked up in the local server's hosts first, and a value -// with a port is always an address. It returns the endpoint that answered, -// and the host's label if a label named it. -func connect(ctx context.Context, server string) (*rex.Conn, rex.Endpoint, string, error) { - info := rex.ClientInfo{Kind: "app", Name: "100gex"} - if server == "" { - ep, err := rex.DiscoverEndpoint() - if err != nil { - return nil, rex.Endpoint{}, "", err } - c, err := rex.Dial(ctx, ep, info) - return c, ep, "", err - } - var candidates []rex.Endpoint - label := "" - if rex.LooksLikeLabel(server) { - if host, ok := lookupHost(ctx, server); ok { - label = host.Label - for _, address := range host.Endpoints { - eps, err := rex.Candidates(address) - if err != nil { - log.Printf("host %s: %v", host.Label, err) - continue - } - candidates = append(candidates, eps...) - } - } - } - if label == "" { - eps, err := rex.Candidates(server) - if err != nil { - return nil, rex.Endpoint{}, "", err - } - candidates = eps - } - c, ep, err := rex.DialAny(ctx, candidates, info) - if err != nil { - return nil, rex.Endpoint{}, "", fmt.Errorf("connect to %s: %w", server, err) - } - return c, ep, label, nil -} - -// lookupHost finds a host by its label in the local server's hosts. With no -// local server, or no such host, it reports false. -func lookupHost(ctx context.Context, label string) (rex.Host, bool) { - ep, err := rex.DiscoverEndpoint() - if err != nil { - return rex.Host{}, false - } - ctx, cancel := context.WithTimeout(ctx, 3*time.Second) - defer cancel() - c, err := rex.Dial(ctx, ep, rex.ClientInfo{Kind: "app", Name: "100gex"}) - if err != nil { - return rex.Host{}, false - } - defer c.Close() - hosts, err := c.Hosts(ctx) - if err != nil { - return rex.Host{}, false } - return rex.FindHost(hosts, label) } diff --git a/main_test.go b/main_test.go deleted file mode 100644 index c3f3d3c..0000000 --- a/main_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "context" - "testing" - "time" - - "100gex/internal/rex" - "100gex/internal/rex/rextest" -) - -// TestConnectLabel names a server by a host's label, which the local server -// (here, the one REX_SERVER names) knows, as rex -S does. -func TestConnectLabel(t *testing.T) { - local := rextest.Start(t) - studio := rextest.Start(t) - t.Setenv(rex.ServerEnv, local.Endpoint.String()) - - c := local.Dial(t, "setup") - rextest.Call(t, c, "hosts.put", map[string]any{"host": map[string]any{ - "label": "studio", - "endpoints": []string{studio.Endpoint.String()}, - }}, nil) - - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - conn, ep, label, err := connect(ctx, "Studio") // labels ignore case - if err != nil { - t.Fatal(err) - } - defer conn.Close() - if label != "studio" || ep != studio.Endpoint { - t.Errorf("connect(Studio) = %v, label %q; want %v, studio", ep, label, studio.Endpoint) - } - - // A name that isn't a label is an address. - if _, _, _, err := connect(ctx, "nosuchhost.invalid"); err == nil { - t.Error("connected to an address that can't resolve") - } -}