diff --git a/app/lib/features/chat/shell/chat_shell_terminal_feed.dart b/app/lib/features/chat/shell/chat_shell_terminal_feed.dart new file mode 100644 index 00000000..6c73a60a --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_feed.dart @@ -0,0 +1,130 @@ +import 'dart:async'; +import 'dart:collection'; + +/// UTF-16 units one emulator write takes at most. +const int chatShellFeedSlice = 16 * 1024; + +/// How long one turn of the event loop writes output before yielding, so a +/// large replay or burst never holds a UI frame for long. +const Duration chatShellFeedBudget = Duration(milliseconds: 6); + +/// Output on its way into one emulator, in order: written in slices of at +/// most [slice] units, and after [budget] of writing the rest waits for the +/// next turn of the event loop. Each piece carries the server's absolute +/// byte offset its text ends at; [drawn] is the end of the last piece +/// written whole (what a terminal acknowledges as consumed). +class ChatShellTerminalFeed { + ChatShellTerminalFeed( + this._write, { + this.budget = chatShellFeedBudget, + this.slice = chatShellFeedSlice, + }); + + /// Writes [text] into the emulator; [replay] marks a redraw of old output. + final void Function(String text, bool replay) _write; + final Duration budget; + final int slice; + + /// Called with a piece's end once it is drawn. + void Function(int end)? onDrawn; + + final Queue<_Piece> _pieces = Queue(); + Timer? _timer; + bool _pumping = false; + int _drawn = 0; + int _end = 0; + + /// The end of the output drawn so far. + int get drawn => _drawn; + + /// The end of the output drawn or waiting to be. + int get end => _end; + + /// Whether nothing waits to be written. + bool get idle => _pieces.isEmpty; + + /// Drops what waits: the emulator is redrawn and continues from [end]. + void restart(int end) { + _pieces.clear(); + _timer?.cancel(); + _timer = null; + _drawn = end; + _end = end; + } + + /// Queues [text] ending at byte [end]; as much as the budget allows is + /// written at once. + void add(String text, int end, {bool replay = false}) { + _pieces.add(_Piece(text, end, replay, null)); + _end = end; + _schedule(); + } + + /// Runs [action] once everything queued before it is written. + void then(void Function() action) { + if (_pieces.isEmpty && !_pumping) { + action(); + return; + } + _pieces.add(_Piece('', _end, false, action)); + } + + void dispose() { + _pieces.clear(); + _timer?.cancel(); + _timer = null; + } + + void _schedule() { + if (_timer == null && !_pumping) _pump(); + } + + void _pump() { + _timer = null; + _pumping = true; + final clock = Stopwatch()..start(); + try { + while (_pieces.isNotEmpty) { + final piece = _pieces.first; + if (piece.at < piece.text.length) { + var cut = piece.at + slice; + if (cut >= piece.text.length) { + cut = piece.text.length; + } else if (_highSurrogate(piece.text.codeUnitAt(cut - 1))) { + // Never split a surrogate pair between two writes. + cut++; + } + _write(piece.text.substring(piece.at, cut), piece.replay); + piece.at = cut; + } + if (piece.at >= piece.text.length) { + _pieces.removeFirst(); + if (piece.action != null) { + piece.action!(); + } else { + _drawn = piece.end; + onDrawn?.call(piece.end); + } + } + if (_pieces.isNotEmpty && clock.elapsed >= budget) { + _timer = Timer(Duration.zero, _pump); + return; + } + } + } finally { + _pumping = false; + } + } +} + +class _Piece { + _Piece(this.text, this.end, this.replay, this.action); + + final String text; + final int end; + final bool replay; + final void Function()? action; + int at = 0; +} + +bool _highSurrogate(int unit) => unit >= 0xD800 && unit <= 0xDBFF; diff --git a/app/lib/features/chat/shell/chat_shell_terminal_session.dart b/app/lib/features/chat/shell/chat_shell_terminal_session.dart index 01b5103e..590a3f18 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_session.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_session.dart @@ -1,6 +1,7 @@ import 'package:xterm/core.dart'; import 'chat_shell_run.dart'; +import 'chat_shell_terminal_feed.dart'; /// Lines of scrollback one card's terminal keeps. const int chatShellTerminalScrollback = 5000; @@ -17,6 +18,7 @@ class ChatShellTerminalSession { required this.onInput, required this.onResize, }) : terminal = _ChatShellTerminal() { + _feed = ChatShellTerminalFeed(_write); // Drawn at the process's own size until a view lays it out at its own. if (run.cols > 0 && run.rows > 0) terminal.resize(run.cols, run.rows); terminal.onOutput = _output; @@ -32,12 +34,19 @@ class ChatShellTerminalSession { /// Receives the size the view laid the terminal out at. final void Function(int cols, int rows) onResize; - int _end = 0; + late final ChatShellTerminalFeed _feed; bool _live = false; bool _replaying = false; - /// The absolute output byte this terminal has drawn up to. - int get end => _end; + /// The absolute output byte this terminal has drawn up to, or will once + /// the output waiting in its feed is written. + int get end => _feed.end; + + /// The absolute output byte actually drawn so far. + int get drawn => _feed.drawn; + + /// Called with the new [drawn] end each time a chunk is drawn whole. + set onDrawn(void Function(int end)? callback) => _feed.onDrawn = callback; /// Whether typing reaches a running process. bool get live => _live; @@ -45,8 +54,11 @@ class ChatShellTerminalSession { /// Draws [run]'s held output from scratch: on open, after a gap and after /// a readback replaced the card's copy. Answers the emulator gives to old /// queries in that output are not sent: the process asked them long ago. + /// A large output is drawn in slices across turns of the event loop + /// (ChatShellTerminalFeed), so it never stalls the UI. void replay(ChatShellRun run) { _live = run.running && run.terminal; + _feed.restart(run.outputStart); _replaying = true; try { terminal.useMainBuffer(); @@ -57,36 +69,46 @@ class ChatShellTerminalSession { if (run.truncated) { terminal.write('\x1b[2m[earlier output was dropped]\x1b[0m\r\n'); } - var output = _drawable(run, run.output); - // A finished run's final newline would leave an empty line below it. - if (!run.running && output.endsWith('\r\n')) { - output = output.substring(0, output.length - 2); - } - terminal.write(output); - if (!run.running) terminal.setCursorVisibleMode(false); } finally { _replaying = false; } - _end = run.outputEnd; + var output = _drawable(run, run.output); + // A finished run's final newline would leave an empty line below it. + if (!run.running && output.endsWith('\r\n')) { + output = output.substring(0, output.length - 2); + } + _feed.add(output, run.outputEnd, replay: true); + if (!run.running) _feed.then(() => terminal.setCursorVisibleMode(false)); } /// Draws one live chunk covering bytes [offset, end) of [run], which /// already holds it. A chunk after a hole redraws the whole held copy. void append(ChatShellRun run, String text, int offset, int end) { - if (end <= _end) return; - if (offset != _end) { + if (end <= _feed.end) return; + if (offset != _feed.end) { replay(run); return; } - terminal.write(_drawable(run, text)); - _end = end; + _feed.add(_drawable(run, text), end); } /// The run ended: nothing typed reaches it any more. void finish(ChatShellRun run) { if (!_live) return; _live = false; - terminal.setCursorVisibleMode(false); + _feed.then(() => terminal.setCursorVisibleMode(false)); + } + + /// Stops drawing what still waits (the emulator is going away). + void dispose() => _feed.dispose(); + + void _write(String text, bool replay) { + _replaying = replay; + try { + terminal.write(text); + } finally { + _replaying = false; + } } /// The rows the drawn output takes, through the cursor's line, when the diff --git a/app/lib/features/chat/shell/chat_shell_terminals.dart b/app/lib/features/chat/shell/chat_shell_terminals.dart index 5ccb805b..5f6174ca 100644 --- a/app/lib/features/chat/shell/chat_shell_terminals.dart +++ b/app/lib/features/chat/shell/chat_shell_terminals.dart @@ -59,7 +59,7 @@ class ChatShellTerminals { _resizes.remove(runId)?.cancel(); _inputs.remove(runId); _sentSizes.remove(runId); - _sessions.remove(runId); + _sessions.remove(runId)?.dispose(); } /// [run] ended: draw its final output read-only. @@ -98,6 +98,9 @@ class ChatShellTerminals { void dispose() { _disposed = true; + for (final session in _sessions.values) { + session.dispose(); + } for (final timer in _resizes.values) { timer.cancel(); } diff --git a/app/lib/features/terminal/terminal_hub.dart b/app/lib/features/terminal/terminal_hub.dart index 0c6485ed..cf0b39c2 100644 --- a/app/lib/features/terminal/terminal_hub.dart +++ b/app/lib/features/terminal/terminal_hub.dart @@ -101,7 +101,7 @@ class TerminalHub extends ChangeNotifier { } try { final reply = await machine.gateway.call('terminal_open', { - 'terminal_request': {'cwd': ?(cwd.isEmpty ? null : cwd)}, + 'terminal_request': {'cwd': ?(cwd.isEmpty ? null : cwd), 'flow': true}, }); final record = reply['terminal']; if (record is! Map) throw StateError('The server sent no terminal.'); diff --git a/app/lib/features/terminal/terminal_stream.dart b/app/lib/features/terminal/terminal_stream.dart index b66c8436..0c3d4c49 100644 --- a/app/lib/features/terminal/terminal_stream.dart +++ b/app/lib/features/terminal/terminal_stream.dart @@ -28,11 +28,13 @@ class TerminalStream { /// Whether nothing was received yet. bool get empty => stream.isEmpty && end == 0; - /// Replaces the held copy with a read of the server's retained tail. - void reset(String output, int outputStart, String name) { + /// Replaces the held copy with a read of the server's retained tail, + /// covering bytes [outputStart, outputEnd) (the server's offsets: the + /// text's own UTF-8 length differs where invalid bytes were replaced). + void reset(String output, int outputStart, int outputEnd, String name) { text = output; start = outputStart; - end = outputStart + utf8.encode(output).length; + end = outputEnd; stream = name; _bound(); } @@ -55,7 +57,11 @@ class TerminalStream { // Never split a surrogate pair. final unit = text.codeUnitAt(cut); if (unit >= 0xDC00 && unit <= 0xDFFF) cut++; + final dropped = text.substring(0, cut); text = text.substring(cut); - start = end - utf8.encode(text).length; + // The server's offsets are not re-derived from the text: only the + // dropped part is measured (approximately, for replaced bytes). + start += utf8.encode(dropped).length; + if (start > end) start = end; } } diff --git a/app/lib/features/terminal/terminal_tab.dart b/app/lib/features/terminal/terminal_tab.dart index 61b571c9..1f85432f 100644 --- a/app/lib/features/terminal/terminal_tab.dart +++ b/app/lib/features/terminal/terminal_tab.dart @@ -29,6 +29,7 @@ class TerminalTab extends ChangeNotifier { onResize: _resized, ); session.terminal.onTitleChange = _titled; + session.onDrawn = _drawn; } final String machineId; @@ -45,6 +46,12 @@ class TerminalTab extends ChangeNotifier { bool _reading = false; bool _again = false; + /// The flow window the server granted this connection's subscription + /// (0: an older server, which takes no acknowledgements), and the end + /// last acknowledged. + int _window = 0; + int _acked = 0; + /// False while the terminal's machine is not connected. bool connected = true; @@ -83,6 +90,7 @@ class TerminalTab extends ChangeNotifier { _gateway = gateway; connected = true; _sentSize = null; + _window = 0; _update(info); unawaited(resume()); } @@ -119,7 +127,11 @@ class TerminalTab extends ChangeNotifier { Future _read(int? after) async { final reply = await _gateway.call('terminal_output', { - 'terminal_request': {'terminal_id': _info.id, 'after': ?after}, + 'terminal_request': { + 'terminal_id': _info.id, + 'after': ?after, + 'flow': true, + }, }); final record = reply['terminal']; if (_disposed || record is! Map) return; @@ -131,11 +143,18 @@ class TerminalTab extends ChangeNotifier { } final output = '${record['output'] ?? ''}'; final start = (record['output_start'] as num?)?.toInt() ?? 0; + // The reply's own end (an older server's is its total, which a text + // of only valid characters also reaches). + var end = (record['output_end'] as num?)?.toInt() ?? 0; + if (end < start) end = start + _byteLength(output); + // The server counts this connection's window from the reply's end. + _window = (record['window'] as num?)?.toInt() ?? 0; + _acked = end; if (after == null || start > _stream.end) { - _stream.reset(output, start, info.stream); + _stream.reset(output, start, end, info.stream); session.replay(_run()); } else { - _append(output, start, start + _byteLength(output)); + _append(output, start, end); } if (!info.running) session.finish(_run()); } @@ -157,8 +176,9 @@ class TerminalTab extends ChangeNotifier { final before = _stream.end; final fresh = _stream.add(output, offset, end); if (fresh == null) { - // Frames were missed: read the retained tail again. - unawaited(resume()); + // A flow-controlled read in flight covers whatever was sent before + // it; otherwise frames were missed: read the retained tail again. + if (!(_reading && _window > 0)) unawaited(resume()); return; } if (fresh.isNotEmpty) session.append(_run(), fresh, before, end); @@ -176,6 +196,21 @@ class TerminalTab extends ChangeNotifier { _notify(); } + /// The emulator drew output up to [end]: acknowledge it once a quarter + /// of the window is consumed, so the server sends (and reads) more. + void _drawn(int end) { + if (_window <= 0 || !connected || _disposed) return; + if (end - _acked < _window ~/ 4) return; + _acked = end; + unawaited( + _gateway + .call('terminal_ack', { + 'terminal_request': {'terminal_id': _info.id, 'after': end}, + }) + .catchError((Object _) => {}), + ); + } + void _titled(String title) { if (title == _oscTitle) return; _oscTitle = title.trim(); @@ -229,6 +264,8 @@ class TerminalTab extends ChangeNotifier { _resize?.cancel(); _pipe = null; session.terminal.onTitleChange = null; + session.onDrawn = null; + session.dispose(); super.dispose(); } } diff --git a/app/notes/terminal-panel.md b/app/notes/terminal-panel.md index 44683a39..d0db39b4 100644 --- a/app/notes/terminal-panel.md +++ b/app/notes/terminal-panel.md @@ -115,8 +115,55 @@ data?, after?}`. loop: it waits up to 3 s for the shell). - Pushed `terminal_event`: output `{terminal_id, output, offset, end}` to subscribed connections, lifecycle `{terminal_id, terminal}` (opened, - title, exited, closed) to every connection. A slow connection's queue - (256 frames) drops output; the client sees the offset gap and re-reads. + title, exited, closed) to every connection. Output flow is described + under "Output flow" below; offsets are stream bytes, taken from the + server (`end`, `output_end`), never from the text's re-encoded length. + +## Output flow (2026-11-25) + +Server (`terminal_flow.go`, `terminal_clients.go`): each connection's +subscription is a cursor into the terminal's 1 MiB retained tail; the +connection's writer goroutine sends from it as soon as the PTY reader has +written (no tick), coalescing what arrived during the previous write and, +while output streams, letting a frame gather for at most 2 ms. The app asks +for `flow: true` on `terminal_open`/`terminal_output`; those replies carry +`window` (256 KiB) and the app sends `terminal_ack {terminal_id, after}` +each time it has drawn a quarter window. A flow subscription is sent at most +`window` bytes past its last ack, and while one is full the PTY reader stops +(the program blocks on its writes) instead of skipping. One that stays full +for 3 s without acknowledging stops holding the terminal; on its next ack it +gets a frame after a gap and re-reads. A gone connection drops its +subscriptions at once. A subscription without `flow` (an older app build) is +never waited for and keeps the old pacing (newest 64 KiB, one frame per +50 ms). `terminal_open` and `terminal_output` replies are written before the +frames that follow them, which start exactly at the reply's `output_end`. + +Client: `ChatShellTerminalFeed` (shared with chat shells) writes output into +the emulator in 16 Ki-unit slices and yields to the event loop after 6 ms, +so a 1 MiB replay or a burst never holds a UI frame; `drawn` is the server +byte end of what has been written, which `TerminalTab` acknowledges. + +Chat shell runs (`chat_shell_supervise.go`) share the output buffer code: +output is pushed as it arrives, oldest first, while every watcher of the +chat has fewer than 8 queued frames; 256 KiB unpushed stops the reader. A +watcher behind for 3 s gets the old pacing (newest chunk per flush tick, a +gap) until it catches up. The DB snapshot every 2 s is unchanged. + +Measured (`PIPELINES_TERMINAL_MEASURE=1 go test ./internal/server -run +TestMeasureTerminalStream -v`, loopback, fast reading client; before = the +old server or a client without `flow`): + +| workload | before | after | +| --- | --- | --- | +| `seq 1 500000` (3.9 MB) | 3 frames, 3.69 MB skipped, 1.3 MB/s | 70 frames, 0 skipped, 27 MB/s | +| `cat` 2.1 MB | 1 frame, 2.04 MB skipped | 34 frames, 0 skipped, 117 MB/s | +| `yes \| head -1000000` (3.0 MB) | 5 frames, 2.67 MB skipped | 126 frames, 0 skipped, 12 MB/s | +| keystroke echo (median, 40 keys) | 43.3 ms | 0.17 ms | +| longest gap between frames while streaming | 50 ms | 2.5-4.2 ms | + +Emulator (`chat_shell_terminal_feed_test.dart`, 896 KiB replay): one +synchronous write 160 ms; sliced, the same 161 ms over 20 turns, the +longest turn 12.5 ms. ## Login and lifetime (server) diff --git a/app/test/features/chat/shell/chat_shell_terminal_feed_test.dart b/app/test/features/chat/shell/chat_shell_terminal_feed_test.dart new file mode 100644 index 00000000..a83e34b7 --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_terminal_feed_test.dart @@ -0,0 +1,124 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_feed.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_session.dart'; +import 'package:xterm/core.dart'; + +Future turn() => Future.delayed(Duration.zero); + +void main() { + test('output is written in slices, one turn at a time past the ' + 'budget, in order', () async { + final writes = <(String, bool)>[]; + final drawn = []; + final feed = ChatShellTerminalFeed( + (text, replay) => writes.add((text, replay)), + budget: Duration.zero, + slice: 1000, + )..onDrawn = drawn.add; + feed.add('a' * 2500, 2500, replay: true); + feed.add('b' * 10, 2510); + // Only the first slice is written at once. + expect(writes, [('a' * 1000, true)]); + expect(feed.drawn, 0); + expect(feed.end, 2510); + await turn(); + await turn(); + expect(writes.map((w) => w.$1.length), [1000, 1000, 500]); + expect(drawn, [2500]); + await turn(); + expect(writes.last, ('b' * 10, false)); + expect(drawn, [2500, 2510]); + expect(feed.idle, isTrue); + }); + + test( + 'a restart drops what waits; then() runs after what is queued', + () async { + final writes = []; + final feed = ChatShellTerminalFeed( + (text, _) => writes.add(text), + budget: Duration.zero, + slice: 4, + ); + feed.add('abcdefgh', 8); + feed.restart(20); + await turn(); + expect(writes, ['abcd']); + expect((feed.drawn, feed.end), (20, 20)); + final order = []; + feed.add('wxyz12', 26); + feed.then(() => order.add('then@${writes.last}')); + await turn(); + await turn(); + expect(order, ['then@12']); + }, + ); + + test('a surrogate pair is never split between two writes', () { + final writes = []; + final feed = ChatShellTerminalFeed((text, _) => writes.add(text), slice: 3); + feed.add('ab\u{1F600}cd', 8); + expect(writes.first, 'ab\u{1F600}'); + expect(writes.join(), 'ab\u{1F600}cd'); + }); + + test('a 1 MiB replay never blocks a turn for long (measured)', () async { + final big = List.filled(1 << 16, 'y\r\nline 0123\r\n').join(); + final direct = Stopwatch()..start(); + (Terminal( + maxLines: chatShellTerminalScrollback, + )..resize(80, 24)).write(big); + direct.stop(); + final run = ChatShellRun.fromJson({ + 'id': 'run_1', + 'command': 'yes', + 'directory': '/w', + 'status': 'running', + 'started_at': 1, + 'output': '', + 'output_bytes': 0, + 'terminal': true, + 'cols': 80, + 'rows': 24, + })!; + final session = ChatShellTerminalSession( + run, + onInput: (_) {}, + onResize: (_, _) {}, + ); + final held = ChatShellRun.fromJson({ + ...{ + 'id': 'run_1', + 'command': 'yes', + 'directory': '/w', + 'status': 'running', + 'started_at': 1, + 'terminal': true, + 'cols': 80, + 'rows': 24, + }, + 'output': big, + 'output_bytes': big.length, + })!; + final clock = Stopwatch()..start(); + session.replay(held); + var longest = clock.elapsed; + var turns = 1; + while (session.drawn < big.length) { + final before = clock.elapsed; + await turn(); + final spent = clock.elapsed - before; + if (spent > longest) longest = spent; + turns++; + } + // ignore: avoid_print + print( + 'replay of ${big.length >> 10} KiB: one write ${direct.elapsedMilliseconds} ms; ' + 'sliced ${clock.elapsedMilliseconds} ms over $turns turns, ' + 'longest turn ${longest.inMicroseconds / 1000} ms', + ); + expect(longest, lessThan(const Duration(milliseconds: 60))); + expect(session.terminal.buffer.lines.length, greaterThan(1000)); + }); +} diff --git a/app/test/features/terminal/terminal_fixtures.dart b/app/test/features/terminal/terminal_fixtures.dart index ccd2808a..35d6ef9a 100644 --- a/app/test/features/terminal/terminal_fixtures.dart +++ b/app/test/features/terminal/terminal_fixtures.dart @@ -21,6 +21,13 @@ class TerminalGateway implements ApiGateway { /// When set, requests of this type fail with this message. final Map refuse = {}; + /// The flow window terminal_output grants (0: an older server). + int window = 0; + + /// Bytes a terminal's stream holds beyond its text's UTF-8 (negative + /// where runs of invalid bytes became one shorter replacement character). + final Map byteShift = {}; + @override Stream get frames => _frames.stream; @@ -52,9 +59,10 @@ class TerminalGateway implements ApiGateway { return { ...terminals[id]!, 'stream': stream, - 'output_end': bytes.length, + 'output_end': bytes.length + (byteShift[id] ?? 0), if (withOutput) 'output': utf8.decode(bytes.sublist(start)), if (withOutput) 'output_start': start, + if (withOutput && window > 0) 'window': window, }; } @@ -67,15 +75,16 @@ class TerminalGateway implements ApiGateway { } } - void pushOutput(String id, String text, int offset) => _frames.add({ - 'type': 'terminal_event', - 'terminal_event': { - 'terminal_id': id, - 'output': text, - 'offset': offset, - 'end': offset + utf8.encode(text).length, - }, - }); + void pushOutput(String id, String text, int offset, {int? end}) => + _frames.add({ + 'type': 'terminal_event', + 'terminal_event': { + 'terminal_id': id, + 'output': text, + 'offset': offset, + 'end': end ?? offset + utf8.encode(text).length, + }, + }); void lifecycle(String id, Map changes) { terminals[id] = {...terminals[id]!, ...changes}; @@ -117,6 +126,7 @@ class TerminalGateway implements ApiGateway { terminals.remove(id); return {'type': type, 'terminal': record}; case 'terminal_input': + case 'terminal_ack': return {'type': type}; case 'terminal_resize': return {'type': type, 'terminal': _record(id)}; diff --git a/app/test/features/terminal/terminal_flow_test.dart b/app/test/features/terminal/terminal_flow_test.dart new file mode 100644 index 00000000..05518cdd --- /dev/null +++ b/app/test/features/terminal/terminal_flow_test.dart @@ -0,0 +1,103 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/terminal/terminal_hub.dart'; +import 'package:pipelines_app/features/terminal/terminal_tab.dart'; + +import 'terminal_fixtures.dart'; + +String screen(TerminalTab tab) { + final buffer = tab.session.terminal.buffer; + return [ + for (var y = 0; y < buffer.height; y++) + buffer.lines[y].getText().trimRight(), + ].where((line) => line.isNotEmpty).join('\n'); +} + +void main() { + late TerminalGateway mac; + late TerminalHub hub; + + setUp(() { + mac = TerminalGateway(); + hub = TerminalHub(TestMachines([machine('mac', mac, name: 'Mac')])); + }); + tearDown(() async { + hub.dispose(); + await mac.close(); + }); + + Future settle() async { + for (var i = 0; i < 3; i++) { + await Future.delayed(Duration.zero); + } + } + + Future opened(String text) async { + mac.add('term_a', text: text); + hub.activate(); + await settle(); + return hub.tabs.single; + } + + test('offsets come from the server, not the re-encoded text', () async { + // The server replaced two invalid bytes with one U+FFFD (three bytes): + // its stream holds 3 bytes where the text re-encodes to 4. + mac.byteShift['term_a'] = -1; + final tab = await opened('a�'); + expect(tab.session.end, 3); + mac.pushOutput('term_a', 'b', 3); + await settle(); + expect(screen(tab), 'a�b'); + expect(tab.session.end, 4); + // A continuation, not a gap: nothing is read again. + expect(mac.bodies('terminal_output'), hasLength(1)); + }); + + test('reads ask for flow; what is drawn is acknowledged per quarter ' + 'window', () async { + mac.window = 1024; + final tab = await opened(''); + expect(mac.bodies('terminal_output').single['flow'], isTrue); + var end = 0; + void push(int bytes) { + mac.pushOutput('term_a', 'x' * bytes, end); + end += bytes; + } + + push(300); + await settle(); + expect(mac.bodies('terminal_ack'), [ + {'terminal_id': 'term_a', 'after': 300}, + ]); + push(100); + await settle(); + expect(mac.bodies('terminal_ack'), hasLength(1)); + push(200); + await settle(); + expect(mac.bodies('terminal_ack').last, { + 'terminal_id': 'term_a', + 'after': 600, + }); + expect(tab.session.drawn, 600); + }); + + test('an older server (no window) is never acknowledged', () async { + await opened(''); + mac.pushOutput('term_a', 'x' * 100000, 0); + await settle(); + expect(mac.bodies('terminal_ack'), isEmpty); + }); + + test('a large retained tail is drawn over several turns', () async { + final big = List.filled(40000, 'line of output\r\n').join(); + final tab = await opened(''); + mac.output['term_a'] = big; + await tab.resume(); + // The read is drawn in slices: not all of it in the turn it arrived. + expect(tab.session.drawn, lessThan(tab.session.end)); + for (var turn = 0; turn < 1000 && tab.session.drawn < big.length; turn++) { + await Future.delayed(Duration.zero); + } + expect(tab.session.drawn, big.length); + expect(screen(tab).split('\n').last, 'line of output'); + }); +} diff --git a/docs/cli.md b/docs/cli.md index 2570615b..cff53af8 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1299,7 +1299,7 @@ including before the browser has opened its application websocket. Interactive login shells on a server's machine, independent of chats (the app's terminal panel). Every request carries `terminal_request` -`{terminal_id?, cwd?, cols?, rows?, data?, after?}`: +`{terminal_id?, cwd?, cols?, rows?, data?, after?, flow?}`: - `terminal_open {cwd, cols, rows}` starts the machine's login prompt for the server's own account (`su -l ` in a PTY; macOS and Linux) and replies @@ -1317,11 +1317,26 @@ app's terminal panel). Every request carries `terminal_request` - `terminal_list` replies with `terminals` (running and ended, oldest first). - `terminal_input {terminal_id, data}` writes UTF-8 input (at most 16 KiB); `terminal_resize {terminal_id, cols, rows}` resizes. Neither is logged. -- `terminal_output {terminal_id, after}` replies with the retained output (1 - MiB tail) from byte `after` of the stream named `stream`. Opening or reading subscribes the connection to - the terminal's output frames. +- `terminal_output {terminal_id, after, flow?}` replies with the retained + output (1 MiB tail) from byte `after` of the stream named `stream`, covering + bytes `[output_start, output_end)`; the output frames that follow the reply + start at `output_end`. Opening or reading subscribes the connection to the + terminal's output frames. +- `terminal_ack {terminal_id, after}` (flow-controlled subscriptions only): + the connection has drawn the output up to byte `after`. Not logged. - `terminal_close {terminal_id}` kills the login or shell. - Pushed `terminal_event {terminal_id, output, offset, end}` (output) or - `{terminal_id, terminal}` (opened, title, exited, closed). + `{terminal_id, terminal}` (opened, title, exited, closed). Offsets are bytes + of the terminal's stream (invalid UTF-8 is shown as U+FFFD, so a client takes + `end`, never the text's length). +- Output flow: an `open` or `output` with `flow: true` gets `window` in its + reply (256 KiB). Output is pushed as soon as it is read (bursts coalesce for + at most 2 ms), every byte in order, at most `window` bytes past the last + `terminal_ack`; while a flow-controlled subscription is full the server stops + reading the PTY, so the program waits. One that stays full for 3 s without + acknowledging stops holding the terminal; after its next ack it sees a gap + (`offset` past its end) and reads `terminal_output` again. A subscription + without `flow` (older clients) is never waited for: one frame of the newest + 64 KiB per 50 ms, gaps re-read as before. See `app/notes/terminal-panel.md`. diff --git a/internal/protocol/terminal.go b/internal/protocol/terminal.go index 70da0950..3bc24512 100644 --- a/internal/protocol/terminal.go +++ b/internal/protocol/terminal.go @@ -33,9 +33,25 @@ const ( // TerminalClose ends a terminal: its login or shell is killed // and its record removed. The reply echoes the last record. TerminalClose = "terminal_close" + // TerminalAck tells the server that this connection has consumed + // (drawn) a terminal's output up to the absolute byte After. Only a + // connection whose terminal_open or terminal_output carried Flow (and + // whose reply carried Window) sends it; the reply has no body. + TerminalAck = "terminal_ack" // TerminalEvent is pushed: an output chunk to the connections subscribed // to that terminal (Output, Offset, End), or a lifecycle change (Terminal // set: opened, title, exited, closed) to every connection. + // + // Output flow: a subscription opened with Flow gets every byte in order, + // at most Window bytes past its last terminal_ack; while such a + // subscription is full the server stops reading the terminal, so the + // program waits (a subscription that stays full without acknowledging for + // a few seconds stops holding it back, and later sees a gap). A + // subscription without Flow is never waited for: it gets at most one + // TerminalChunkLimit frame per 50 ms, the newest bytes, and a gap when it + // falls behind. A gap (Offset after the client's end) is repaired by + // terminal_output, whose reply's OutputEnd is where the frames that + // follow it start. TerminalEvent = "terminal_event" ) @@ -54,6 +70,9 @@ const ( TerminalRetained = 1 << 20 // TerminalChunkLimit bounds one live output frame. TerminalChunkLimit = 64 << 10 + // TerminalFlowWindow bounds the output sent to a flow-controlled + // subscription past its last terminal_ack. + TerminalFlowWindow = 256 << 10 // TerminalEndedKept bounds the ended terminals still listed. TerminalEndedKept = 16 // TerminalTitleLimit bounds a recorded title. @@ -68,6 +87,9 @@ type TerminalRequest struct { Rows int `json:"rows,omitempty"` Data string `json:"data,omitempty"` After int64 `json:"after,omitempty"` + // Flow (terminal_open, terminal_output) asks for flow-controlled output: + // the connection acknowledges what it consumed with terminal_ack. + Flow bool `json:"flow,omitempty"` } // TerminalRecord is one terminal. Output and OutputStart are set only on @@ -89,12 +111,18 @@ type TerminalRecord struct { Cols int `json:"cols"` Rows int `json:"rows"` // Stream names this server process's output stream of the terminal; - // OutputEnd is the absolute byte count read into it. A client holding - // another stream reads the terminal again from its start. + // OutputEnd is the absolute byte count read into it (on a + // terminal_output reply, the end of Output: an incomplete trailing + // character follows in the next frame). A client holding another stream + // reads the terminal again from its start. Stream string `json:"stream,omitempty"` OutputEnd int64 `json:"output_end"` Output string `json:"output,omitempty"` OutputStart int64 `json:"output_start,omitempty"` + // Window is set on the terminal_open and terminal_output replies of a + // flow-controlled subscription: the bytes the server sends past the + // last terminal_ack. Its absence means the server takes no acks. + Window int64 `json:"window,omitempty"` } // TerminalEventFrame is one pushed terminal change: either Terminal (a diff --git a/internal/server/chat_room.go b/internal/server/chat_room.go index 83f47c29..a989beca 100644 --- a/internal/server/chat_room.go +++ b/internal/server/chat_room.go @@ -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 diff --git a/internal/server/chat_shell_flow_test.go b/internal/server/chat_shell_flow_test.go new file mode 100644 index 00000000..49bf6d8f --- /dev/null +++ b/internal/server/chat_shell_flow_test.go @@ -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:]) + } + } +} diff --git a/internal/server/chat_shell_run_output.go b/internal/server/chat_shell_run_output.go index 53635a53..1bcf7aba 100644 --- a/internal/server/chat_shell_run_output.go +++ b/internal/server/chat_shell_run_output.go @@ -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 diff --git a/internal/server/chat_shell_runner.go b/internal/server/chat_shell_runner.go index 1de83da0..614106c4 100644 --- a/internal/server/chat_shell_runner.go +++ b/internal/server/chat_shell_runner.go @@ -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) } diff --git a/internal/server/chat_shell_runner_test.go b/internal/server/chat_shell_runner_test.go index b84a3604..6ba1b812 100644 --- a/internal/server/chat_shell_runner_test.go +++ b/internal/server/chat_shell_runner_test.go @@ -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}) diff --git a/internal/server/chat_shell_supervise.go b/internal/server/chat_shell_supervise.go index 48c1494d..7693c045 100644 --- a/internal/server/chat_shell_supervise.go +++ b/internal/server/chat_shell_supervise.go @@ -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 diff --git a/internal/server/terminal_clients.go b/internal/server/terminal_clients.go index 4578dd63..50f21a8a 100644 --- a/internal/server/terminal_clients.go +++ b/internal/server/terminal_clients.go @@ -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} +} diff --git a/internal/server/terminal_flow.go b/internal/server/terminal_flow.go new file mode 100644 index 00000000..9d67df43 --- /dev/null +++ b/internal/server/terminal_flow.go @@ -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() + } +} diff --git a/internal/server/terminal_flow_test.go b/internal/server/terminal_flow_test.go new file mode 100644 index 00000000..d510b148 --- /dev/null +++ b/internal/server/terminal_flow_test.go @@ -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 + } + } +} diff --git a/internal/server/terminal_handlers.go b/internal/server/terminal_handlers.go index bd8bd219..31fbae77 100644 --- a/internal/server/terminal_handlers.go +++ b/internal/server/terminal_handlers.go @@ -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() + } + } } diff --git a/internal/server/terminal_lifetime_test.go b/internal/server/terminal_lifetime_test.go index 2bd627a4..7bb584a4 100644 --- a/internal/server/terminal_lifetime_test.go +++ b/internal/server/terminal_lifetime_test.go @@ -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) } diff --git a/internal/server/terminal_login_test.go b/internal/server/terminal_login_test.go index e4d8ff3a..878fdf5a 100644 --- a/internal/server/terminal_login_test.go +++ b/internal/server/terminal_login_test.go @@ -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) } } diff --git a/internal/server/terminal_manager.go b/internal/server/terminal_manager.go index 91af233a..7936bbf8 100644 --- a/internal/server/terminal_manager.go +++ b/internal/server/terminal_manager.go @@ -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 } diff --git a/internal/server/terminal_measure_test.go b/internal/server/terminal_measure_test.go new file mode 100644 index 00000000..fe6942b3 --- /dev/null +++ b/internal/server/terminal_measure_test.go @@ -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])) +} diff --git a/internal/server/terminal_process.go b/internal/server/terminal_process.go index 2d7f2aec..df0c76ba 100644 --- a/internal/server/terminal_process.go +++ b/internal/server/terminal_process.go @@ -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: diff --git a/internal/server/terminal_supervise.go b/internal/server/terminal_supervise.go index f053d426..e431bbab 100644 --- a/internal/server/terminal_supervise.go +++ b/internal/server/terminal_supervise.go @@ -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) { diff --git a/internal/server/terminal_ws_test.go b/internal/server/terminal_ws_test.go index 3d76ebfb..819abe54 100644 --- a/internal/server/terminal_ws_test.go +++ b/internal/server/terminal_ws_test.go @@ -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) diff --git a/internal/server/websocket.go b/internal/server/websocket.go index 9992cfa4..98802367 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -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) }