Files
pipelines/internal/server/terminal_clients.go
T
alan 0963a071d0 Terminals: flow-controlled output, immediate echo, sliced emulator writes
Machine terminals no longer skip output for live viewers. Each connection's
subscription is a cursor into the 1 MiB retained tail, drained by the
connection's writer as soon as the PTY reader writes (no 50 ms tick; a
streaming frame gathers for at most 2 ms). A subscription opened with
flow: true gets window (256 KiB) in its reply and acknowledges drawn output
with terminal_ack; while one is full the reader stops reading the PTY, so
the program waits. A subscription full for 3 s without acking stops holding
the terminal and later sees a gap; a gone connection drops its
subscriptions. Clients that never ask for flow keep the old pacing (newest
64 KiB per 50 ms). terminal_open/terminal_output replies precede the frames
that follow them, which start exactly at the reply's output_end.

Chat shell runs share the buffer code: output is pushed as it arrives,
oldest first, while the chat's watchers keep short queues; 256 KiB unpushed
stops the reader, and watchers behind for 3 s get the old pacing.

The app asks for flow, takes offsets from the server (frame end, reply
output_end) instead of re-encoded text length, acks per quarter window, and
writes replays and bursts into the emulator in slices that yield to the
event loop (ChatShellTerminalFeed, shared with chat shells).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 23:57:18 +00:00

275 lines
6.5 KiB
Go

