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>
This commit is contained in:
2026-11-25 23:57:18 +00:00
parent 5ab1ec9e00
commit 0963a071d0
30 changed files with 1958 additions and 182 deletions
+13
View File
@@ -382,6 +382,19 @@ func (h *chatHub) detachClient(clientID string) {
// fanout delivers one frame to every client watching sessionID except the one
// named by except (the sender, who already has it locally).
// roomBacklog is the most frames any client watching sessionID has queued.
func (h *chatHub) roomBacklog(sessionID string) int {
h.mu.Lock()
defer h.mu.Unlock()
most := 0
if room := h.rooms[sessionID]; room != nil {
for _, sub := range room.subs {
most = max(most, len(sub.ch))
}
}
return most
}
func (h *chatHub) fanout(sessionID string, msg protocol.Message, except string) {
h.mu.Lock()
var targets []*chatSub
+122
View File
@@ -0,0 +1,122 @@
//go:build darwin || linux
package server
import (
"context"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// outputFrames is runID's output frames so far, in order.
func (f *shellFrames) outputFrames(runID string) []protocol.ChatShellRunEventFrame {
f.mu.Lock()
defer f.mu.Unlock()
var out []protocol.ChatShellRunEventFrame
for _, frame := range f.frames {
if frame.RunID == runID && frame.Run == nil && !frame.Dismissed {
out = append(out, frame)
}
}
return out
}
// joined is the frames' text and the bytes skipped between them.
func joined(t *testing.T, frames []protocol.ChatShellRunEventFrame) (string, int64) {
t.Helper()
var text strings.Builder
var end, skipped int64
for _, frame := range frames {
if frame.Offset < end {
t.Fatalf("frame [%d, %d) overlaps %d", frame.Offset, frame.End, end)
}
skipped += frame.Offset - end
text.WriteString(frame.Output)
end = frame.End
}
return text.String(), skipped
}
// A command writing more than the retained tail to watchers that keep up
// is streamed whole, oldest first, without a gap.
func TestChatShellFlowStreamsEveryByte(t *testing.T) {
runner, frames := testShellRunner(t, context.Background())
runner.flush = time.Hour // output must not wait for a tick
run, err := runner.Start(context.Background(), "ses_1", t.TempDir(), "seq 1 300000", 0, 0)
if err != nil {
t.Fatal(err)
}
runner.Wait()
text, skipped := joined(t, frames.outputFrames(run.ID))
if skipped != 0 {
t.Fatalf("%d bytes skipped", skipped)
}
sep := "\n"
if run.Terminal {
sep = "\r\n"
}
var want strings.Builder
for i := 1; i <= 300000; i++ {
want.WriteString(itoa(i) + sep)
}
if text != want.String() {
t.Fatalf("streamed %d bytes, want %d", len(text), want.Len())
}
}
// Output is pushed when it arrives, not on the flush tick.
func TestChatShellFlowPushesAtOnce(t *testing.T) {
runner, frames := testShellRunner(t, context.Background())
runner.flush = time.Hour
run, err := runner.Start(context.Background(), "ses_1", t.TempDir(), "echo early; sleep 5", 0, 0)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = runner.Stop("ses_1", run.ID); runner.Wait() })
for deadline := time.Now().Add(3 * time.Second); ; time.Sleep(5 * time.Millisecond) {
if text, _ := joined(t, frames.outputFrames(run.ID)); strings.Contains(text, "early") {
return
}
if time.Now().After(deadline) {
t.Fatal("no output frame while the command runs")
}
}
}
// Watchers that stop draining hold the command back only for
// chatShellStall; then the output skips ahead and the command finishes.
func TestChatShellFlowStalledWatchersDoNotHoldForever(t *testing.T) {
runner, frames := testShellRunner(t, context.Background())
runner.backlog = func(string) int { return chatShellBacklog }
start := time.Now()
run, err := runner.Start(context.Background(), "ses_1", t.TempDir(), "seq 1 400000", 0, 0)
if err != nil {
t.Fatal(err)
}
runner.Wait()
if elapsed := time.Since(start); elapsed < chatShellStall || elapsed > 6*chatShellStall {
t.Fatalf("finished after %s", elapsed)
}
if _, skipped := joined(t, frames.outputFrames(run.ID)); skipped == 0 {
t.Fatal("stalled watchers were sent everything")
}
if final := frames.final(run.ID); final == nil || final.Status != protocol.ChatShellRunExited {
t.Fatalf("final = %+v", final)
}
}
func itoa(i int) string {
var b [20]byte
n := len(b)
for {
n--
b[n] = byte('0' + i%10)
i /= 10
if i == 0 {
return string(b[n:])
}
}
}
+67 -17
View File
@@ -42,29 +42,79 @@ func (o *chatShellOutput) tail(max int) (string, int64) {
return validChatShellText(o.data[from:]), o.start + int64(from)
}
// pending returns the output not yet emitted, at most max bytes (the newest
// ones when more is waiting: the skipped bytes are a visible gap to clients).
// An incomplete trailing character is held back unless final is set.
// pending returns the oldest output not yet emitted, at most max bytes, and
// marks it emitted. An incomplete trailing character is held back unless
// final is set.
func (o *chatShellOutput) pending(max int, final bool) (text string, offset, end int64, ok bool) {
from := o.emitted
if from < o.start {
from = o.start
text, offset, end, ok = o.chunk(o.emitted, o.total, max, final)
if ok {
o.emitted = end
}
available := o.data[from-o.start:]
if !final {
available = available[:completeUTF8Prefix(available)]
return text, offset, end, ok
}
// unemitted is how many written bytes no frame has carried yet.
func (o *chatShellOutput) unemitted() int64 { return o.total - max(o.emitted, o.start) }
// skipUnemitted gives up all but the newest max unemitted bytes (watchers
// that stopped draining): the next frame starts after a visible gap.
func (o *chatShellOutput) skipUnemitted(max int) {
o.emitted = o.newestFrom(o.emitted, max)
}
// newestFrom moves from forward so that at most max retained bytes follow
// it, onto a character boundary.
func (o *chatShellOutput) newestFrom(from int64, max int) int64 {
from = maxInt64(from, o.start)
if o.total-from <= int64(max) {
return from
}
if len(available) == 0 {
return o.start + int64(runeStartAfter(o.data, int(o.total-int64(max)-o.start)))
}
// chunk returns the retained bytes from absolute offset from (the oldest
// retained byte when from was dropped) up to limit, at most max of them,
// never splitting a character inside the retained bytes. An incomplete
// character at the newest byte is held back unless final is set. offset is
// where the text starts, which is after from when from was dropped.
func (o *chatShellOutput) chunk(from, limit int64, max int, final bool) (text string, offset, end int64, ok bool) {
from = maxInt64(from, o.start)
limit = min(limit, o.total)
if from >= limit {
return "", 0, 0, false
}
end = from + int64(len(available))
if len(available) > max {
skip := runeStartAfter(available, len(available)-max)
available = available[skip:]
from += int64(skip)
data := o.data[from-o.start : limit-o.start]
if len(data) > max {
data = data[:runeStartBefore(data, max)]
} else if limit < o.total {
data = data[:runeStartBefore(o.data[from-o.start:], len(data))]
} else if !final {
data = data[:completeUTF8Prefix(data)]
}
o.emitted = end
return validChatShellText(available), from, end, true
if len(data) == 0 {
return "", 0, 0, false
}
return validChatShellText(data), from, from + int64(len(data)), true
}
func maxInt64(a, b int64) int64 {
if a > b {
return a
}
return b
}
// runeStartBefore moves index back (at most three bytes) to a byte that
// starts a character, so a cut at it never splits one (zero when the only
// character there is incomplete); invalid bytes, which start nothing, are
// cut where they are.
func runeStartBefore(data []byte, index int) int {
for back := 0; back < utf8.UTFMax && index-back >= 0; back++ {
if index-back >= len(data) || utf8.RuneStart(data[index-back]) {
return index - back
}
}
return index
}
// runeStartAfter moves index forward (at most three bytes) to the first byte
+14 -3
View File
@@ -42,10 +42,14 @@ type chatShellRunner struct {
base context.Context
store chatShellRunStore
publish func(sessionID string, frame protocol.ChatShellRunEventFrame)
// backlog is the most frames one of the session's watchers has queued
// (nil: nobody is waited for); live output waits while it is high.
backlog func(sessionID string) int
now func() time.Time
shell func() string
// grace separates Stop's SIGINT from its SIGKILL; flush batches live output
// frames; persist is the interval a running run's output is saved at.
// grace separates Stop's SIGINT from its SIGKILL; flush is the interval a
// running run is checked for saving at; persist is the interval a running
// run's output is saved at. Live output is pushed as it arrives.
grace time.Duration
flush time.Duration
persist time.Duration
@@ -69,6 +73,9 @@ type chatShellProcess struct {
// closed is set once the reader is closed; a read still blocked on a
// terminal a descendant holds open records nothing after it.
closed bool
// wake is signalled when output arrives; room when output was pushed,
// which may let a reader waiting on unpushed output go on.
wake, room chan struct{}
}
func newChatShellRunner(base context.Context, store chatShellRunStore, publish func(string, protocol.ChatShellRunEventFrame)) *chatShellRunner {
@@ -170,7 +177,10 @@ func (r *chatShellRunner) Start(ctx context.Context, sessionID, directory, comma
if terminal != nil {
record.Terminal, record.Cols, record.Rows = true, cols, rows
}
p := &chatShellProcess{record: record, out: newChatShellOutput(protocol.ChatShellRunRetained), cmd: cmd, terminal: terminal, done: make(chan struct{})}
p := &chatShellProcess{
record: record, out: newChatShellOutput(protocol.ChatShellRunRetained), cmd: cmd, terminal: terminal, done: make(chan struct{}),
wake: make(chan struct{}, 1), room: make(chan struct{}, 1),
}
if err := r.store.SaveChatShellRun(ctx, record, protocol.ChatShellRunHistory); err != nil {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
reader.Close()
@@ -263,5 +273,6 @@ func (h *chatHub) startShellRunner(ctx context.Context, store chatShellRunStore)
h.shellRuns = newChatShellRunner(ctx, store, func(sessionID string, frame protocol.ChatShellRunEventFrame) {
h.fanout(sessionID, protocol.Message{Type: protocol.ChatShellRunEvent, ChatShellRunEvent: &frame}, "")
})
h.shellRuns.backlog = h.roomBacklog
h.shellRuns.recover(ctx)
}
+29 -1
View File
@@ -134,15 +134,43 @@ func TestChatShellOutputKeepsCharactersWhole(t *testing.T) {
t.Fatalf("partial character emitted: %q %d %d", text, offset, end)
}
out.write([]byte("\xa9cdefghij"))
// The oldest retained bytes go first; the dropped ones are a gap.
text, offset, end, ok := out.pending(3, false)
if !ok || text != "hij" || offset != 9 || end != 12 {
if !ok || text != "ghi" || offset != 8 || end != 11 {
t.Fatalf("bounded chunk = %q %d %d", text, offset, end)
}
if text, offset, end, ok := out.pending(3, false); !ok || text != "j" || offset != 11 || end != 12 {
t.Fatalf("next chunk = %q %d %d", text, offset, end)
}
if tail, start := out.tail(6); tail != "ghij" || start != 8 {
t.Fatalf("tail = %q at %d", tail, start)
}
}
// A chunk never ends inside a character, whether a size bound or a limit
// (a flow window) cuts it; invalid bytes keep their exact offsets.
func TestChatShellOutputChunkBounds(t *testing.T) {
out := newChatShellOutput(1 << 10)
out.write([]byte("a\xe2\x82\xacb\xff\xfec"))
if text, offset, end, ok := out.chunk(0, 3, 64, false); !ok || text != "a" || offset != 0 || end != 1 {
t.Fatalf("limit inside the euro sign = %q %d %d", text, offset, end)
}
if _, _, _, ok := out.chunk(1, 3, 64, false); ok {
t.Fatal("a chunk of only part of a character was sent")
}
if text, offset, end, ok := out.chunk(0, 9, 3, false); !ok || text != "a" || end != 1 || offset != 0 {
t.Fatalf("size bound inside the euro sign = %q %d %d", text, offset, end)
}
text, offset, end, ok := out.chunk(1, 9, 64, false)
if !ok || text != "\u20acb\ufffdc" || offset != 1 || end != 8 {
t.Fatalf("rest = %q %d %d", text, offset, end)
}
out.skipUnemitted(2)
if text, offset, end, ok := out.pending(64, false); !ok || text != "\ufffdc" || offset != 6 || end != 8 {
t.Fatalf("after skipping = %q %d %d", text, offset, end)
}
}
func TestChatShellSharePromptFencesOutput(t *testing.T) {
code := 1
prompt := chatShellSharePrompt(protocol.ChatShellRunRecord{Command: "cat notes.md", Directory: "/w", Status: protocol.ChatShellRunExited, ExitCode: &code, DurationMS: 1500, Output: "```go\nx\n```\n", OutputBytes: 13})
+122 -11
View File
@@ -11,16 +11,32 @@ import (
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// supervise reads one command's merged output (or terminal stream), streams it in batches, saves
// it periodically and records how the command ended. It owns the reader.
// Live output flow of a run: output is pushed as soon as it arrives, oldest
// first, while the session's watchers keep their queues short
// (chatShellBacklog frames). While chatShellWindow bytes wait unpushed the
// command's output is not read, so the command waits for its watchers. A
// watcher that has not drained for chatShellStall stops holding it: the
// output then skips to the newest chunk, a gap the client shows. While output
// streams, a frame waits up to chatShellRetry for more to join it.
const (
chatShellBacklog = 8
chatShellWindow = 256 << 10
chatShellStall = 3 * time.Second
chatShellRetry = 2 * time.Millisecond
)
// supervise reads one command's merged output (or terminal stream), streams
// it live, saves it periodically and records how the command ended. It owns
// the reader.
func (r *chatShellRunner) supervise(p *chatShellProcess, reader *os.File) {
defer r.wg.Done()
defer close(p.done)
readDone := make(chan struct{})
readDone, exitedCh := make(chan struct{}), make(chan struct{})
go func() {
defer close(readDone)
buffer := make([]byte, 32<<10)
for {
p.awaitPushed(exitedCh)
n, err := reader.Read(buffer)
if n > 0 {
p.mu.Lock()
@@ -28,6 +44,7 @@ func (r *chatShellRunner) supervise(p *chatShellProcess, reader *os.File) {
p.out.write(buffer[:n])
}
p.mu.Unlock()
signalChatShell(p.wake)
}
if err != nil {
return
@@ -41,19 +58,31 @@ func (r *chatShellRunner) supervise(p *chatShellProcess, reader *os.File) {
defer flush.Stop()
lastSaved := r.now()
var waitErr error
var drainDone <-chan time.Time
var drainDone, retry <-chan time.Time
var flow chatShellFlow
exited, drained, shutdown := false, false, false
base := r.base.Done()
push := func() {
retry = nil
if r.pushOutput(p, &flow) {
retry = time.After(chatShellRetry)
}
}
for !exited || !drained {
select {
case <-p.wake:
push()
case <-retry:
push()
case <-flush.C:
r.emitOutput(p, false)
push()
if r.now().Sub(lastSaved) >= r.persist {
lastSaved = r.now()
r.save(p.snapshot(protocol.ChatShellRunRetained))
}
case waitErr = <-waitDone:
exited = true
close(exitedCh)
// Descendants may hold the pipe or terminal open; read what
// they write briefly, then stop reading. A terminal may not
// support deadlines, so the timer also ends the wait.
@@ -77,7 +106,8 @@ func (r *chatShellRunner) supervise(p *chatShellProcess, reader *os.File) {
reader.Close()
p.closed = true
p.mu.Unlock()
r.emitOutput(p, true)
for r.emitOutput(p, true) {
}
p.mu.Lock()
finishChatShellRecord(&p.record, waitErr, p.stopped, shutdown || r.base.Err() != nil, r.now())
p.mu.Unlock()
@@ -122,16 +152,97 @@ func finishChatShellRecord(record *protocol.ChatShellRunRecord, waitErr error, s
}
}
// emitOutput pushes the output written since the last frame.
func (r *chatShellRunner) emitOutput(p *chatShellProcess, final bool) {
// chatShellFlow is one run's live push state: held is when its watchers
// were first found behind, paced when a stalled push last went out, last
// when a frame last went out.
type chatShellFlow struct {
held, paced, last time.Time
}
// pushOutput pushes the unpushed output, oldest first, while the session's
// watchers drain; it reports whether output still waits for them. Watchers
// behind for chatShellStall get the old pacing until they catch up: the
// newest chunk once per flush interval, the rest skipped (a gap).
func (r *chatShellRunner) pushOutput(p *chatShellProcess, flow *chatShellFlow) bool {
for {
if r.backlog != nil && r.backlog(p.sessionID()) >= chatShellBacklog {
now := time.Now()
if flow.held.IsZero() {
flow.held = now
}
if now.Sub(flow.held) < chatShellStall {
return true
}
p.mu.Lock()
p.out.skipUnemitted(protocol.ChatShellRunChunkLimit)
p.mu.Unlock()
signalChatShell(p.room)
if now.Sub(flow.paced) >= r.flush {
flow.paced = now
r.emitOutput(p, false)
}
return true
}
flow.held = time.Time{}
p.mu.Lock()
waiting := p.out.unemitted()
p.mu.Unlock()
if waiting > 0 && waiting < protocol.ChatShellRunChunkLimit && time.Since(flow.last) < chatShellRetry {
return true // streaming: let the rest gather into one frame
}
if !r.emitOutput(p, false) {
return false
}
flow.last = time.Now()
}
}
// emitOutput pushes the oldest output not pushed yet (one frame) and
// reports whether there was any.
func (r *chatShellRunner) emitOutput(p *chatShellProcess, final bool) bool {
p.mu.Lock()
text, offset, end, ok := p.out.pending(protocol.ChatShellRunChunkLimit, final)
sessionID, runID := p.record.SessionID, p.record.ID
p.mu.Unlock()
if !ok || r.publish == nil {
return
if !ok {
return false
}
signalChatShell(p.room)
if r.publish != nil {
r.publish(sessionID, protocol.ChatShellRunEventFrame{SessionID: sessionID, RunID: runID, Output: text, Offset: offset, End: end})
}
return true
}
func (p *chatShellProcess) sessionID() string {
p.mu.Lock()
defer p.mu.Unlock()
return p.record.SessionID
}
// awaitPushed holds the reader while chatShellWindow bytes wait unpushed,
// until the command exited (its output is then drained regardless).
func (p *chatShellProcess) awaitPushed(exited <-chan struct{}) {
for {
p.mu.Lock()
waiting := p.out.unemitted() >= chatShellWindow
p.mu.Unlock()
if !waiting {
return
}
select {
case <-p.room:
case <-exited:
return
}
}
}
func signalChatShell(ch chan struct{}) {
select {
case ch <- struct{}{}:
default:
}
r.publish(sessionID, protocol.ChatShellRunEventFrame{SessionID: sessionID, RunID: runID, Output: text, Offset: offset, End: end})
}
// save persists a record; a shutdown's base context is already canceled, so
+220 -37
View File
@@ -2,13 +2,15 @@ package server
import (
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// terminalClientQueue bounds the frames waiting for one slow connection.
// A full queue drops output frames; the client sees the gap in the next
// frame's offset and reads the retained tail again (terminal_output after).
// 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
@@ -21,71 +23,252 @@ type terminalClients struct {
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{}
subs map[string]bool
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), done: make(chan struct{}), subs: map[string]bool{}}
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{}
}
if old := c.clients[clientID]; old != nil {
close(old.done)
}
old := c.clients[clientID]
c.clients[clientID] = client
c.mu.Unlock()
go func() {
for {
select {
case <-client.done:
return
case msg := <-client.ch:
if write(msg) != nil {
return
}
}
}
}()
if old != nil {
old.stop()
}
go client.run(write)
}
func (c *terminalClients) detach(clientID string) {
c.mu.Lock()
defer c.mu.Unlock()
if client := c.clients[clientID]; client != nil {
close(client.done)
delete(c.clients, clientID)
client := c.clients[clientID]
delete(c.clients, clientID)
c.mu.Unlock()
if client != nil {
client.stop()
}
}
// subscribe sends terminalID's output frames to clientID from now on.
func (c *terminalClients) subscribe(clientID, terminalID string) {
func (c *terminalClients) client(clientID string) *terminalClient {
c.mu.Lock()
defer c.mu.Unlock()
if client := c.clients[clientID]; client != nil {
client.subs[terminalID] = true
}
return c.clients[clientID]
}
// publish queues frame for its recipients without blocking: a lifecycle
// change for everyone, output for the terminal's subscribers.
// 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 {
if frame.Terminal == nil && !client.subs[frame.TerminalID] {
continue
}
if frame.Terminal != nil && frame.Terminal.Status == protocol.TerminalClosed {
delete(client.subs, frame.TerminalID)
}
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}
}
+210
View File
@@ -0,0 +1,210 @@
package server
import (
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Output flow of machine terminals (protocol.TerminalEvent). Each
// connection's subscription to a terminal is a cursor into the terminal's
// retained output; the connection's writer sends from it as soon as output
// is there, so a frame carries what arrived while the previous write was in
// flight. A flow-controlled subscription is sent at most
// TerminalFlowWindow bytes past its last terminal_ack, and while one is full
// the terminal's reader stops reading the PTY: the program blocks on its
// writes instead of output being skipped. A subscription that stays full
// without acknowledging for terminalStall no longer holds the terminal back;
// it sees a gap later and reads the tail again. While output streams, a
// frame waits up to terminalBurst for more to join it. A subscription
// without flow (an older client) keeps the old pacing: the newest bytes, one
// frame per terminalLegacyPace.
const (
terminalStall = 3 * time.Second
terminalLegacyPace = 50 * time.Millisecond
terminalBurst = 2 * time.Millisecond
)
// terminalView is one connection's subscription to one terminal's output.
// Its fields after p are guarded by p.mu.
type terminalView struct {
client *terminalClient
p *terminalProcess
flow bool
// sent is the next byte to send; acked is the end the client consumed.
sent, acked int64
// fullSince is when the window was last seen full without progress.
fullSince time.Time
// paused: a terminal_output reply is on its way; frames wait for it.
paused bool
lastSent time.Time
gone bool
}
func (p *terminalProcess) id() string {
p.mu.Lock()
defer p.mu.Unlock()
return p.record.ID
}
// join adds v to the terminal's subscriptions.
func (p *terminalProcess) join(v *terminalView) {
p.mu.Lock()
defer p.mu.Unlock()
p.views[v] = struct{}{}
}
// leave ends v: it is sent nothing more and no longer holds the reader.
func (v *terminalView) leave() {
p := v.p
p.mu.Lock()
v.gone = true
delete(p.views, v)
p.mu.Unlock()
p.signalRoom()
}
// next takes the frame v may be sent now and advances v past it. force
// ignores the window and the pacing (an ended terminal's rest). again is how
// long a paced subscription waits before its next frame.
func (v *terminalView) next(now time.Time, force bool) (frame protocol.TerminalEventFrame, ok bool, again time.Duration) {
p := v.p
p.mu.Lock()
defer p.mu.Unlock()
if v.gone || v.paused {
return frame, false, 0
}
out := p.out
if v.sent < out.start {
// The bytes after sent were dropped (a stale subscription). Once it
// acknowledges again the stream goes on after a gap, with a fresh
// window: the client reads the tail again (terminal_output).
if v.flow && !force && v.sent-v.acked >= protocol.TerminalFlowWindow {
return frame, false, 0
}
v.sent, v.acked = out.start, out.start
}
from, limit := v.sent, out.total
switch {
case force:
case v.flow:
limit = min(limit, v.acked+protocol.TerminalFlowWindow)
// Streaming (a frame went out within terminalBurst): let a small
// remainder gather into one frame rather than one per PTY read.
// A keystroke's echo after a pause goes at once.
waiting := limit - from
if since := now.Sub(v.lastSent); waiting > 0 && waiting < protocol.TerminalChunkLimit &&
limit == out.total && !p.outDone && since < terminalBurst {
return frame, false, terminalBurst - since
}
default:
if out.total <= v.sent {
return frame, false, 0
}
if wait := terminalLegacyPace - now.Sub(v.lastSent); wait > 0 {
return frame, false, wait
}
from = out.newestFrom(from, protocol.TerminalChunkLimit)
}
text, offset, end, ok := out.chunk(from, limit, protocol.TerminalChunkLimit, p.outDone)
if !ok {
return frame, false, 0
}
v.sent, v.lastSent = end, now
return protocol.TerminalEventFrame{TerminalID: p.record.ID, Output: text, Offset: offset, End: end}, true, 0
}
// ack records that the client consumed the output up to end.
func (v *terminalView) ack(end int64) {
p := v.p
p.mu.Lock()
end = min(end, v.sent)
advanced := end > v.acked
if advanced {
v.acked, v.fullSince = end, time.Time{}
}
p.mu.Unlock()
if advanced {
p.signalRoom()
v.client.poke()
}
}
// resetLocked restarts v at end (a terminal_output reply covers what was
// before), paused until that reply is written. p.mu is held.
func (v *terminalView) resetLocked(end int64) {
v.sent, v.acked, v.fullSince, v.paused = end, end, time.Time{}, true
}
// release lets frames follow the terminal_output reply just written.
func (v *terminalView) release() {
v.p.mu.Lock()
v.paused = false
v.p.mu.Unlock()
v.client.poke()
}
// pokeViewsLocked wakes the writer of every subscription. p.mu is held.
func (p *terminalProcess) pokeViewsLocked() {
for v := range p.views {
v.client.poke()
}
}
func (p *terminalProcess) signalRoom() {
select {
case p.room <- struct{}{}:
default:
}
}
// heldLocked reports whether a flow-controlled subscription is full and
// still within terminalStall of its last progress, and how long until the
// first such one goes stale. p.mu is held.
func (p *terminalProcess) heldLocked(now time.Time) (bool, time.Duration) {
held, wait := false, time.Duration(0)
for v := range p.views {
if !v.flow || v.gone {
continue
}
if p.out.total-v.acked < protocol.TerminalFlowWindow {
v.fullSince = time.Time{}
continue
}
if v.fullSince.IsZero() {
v.fullSince = now
}
left := terminalStall - now.Sub(v.fullSince)
if left <= 0 {
continue
}
if !held || left < wait {
wait = left
}
held = true
}
return held, wait
}
// awaitRoom blocks the reader while a live flow-controlled subscription is
// full. Once the attachment exited its output is drained regardless.
func (p *terminalProcess) awaitRoom() {
for {
p.mu.Lock()
held, wait := p.heldLocked(time.Now())
p.mu.Unlock()
if !held {
return
}
timer := time.NewTimer(wait)
select {
case <-p.room:
case <-p.exited:
timer.Stop()
return
case <-timer.C:
}
timer.Stop()
}
}
+255
View File
@@ -0,0 +1,255 @@
//go:build darwin || linux
package server
import (
"context"
"fmt"
"net/http/httptest"
"sort"
"strings"
"testing"
"time"
"github.com/coder/websocket"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// dialTerminalConns connects n clients that accept full-size output frames.
func dialTerminalConns(t *testing.T, n int, timeout time.Duration) (context.Context, []*websocket.Conn) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
srv := httptest.NewServer(HandlerWithOptions(ctx, Options{OperatorRegistry: newOperatorStore(t)}))
t.Cleanup(func() { srv.Close(); cancel() })
var conns []*websocket.Conn
for range n {
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
if err != nil {
t.Fatal(err)
}
conn.SetReadLimit(4 << 20)
t.Cleanup(func() { conn.CloseNow() })
conns = append(conns, conn)
}
return ctx, conns
}
// openLoggedIn opens a terminal on conn (flow-controlled or not), logs in
// and returns it read again (its OutputEnd is where the next frame starts).
func openLoggedIn(t *testing.T, ctx context.Context, conn *websocket.Conn, flow bool) protocol.TerminalRecord {
t.Helper()
opened := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalOpen, "open", protocol.TerminalRequest{Cols: 80, Rows: 24, Flow: flow}))
if opened.Terminal == nil {
t.Fatalf("open reply = %+v", opened)
}
if want := map[bool]int64{true: protocol.TerminalFlowWindow, false: 0}[flow]; opened.Terminal.Window != want {
t.Fatalf("window = %d, want %d", opened.Terminal.Window, want)
}
terminalLogIn(t, ctx, conn, opened.Terminal.ID)
read := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalOutput, "reread", protocol.TerminalRequest{TerminalID: opened.Terminal.ID, Flow: flow}))
return *read.Terminal
}
// terminalReader follows one connection's output of one terminal.
type terminalReader struct {
t *testing.T
ctx context.Context
conn *websocket.Conn
id string
end int64
acked int64
ack bool
gaps int64
text strings.Builder
}
// frame reads the next output frame of the terminal, checks it continues
// the stream (counting gaps), records it and acknowledges it when acking.
func (r *terminalReader) frame() protocol.TerminalEventFrame {
r.t.Helper()
frame := *readShellFrame(r.t, r.ctx, r.conn, func(m protocol.Message) bool {
return m.Type == protocol.TerminalEvent && m.TerminalEvent.TerminalID == r.id && m.TerminalEvent.Terminal == nil
}).TerminalEvent
switch {
case frame.Offset > r.end:
r.gaps += frame.Offset - r.end
case frame.Offset < r.end:
r.t.Fatalf("frame [%d, %d) overlaps the end %d", frame.Offset, frame.End, r.end)
}
r.text.WriteString(frame.Output)
r.end = frame.End
if r.ack && r.end-r.acked >= protocol.TerminalFlowWindow/4 {
r.acked = r.end
writeChat(r.t, r.ctx, r.conn, terminalRequest(protocol.TerminalAck, "", protocol.TerminalRequest{TerminalID: r.id, After: r.end}))
}
return frame
}
// until reads frames until the text holds want.
func (r *terminalReader) until(want string, each func()) {
r.t.Helper()
for !strings.Contains(r.text.String(), want) {
r.frame()
if each != nil {
each()
}
}
}
func typeInto(t *testing.T, ctx context.Context, conn *websocket.Conn, id, data string) {
t.Helper()
writeChat(t, ctx, conn, terminalRequest(protocol.TerminalInput, "", protocol.TerminalRequest{TerminalID: id, Data: data}))
}
// seqCommand prints 1..n between markers that its own echo does not show.
func seqCommand(n int) string { return fmt.Sprintf("echo BEG$((1))IN; seq 1 %d; echo EN$((1))D\r", n) }
// seqOutput is what seqCommand prints between its markers in a terminal.
func seqOutput(t *testing.T, text string, n int) {
t.Helper()
begin := strings.Index(text, "BEG1IN\r\n")
finish := strings.Index(text, "EN1D")
if begin < 0 || finish < begin {
t.Fatalf("markers missing in %d bytes", len(text))
}
got := text[begin+len("BEG1IN\r\n") : finish]
var want strings.Builder
for i := 1; i <= n; i++ {
fmt.Fprintf(&want, "%d\r\n", i)
}
if got != want.String() {
first := 0
for first < min(len(got), want.Len()) && got[first] == want.String()[first] {
first++
}
t.Fatalf("output differs at byte %d of %d (got %d bytes)", first, want.Len(), len(got))
}
}
// A program writing far more than the retained tail to a slow,
// acknowledging client is held back: the client gets every byte in order.
func TestTerminalFlowSlowConsumerGetsEveryByte(t *testing.T) {
terminalHome(t)
ctx, conns := dialTerminalConns(t, 1, 60*time.Second)
term := openLoggedIn(t, ctx, conns[0], true)
reader := &terminalReader{t: t, ctx: ctx, conn: conns[0], id: term.ID, end: term.OutputEnd, ack: true}
const n = 300000 // about 2.1 MB, twice the retained tail
typeInto(t, ctx, conns[0], term.ID, seqCommand(n))
reader.until("EN1D", func() { time.Sleep(3 * time.Millisecond) })
if reader.gaps != 0 {
t.Fatalf("%d bytes skipped", reader.gaps)
}
seqOutput(t, reader.text.String(), n)
}
// A subscriber that stops reading holds the terminal back only until it is
// stale; the reading one gets everything meanwhile, and the stalled one
// sees a gap once it acknowledges again.
func TestTerminalFlowStalledClientDoesNotBlockOthers(t *testing.T) {
terminalHome(t)
ctx, conns := dialTerminalConns(t, 2, 60*time.Second)
term := openLoggedIn(t, ctx, conns[0], true)
stalled := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalOutput, "read", protocol.TerminalRequest{TerminalID: term.ID, Flow: true}))
if stalled.Terminal == nil || stalled.Terminal.Window != protocol.TerminalFlowWindow {
t.Fatalf("output reply = %+v", stalled)
}
reader := &terminalReader{t: t, ctx: ctx, conn: conns[0], id: term.ID, end: term.OutputEnd, ack: true}
const n = 450000 // about 3.3 MB
start := time.Now()
typeInto(t, ctx, conns[0], term.ID, seqCommand(n))
reader.until("EN1D", nil)
elapsed := time.Since(start)
if reader.gaps != 0 {
t.Fatalf("the reading client skipped %d bytes", reader.gaps)
}
seqOutput(t, reader.text.String(), n)
if elapsed < terminalStall/2 || elapsed > terminalStall+10*time.Second {
t.Fatalf("finished after %s; the stalled client should hold it about %s", elapsed, terminalStall)
}
// The stalled client got a window's worth, then nothing; acknowledging
// it brings the next frame, after a gap.
late := &terminalReader{t: t, ctx: ctx, conn: conns[1], id: term.ID, end: stalled.Terminal.OutputEnd, ack: true}
for late.end-stalled.Terminal.OutputEnd < protocol.TerminalFlowWindow-protocol.TerminalChunkLimit {
late.frame()
}
if late.gaps != 0 {
t.Fatalf("the window itself had a gap of %d", late.gaps)
}
writeChat(t, ctx, conns[1], terminalRequest(protocol.TerminalAck, "", protocol.TerminalRequest{TerminalID: term.ID, After: late.end}))
for late.gaps == 0 {
late.frame()
}
}
// A client that never asks for flow keeps the old behaviour: it is never
// waited for, gets paced frames of the newest output, and sends no acks.
func TestTerminalFlowLegacyClientIsNotWaitedFor(t *testing.T) {
terminalHome(t)
ctx, conns := dialTerminalConns(t, 1, 60*time.Second)
term := openLoggedIn(t, ctx, conns[0], false)
reader := &terminalReader{t: t, ctx: ctx, conn: conns[0], id: term.ID, end: term.OutputEnd}
reader.until("$ ", nil)
typeInto(t, ctx, conns[0], term.ID, seqCommand(500000))
var frames int
var times []time.Time
reader.until("EN1D", func() { frames++; times = append(times, time.Now()) })
if reader.gaps == 0 {
t.Fatal("a paced client received all 3.9 MB")
}
for i := 2; i < len(times); i++ {
if gap := times[i].Sub(times[i-1]); gap < terminalLegacyPace/2 {
t.Fatalf("frames %d and %d only %s apart", i-1, i, gap)
}
}
}
// A keystroke's echo is pushed as soon as it is read, not on a timer.
func TestTerminalFlowEchoIsImmediate(t *testing.T) {
terminalHome(t)
ctx, conns := dialTerminalConns(t, 1, 30*time.Second)
term := openLoggedIn(t, ctx, conns[0], true)
reader := &terminalReader{t: t, ctx: ctx, conn: conns[0], id: term.ID, end: term.OutputEnd, ack: true}
reader.until("$ ", nil)
var latencies []time.Duration
for i := 0; i < 15; i++ {
start := time.Now()
typeInto(t, ctx, conns[0], term.ID, "z")
for !strings.HasSuffix(reader.text.String(), "z") {
reader.frame()
}
latencies = append(latencies, time.Since(start))
time.Sleep(13 * time.Millisecond)
}
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
if median := latencies[len(latencies)/2]; median > 15*time.Millisecond {
t.Fatalf("median echo latency %s (all %v)", median, latencies)
}
}
// Frames after a terminal_output reply continue exactly where its output
// ends, even while the terminal is writing.
func TestTerminalFlowOutputReplyResumesExactly(t *testing.T) {
terminalHome(t)
ctx, conns := dialTerminalConns(t, 1, 60*time.Second)
term := openLoggedIn(t, ctx, conns[0], true)
typeInto(t, ctx, conns[0], term.ID, seqCommand(300000))
for round := 0; round < 5; round++ {
reply := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalOutput, fmt.Sprintf("read%d", round), protocol.TerminalRequest{TerminalID: term.ID, After: 1 << 40, Flow: true}))
end := reply.Terminal.OutputEnd
reader := &terminalReader{t: t, ctx: ctx, conn: conns[0], id: term.ID, end: end, ack: true}
for {
frame := *readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool {
return m.Type == protocol.TerminalEvent && m.TerminalEvent.TerminalID == term.ID && m.TerminalEvent.Terminal == nil
}).TerminalEvent
if frame.End <= end {
continue // taken before the reply, already covered by it
}
if frame.Offset != end {
t.Fatalf("round %d: frame at %d after a reply ending at %d", round, frame.Offset, end)
}
reader.end = frame.End
break
}
}
}
+17 -4
View File
@@ -11,7 +11,7 @@ import (
func isTerminalRequest(kind string) bool {
switch kind {
case protocol.TerminalOpen, protocol.TerminalList, protocol.TerminalInput, protocol.TerminalResize,
protocol.TerminalOutput, protocol.TerminalClose:
protocol.TerminalOutput, protocol.TerminalClose, protocol.TerminalAck:
return true
}
return false
@@ -39,7 +39,7 @@ func handleTerminalRequest(ctx context.Context, request protocol.Message, m *ter
var err error
switch request.Type {
case protocol.TerminalOpen:
record, err = m.Open(ctx, clientID, body.Cwd, body.Cols, body.Rows)
record, err = m.Open(ctx, clientID, body.Cwd, body.Cols, body.Rows, body.Flow)
case protocol.TerminalList:
var records []protocol.TerminalRecord
records, err = m.List(ctx)
@@ -49,8 +49,15 @@ func handleTerminalRequest(ctx context.Context, request protocol.Message, m *ter
case protocol.TerminalResize:
record, err = m.Resize(body.TerminalID, body.Cols, body.Rows)
case protocol.TerminalOutput:
m.clients.subscribe(clientID, body.TerminalID)
record, err = m.Output(ctx, body.TerminalID, body.After)
// The output frames that follow the reply wait until it is written.
defer func() {
if v := m.clients.view(clientID, body.TerminalID); v != nil {
v.release()
}
}()
record, err = m.Output(ctx, clientID, body.TerminalID, body.After, body.Flow)
case protocol.TerminalAck:
err = m.Ack(clientID, body.TerminalID, body.After)
case protocol.TerminalClose:
record, err = m.Close(ctx, body.TerminalID)
}
@@ -62,4 +69,10 @@ func handleTerminalRequest(ctx context.Context, request protocol.Message, m *ter
reply.Terminal = &record
}
_ = write(reply)
if request.Type == protocol.TerminalOpen {
// The login's output frames follow the reply.
if v := m.clients.view(clientID, record.ID); v != nil {
v.release()
}
}
}
+2 -2
View File
@@ -18,7 +18,7 @@ func TestTerminalEndsWithServer(t *testing.T) {
terminalHome(t)
store := newOperatorStore(t)
first, stop := newTestTerminals(t, store)
term, err := first.Open(context.Background(), "", "", 0, 0)
term, err := first.Open(context.Background(), "", "", 0, 0, false)
if err != nil {
t.Fatal(err)
}
@@ -80,7 +80,7 @@ func TestTerminalTitles(t *testing.T) {
}
terminalHome(t)
m, _ := newTestTerminals(t, newOperatorStore(t))
term, err := m.Open(context.Background(), "", "", 0, 0)
term, err := m.Open(context.Background(), "", "", 0, 0, false)
if err != nil {
t.Fatal(err)
}
+6 -6
View File
@@ -31,7 +31,7 @@ func waitTerminalOutput(t *testing.T, m *terminalManager, id, want string) proto
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for {
record, err := m.Output(context.Background(), id, 0)
record, err := m.Output(context.Background(), "", id, 0, false)
if err != nil {
t.Fatal(err)
}
@@ -119,7 +119,7 @@ func TestTerminalRefusedWithoutSu(t *testing.T) {
t.Fatalf("found su %q", found)
}
m, _ := newTestTerminals(t, newOperatorStore(t))
if _, err := m.Open(context.Background(), "", "", 0, 0); err == nil || !strings.Contains(err.Error(), "su is not installed") {
if _, err := m.Open(context.Background(), "", "", 0, 0, false); err == nil || !strings.Contains(err.Error(), "su is not installed") {
t.Fatalf("open without su = %v", err)
}
if list, _ := m.List(context.Background()); len(list) != 0 {
@@ -141,7 +141,7 @@ func TestTerminalShowsLoginPrompt(t *testing.T) {
t.Fatal(err)
}
m, _ := newTestTerminals(t, newOperatorStore(t))
wrong, err := m.Open(context.Background(), "", "", 0, 0)
wrong, err := m.Open(context.Background(), "", "", 0, 0, false)
if err != nil {
t.Fatal(err)
}
@@ -151,7 +151,7 @@ func TestTerminalShowsLoginPrompt(t *testing.T) {
if raw, _ := json.Marshal(wrong); strings.Contains(string(raw), "tmux") {
t.Fatalf("record mentions tmux: %s", raw)
}
if out, _ := m.Output(context.Background(), wrong.ID, 0); !strings.Contains(out.Output, "Password:") {
if out, _ := m.Output(context.Background(), "", wrong.ID, 0, false); !strings.Contains(out.Output, "Password:") {
t.Fatalf("output = %q", out.Output)
}
if err := m.Input(wrong.ID, "not-it\r"); err != nil {
@@ -163,7 +163,7 @@ func TestTerminalShowsLoginPrompt(t *testing.T) {
}
waitTerminalOutput(t, m, wrong.ID, "Authentication failed")
right, err := m.Open(context.Background(), "", "~/sub dir", 0, 0)
right, err := m.Open(context.Background(), "", "~/sub dir", 0, 0, false)
if err != nil {
t.Fatal(err)
}
@@ -220,7 +220,7 @@ func TestTerminalRefusesUnpromptedLogin(t *testing.T) {
"notty": "su: must be run from a terminal",
} {
t.Setenv("FAKE_SU_MODE", mode)
if record, err := m.Open(context.Background(), "", "", 0, 0); err == nil || !strings.Contains(err.Error(), phrase) {
if record, err := m.Open(context.Background(), "", "", 0, 0, false); err == nil || !strings.Contains(err.Error(), phrase) {
t.Fatalf("%s: open = %+v, %v", mode, record, err)
}
}
+48 -13
View File
@@ -35,7 +35,6 @@ type terminalManager struct {
promptWait time.Duration
home func() (string, error)
now func() time.Time
flush time.Duration
mu sync.Mutex
terms map[string]*terminalProcess
@@ -45,7 +44,7 @@ type terminalManager struct {
func newTerminalManager(base context.Context, store terminalStore) *terminalManager {
return &terminalManager{
base: base, store: store, clients: &terminalClients{},
login: terminalLoginCommand, promptWait: terminalPromptWait, home: OperatorHomeDirectory, now: time.Now, flush: 50 * time.Millisecond,
login: terminalLoginCommand, promptWait: terminalPromptWait, home: OperatorHomeDirectory, now: time.Now,
terms: map[string]*terminalProcess{},
}
}
@@ -60,9 +59,10 @@ func newTerminalID() (string, error) {
// Open starts a terminal in cwd at cols x rows at the machine's login prompt
// and returns its record once the prompt shows. clientID (when set) is
// subscribed to its output before the login writes. A login that cannot ask
// for the password is refused.
func (m *terminalManager) Open(ctx context.Context, clientID, cwd string, cols, rows int) (protocol.TerminalRecord, error) {
// subscribed to its output before the login writes (flow: acknowledged, and
// the record carries the window). A login that cannot ask for the password
// is refused.
func (m *terminalManager) Open(ctx context.Context, clientID, cwd string, cols, rows int, flow bool) (protocol.TerminalRecord, error) {
if m.store == nil {
return protocol.TerminalRecord{}, errors.New("terminals need the server's store, which is not configured")
}
@@ -85,7 +85,7 @@ func (m *terminalManager) Open(ctx context.Context, clientID, cwd string, cols,
if err != nil {
return protocol.TerminalRecord{}, err
}
p, err := m.start(clientID, id, dir, cmd, cols, rows)
p, err := m.start(clientID, id, dir, cmd, cols, rows, flow)
if err != nil {
return protocol.TerminalRecord{}, err
}
@@ -100,12 +100,15 @@ func (m *terminalManager) Open(ctx context.Context, clientID, cwd string, cols,
}
record = p.snapshot(false, 0)
m.publishRecord(record)
if flow && clientID != "" && m.clients.view(clientID, id) != nil {
record.Window = protocol.TerminalFlowWindow
}
return record, nil
}
// start runs cmd in a new terminal's PTY and supervises it; the terminal
// counts against the limit from here on.
func (m *terminalManager) start(clientID, id, dir string, cmd *exec.Cmd, cols, rows int) (*terminalProcess, error) {
func (m *terminalManager) start(clientID, id, dir string, cmd *exec.Cmd, cols, rows int, flow bool) (*terminalProcess, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.base.Err() != nil {
@@ -124,7 +127,12 @@ func (m *terminalManager) start(clientID, id, dir string, cmd *exec.Cmd, cols, r
}
m.terms[id] = p
if clientID != "" {
m.clients.subscribe(clientID, id)
// Its frames follow the open reply (the handler releases them).
if v := m.clients.subscribe(clientID, p, flow); v != nil {
p.mu.Lock()
v.paused = true
p.mu.Unlock()
}
}
m.wg.Add(1)
go m.supervise(p, cmd, terminal)
@@ -166,6 +174,16 @@ func (m *terminalManager) refuse(p *terminalProcess) {
p.mu.Unlock()
p.signal(syscall.SIGKILL)
<-p.done
p.mu.Lock()
views := make([]*terminalView, 0, len(p.views))
for v := range p.views {
views = append(views, v)
}
id := p.record.ID
p.mu.Unlock()
for _, v := range views {
v.client.unsubscribe(id)
}
}
// terminalLastLine is the last non-empty line of a terminal's output, for a
@@ -269,11 +287,18 @@ func (m *terminalManager) Resize(id string, cols, rows int) (protocol.TerminalRe
return p.snapshot(false, 0), nil
}
// Output is one terminal with its retained output from byte after on. A
// terminal ended before this process started has no output.
func (m *terminalManager) Output(ctx context.Context, id string, after int64) (protocol.TerminalRecord, error) {
// Output is one terminal with its retained output from byte after on,
// subscribing clientID (when set) to the output that follows it (flow:
// acknowledged); the caller releases that subscription once the reply is
// written (m.clients.view(...).release). A terminal ended before this
// process started has no output.
func (m *terminalManager) Output(ctx context.Context, clientID, id string, after int64, flow bool) (protocol.TerminalRecord, error) {
if p := m.process(id); p != nil {
return p.snapshot(true, after), nil
var v *terminalView
if clientID != "" {
v = m.clients.subscribe(clientID, p, flow)
}
return p.readFor(after, v), nil
}
records, err := m.List(ctx)
if err != nil {
@@ -287,6 +312,16 @@ func (m *terminalManager) Output(ctx context.Context, id string, after int64) (p
return protocol.TerminalRecord{}, errors.New("this machine has no such terminal")
}
// Ack records that clientID consumed terminal id's output up to end.
func (m *terminalManager) Ack(clientID, id string, end int64) error {
v := m.clients.view(clientID, id)
if v == nil {
return errors.New("this connection does not read that terminal")
}
v.ack(end)
return nil
}
// Close ends a terminal (killing its login and shell) and forgets
// it. It waits briefly for the shell to go and returns the closed record.
func (m *terminalManager) Close(ctx context.Context, id string) (protocol.TerminalRecord, error) {
@@ -307,7 +342,7 @@ func (m *terminalManager) Close(ctx context.Context, id string) (protocol.Termin
}
return p.snapshot(false, 0), nil
}
record, err := m.Output(ctx, id, 0)
record, err := m.Output(ctx, "", id, 0, false)
if err != nil {
return protocol.TerminalRecord{}, err
}
+203
View File
@@ -0,0 +1,203 @@
//go:build darwin || linux
package server
import (
"context"
"encoding/json"
"fmt"
"net/http/httptest"
"os"
"sort"
"strings"
"testing"
"time"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
)
// measureFrame is the part of a server frame the measurement reads; it is
// decoded loosely so the same driver measures servers with and without flow
// control.
type measureFrame struct {
Type string `json:"type"`
ID string `json:"id"`
Error string `json:"error"`
Terminal *struct {
ID string `json:"id"`
Window int64 `json:"window"`
OutputEnd int64 `json:"output_end"`
} `json:"terminal"`
Event *struct {
TerminalID string `json:"terminal_id"`
Output string `json:"output"`
Offset int64 `json:"offset"`
End int64 `json:"end"`
Terminal *struct {
Status string `json:"status"`
} `json:"terminal"`
} `json:"terminal_event"`
}
type measureConn struct {
t *testing.T
ctx context.Context
conn *websocket.Conn
id string
window int64
acked int64
seq int
}
func (c *measureConn) send(kind string, body map[string]any) string {
c.seq++
id := fmt.Sprintf("m%d", c.seq)
if err := wsjson.Write(c.ctx, c.conn, map[string]any{"type": kind, "id": id, "terminal_request": body}); err != nil {
c.t.Fatal(err)
}
return id
}
func (c *measureConn) read() measureFrame {
var raw json.RawMessage
if err := wsjson.Read(c.ctx, c.conn, &raw); err != nil {
c.t.Fatal(err)
}
var frame measureFrame
if err := json.Unmarshal(raw, &frame); err != nil {
c.t.Fatal(err)
}
return frame
}
// reply waits for the reply to id; output frames read meanwhile go to seen.
func (c *measureConn) reply(id string, seen func(measureFrame)) measureFrame {
for {
frame := c.read()
if frame.ID == id {
if frame.Type == "error" {
c.t.Fatalf("request %s: %s", id, frame.Error)
}
return frame
}
if seen != nil {
seen(frame)
}
}
}
// ack acknowledges consumption up to end when the server granted a window.
func (c *measureConn) ack(end int64) {
if c.window > 0 && end-c.acked >= c.window/4 {
c.acked = end
c.send("terminal_ack", map[string]any{"terminal_id": c.id, "after": end})
}
}
// TestMeasureTerminalStream measures a live terminal over the websocket:
// bulk output delivered (bytes, frames, bytes skipped, throughput) and the
// echo latency of single keystrokes. It prints numbers and asserts nothing
// beyond the stream being readable; set PIPELINES_TERMINAL_MEASURE=1 (or
// =legacy for a client that does not ask for flow control).
func TestMeasureTerminalStream(t *testing.T) {
if os.Getenv("PIPELINES_TERMINAL_MEASURE") == "" {
t.Skip("set PIPELINES_TERMINAL_MEASURE=1 to measure")
}
terminalHome(t)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
srv := httptest.NewServer(HandlerWithOptions(ctx, Options{OperatorRegistry: newOperatorStore(t)}))
defer srv.Close()
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
if err != nil {
t.Fatal(err)
}
defer conn.CloseNow()
conn.SetReadLimit(8 << 20)
c := &measureConn{t: t, ctx: ctx, conn: conn}
opened := c.reply(c.send("terminal_open", map[string]any{"cols": 80, "rows": 24, "flow": os.Getenv("PIPELINES_TERMINAL_MEASURE") != "legacy"}), nil)
c.id, c.window = opened.Terminal.ID, opened.Terminal.Window
var end int64
consume := func(f measureFrame) (string, bool) {
if f.Event == nil || f.Event.TerminalID != c.id || f.Event.Terminal != nil {
return "", false
}
end = f.Event.End
c.ack(end)
return f.Event.Output, true
}
until := func(want string) {
var seen strings.Builder
for !strings.Contains(seen.String(), want) {
if text, ok := consume(c.read()); ok {
seen.WriteString(text)
}
}
}
c.send("terminal_input", map[string]any{"terminal_id": c.id, "data": fakeSuPassword + "\r"})
c.send("terminal_input", map[string]any{"terminal_id": c.id, "data": "PS1='$ '\r"})
until("$ ")
t.Logf("flow window granted: %d", c.window)
for _, job := range []struct{ name, command string }{
{"seq 1 500000", "seq 1 500000; echo DONE-$((1+1))"},
{"cat 2.1 MB", "head -c 2100000 /dev/zero | tr '\\0' 'x'; echo; echo DONE-$((1+1))"},
{"yes | head -1000000", "yes | head -1000000; echo DONE-$((1+1))"},
} {
start := time.Now()
from := end
frames, skipped, received := 0, int64(0), int64(0)
var maxGap time.Duration
last := time.Now()
c.send("terminal_input", map[string]any{"terminal_id": c.id, "data": job.command + "\r"})
var tail strings.Builder
for !strings.Contains(tail.String(), "DONE-2") {
if time.Since(start) > 15*time.Second {
t.Fatalf("%s: no end after %d frames, end %d, tail %q", job.name, frames, end, tail.String())
}
f := c.read()
if f.Event == nil || f.Event.TerminalID != c.id || f.Event.Terminal != nil {
continue
}
if gap := time.Since(last); gap > maxGap && frames > 0 {
maxGap = gap
}
last = time.Now()
if f.Event.Offset > end {
skipped += f.Event.Offset - end
}
received += int64(len(f.Event.Output))
frames++
text, _ := consume(f)
tail.WriteString(text)
if tail.Len() > 8192 {
s := tail.String()
tail.Reset()
tail.WriteString(s[len(s)-4096:])
}
}
elapsed := time.Since(start)
t.Logf("%-20s stream %8d B, received %8d B in %5d frames, skipped %8d B, %6.1f ms, %6.1f MB/s, max frame gap %5.1f ms",
job.name, end-from, received, frames, skipped, float64(elapsed.Microseconds())/1000,
float64(received)/elapsed.Seconds()/1e6, float64(maxGap.Microseconds())/1000)
}
var latencies []time.Duration
for i := 0; i < 40; i++ {
start := time.Now()
c.send("terminal_input", map[string]any{"terminal_id": c.id, "data": "z"})
for {
text, ok := consume(c.read())
if ok && strings.Contains(text, "z") {
break
}
}
latencies = append(latencies, time.Since(start))
time.Sleep(7 * time.Millisecond)
}
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
ms := func(d time.Duration) float64 { return float64(d.Microseconds()) / 1000 }
t.Logf("echo latency over %d keys: min %.2f ms, median %.2f ms, p90 %.2f ms, max %.2f ms",
len(latencies), ms(latencies[0]), ms(latencies[len(latencies)/2]), ms(latencies[len(latencies)*9/10]), ms(latencies[len(latencies)-1]))
}
+44 -6
View File
@@ -35,6 +35,14 @@ type terminalProcess struct {
// refused: the login never asked for a password; the terminal is
// forgotten without being listed.
refused bool
// views are the connections' subscriptions to the output
// (terminal_flow.go); room is signalled when one may have room again,
// exited is closed once the attachment exited, and outDone is set once
// its stream is fully read.
views map[*terminalView]struct{}
room chan struct{}
exited chan struct{}
outDone bool
}
func newTerminalProcess(record protocol.TerminalRecord) *terminalProcess {
@@ -46,6 +54,9 @@ func newTerminalProcess(record protocol.TerminalRecord) *terminalProcess {
out: newChatShellOutput(protocol.TerminalRetained),
input: make(chan []byte, protocol.ChatShellInputQueue),
done: make(chan struct{}),
views: map[*terminalView]struct{}{},
room: make(chan struct{}, 1),
exited: make(chan struct{}),
loginChanged: make(chan struct{}, 1),
}
@@ -70,16 +81,40 @@ func (p *terminalProcess) running() bool {
func (p *terminalProcess) snapshot(output bool, after int64) protocol.TerminalRecord {
p.mu.Lock()
defer p.mu.Unlock()
return p.snapshotLocked(output, after)
}
// snapshotLocked is snapshot with p.mu held. The output ends at OutputEnd:
// an incomplete trailing character waits for the next frame.
func (p *terminalProcess) snapshotLocked(output bool, after int64) protocol.TerminalRecord {
record := p.record
record.OutputEnd = p.out.total
if output {
text, start := p.out.tail(protocol.TerminalRetained)
if after > start {
skip := min(after-start, int64(len(text)))
cut := runeStartAfter([]byte(text), int(skip))
text, start = text[cut:], start+int64(cut)
from := max(after, p.out.start)
text, start, end, ok := p.out.chunk(from, p.out.total, protocol.TerminalRetained, p.outDone)
if !ok {
// Nothing new (or only part of a character): the reply ends
// where the frames that follow it start.
from = min(from, p.out.total)
text, start, end = "", from, from
}
record.Output, record.OutputStart, record.OutputEnd = text, start, end
}
return record
}
// readFor is the record with its output from after on, read for
// subscription v (when set): v's frames continue where the output ends,
// once the reply is written (v.release).
func (p *terminalProcess) readFor(after int64, v *terminalView) protocol.TerminalRecord {
p.mu.Lock()
defer p.mu.Unlock()
record := p.snapshotLocked(true, after)
if v != nil && !v.gone {
v.resetLocked(record.OutputEnd)
if v.flow {
record.Window = protocol.TerminalFlowWindow
}
record.Output, record.OutputStart = text, start
}
return record
}
@@ -108,10 +143,12 @@ func (p *terminalProcess) startAttachment(cmd *exec.Cmd) (*os.File, error) {
func (p *terminalProcess) read(terminal *os.File, titled func(string)) {
buffer := make([]byte, 32<<10)
for {
p.awaitRoom()
n, err := terminal.Read(buffer)
if n > 0 {
p.mu.Lock()
p.out.write(buffer[:n])
p.pokeViewsLocked()
if p.login.feed(buffer[:n]) {
select {
case p.loginChanged <- struct{}{}:
@@ -166,6 +203,7 @@ func (p *terminalProcess) signal(sig syscall.Signal) {
// kills its group and closes its terminal. It returns the exit error.
func (p *terminalProcess) waitAttachment(cmd *exec.Cmd, terminal *os.File, readDone <-chan struct{}) error {
err := cmd.Wait()
close(p.exited)
_ = terminal.SetReadDeadline(time.Now().Add(chatShellDrain))
select {
case <-readDone:
+3 -31
View File
@@ -16,8 +16,6 @@ import (
func (m *terminalManager) supervise(p *terminalProcess, cmd *exec.Cmd, terminal *os.File) {
defer m.wg.Done()
defer close(p.done)
stopFlush, flushDone := make(chan struct{}), make(chan struct{})
go m.flushLoop(p, stopFlush, flushDone)
titled := func(string) {
p.mu.Lock()
listed := !p.refused && p.login.prompted
@@ -48,10 +46,10 @@ func (m *terminalManager) supervise(p *terminalProcess, cmd *exec.Cmd, terminal
}
}
shutdown := m.base.Err() != nil
close(stopFlush)
<-flushDone
m.emit(p, true)
p.mu.Lock()
// The stream is read: its last incomplete character goes out as is.
p.outDone = true
p.pokeViewsLocked()
// A terminal that never showed its prompt was never listed: Open
// refuses it, so it is forgotten unannounced.
listed := p.login.prompted && !p.refused
@@ -85,32 +83,6 @@ func (m *terminalManager) supervise(p *terminalProcess, cmd *exec.Cmd, terminal
}
}
// flushLoop pushes new output in batches until stop is closed.
func (m *terminalManager) flushLoop(p *terminalProcess, stop <-chan struct{}, done chan<- struct{}) {
defer close(done)
ticker := time.NewTicker(m.flush)
defer ticker.Stop()
for {
select {
case <-stop:
return
case <-ticker.C:
m.emit(p, false)
}
}
}
// emit pushes the output written since the last frame.
func (m *terminalManager) emit(p *terminalProcess, final bool) {
p.mu.Lock()
text, offset, end, ok := p.out.pending(protocol.TerminalChunkLimit, final)
id := p.record.ID
p.mu.Unlock()
if ok {
m.clients.publish(protocol.TerminalEventFrame{TerminalID: id, Output: text, Offset: offset, End: end})
}
}
// recover records the terminals a previous server process left running as
// ended: they ended with it.
func (m *terminalManager) recover(ctx context.Context) {
+10 -4
View File
@@ -86,6 +86,7 @@ func terminalReply(t *testing.T, ctx context.Context, conn *websocket.Conn, requ
// readTerminalUntil reads output frames of id from end on, in order, until
// the collected text contains want; it returns the text and the new end.
// A frame ending by end (sent before a read that covered it) is skipped.
func readTerminalUntil(t *testing.T, ctx context.Context, conn *websocket.Conn, id string, end int64, want string) (string, int64) {
t.Helper()
var seen strings.Builder
@@ -93,6 +94,9 @@ func readTerminalUntil(t *testing.T, ctx context.Context, conn *websocket.Conn,
frame := readShellFrame(t, ctx, conn, func(m protocol.Message) bool {
return m.Type == protocol.TerminalEvent && m.TerminalEvent.TerminalID == id && m.TerminalEvent.Terminal == nil
}).TerminalEvent
if frame.End <= end {
continue
}
if frame.Offset != end {
t.Fatalf("frame at %d after %d", frame.Offset, end)
}
@@ -113,10 +117,12 @@ func TestTerminalOverWebsocket(t *testing.T) {
t.Fatalf("open reply = %+v", opened)
}
terminalLogIn(t, ctx, conns[0], term.ID)
if got := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalInput, "in", protocol.TerminalRequest{TerminalID: term.ID, Data: "pwd; echo sum-$((40+2))\r"})); got.Type != protocol.TerminalInput {
t.Fatalf("input reply = %+v", got)
}
_, end := readTerminalUntil(t, ctx, conns[0], term.ID, 0, "sum-42")
// The replies above skipped the login's frames: read up to here, and
// the frames continue from the reply's end.
synced := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalOutput, "sync", protocol.TerminalRequest{TerminalID: term.ID})).Terminal
// Its reply is not awaited: that would skip the echo's frames.
writeChat(t, ctx, conns[0], terminalRequest(protocol.TerminalInput, "in", protocol.TerminalRequest{TerminalID: term.ID, Data: "pwd; echo sum-$((40+2))\r"}))
_, end := readTerminalUntil(t, ctx, conns[0], term.ID, synced.OutputEnd, "sum-42")
resized := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalResize, "size", protocol.TerminalRequest{TerminalID: term.ID, Cols: 120, Rows: 33}))
if resized.Type != protocol.TerminalResize || resized.Terminal.Cols != 120 || resized.Terminal.Rows != 33 {
t.Fatalf("resize reply = %+v", resized)
+2 -1
View File
@@ -282,7 +282,8 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
return
}
if request.Type != protocol.ChatShellInput && request.Type != protocol.ChatShellResize &&
request.Type != protocol.TerminalInput && request.Type != protocol.TerminalResize {
request.Type != protocol.TerminalInput && request.Type != protocol.TerminalResize &&
request.Type != protocol.TerminalAck {
// Keystrokes would be one line each; their data is never logged.
log.Printf("command received: client=%s type=%q id=%q pipeline=%d version=%d", r.RemoteAddr, request.Type, request.ID, request.PipelineID, request.Version)
}