0963a071d0
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>
204 lines
6.2 KiB
Go
204 lines
6.2 KiB
Go
//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]))
|
|
}
|