// Package workspace follows a Rex server: the list of its sessions, and the // one session this client shows, which the person can switch. package workspace import ( "context" "errors" "log" "sync" "time" "100gex/internal/rex" "100gex/internal/rexsession" ) // Workspace is the sessions on one server. Sync and Close must be called // from the goroutine that draws; the other methods may be called from any. type Workspace struct { conn *rex.Conn ep rex.Endpoint notify func() theme *rex.TerminalTheme status rex.ServerStatus // as bootstrap reported it mu sync.Mutex sessions []rex.Session listing bool // a session.list is running again bool // and another is due when it ends current *attached next *attached // switched to, waiting for Sync switchTo string // the session a switch is attaching to // warm are sessions shown before, most recent first, kept attached // with their streams open, so that showing one again is immediate. warm []*attached trackers map[string]*tracker // each session's summary, by ID home string // the home directory, as terminals report it } // attached is a session this client is attached to, and the seq of the // first event that its view doesn't already include. type attached struct { session *rexsession.Session after uint64 since time.Time // when it was attached } // KeepWarm is how many sessions shown before a workspace keeps attached, // besides the one it shows. Each keeps its panes' streams open, and its // terminals current. const KeepWarm = 4 // switchWait is how long a session switched to may take to restore its // panes before it's shown anyway, with whatever has arrived. const switchWait = 1500 * time.Millisecond // Start bootstraps conn and attaches to the session that query names (an // ID, a label, or the end of an ID), or to the one the server picks. A // server with no sessions gets a new one. theme, if set, is asked of every // terminal shown. func Start(ctx context.Context, conn *rex.Conn, ep rex.Endpoint, query string, theme *rex.TerminalTheme, notify func()) (*Workspace, error) { w := &Workspace{conn: conn, ep: ep, notify: notify, theme: theme} args := rex.BootstrapArgs{EventScope: "all"} if query != "" { args.AttachSessionIDs = []string{} // find the session first } boot, seq, err := conn.Bootstrap(ctx, args) if err != nil { return nil, err } w.sessions = boot.AttachAll.Sessions w.status = boot.ServerStatus w.mu.Lock() w.track(w.sessions) w.mu.Unlock() var view rex.View switch { case query != "": s, err := rex.FindSession(boot.AttachAll.Sessions, query) if err != nil { return nil, err } if view, seq, err = conn.Attach(ctx, s.SessionID); err != nil { return nil, err } case boot.SelectedSession != nil: view = boot.SelectedSession.View default: id, err := w.create(ctx) if err != nil { return nil, err } if view, seq, err = conn.Attach(ctx, id); err != nil { return nil, err } w.refreshList() } w.current = w.follow(view, seq) return w, nil } // Watch bootstraps conn without attaching to any session: the workspace // follows the server's list of sessions, parked, until Resume shows one. func Watch(ctx context.Context, conn *rex.Conn, ep rex.Endpoint, theme *rex.TerminalTheme, notify func()) (*Workspace, error) { w := &Workspace{conn: conn, ep: ep, notify: notify, theme: theme} boot, _, err := conn.Bootstrap(ctx, rex.BootstrapArgs{EventScope: "all", AttachSessionIDs: []string{}}) if err != nil { return nil, err } w.sessions = boot.AttachAll.Sessions w.status = boot.ServerStatus w.mu.Lock() w.track(w.sessions) w.mu.Unlock() return w, nil } func (w *Workspace) follow(view rex.View, seq uint64) *attached { s := rexsession.New(w.conn, w.ep, view, w.notify) s.Theme = w.theme s.Typed = func(block string) { w.typed(view.SessionID, block) } return &attached{session: s, after: seq, since: time.Now()} } // Endpoint returns the server's address. func (w *Workspace) Endpoint() rex.Endpoint { return w.ep } // Status returns the server's status as of when the workspace started. Its // session count isn't kept current; Sessions is. func (w *Workspace) Status() rex.ServerStatus { return w.status } // Sessions returns the server's sessions, in its order. func (w *Workspace) Sessions() []rex.Session { w.mu.Lock() defer w.mu.Unlock() return append([]rex.Session(nil), w.sessions...) } // Sync returns the session to show, which is nil if there is none. A // session the person switched to is synced out of sight until its panes // have their terminals, so that the switch never shows empty panes, and // then put in place. func (w *Workspace) Sync() *rexsession.Session { w.mu.Lock() next := w.next w.mu.Unlock() if next != nil { f, err := next.session.Sync() next.session.Release() // only to see if it's ready if err == nil && !f.Ready() && time.Since(next.since) < switchWait { if w.current != nil { return w.current.session } } } w.mu.Lock() if w.next != nil && w.next == next { if w.current != nil { w.warm = append([]*attached{w.current}, w.warm...) } w.current, w.next = w.next, nil w.seen(w.current.session.ID()) } cur := w.current cold := w.trimWarm() w.mu.Unlock() for _, a := range cold { w.leave(a.session) } if cur == nil { return nil } return cur.session } // trimWarm takes from the warm sessions those past KeepWarm, and those // the server no longer lists, and returns them, to leave. w.mu must be // held. func (w *Workspace) trimWarm() []*attached { var cold []*attached kept := w.warm[:0] for _, a := range w.warm { listed := false for _, s := range w.sessions { listed = listed || s.SessionID == a.session.ID() } if listed && len(kept) < KeepWarm { kept = append(kept, a) } else { cold = append(cold, a) } } clear(w.warm[len(kept):]) w.warm = kept return cold } // takeWarm takes a warm session from the list, or returns nil if // sessionID isn't warm. w.mu must be held. func (w *Workspace) takeWarm(sessionID string) *attached { for i, a := range w.warm { if a.session.ID() == sessionID { w.warm = append(w.warm[:i], w.warm[i+1:]...) return a } } return nil } // leave stops showing a session and detaches from it, which gives its // blocks back to their previous owners. func (w *Workspace) leave(s *rexsession.Session) { s.Close() go func() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if _, err := w.conn.Call(ctx, "session.detach", map[string]string{"session_id": s.ID()}, nil); err != nil && !rex.IsCode(err, "session_not_found") { log.Printf("workspace: detach: %v", err) } }() } // Switch shows another session. It attaches in the background; Sync puts // it in place. func (w *Workspace) Switch(sessionID string) { w.mu.Lock() if (w.current != nil && w.current.session.ID() == sessionID) || w.switchTo == sessionID { w.mu.Unlock() return } if a := w.takeWarm(sessionID); a != nil { // Still attached, with its terminals current: nothing to wait for. w.switchTo = "" if w.next != nil { w.warm = append([]*attached{w.next}, w.warm...) } w.next = a w.mu.Unlock() w.notify() return } w.switchTo = sessionID w.mu.Unlock() go func() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() view, seq, err := w.conn.Attach(ctx, sessionID) w.mu.Lock() defer w.mu.Unlock() if w.switchTo != sessionID { return // a later switch took over } w.switchTo = "" if err != nil { log.Printf("workspace: switch: %v", err) return } if w.next != nil { // Not shown yet; it may be shown again soon. w.warm = append([]*attached{w.next}, w.warm...) } w.next = w.follow(view, seq) w.notify() }() } // Park stops showing sessions, but keeps following the server's list of // sessions, for a window that has switched to another server and may // switch back with Resume. The sessions shown stay warm. It returns the // session that was shown, or "". func (w *Workspace) Park() string { w.mu.Lock() defer w.mu.Unlock() cur, next := w.current, w.next w.current, w.next, w.switchTo = nil, nil, "" id := "" for _, a := range []*attached{next, cur} { if a != nil { w.warm = append([]*attached{a}, w.warm...) } } if cur != nil { id = cur.session.ID() } return id } // ResumeNew makes a session with one shell on a parked workspace's server, // and attaches to it, as Resume does. func (w *Workspace) ResumeNew(ctx context.Context) error { id, err := w.create(ctx) if err != nil { return err } w.refreshList() view, seq, err := w.conn.Attach(ctx, id) if err != nil { return err } a := w.follow(view, seq) w.mu.Lock() w.current = a w.seen(a.session.ID()) w.mu.Unlock() return nil } // Resume attaches a parked workspace to a session again, so that Sync // shows it: sessionID, or if that's gone, the first session, or a new one // if the server has none. It may be called from any goroutine while the // workspace isn't shown. func (w *Workspace) Resume(ctx context.Context, sessionID string) error { sessions := w.Sessions() found := false for _, s := range sessions { if s.SessionID == sessionID { found = true } } w.mu.Lock() if a := w.takeWarm(sessionID); a != nil && found { w.current = a w.seen(sessionID) w.mu.Unlock() return nil } else if a != nil { w.warm = append([]*attached{a}, w.warm...) } w.mu.Unlock() id := sessionID switch { case found: case len(sessions) > 0: id = sessions[0].SessionID default: var err error if id, err = w.create(ctx); err != nil { return err } w.refreshList() } view, seq, err := w.conn.Attach(ctx, id) if err != nil { return err } a := w.follow(view, seq) w.mu.Lock() w.current = a w.seen(a.session.ID()) w.mu.Unlock() return nil } // NewSession creates a session with one shell and switches to it. func (w *Workspace) NewSession() { go func() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() id, err := w.create(ctx) if err != nil { log.Printf("workspace: new session: %v", err) return } w.Switch(id) }() } func (w *Workspace) create(ctx context.Context) (string, error) { var created struct { SessionID string `json:"session_id"` } _, err := w.conn.Call(ctx, "session.create", map[string]any{ "initial_windows": []any{map[string]any{ "layout": map[string]any{"block": map[string]any{"flavor": "com.superlogical.terminal.shell"}}, }}, }, &created) if err == nil && created.SessionID == "" { err = errors.New("session.create returned no session") } return created.SessionID, err } // HandleEvent updates the workspace from a control connection event. Pass // it every event. func (w *Workspace) HandleEvent(ev rex.Event) { w.mu.Lock() targets := make([]*attached, 0, 2+len(w.warm)) for _, a := range append([]*attached{w.current, w.next}, w.warm...) { if a != nil && ev.Seq > a.after { targets = append(targets, a) } } w.mu.Unlock() for _, a := range targets { a.session.HandleEvent(ev) } w.summarize(ev) switch ev.Name { case "session_created", "session_destroyed", "session_moved", "session_label_changed": w.refreshList() } if ev.Name == "session_destroyed" { var e struct { SessionID string `json:"session_id"` } _ = ev.Decode(&e) w.mu.Lock() gone := w.current != nil && w.current.session.ID() == e.SessionID w.mu.Unlock() if gone { w.afterDestroyed(e.SessionID) } } } // afterDestroyed switches away from the shown session once it's gone. func (w *Workspace) afterDestroyed(id string) { go func() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() var list struct { Sessions []rex.Session `json:"sessions"` } if _, err := w.conn.Call(ctx, "session.list", nil, &list); err != nil { return } for _, s := range list.Sessions { if s.SessionID != id { w.Switch(s.SessionID) return } } }() } // refreshList fetches the session list. Changes that arrive while a fetch // runs share the next one. func (w *Workspace) refreshList() { w.mu.Lock() if w.listing { w.again = true w.mu.Unlock() return } w.listing = true w.mu.Unlock() go func() { for { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) var list struct { Sessions []rex.Session `json:"sessions"` } _, err := w.conn.Call(ctx, "session.list", nil, &list) cancel() w.mu.Lock() if err == nil { w.sessions = list.Sessions w.track(list.Sessions) } again := w.again && err == nil w.again = false if !again { w.listing = false } w.mu.Unlock() w.notify() if !again { return } } }() } // Close stops showing sessions. It doesn't close the connection. func (w *Workspace) Close() { w.mu.Lock() all := append([]*attached{w.current, w.next}, w.warm...) w.current, w.next, w.warm = nil, nil, nil w.mu.Unlock() for _, a := range all { if a != nil { a.session.Close() } } } // Reveal makes a block its session's focused block, and its window the // active one, so that the session shows it when it's shown. A session this // client is attached to changes at once, before the server confirms. func (w *Workspace) Reveal(sessionID, windowID, blockID string) { if blockID == "" { return } w.mu.Lock() var s *rexsession.Session for _, a := range append([]*attached{w.current, w.next}, w.warm...) { if a != nil && a.session.ID() == sessionID { s = a.session break } } w.mu.Unlock() if s != nil { if windowID != "" { s.FocusWindow(windowID) } s.FocusBlock(blockID) return } go func() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if _, err := w.conn.Call(ctx, "session.focus_block", map[string]string{"session_id": sessionID, "block_id": blockID}, nil); err != nil { log.Printf("reveal %s in %s: %v", blockID, sessionID, err) } }() }