package ui import ( "context" "fmt" "os" "slices" "sort" "strings" "time" "100gex/internal/hosts" "100gex/internal/rex" "100gex/internal/workspace" ) // The sidebar lists every host: this machine, the saved hosts, and any // other server the window is connected to. With KeepHosts, the window // connects to each of them in the background, and again after a // connection drops, so that their sessions are listed without switching to // them. // hostState is how a host's connection stands. type hostState int const ( hostIdle hostState = iota // not connected, and not trying hostConnecting // trying, for the first time or again hostOnline // connected hostOffline // the last attempt failed; trying again later ) // hostEntry is a host as the sidebar lists it. type hostEntry struct { key string // stays the same while the host is listed target string // what Connect takes: "" for this machine, a label, or an address name string host *rex.Host // the saved host, or nil local bool // this machine srv *server // the connection, or nil state hostState err error // why it's offline retry time.Time // when it's tried again, if offline } // keeper connects to a host in the background until it answers. type keeper struct { target string wake chan struct{} // try again now // Guarded by UI.mu. trying bool err error retry time.Time } // keepDelays are the waits between a keeper's attempts. var keepDelays = []time.Duration{2 * time.Second, 5 * time.Second, 15 * time.Second, 30 * time.Second, time.Minute} // KeepHosts makes the window connect to this machine and every saved host // in the background, so that the sidebar lists their sessions. func (u *UI) KeepHosts() { u.mu.Lock() u.keepHosts = true u.mu.Unlock() u.fetchSaved() } // fetchSaved asks the local server for the saved hosts. func (u *UI) fetchSaved() { go func() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() saved, err := hosts.Saved(ctx) u.mu.Lock() if err == nil { u.saved = saved } u.mu.Unlock() u.notify() }() } // startKeeper connects to target in the background, unless something // already is. func (u *UI) startKeeper(target string) { u.mu.Lock() defer u.mu.Unlock() if u.closed || u.keepers[target] != nil { return } k := &keeper{target: target, wake: make(chan struct{}, 1), trying: true} if u.keepers == nil { u.keepers = make(map[string]*keeper) } u.keepers[target] = k go u.keep(k) } func (u *UI) keep(k *keeper) { for i := 0; ; i++ { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) conn, ep, label, err := hosts.Dial(ctx, k.target) var ws *workspace.Workspace if err == nil { ws, err = workspace.Watch(ctx, conn, ep, u.TerminalTheme, u.notify) if err != nil { conn.Close() } } cancel() u.mu.Lock() if u.closed || u.keepers[k.target] != k { u.mu.Unlock() if err == nil { ws.Close() conn.Close() } return } if err == nil { delete(u.keepers, k.target) u.arrived = append(u.arrived, &server{conn: conn, ws: ws, label: label, target: k.target}) u.mu.Unlock() u.notify() return } if !u.wanted(k.target) { delete(u.keepers, k.target) // removed meanwhile u.mu.Unlock() return } d := keepDelays[min(i, len(keepDelays)-1)] k.trying, k.err, k.retry = false, err, time.Now().Add(d) u.mu.Unlock() u.notify() t := time.NewTimer(d) select { case <-t.C: case <-k.wake: t.Stop() } u.mu.Lock() k.trying = true u.mu.Unlock() u.notify() } } // wanted reports whether target is a host to keep connected to: this // machine or a saved host. u.mu must be held. func (u *UI) wanted(target string) bool { if target == localTarget { return true } for _, h := range u.saved { if strings.EqualFold(h.Label, target) { return true } } return false } // retryHost tries an offline host again now. func (u *UI) retryHost(target string) { u.mu.Lock() k := u.keepers[target] u.mu.Unlock() if k == nil { u.startKeeper(target) return } select { case k.wake <- struct{}{}: default: } } // syncHosts runs on the drawing goroutine: it lists the servers that // keepers have connected to, and starts keepers for hosts that have no // connection. func (u *UI) syncHosts() { u.mu.Lock() arrived := u.arrived u.arrived = nil keep := u.keepHosts saved := u.saved switching := "" if u.connecting != nil { switching = u.connecting.target } u.mu.Unlock() for _, s := range arrived { if u.find(s.target) != nil || (s.label != "" && u.find(s.label) != nil) { // Connected meanwhile, by a switch to it. go func() { s.ws.Close(); s.conn.Close() }() continue } u.servers = append(u.servers, s) u.watch(s) go u.fetchServerDetails(s) } if !keep { return } for _, e := range u.hostEntries(saved) { if e.srv == nil && e.target != switching { u.startKeeper(e.target) } } } // matches reports whether s is the server that a saved host names. func matches(s *server, h *rex.Host) bool { return (s.label != "" && strings.EqualFold(s.label, h.Label)) || strings.EqualFold(s.target, h.Label) || slices.Contains(h.Endpoints, s.target) } // hosts lists the hosts for the sidebar, in a stable order: this machine, // then the saved hosts by label, then any other server connected to. func (u *UI) hosts() []hostEntry { u.mu.Lock() saved := u.saved u.mu.Unlock() entries := u.hostEntries(saved) u.mu.Lock() defer u.mu.Unlock() for i := range entries { e := &entries[i] switch { case e.srv != nil && e.srv.conn.Err() == nil: e.state = hostOnline case u.connecting != nil && u.connecting.target == e.target && u.connecting.err == nil: e.state = hostConnecting case e.srv != nil && e.srv == u.srv: e.state = hostConnecting // reconnecting case u.keepers[e.target] != nil: k := u.keepers[e.target] if k.trying || k.err == nil { e.state = hostConnecting } else { e.state, e.err, e.retry = hostOffline, k.err, k.retry } case u.connecting != nil && u.connecting.target == e.target: e.state, e.err = hostOffline, u.connecting.err } } return entries } // hostEntries lists the hosts, with the servers connected to them, but // not their states. Without KeepHosts, this machine is listed only when // connected to. u.mu must not be held; keepHosts is read without it, as // only the drawing goroutine sets it. func (u *UI) hostEntries(saved []rex.Host) []hostEntry { used := make(map[*server]bool) var local *server for _, s := range u.servers { if s.target == localTarget { local = s used[s] = true break } } hostname, _ := os.Hostname() if local != nil { hostname, _ = local.name() } var entries []hostEntry if local != nil || u.keepHosts { entries = append(entries, hostEntry{key: "local", target: localTarget, name: hostname, local: true, srv: local}) } saved = slices.Clone(saved) sort.Slice(saved, func(i, j int) bool { return strings.ToLower(saved[i].Label) < strings.ToLower(saved[j].Label) }) for i := range saved { h := &saved[i] e := hostEntry{key: "host:" + h.Label, target: h.Label, name: h.Label, host: h} for _, s := range u.servers { if !used[s] && matches(s, h) { e.srv, used[s] = s, true break } } entries = append(entries, e) } for _, s := range u.servers { if !used[s] { name, _ := s.name() entries = append(entries, hostEntry{key: fmt.Sprintf("srv:%p", s), target: s.target, name: name, srv: s}) } } return entries }