Terminals: one active client per terminal; keystrokes skip the request queue
Several clients drawing one terminal (machine terminal or chat terminal command) no longer interfere. The server tracks, per terminal, the connections drawing it, most recently active first: the active client (the opener, then whoever last typed or focused it) owns the PTY size and is the only one whose emulator's automatic query answers reach the process; other clients' answers are acknowledged and dropped, and their sizes recorded but not applied. When the active connection closes the next most recent client's size is applied. Protocol (backwards compatible; all new fields optional): - terminal_input / chat_shell_input: reply (emulator answer), cols/rows (the typist's size, applied before the input). - terminal_resize / chat_shell_resize: activate (the client focused it). Latency: PipelinesClient sends terminal_input, terminal_resize, chat_shell_input and chat_shell_resize at once rather than behind the previous request's reply. The server reads those onto a per-connection terminal lane handled in order beside the ordinary request loop, and terminal_open (up to 5 s waiting for su) now runs off the read loop. Client: ChatShellTerminalSession routes what the emulator emits while drawing output to onReply and reports focus through activate(); ChatShellInputPipe keeps answers and typing in separate requests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -56,6 +56,7 @@ func handleChatShellRunRequest(ctx context.Context, request protocol.Message, br
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
runner.attachViewer(clientID, sessionID, record.ID, record.Cols, record.Rows)
|
||||
_ = write(protocol.Message{Type: protocol.ChatShellRun, ID: request.ID, ChatShellRun: &record})
|
||||
case protocol.ChatShellStop:
|
||||
record, err := runner.Stop(sessionID, body.RunID)
|
||||
@@ -92,13 +93,13 @@ func handleChatShellRunRequest(ctx context.Context, request protocol.Message, br
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatShellRestore, ID: request.ID, ChatShellRuns: runs})
|
||||
case protocol.ChatShellInput:
|
||||
if err := runner.Input(sessionID, body.RunID, body.Data); err != nil {
|
||||
if err := runner.ClientInput(clientID, sessionID, body.RunID, body.Data, body.Reply, body.Cols, body.Rows); err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatShellInput, ID: request.ID})
|
||||
case protocol.ChatShellResize:
|
||||
record, err := runner.Resize(sessionID, body.RunID, body.Cols, body.Rows)
|
||||
record, err := runner.ClientResize(clientID, sessionID, body.RunID, body.Cols, body.Rows, body.Activate)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
return
|
||||
|
||||
@@ -66,6 +66,8 @@ type chatShellProcess struct {
|
||||
// input feeds it in order (chat_shell_terminal.go).
|
||||
terminal *os.File
|
||||
input chan []byte
|
||||
// viewers are the connections drawing the terminal (terminal_viewers.go).
|
||||
viewers terminalViewers
|
||||
// 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
|
||||
|
||||
@@ -37,7 +37,9 @@ func TestChatShellTerminalOverWebsocket(t *testing.T) {
|
||||
resize := shellRequest(protocol.ChatShellResize, "size", run.ID, "")
|
||||
resize.ChatShellRunRequest.Cols, resize.ChatShellRunRequest.Rows = 120, 33
|
||||
writeChat(t, ctx, conns[1], resize)
|
||||
if got := readShellFrame(t, ctx, conns[1], func(m protocol.Message) bool { return m.ID == "size" }); got.Type != protocol.ChatShellResize || got.ChatShellRun.Cols != 120 {
|
||||
// The starter stays the active client until the watcher types: then the
|
||||
// watcher's size applies (stty size below).
|
||||
if got := readShellFrame(t, ctx, conns[1], func(m protocol.Message) bool { return m.ID == "size" }); got.Type != protocol.ChatShellResize || got.ChatShellRun.Cols != 80 {
|
||||
t.Fatalf("resize reply = %+v", got)
|
||||
}
|
||||
input := shellRequest(protocol.ChatShellInput, "in", run.ID, "")
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// The active-client policy (terminal_viewers.go) applied to machine
|
||||
// terminals and to chats' terminal commands: requests name their
|
||||
// connection, and a connection that closes hands the terminal to the next.
|
||||
|
||||
// ClientInput is Input from clientID: typing makes it the active client
|
||||
// (its size, cols x rows when it sent one, else its last, is applied
|
||||
// first); an automatic reply (reply) from any other client is acknowledged
|
||||
// and dropped.
|
||||
func (m *terminalManager) ClientInput(clientID, id, data string, reply bool, cols, rows int) error {
|
||||
if p := m.process(id); p != nil && p.running() {
|
||||
if reply && !p.viewers.answers(clientID) {
|
||||
return nil
|
||||
}
|
||||
if !reply {
|
||||
if size := p.viewers.typedAt(clientID, cols, rows); size.ok && !p.sized(size) {
|
||||
if err := p.applySize(size.cols, size.rows); err != nil {
|
||||
log.Printf("terminal %s resize: %v", id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return m.Input(id, data)
|
||||
}
|
||||
|
||||
// ClientResize records the size clientID draws terminal id at and applies
|
||||
// it when clientID is (or, with activate, becomes) the active client. The
|
||||
// record carries the size the terminal has.
|
||||
func (m *terminalManager) ClientResize(clientID, id string, cols, rows int, activate bool) (protocol.TerminalRecord, error) {
|
||||
if cols <= 0 || rows <= 0 {
|
||||
return protocol.TerminalRecord{}, errors.New("positive cols and rows are required")
|
||||
}
|
||||
p, err := m.live(id)
|
||||
if err != nil {
|
||||
return protocol.TerminalRecord{}, err
|
||||
}
|
||||
if size := p.viewers.resize(clientID, cols, rows, activate); size.ok {
|
||||
return m.Resize(id, size.cols, size.rows)
|
||||
}
|
||||
return p.snapshot(false, 0), nil
|
||||
}
|
||||
|
||||
// attachViewer records clientID as drawing terminal id (it read it).
|
||||
func (m *terminalManager) attachViewer(clientID, id string) {
|
||||
if p := m.process(id); p != nil {
|
||||
p.viewers.attach(clientID)
|
||||
}
|
||||
}
|
||||
|
||||
// detach drops clientID's connection: its output frames, and its part in
|
||||
// every terminal it drew; a terminal it was active in takes the next
|
||||
// client's size.
|
||||
func (m *terminalManager) detach(clientID string) {
|
||||
m.clients.detach(clientID)
|
||||
m.mu.Lock()
|
||||
terms := make(map[string]*terminalProcess, len(m.terms))
|
||||
for id, p := range m.terms {
|
||||
terms[id] = p
|
||||
}
|
||||
m.mu.Unlock()
|
||||
for id, p := range terms {
|
||||
if size := p.viewers.leave(clientID); size.ok && p.running() {
|
||||
if err := p.applySize(size.cols, size.rows); err != nil {
|
||||
log.Printf("terminal %s resize: %v", id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ClientInput is Input from clientID, under the same policy as the machine
|
||||
// terminals' ClientInput.
|
||||
func (r *chatShellRunner) ClientInput(clientID, sessionID, runID, data string, reply bool, cols, rows int) error {
|
||||
if p := r.activeProcess(sessionID, runID); p != nil && p.terminal != nil {
|
||||
if reply && !p.viewers.answers(clientID) {
|
||||
return nil
|
||||
}
|
||||
if !reply {
|
||||
if size := p.viewers.typedAt(clientID, cols, rows); size.ok && !p.sized(size) {
|
||||
if _, err := r.Resize(sessionID, runID, size.cols, size.rows); err != nil {
|
||||
log.Printf("chat shell %s resize: %v", runID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return r.Input(sessionID, runID, data)
|
||||
}
|
||||
|
||||
// ClientResize is Resize from clientID, applied only when it is (or, with
|
||||
// activate, becomes) the active client.
|
||||
func (r *chatShellRunner) ClientResize(clientID, sessionID, runID string, cols, rows int, activate bool) (protocol.ChatShellRunRecord, error) {
|
||||
if cols <= 0 || rows <= 0 {
|
||||
return protocol.ChatShellRunRecord{}, errors.New("positive cols and rows are required")
|
||||
}
|
||||
p, err := r.terminalProcess(sessionID, runID)
|
||||
if err != nil {
|
||||
return protocol.ChatShellRunRecord{}, err
|
||||
}
|
||||
if size := p.viewers.resize(clientID, cols, rows, activate); size.ok {
|
||||
return r.Resize(sessionID, runID, size.cols, size.rows)
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.record, nil
|
||||
}
|
||||
|
||||
// attachViewer makes clientID, which started runID at cols x rows, its
|
||||
// active client.
|
||||
func (r *chatShellRunner) attachViewer(clientID, sessionID, runID string, cols, rows int) {
|
||||
if p := r.activeProcess(sessionID, runID); p != nil && p.terminal != nil && cols > 0 && rows > 0 {
|
||||
p.viewers.resize(clientID, cols, rows, true)
|
||||
}
|
||||
}
|
||||
|
||||
// leave drops clientID's part in every running terminal command it drew.
|
||||
func (r *chatShellRunner) leave(clientID string) {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
type run struct{ sessionID, runID string }
|
||||
r.mu.Lock()
|
||||
procs := make(map[run]*chatShellProcess, len(r.active))
|
||||
for id, p := range r.active {
|
||||
procs[run{p.record.SessionID, id}] = p
|
||||
}
|
||||
r.mu.Unlock()
|
||||
for key, p := range procs {
|
||||
if p.terminal == nil {
|
||||
continue
|
||||
}
|
||||
if size := p.viewers.leave(clientID); size.ok {
|
||||
if _, err := r.Resize(key.sessionID, key.runID, size.cols, size.rows); err != nil {
|
||||
log.Printf("chat shell %s resize: %v", key.runID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sized reports whether the terminal already has size (clamped).
|
||||
func (p *terminalProcess) sized(size terminalSize) bool {
|
||||
cols, rows := chatShellTerminalSize(size.cols, size.rows)
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.record.Cols == cols && p.record.Rows == rows
|
||||
}
|
||||
|
||||
// sized reports whether the terminal command already has size (clamped).
|
||||
func (p *chatShellProcess) sized(size terminalSize) bool {
|
||||
cols, rows := chatShellTerminalSize(size.cols, size.rows)
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.record.Cols == cols && p.record.Rows == rows
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// readTerminalText reads conn's output frames of id, from wherever its
|
||||
// subscription started, until the text contains want.
|
||||
func readTerminalText(t *testing.T, ctx context.Context, conn *websocket.Conn, id, want string) string {
|
||||
t.Helper()
|
||||
var seen strings.Builder
|
||||
for !strings.Contains(seen.String(), want) {
|
||||
seen.WriteString(readShellFrame(t, ctx, conn, func(m protocol.Message) bool {
|
||||
return m.Type == protocol.TerminalEvent && m.TerminalEvent.TerminalID == id && m.TerminalEvent.Terminal == nil
|
||||
}).TerminalEvent.Output)
|
||||
}
|
||||
return seen.String()
|
||||
}
|
||||
|
||||
// Two clients draw one terminal: only the active client's emulator answers
|
||||
// reach the shell, the terminal takes the active client's size, typing or
|
||||
// focusing makes a client active, and when the active client leaves the
|
||||
// next one's size comes back.
|
||||
func TestTerminalTwoClientsActiveClient(t *testing.T) {
|
||||
terminalHome(t)
|
||||
ctx, _, conns := dialChatConns(t, Options{OperatorRegistry: newOperatorStore(t)}, 2)
|
||||
a, b := conns[0], conns[1]
|
||||
term := terminalReply(t, ctx, a, terminalRequest(protocol.TerminalOpen, "open", protocol.TerminalRequest{Cols: 156, Rows: 37})).Terminal
|
||||
terminalLogIn(t, ctx, a, term.ID)
|
||||
terminalReply(t, ctx, b, terminalRequest(protocol.TerminalOutput, "read", protocol.TerminalRequest{TerminalID: term.ID}))
|
||||
// b draws it smaller; the opener is active and keeps its size.
|
||||
if got := terminalReply(t, ctx, b, terminalRequest(protocol.TerminalResize, "small", protocol.TerminalRequest{TerminalID: term.ID, Cols: 121, Rows: 11})); got.Terminal == nil || got.Terminal.Cols != 156 || got.Terminal.Rows != 37 {
|
||||
t.Fatalf("background resize = %+v", got)
|
||||
}
|
||||
// A query both emulators answer: only the active client's answer arrives.
|
||||
terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "ask", protocol.TerminalRequest{TerminalID: term.ID, Data: "read -r ans; echo got:$ans; stty size\r"}))
|
||||
if got := terminalReply(t, ctx, b, terminalRequest(protocol.TerminalInput, "b-reply", protocol.TerminalRequest{TerminalID: term.ID, Data: "b-answer\r", Reply: true})); got.Type != protocol.TerminalInput {
|
||||
t.Fatalf("dropped reply is acknowledged: %+v", got)
|
||||
}
|
||||
terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "a-reply", protocol.TerminalRequest{TerminalID: term.ID, Data: "a-answer\r", Reply: true}))
|
||||
text := readTerminalText(t, ctx, a, term.ID, "37 156")
|
||||
if !strings.Contains(text, "got:a-answer") || strings.Contains(text, "b-answer") {
|
||||
t.Fatalf("output = %q", text)
|
||||
}
|
||||
// b types: it becomes active at its own size, before its keystrokes.
|
||||
terminalReply(t, ctx, b, terminalRequest(protocol.TerminalInput, "b-type", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r"}))
|
||||
readTerminalText(t, ctx, a, term.ID, "11 121")
|
||||
// Now a's answers are the ones dropped.
|
||||
terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "a-late", protocol.TerminalRequest{TerminalID: term.ID, Data: "echo a-late-$((1+1))\r", Reply: true}))
|
||||
// a focuses its terminal: active again at its size.
|
||||
if got := terminalReply(t, ctx, a, terminalRequest(protocol.TerminalResize, "focus", protocol.TerminalRequest{TerminalID: term.ID, Cols: 150, Rows: 40, Activate: true})); got.Terminal.Cols != 150 || got.Terminal.Rows != 40 {
|
||||
t.Fatalf("activate = %+v", got)
|
||||
}
|
||||
terminalReply(t, ctx, a, terminalRequest(protocol.TerminalInput, "a-type", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r"}))
|
||||
if text := readTerminalText(t, ctx, a, term.ID, "40 150"); strings.Contains(text, "a-late-2") {
|
||||
t.Fatalf("a background answer reached the shell: %q", text)
|
||||
}
|
||||
// a leaves: b, the next most recent, has its size back.
|
||||
a.Close(websocket.StatusNormalClosure, "")
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
list := terminalReply(t, ctx, b, terminalRequest(protocol.TerminalList, "list", protocol.TerminalRequest{}))
|
||||
if len(list.Terminals) == 1 && list.Terminals[0].Cols == 121 && list.Terminals[0].Rows == 11 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("size after the active client left = %+v", list.Terminals)
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
// And b's emulator answers now reach the shell.
|
||||
terminalReply(t, ctx, b, terminalRequest(protocol.TerminalInput, "b-answers", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r", Reply: true}))
|
||||
readTerminalText(t, ctx, b, term.ID, "11 121")
|
||||
}
|
||||
|
||||
// A chat's terminal command watched by two clients follows the same policy.
|
||||
func TestChatShellTerminalTwoClientsActiveClient(t *testing.T) {
|
||||
ctx, conns, _ := shellChat(t)
|
||||
a, b := conns[0], conns[1]
|
||||
start := shellRequest(protocol.ChatShellRun, "r1", "", `read -r first; echo got:$first; read -r second; stty size; echo done`)
|
||||
start.ChatShellRunRequest.Cols, start.ChatShellRunRequest.Rows = 100, 30
|
||||
writeChat(t, ctx, a, start)
|
||||
run := readShellFrame(t, ctx, a, func(m protocol.Message) bool { return m.ID == "r1" }).ChatShellRun
|
||||
resize := shellRequest(protocol.ChatShellResize, "size", run.ID, "")
|
||||
resize.ChatShellRunRequest.Cols, resize.ChatShellRunRequest.Rows = 120, 33
|
||||
writeChat(t, ctx, b, resize)
|
||||
if got := readShellFrame(t, ctx, b, func(m protocol.Message) bool { return m.ID == "size" }); got.ChatShellRun == nil || got.ChatShellRun.Cols != 100 {
|
||||
t.Fatalf("background resize = %+v", got)
|
||||
}
|
||||
send := func(conn *websocket.Conn, id, data string, reply bool, cols, rows int) {
|
||||
t.Helper()
|
||||
input := shellRequest(protocol.ChatShellInput, id, run.ID, "")
|
||||
input.ChatShellRunRequest.Data, input.ChatShellRunRequest.Reply = data, reply
|
||||
input.ChatShellRunRequest.Cols, input.ChatShellRunRequest.Rows = cols, rows
|
||||
writeChat(t, ctx, conn, input)
|
||||
if got := readShellFrame(t, ctx, conn, func(m protocol.Message) bool { return m.ID == id }); got.Type != protocol.ChatShellInput {
|
||||
t.Fatalf("input %s = %+v", id, got)
|
||||
}
|
||||
}
|
||||
send(b, "b-reply", "b-answer\r", true, 0, 0)
|
||||
send(a, "a-reply", "a-answer\r", true, 0, 0)
|
||||
// b types the second line carrying the size it now draws at: it becomes
|
||||
// active at that size before the keystrokes are written.
|
||||
send(b, "b-type", "next\r", false, 90, 20)
|
||||
_, output := finishedShell(t, ctx, a, run.ID)
|
||||
if !strings.Contains(output, "got:a-answer") || strings.Contains(output, "b-answer") || !strings.Contains(output, "20 90") {
|
||||
t.Fatalf("output = %q", output)
|
||||
}
|
||||
}
|
||||
|
||||
// Keystrokes take their own lane: they are answered, in order, while an
|
||||
// ordinary request on the same connection is still being handled.
|
||||
func TestTerminalInputDoesNotWaitBehindSlowRequest(t *testing.T) {
|
||||
store := newOperatorStore(t)
|
||||
gate := make(chan struct{})
|
||||
broker := scriptedChat()
|
||||
broker.block = true
|
||||
broker.createGate, broker.createStarted = gate, make(chan struct{})
|
||||
ctx, _, conns := dialChatConns(t, Options{Chat: broker, OperatorRegistry: store}, 1)
|
||||
conn := conns[0]
|
||||
dir := t.TempDir()
|
||||
if err := store.RecordOperatorSession(ctx, "ses_1", dir, "Shell", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "sub", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}})
|
||||
readShellFrame(t, ctx, conn, func(m protocol.Message) bool { return m.ID == "sub" })
|
||||
run := runShell(t, ctx, conn, "r1", `for i in $(seq 1 40); do read -r line; echo "seen:$line"; done`)
|
||||
defer close(gate)
|
||||
writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatCreate, ID: "slow", ChatCreate: &protocol.ChatCreateRequest{Title: "slow", Directory: dir, OperationID: "slow-op"}})
|
||||
select {
|
||||
case <-broker.createStarted:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("chat_create never reached the broker")
|
||||
}
|
||||
// Forty keystroke requests, written without waiting for replies.
|
||||
started := time.Now()
|
||||
for i := 1; i <= 40; i++ {
|
||||
input := shellRequest(protocol.ChatShellInput, fmt.Sprintf("in-%d", i), run.ID, "")
|
||||
input.ChatShellRunRequest.Data = fmt.Sprintf("k%02d\r", i)
|
||||
writeChat(t, ctx, conn, input)
|
||||
}
|
||||
var output strings.Builder
|
||||
replies := 0
|
||||
for replies < 40 || !strings.Contains(output.String(), "seen:k40") {
|
||||
m := readShellFrame(t, ctx, conn, func(m protocol.Message) bool {
|
||||
return strings.HasPrefix(m.ID, "in-") || m.ID == "slow" ||
|
||||
m.Type == protocol.ChatShellRunEvent && m.ChatShellRunEvent.RunID == run.ID && m.ChatShellRunEvent.Run == nil
|
||||
})
|
||||
switch {
|
||||
case m.ID == "slow":
|
||||
t.Fatal("the slow request answered first; it should still be waiting")
|
||||
case m.Type == protocol.Error:
|
||||
t.Fatalf("input refused: %+v", m)
|
||||
case strings.HasPrefix(m.ID, "in-"):
|
||||
replies++
|
||||
if m.ID != fmt.Sprintf("in-%d", replies) {
|
||||
t.Fatalf("reply %d is %s", replies, m.ID)
|
||||
}
|
||||
default:
|
||||
output.WriteString(m.ChatShellRunEvent.Output)
|
||||
}
|
||||
}
|
||||
t.Logf("40 keystrokes answered and echoed in %s behind a blocked request", time.Since(started))
|
||||
// The shell saw them in the order they were typed.
|
||||
var want strings.Builder
|
||||
for i := 1; i <= 40; i++ {
|
||||
fmt.Fprintf(&want, "seen:k%02d\r\n", i)
|
||||
}
|
||||
got := output.String()
|
||||
var seen strings.Builder
|
||||
for _, line := range strings.Split(got, "\r\n") {
|
||||
if strings.HasPrefix(line, "seen:") {
|
||||
seen.WriteString(line + "\r\n")
|
||||
}
|
||||
}
|
||||
if seen.String() != want.String() {
|
||||
t.Fatalf("order = %q", seen.String())
|
||||
}
|
||||
}
|
||||
@@ -45,11 +45,12 @@ func handleTerminalRequest(ctx context.Context, request protocol.Message, m *ter
|
||||
records, err = m.List(ctx)
|
||||
reply.Terminals = records
|
||||
case protocol.TerminalInput:
|
||||
err = m.Input(body.TerminalID, body.Data)
|
||||
err = m.ClientInput(clientID, body.TerminalID, body.Data, body.Reply, body.Cols, body.Rows)
|
||||
case protocol.TerminalResize:
|
||||
record, err = m.Resize(body.TerminalID, body.Cols, body.Rows)
|
||||
record, err = m.ClientResize(clientID, body.TerminalID, body.Cols, body.Rows, body.Activate)
|
||||
case protocol.TerminalOutput:
|
||||
m.clients.subscribe(clientID, body.TerminalID)
|
||||
m.attachViewer(clientID, body.TerminalID)
|
||||
record, err = m.Output(ctx, body.TerminalID, body.After)
|
||||
case protocol.TerminalClose:
|
||||
record, err = m.Close(ctx, body.TerminalID)
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// connectionQueue bounds the requests read ahead of their handling on one
|
||||
// connection, per lane. The app sends one ordinary request at a time, so
|
||||
// the ordinary lane rarely holds more than a few.
|
||||
const connectionQueue = 256
|
||||
|
||||
// isTerminalLaneRequest reports the requests a connection handles on its
|
||||
// terminal lane: what a terminal's keystrokes and size become. They are
|
||||
// quick (a queued write, an ioctl) and ordered among themselves, and must
|
||||
// never wait behind an ordinary request read before them on the same
|
||||
// connection (an elevation's password check, a chat backend call).
|
||||
func isTerminalLaneRequest(kind string) bool {
|
||||
switch kind {
|
||||
case protocol.TerminalInput, protocol.TerminalResize, protocol.ChatShellInput, protocol.ChatShellResize:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// readConnectionRequests reads conn's requests until it fails or ctx ends.
|
||||
// Terminal-lane requests are handled in arrival order by lane on a goroutine
|
||||
// of their own; the others are returned, in arrival order, for the
|
||||
// connection's ordinary loop, and the channel closes when reading stops.
|
||||
// Order is kept within each lane, not across them: a client that needs a
|
||||
// terminal request to follow an ordinary one (input after terminal_open)
|
||||
// waits for its reply first. stop ends the reading and waits for the lane
|
||||
// to finish what it took.
|
||||
func readConnectionRequests(ctx context.Context, conn *websocket.Conn, lane func(context.Context, protocol.Message)) (requests <-chan protocol.Message, stop func()) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
ordinary := make(chan protocol.Message, connectionQueue)
|
||||
terminal := make(chan protocol.Message, connectionQueue)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for request := range terminal {
|
||||
lane(ctx, request)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
defer close(ordinary)
|
||||
defer close(terminal)
|
||||
for {
|
||||
var request protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &request); err != nil {
|
||||
return
|
||||
}
|
||||
queue := ordinary
|
||||
if isTerminalLaneRequest(request.Type) {
|
||||
queue = terminal
|
||||
}
|
||||
select {
|
||||
case queue <- request:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return ordinary, func() {
|
||||
cancel()
|
||||
wg.Wait()
|
||||
}
|
||||
}
|
||||
@@ -125,6 +125,8 @@ func (m *terminalManager) start(clientID, id, dir string, cmd *exec.Cmd, cols, r
|
||||
m.terms[id] = p
|
||||
if clientID != "" {
|
||||
m.clients.subscribe(clientID, id)
|
||||
// The opener draws it first: it is the active client.
|
||||
p.viewers.resize(clientID, cols, rows, true)
|
||||
}
|
||||
m.wg.Add(1)
|
||||
go m.supervise(p, cmd, terminal)
|
||||
@@ -256,17 +258,23 @@ func (m *terminalManager) Resize(id string, cols, rows int) (protocol.TerminalRe
|
||||
if err != nil {
|
||||
return protocol.TerminalRecord{}, err
|
||||
}
|
||||
if err := p.applySize(cols, rows); err != nil {
|
||||
return protocol.TerminalRecord{}, err
|
||||
}
|
||||
return p.snapshot(false, 0), nil
|
||||
}
|
||||
|
||||
// applySize sets the terminal's PTY to cols x rows (clamped).
|
||||
func (p *terminalProcess) applySize(cols, rows int) error {
|
||||
cols, rows = chatShellTerminalSize(cols, rows)
|
||||
p.mu.Lock()
|
||||
p.record.Cols, p.record.Rows = cols, rows
|
||||
terminal := p.pty
|
||||
p.mu.Unlock()
|
||||
if terminal != nil {
|
||||
if err := resizeChatShellTerminal(terminal, cols, rows); err != nil {
|
||||
return protocol.TerminalRecord{}, err
|
||||
}
|
||||
return resizeChatShellTerminal(terminal, cols, rows)
|
||||
}
|
||||
return p.snapshot(false, 0), nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// Output is one terminal with its retained output from byte after on. A
|
||||
|
||||
@@ -35,6 +35,8 @@ type terminalProcess struct {
|
||||
// refused: the login never asked for a password; the terminal is
|
||||
// forgotten without being listed.
|
||||
refused bool
|
||||
// viewers are the connections drawing it (terminal_viewers.go).
|
||||
viewers terminalViewers
|
||||
}
|
||||
|
||||
func newTerminalProcess(record protocol.TerminalRecord) *terminalProcess {
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
package server
|
||||
|
||||
import "sync"
|
||||
|
||||
// terminalViewers is the set of client connections drawing one terminal (a
|
||||
// machine terminal or a chat's terminal command), most recently active
|
||||
// first. The first is the active client: the terminal's size is the size it
|
||||
// draws at, and only its emulator's automatic answers to terminal queries
|
||||
// (cursor position, device attributes) reach the process. Every client's
|
||||
// emulator answers each query it draws, so without this a query got one
|
||||
// answer per client, and the size was whichever client resized last, even
|
||||
// after it left.
|
||||
//
|
||||
// A client becomes active by typing, by a resize marked activate (the
|
||||
// client focused the terminal), or by being the first to attach or resize.
|
||||
// When the active client leaves, the next most recent one becomes active
|
||||
// and its last size is applied. The zero value is ready to use.
|
||||
type terminalViewers struct {
|
||||
mu sync.Mutex
|
||||
list []terminalViewer
|
||||
}
|
||||
|
||||
type terminalViewer struct {
|
||||
client string
|
||||
cols, rows int
|
||||
}
|
||||
|
||||
// terminalSize is a size to apply to the terminal, when ok.
|
||||
type terminalSize struct {
|
||||
cols, rows int
|
||||
ok bool
|
||||
}
|
||||
|
||||
func (v *terminalViewers) indexLocked(client string) int {
|
||||
for i, viewer := range v.list {
|
||||
if viewer.client == client {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// frontLocked moves client to the front, adding it when absent, and
|
||||
// returns its entry.
|
||||
func (v *terminalViewers) frontLocked(client string) *terminalViewer {
|
||||
viewer := terminalViewer{client: client}
|
||||
if i := v.indexLocked(client); i >= 0 {
|
||||
viewer = v.list[i]
|
||||
v.list = append(v.list[:i], v.list[i+1:]...)
|
||||
}
|
||||
v.list = append([]terminalViewer{viewer}, v.list...)
|
||||
return &v.list[0]
|
||||
}
|
||||
|
||||
// attach records client as drawing the terminal (it opened or read it): the
|
||||
// active one when no client is.
|
||||
func (v *terminalViewers) attach(client string) {
|
||||
if client == "" {
|
||||
return
|
||||
}
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
if v.indexLocked(client) < 0 {
|
||||
v.list = append(v.list, terminalViewer{client: client})
|
||||
}
|
||||
}
|
||||
|
||||
// resize records the size client draws the terminal at and reports the
|
||||
// size to apply: client's, when it is (or, with activate, becomes) the
|
||||
// active client, or when the active client has not reported a size yet.
|
||||
// An unknown client (empty) always applies its size, as before clients
|
||||
// were told apart.
|
||||
func (v *terminalViewers) resize(client string, cols, rows int, activate bool) terminalSize {
|
||||
if client == "" {
|
||||
return terminalSize{cols, rows, true}
|
||||
}
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
i := v.indexLocked(client)
|
||||
switch {
|
||||
case activate || len(v.list) == 0 || i == 0:
|
||||
viewer := v.frontLocked(client)
|
||||
viewer.cols, viewer.rows = cols, rows
|
||||
return terminalSize{cols, rows, true}
|
||||
case i < 0:
|
||||
v.list = append(v.list, terminalViewer{client: client, cols: cols, rows: rows})
|
||||
default:
|
||||
v.list[i].cols, v.list[i].rows = cols, rows
|
||||
}
|
||||
front := v.list[0]
|
||||
return terminalSize{cols, rows, front.cols == 0 || front.rows == 0}
|
||||
}
|
||||
|
||||
// typedAt is typed from a client drawing the terminal at cols x rows
|
||||
// (zero when it did not say): it becomes the active client at that size.
|
||||
func (v *terminalViewers) typedAt(client string, cols, rows int) terminalSize {
|
||||
if client != "" && cols > 0 && rows > 0 {
|
||||
return v.resize(client, cols, rows, true)
|
||||
}
|
||||
return v.typed(client)
|
||||
}
|
||||
|
||||
// typed makes client, which typed into the terminal, the active client and
|
||||
// reports its last size when that changes who is active.
|
||||
func (v *terminalViewers) typed(client string) terminalSize {
|
||||
if client == "" {
|
||||
return terminalSize{}
|
||||
}
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
if len(v.list) > 0 && v.list[0].client == client {
|
||||
return terminalSize{}
|
||||
}
|
||||
viewer := v.frontLocked(client)
|
||||
return terminalSize{viewer.cols, viewer.rows, viewer.cols > 0 && viewer.rows > 0}
|
||||
}
|
||||
|
||||
// answers reports whether client's emulator's automatic answers reach the
|
||||
// process: only the active client's do, or anyone's while no client is
|
||||
// known.
|
||||
func (v *terminalViewers) answers(client string) bool {
|
||||
if client == "" {
|
||||
return true
|
||||
}
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
return len(v.list) == 0 || v.list[0].client == client
|
||||
}
|
||||
|
||||
// leave forgets client (its connection closed) and, when it was the active
|
||||
// client, reports the size of the next one, which becomes active.
|
||||
func (v *terminalViewers) leave(client string) terminalSize {
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
i := v.indexLocked(client)
|
||||
if i < 0 {
|
||||
return terminalSize{}
|
||||
}
|
||||
v.list = append(v.list[:i], v.list[i+1:]...)
|
||||
if i != 0 || len(v.list) == 0 {
|
||||
return terminalSize{}
|
||||
}
|
||||
next := v.list[0]
|
||||
return terminalSize{next.cols, next.rows, next.cols > 0 && next.rows > 0}
|
||||
}
|
||||
|
||||
// active is the active client, or empty (tests).
|
||||
func (v *terminalViewers) active() string {
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
if len(v.list) == 0 {
|
||||
return ""
|
||||
}
|
||||
return v.list[0].client
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package server
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestTerminalViewersActiveClient(t *testing.T) {
|
||||
var v terminalViewers
|
||||
// The first client to resize is active and sizes the terminal.
|
||||
if got := v.resize("a", 156, 37, false); got != (terminalSize{156, 37, true}) {
|
||||
t.Fatalf("first resize = %+v", got)
|
||||
}
|
||||
v.attach("b")
|
||||
// Another client's size is kept but not applied; its answers are dropped.
|
||||
if got := v.resize("b", 121, 11, false); got.ok {
|
||||
t.Fatalf("background resize applied: %+v", got)
|
||||
}
|
||||
if !v.answers("a") || v.answers("b") || v.answers("stranger") {
|
||||
t.Fatal("only the active client answers")
|
||||
}
|
||||
// Typing hands the terminal to b, at b's size; typing again changes nothing.
|
||||
if got := v.typed("b"); got != (terminalSize{121, 11, true}) {
|
||||
t.Fatalf("typed = %+v", got)
|
||||
}
|
||||
if got := v.typed("b"); got.ok || v.active() != "b" || v.answers("a") {
|
||||
t.Fatalf("typed again = %+v, active %q", got, v.active())
|
||||
}
|
||||
// Focusing (activate) hands it back at a's new size.
|
||||
if got := v.resize("a", 150, 40, true); got != (terminalSize{150, 40, true}) || v.active() != "a" {
|
||||
t.Fatalf("activate = %+v", got)
|
||||
}
|
||||
// A background client leaving changes nothing; the active one leaving
|
||||
// hands the terminal to the next most recent, at its last size.
|
||||
v.attach("c")
|
||||
if got := v.leave("c"); got.ok {
|
||||
t.Fatalf("background leave = %+v", got)
|
||||
}
|
||||
if got := v.leave("a"); got != (terminalSize{121, 11, true}) || v.active() != "b" || !v.answers("b") {
|
||||
t.Fatalf("leave = %+v, active %q", got, v.active())
|
||||
}
|
||||
if got := v.leave("b"); got.ok || v.active() != "" || !v.answers("anyone") {
|
||||
t.Fatalf("last leave = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalViewersWithoutSizes(t *testing.T) {
|
||||
var v terminalViewers
|
||||
v.attach("reader")
|
||||
// The active client has drawn nothing yet: another's size is applied.
|
||||
if got := v.resize("other", 90, 20, false); !got.ok || v.active() != "reader" {
|
||||
t.Fatalf("resize = %+v, active %q", got, v.active())
|
||||
}
|
||||
// Typing from a client of unknown size makes it active without a resize.
|
||||
if got := v.typed("typist"); got.ok || v.active() != "typist" {
|
||||
t.Fatalf("typed = %+v", got)
|
||||
}
|
||||
// A connection that is not told apart (tests, internal callers) always
|
||||
// applies and answers.
|
||||
if got := v.resize("", 10, 5, false); !got.ok || !v.answers("") {
|
||||
t.Fatalf("anonymous = %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -117,12 +117,14 @@ func TestTerminalOverWebsocket(t *testing.T) {
|
||||
t.Fatalf("input reply = %+v", got)
|
||||
}
|
||||
_, end := readTerminalUntil(t, ctx, conns[0], term.ID, 0, "sum-42")
|
||||
// The second client draws it larger; the opener stays the active client
|
||||
// (terminal_active_test.go) until the second one types below.
|
||||
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 {
|
||||
if resized.Type != protocol.TerminalResize || resized.Terminal.Cols != 80 || resized.Terminal.Rows != 24 {
|
||||
t.Fatalf("resize reply = %+v", resized)
|
||||
}
|
||||
list := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalList, "list", protocol.TerminalRequest{}))
|
||||
if len(list.Terminals) != 1 || list.Terminals[0].ID != term.ID || list.Terminals[0].Cols != 120 || list.Terminals[0].Output != "" {
|
||||
if len(list.Terminals) != 1 || list.Terminals[0].ID != term.ID || list.Terminals[0].Cols != 80 || list.Terminals[0].Output != "" {
|
||||
t.Fatalf("list = %+v", list.Terminals)
|
||||
}
|
||||
// The second client reads everything once, then only what follows.
|
||||
|
||||
@@ -267,7 +267,10 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
// Terminal lifecycle changes reach every connection; output only the
|
||||
// connections that opened or read that terminal.
|
||||
terminals.clients.attach(clientID, write)
|
||||
defer terminals.clients.detach(clientID)
|
||||
defer terminals.detach(clientID)
|
||||
// A closed connection hands the chats' terminal commands it was
|
||||
// active in to their next client.
|
||||
defer func() { hub.shellRunner().leave(clientID) }()
|
||||
if notes != nil {
|
||||
defer notes.detach(clientID)
|
||||
}
|
||||
@@ -276,16 +279,23 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
// previous, whose reply the client would discard as stale anyway.
|
||||
cancelChatSearch := func() {}
|
||||
defer func() { cancelChatSearch() }()
|
||||
for {
|
||||
var request protocol.Message
|
||||
if err := wsjson.Read(connCtx, conn, &request); err != nil {
|
||||
// Keystrokes and sizes take their own lane (terminal_lane.go), so
|
||||
// they never wait behind a slow request read before them. The lane
|
||||
// is drained before the deferred detaches above run.
|
||||
requests, stopReading := readConnectionRequests(connCtx, conn, func(laneCtx context.Context, request protocol.Message) {
|
||||
if elevation.refuse(request, elevationKey, write) {
|
||||
return
|
||||
}
|
||||
if request.Type != protocol.ChatShellInput && request.Type != protocol.ChatShellResize &&
|
||||
request.Type != protocol.TerminalInput && request.Type != protocol.TerminalResize {
|
||||
// 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)
|
||||
if isTerminalRequest(request.Type) {
|
||||
handleTerminalRequest(laneCtx, request, terminals, clientID, write)
|
||||
return
|
||||
}
|
||||
handleChat(laneCtx, request, options.Chat, hub, registry, clientID, write)
|
||||
})
|
||||
defer stopReading()
|
||||
for request := range requests {
|
||||
// Keystrokes take the terminal lane and are 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)
|
||||
if request.Type == protocol.Submit && !options.AllowAuthoring {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "pipeline authoring is disabled on this execution server; ask the operator to publish through an explicitly enabled authoring server"})
|
||||
continue
|
||||
@@ -327,9 +337,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
continue
|
||||
}
|
||||
if isTerminalRequest(request.Type) {
|
||||
// Closing waits for the shell to go; it never delays input
|
||||
// to the other terminals behind it.
|
||||
if request.Type == protocol.TerminalClose {
|
||||
// Opening waits up to the login's prompt wait and closing for
|
||||
// the shell to go; neither delays the requests behind it.
|
||||
if request.Type == protocol.TerminalClose || request.Type == protocol.TerminalOpen {
|
||||
go handleTerminalRequest(connCtx, request, terminals, clientID, write)
|
||||
} else {
|
||||
handleTerminalRequest(connCtx, request, terminals, clientID, write)
|
||||
|
||||
Reference in New Issue
Block a user