//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 } } }