package server
import (
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// terminalClientQueue bounds the lifecycle frames waiting for one slow
// connection; a full queue drops them (the next terminal_list repairs the
// tabs). Output is not queued: each connection's writer reads it from the
// terminal's retained tail (terminal_flow.go).
const terminalClientQueue = 256
// terminalClients delivers terminal_event frames to open connections, in
// order per connection: lifecycle changes to every connection, output only
// to connections subscribed to that terminal (by terminal_open or
// terminal_output). It holds each connection's serialized write function,
// never the socket. The zero value is ready to use.
type terminalClients struct {
mu sync.Mutex
clients map[string]*terminalClient
}
// terminalClient is one connection: its queued lifecycle frames and its
// subscriptions, which one writer goroutine drains through write.
type terminalClient struct {
ch chan protocol.Message
wake chan struct{}
done chan struct{}
once sync.Once
mu sync.Mutex
subs map[string]*terminalView
}
func (c *terminalClients) attach(clientID string, write func(protocol.Message) error) {
client := &terminalClient{
ch: make(chan protocol.Message, terminalClientQueue), wake: make(chan struct{}, 1),
done: make(chan struct{}), subs: map[string]*terminalView{},
}
c.mu.Lock()
if c.clients == nil {
c.clients = map[string]*terminalClient{}
}
old := c.clients[clientID]
c.clients[clientID] = client
c.mu.Unlock()
if old != nil {
old.stop()
}
go client.run(write)
}
func (c *terminalClients) detach(clientID string) {
c.mu.Lock()
client := c.clients[clientID]
delete(c.clients, clientID)
c.mu.Unlock()
if client != nil {
client.stop()
}
}
func (c *terminalClients) client(clientID string) *terminalClient {
c.mu.Lock()
defer c.mu.Unlock()
return c.clients[clientID]
}
// subscribe sends p's output to clientID from now on (flow: acknowledged)
// and returns the subscription, or nil for an unknown connection.
func (c *terminalClients) subscribe(clientID string, p *terminalProcess, flow bool) *terminalView {
client := c.client(clientID)
if client == nil {
return nil
}
return client.subscribe(p, flow)
}
// view is clientID's subscription to terminalID, or nil.
func (c *terminalClients) view(clientID, terminalID string) *terminalView {
client := c.client(clientID)
if client == nil {
return nil
}
return client.sub(terminalID)
}
// publish queues a lifecycle frame for every connection without blocking.
func (c *terminalClients) publish(frame protocol.TerminalEventFrame) {
msg := protocol.Message{Type: protocol.TerminalEvent, TerminalEvent: &frame}
c.mu.Lock()
defer c.mu.Unlock()
for _, client := range c.clients {
select {
case client.ch <- msg:
default:
}
}
}
func (c *terminalClient) subscribe(p *terminalProcess, flow bool) *terminalView {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.done:
return nil
default:
}
id := p.id()
v := c.subs[id]
if v == nil || v.p != p {
if v != nil {
v.leave()
}
v = &terminalView{client: c, p: p}
c.subs[id] = v
p.join(v)
}
p.mu.Lock()
v.flow = flow
v.fullSince = time.Time{}
p.mu.Unlock()
return v
}
func (c *terminalClient) sub(terminalID string) *terminalView {
c.mu.Lock()
defer c.mu.Unlock()
return c.subs[terminalID]
}
func (c *terminalClient) unsubscribe(terminalID string) {
c.mu.Lock()
v := c.subs[terminalID]
delete(c.subs, terminalID)
c.mu.Unlock()
if v != nil {
v.leave()
}
}
func (c *terminalClient) views() []*terminalView {
c.mu.Lock()
defer c.mu.Unlock()
views := make([]*terminalView, 0, len(c.subs))
for _, v := range c.subs {
views = append(views, v)
}
return views
}
// poke tells the writer that output or window room may be waiting.
func (c *terminalClient) poke() {
select {
case c.wake <- struct{}{}:
default:
}
}
// stop ends the writer and drops every subscription, so a gone connection
// never holds a terminal back.
func (c *terminalClient) stop() {
c.once.Do(func() {
close(c.done)
c.mu.Lock()
subs := c.subs
c.subs = map[string]*terminalView{}
c.mu.Unlock()
for _, v := range subs {
v.leave()
}
})
}
// run writes this connection's frames until it is stopped or a write fails:
// lifecycle frames in order, and between them every subscription's output
// as soon as it is available, coalescing what arrived during a write.
func (c *terminalClient) run(write func(protocol.Message) error) {
defer c.stop()
retry := time.NewTimer(time.Hour)
retry.Stop()
defer retry.Stop()
for {
select {
case <-c.done:
return
case msg := <-c.ch:
if !c.lifecycle(msg, write) {
return
}
case <-c.wake:
case <-retry.C:
}
wait, ok := c.pump(write)
if !ok {
return
}
// The earliest paced or gathering subscription wakes it again.
retry.Stop()
if wait > 0 {
retry.Reset(wait)
}
}
}
// pump writes output frames, one per subscription per round, until none has
// more to send now; it returns how soon a paced subscription may send again.
func (c *terminalClient) pump(write func(protocol.Message) error) (time.Duration, bool) {
for {
select {
case <-c.done:
return 0, false
default:
}
var wait time.Duration
progressed := false
for _, v := range c.views() {
frame, ok, again := v.next(time.Now(), false)
if again > 0 && (wait == 0 || again < wait) {
wait = again
}
if !ok {
continue
}
if write(terminalOutputMessage(frame)) != nil {
return 0, false
}
progressed = true
}
for queued := true; queued; {
select {
case msg := <-c.ch:
if !c.lifecycle(msg, write) {
return 0, false
}
default:
queued = false
}
}
if !progressed {
return wait, true
}
}
}
// lifecycle writes one lifecycle frame. An ended terminal's remaining output
// goes first (whatever the window), and a closed one's subscription ends.
func (c *terminalClient) lifecycle(msg protocol.Message, write func(protocol.Message) error) bool {
frame := msg.TerminalEvent
if frame != nil && frame.Terminal != nil && frame.Terminal.Status != protocol.TerminalRunning {
if v := c.sub(frame.TerminalID); v != nil {
for {
out, ok, _ := v.next(time.Now(), true)
if !ok {
break
}
if write(terminalOutputMessage(out)) != nil {
return false
}
}
if frame.Terminal.Status == protocol.TerminalClosed {
c.unsubscribe(frame.TerminalID)
}
}
}
return write(msg) == nil
}
func terminalOutputMessage(frame protocol.TerminalEventFrame) protocol.Message {
return protocol.Message{Type: protocol.TerminalEvent, TerminalEvent: &frame}
}