diff --git a/plugins/VelaShell.Plugin.S3/S3Plugin.cs b/plugins/VelaShell.Plugin.S3/S3Plugin.cs index b30b9ce..bebc22c 100644 --- a/plugins/VelaShell.Plugin.S3/S3Plugin.cs +++ b/plugins/VelaShell.Plugin.S3/S3Plugin.cs @@ -33,13 +33,18 @@ public Task ActivateAsync(IPluginContext context, CancellationToken cancellation _actions.Attach(_fileSystem); _registration = context.Protocols.Register(BuildDescriptor(context), _fileSystem); // 语言切换后重注册:描述里的字段标签是插件自己的文案,宿主不会替我们翻。 - context.Events.LocaleChanged += _ => Reregister(); + context.Events.LocaleChanged += OnLocaleChanged; return Task.CompletedTask; } /// public async Task DeactivateAsync(CancellationToken cancellationToken) { + // 不退订的话宿主的事件表一直握着本插件实例,可收集 ALC 就卸不掉这份程序集。 + if (_context is { } context) + { + context.Events.LocaleChanged -= OnLocaleChanged; + } _registration?.Dispose(); _registration = null; if (_fileSystem is { } fileSystem) @@ -53,6 +58,9 @@ public async Task DeactivateAsync(CancellationToken cancellationToken) _context = null; } + /// 语言切换:按新语言重注册。命名方法而不是 lambda —— 停用时要能退订。 + private void OnLocaleChanged(string locale) => Reregister(); + private void Reregister() { if (_context is not { } context || _fileSystem is not { } fileSystem) diff --git a/plugins/VelaShell.Plugin.Serial/LocalEchoRenderer.cs b/plugins/VelaShell.Plugin.Serial/LocalEchoRenderer.cs new file mode 100644 index 0000000..40156c8 --- /dev/null +++ b/plugins/VelaShell.Plugin.Serial/LocalEchoRenderer.cs @@ -0,0 +1,160 @@ +namespace VelaShell.Plugin.Serial; + +/// +/// 本地回显:把用户敲的键翻成"屏幕上该出现什么",而不是把原始按键字节原样喂回终端引擎。 +/// +/// 原样喂回的三个症状,都是"能用但看着不对": +/// +/// +/// 回车只是 CR —— 光标回到行首却不下移,对端的应答随即盖掉刚敲的那一行; +/// 退格是 DEL(0x7F)—— VT 引擎不画它,屏幕上的字删不掉; +/// 方向键是 ESC [ A 之类 —— 喂回去就是在本地真的移动光标。 +/// +/// +/// 这里做的是终端驱动在 ECHO + ICANON 下做的那部分显示:CR / LF / CR LF 一律显示成换行, +/// 退格擦掉本行上一个字符(擦不过行首,提示符不会被擦掉),控制序列与其余 C0 控制字符不显示。 +/// 线上的字节不受影响 —— 这只是显示。 +/// +/// +/// 宽字符按 UTF-8 首字节粗判(CJK、韩文、补充平面的 emoji 记两格):退格要擦几格只取决于它, +/// 判错的代价只是半个字残影,不值得为此带一张 Unicode 宽度表。 +/// +/// 状态跨调用保持(一个控制序列、一对 CR LF 都可能被切在两次写入之间),调用方须串行调用。 +/// +internal sealed class LocalEchoRenderer +{ + private const byte Cr = 0x0D; + private const byte Lf = 0x0A; + + /// 本行最多记这么多个字符的宽度;更长的行只是退格擦不回最早那部分。 + private const int MaxTrackedCells = 4096; + + private enum State + { + Text, + Escape, + ControlSequence, + SingleShift + } + + /// 本行已回显字符的显示宽度(1 或 2),退格按它擦。换行即清空。 + private readonly List _widths = []; + + private State _state; + private bool _afterCr; + + /// 把一次写入翻成要喂回终端的显示字节。 + /// 用户这次写入的字节。 + /// 要显示的字节;可能为空。 + public byte[] Render(ReadOnlySpan input) + { + var output = new List(input.Length + 8); + foreach (byte value in input) + { + switch (_state) + { + case State.Escape: + if (value == (byte)'[') + { + _state = State.ControlSequence; + continue; + } + if (value == (byte)'O') + { + _state = State.SingleShift; + continue; + } + // 单独按下的 ESC(或 Alt+键):ESC 本身不显示,这个字节照常处理。 + _state = State.Text; + break; + case State.ControlSequence: + // CSI 的参数与中间字节在 0x20–0x3F,终止字节在 0x40–0x7E。 + if (value is >= 0x40 and <= 0x7E) + { + _state = State.Text; + } + continue; + case State.SingleShift: + _state = State.Text; // ESC O x(小键盘、部分终端的方向键):x 是终止字节。 + continue; + } + RenderText(value, output); + } + return [.. output]; + } + + private void RenderText(byte value, List output) + { + bool afterCr = _afterCr; + _afterCr = false; + switch (value) + { + case 0x1B: + _state = State.Escape; + break; + case Cr: + NewLine(output); + _afterCr = true; + break; + case Lf: + if (!afterCr) + { + NewLine(output); // 裸 LF 也得回到行首,否则就是阶梯。 + } + break; + case 0x08 or 0x7F: + Erase(output); + break; + case 0x09: + output.Add(value); + Track(1); // 制表位的真实宽度不可知;按一格记,退格时最多少擦几格。 + break; + case < 0x20: + break; // Ctrl-C / Ctrl-D 之类没有字形。 + case >= 0x80 and < 0xC0: + output.Add(value); // UTF-8 续字节:属于前一个字符,不另占格。 + break; + default: + output.Add(value); + Track(value is >= 0xE3 and <= 0xED or >= 0xF0 ? (byte)2 : (byte)1); + break; + } + } + + private void NewLine(List output) + { + output.Add(Cr); + output.Add(Lf); + _widths.Clear(); + } + + private void Erase(List output) + { + if (_widths.Count == 0) + { + return; // 已在行首:别把提示符也擦了。 + } + int width = _widths[^1]; + _widths.RemoveAt(_widths.Count - 1); + for (int i = 0; i < width; i++) + { + output.Add(0x08); + } + for (int i = 0; i < width; i++) + { + output.Add((byte)' '); + } + for (int i = 0; i < width; i++) + { + output.Add(0x08); + } + } + + private void Track(byte width) + { + if (_widths.Count < MaxTrackedCells) + { + _widths.Add(width); + } + } +} diff --git a/plugins/VelaShell.Plugin.Serial/README.md b/plugins/VelaShell.Plugin.Serial/README.md index 6f99307..a9ac3c2 100644 --- a/plugins/VelaShell.Plugin.Serial/README.md +++ b/plugins/VelaShell.Plugin.Serial/README.md @@ -34,8 +34,8 @@ Break 与 DTR/RTS)。 | 打开时置 DTR / RTS | 开 / 开 | 高级。RTS 在流控制取 RTS/CTS 时自动隐藏(那时归驱动) | | 收到裸 CR 补 LF | 关 | 高级。**输出每行盖在上一行上**时打开它 | | 收到裸 LF 补 CR | 关 | 高级。**输出呈阶梯状**时打开它 | -| 本地回显 | 关 | 高级。对着从不回显的设备才需要开 | -| 发送延时(字符 / 行) | 0 / 0 | 高级。给没有流控、粘贴配置会丢字符的老设备用 | +| 本地回显 | 关 | 高级。对着从不回显的设备才需要开。回显按屏幕该有的样子画:CR / LF 都显示成换行,退格擦字(不擦过行首),方向键等控制序列不显示 | +| 发送延时(字符 / 行) | 0 / 0 | 高级。给没有流控、粘贴配置会丢字符的老设备用。在专用线程上按毫秒精度等待(`Task.Delay` 在 Windows 上粒度约 15.6ms);CR LF 只算一行;关会话即停 | 用户名/口令两栏由 `ProtocolFeatures.NoCredentials` 收起(登录发生在带内), 端口那一栏由 `ProtocolFeatures.NoEndpoint` 收起(串口的目标不是 `host:port`)。 @@ -97,7 +97,11 @@ Unix 上响应 —— 一个平台间行为不一致的地基,换来的只是省 `/sys/class/tty/<名>/device` 是否存在。 - **macOS 绝不能列 `/dev/tty.*`**。那是 dial-in 设备,打开时会**阻塞等待 DCD 载波** —— 对着一个没接线的适配器打开它,进程永久挂起,而用户看到的是"点了连接没反应"。 - `/dev/cu.*` 是 call-out,立即打开。 + `/dev/cu.*` 是 call-out,立即打开。手输或旧配置里的 `/dev/tty.xxx`,打开时自动换成存在的 + `/dev/cu.xxx`(同一个硬件)。 + +打开端口本身放在线程池上做,而且可取消:`SerialPort.Open` 是阻塞调用(设备不在场的蓝牙 COM 口 +能卡十几秒),中途打断不了 —— 取消立即生效,那次迟到的打开返回后再由插件把端口关掉。 ## 打包 diff --git a/plugins/VelaShell.Plugin.Serial/SerialLineDiscipline.cs b/plugins/VelaShell.Plugin.Serial/SerialLineDiscipline.cs index 59bbed1..5851b2c 100644 --- a/plugins/VelaShell.Plugin.Serial/SerialLineDiscipline.cs +++ b/plugins/VelaShell.Plugin.Serial/SerialLineDiscipline.cs @@ -1,7 +1,8 @@ namespace VelaShell.Plugin.Serial; /// -/// 串口的"行规程":换行改写与本地回显。全部是纯字节变换,不碰硬件 —— +/// 串口的"行规程":收发两个方向的换行改写(本地回显怎么显示见 )。 +/// 全部是纯字节变换,不碰硬件 —— /// 于是这一层可以脱离真实串口单测,而这恰恰是串口最难验证的部分 /// (没有 telnetd 那样的环回可用,调研文档 §五.4 记的就是这条)。 /// @@ -28,6 +29,9 @@ internal sealed class SerialLineDiscipline(SerialConfig config) /// private bool _swallowLeadingLf; + /// 上一次**出方向**写入以裸 CR 收尾(已按 发成换行)。 + private bool _transmitEndedWithCr; + /// /// 入方向:按 / /// 补齐换行。两项都关时**原样返回同一段内存**(零拷贝,这是默认路径)。 @@ -101,8 +105,8 @@ public ReadOnlyMemory Receive(ReadOnlyMemory data) /// /// /// 粘贴的 CRLF 文本不会被打成 CR LF LF:CR 后面已经跟着 LF 时不再补。 - /// 这个判断按**本次写入**的缓冲区做,不跨调用 —— 一次粘贴是一次写入, - /// 要跨调用切开 CRLF 得宿主正好在这两个字节之间断开,不会发生。 + /// 宿主把一大段粘贴分块写入时,CRLF 也可能正好被切在两次写入之间 —— 所以"上一次以裸 CR 收尾" + /// 要跨调用记住,下一次若以 LF 开头就吞掉它。调用方须串行调用(会话在写锁里调)。 /// /// /// 用户输入的字节。 @@ -115,7 +119,18 @@ public ReadOnlyMemory Transmit(ReadOnlyMemory data) } ReadOnlySpan input = data.Span; var output = new List(input.Length + 8); - for (int i = 0; i < input.Length; i++) + int start = 0; + if (_transmitEndedWithCr) + { + _transmitEndedWithCr = false; + // 上一块末尾那个 CR 已经按换行发出去了:这个 LF 是同一个换行的后半截。 + if (input.Length > 0 && input[0] == Lf) + { + start = 1; + } + } + _transmitEndedWithCr = input.Length > start && input[^1] == Cr; + for (int i = start; i < input.Length; i++) { byte b = input[i]; if (b != Cr) @@ -145,30 +160,4 @@ public ReadOnlyMemory Transmit(ReadOnlyMemory data) } return output.ToArray(); } - - /// - /// 本地回显要往屏幕上打的字节。 - /// - /// 取的是**改写之后**要上线的那一份,并且把裸 CR 展开成 CR LF —— - /// 屏幕上的"回车"必须同时回到行首并下移一行,只回不移的话用户看到的是 - /// 自己敲的下一行盖在上一行上。这一步只影响显示,不影响线上字节。 - /// - /// - /// 已按 改写过的字节。 - /// 喂回终端的字节;无需回显时为空。 - public static ReadOnlyMemory BuildEcho(ReadOnlyMemory transmitted) - { - ReadOnlySpan input = transmitted.Span; - var output = new List(input.Length + 4); - for (int i = 0; i < input.Length; i++) - { - byte b = input[i]; - output.Add(b); - if (b == Cr && (i + 1 >= input.Length || input[i + 1] != Lf)) - { - output.Add(Lf); - } - } - return output.ToArray(); - } } diff --git a/plugins/VelaShell.Plugin.Serial/SerialPlugin.cs b/plugins/VelaShell.Plugin.Serial/SerialPlugin.cs index 3e89f71..b38c299 100644 --- a/plugins/VelaShell.Plugin.Serial/SerialPlugin.cs +++ b/plugins/VelaShell.Plugin.Serial/SerialPlugin.cs @@ -36,13 +36,18 @@ public Task ActivateAsync(IPluginContext context, CancellationToken cancellation _registration = context.Protocols.Register(BuildDescriptor(context), _terminal); RegisterCommands(context); // 语言切换后重注册:表单标签与命令标题都是插件自己的文案,宿主不会替我们翻。 - context.Events.LocaleChanged += _ => Reregister(); + context.Events.LocaleChanged += OnLocaleChanged; return Task.CompletedTask; } /// public Task DeactivateAsync(CancellationToken cancellationToken) { + // 不退订的话宿主的事件表一直握着本插件实例,可收集 ALC 就卸不掉这份程序集。 + if (_context is { } context) + { + context.Events.LocaleChanged -= OnLocaleChanged; + } foreach (IDisposable command in _commands) { command.Dispose(); @@ -55,6 +60,9 @@ public Task DeactivateAsync(CancellationToken cancellationToken) return Task.CompletedTask; } + /// 语言切换:按新语言重注册。命名方法而不是 lambda —— 停用时要能退订。 + private void OnLocaleChanged(string locale) => Reregister(); + private void Reregister() { if (_context is not { } context || _terminal is not { } terminal) diff --git a/plugins/VelaShell.Plugin.Serial/SerialSession.cs b/plugins/VelaShell.Plugin.Serial/SerialSession.cs index ee190c3..b94775d 100644 --- a/plugins/VelaShell.Plugin.Serial/SerialSession.cs +++ b/plugins/VelaShell.Plugin.Serial/SerialSession.cs @@ -1,3 +1,4 @@ +using System.Diagnostics; using System.Threading.Channels; using VelaShell.PluginSdk.Logging; using VelaShell.PluginSdk.Protocols; @@ -34,6 +35,7 @@ internal sealed class SerialSession : IProtocolTerminalSession private readonly ISerialPortHandle _port; private readonly SerialConfig _config; private readonly SerialLineDiscipline _discipline; + private readonly LocalEchoRenderer _echo = new(); private readonly IPluginLogger _log; /// @@ -92,6 +94,10 @@ public static SerialSession Connect(SerialConfig config, IPluginLogger log, Func ArgumentNullException.ThrowIfNull(config); ArgumentNullException.ThrowIfNull(log); ISerialPortHandle port = (open ?? SystemSerialPortHandle.Open)(config); + if (!string.Equals(port.PortName, config.PortName, StringComparison.Ordinal)) + { + log.Info($"Serial {config.PortName}: opened {port.PortName} instead (the dial-in tty.* device waits for carrier)."); + } log.Info($"Serial {port.PortName} opened at {config.BaudRate} {config.DataBits}{Describe(config)} " + $"(flow={config.Handshake}, dtr={config.Dtr}, rts={config.Rts})"); return new(port, config, log); @@ -137,22 +143,29 @@ public async ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken c return; } Activity?.Invoke(this); - await _writeGate.WaitAsync(cancellationToken).ConfigureAwait(false); + if (!await EnterWriteGateAsync(cancellationToken).ConfigureAwait(false)) + { + return; + } try { ReadOnlyMemory payload = _discipline.Transmit(data); - if (_config.LocalEcho) + if (_config.LocalEcho && _echo.Render(payload.Span) is { Length: > 0 } echo) { // 先回显再上线:设备的响应总是晚于我们自己的键入,顺序天然正确。 - _ = _inbound.Writer.TryWrite(SerialLineDiscipline.BuildEcho(payload).ToArray()); + // 回显的是**改写之后**上线的那一份,按屏幕该有的样子画(回车换行、退格擦字)。 + _ = _inbound.Writer.TryWrite(echo); } + byte[] bytes = payload.ToArray(); if (_config.IsPaced) { - await WritePacedAsync(payload, cancellationToken).ConfigureAwait(false); + // 节流写可能持续数秒到数分钟,而且字节间隔要比系统定时器精细(见 WritePaced), + // 放在一条专用线程上做:既不占线程池,也绝不会在调用方(可能是界面线程)上阻塞。 + await Task.Factory.StartNew(() => WritePaced(bytes, cancellationToken), cancellationToken, + TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false); } else { - byte[] bytes = payload.ToArray(); await Task.Run(() => _port.Write(bytes, 0, bytes.Length), cancellationToken).ConfigureAwait(false); } } @@ -173,7 +186,7 @@ public async ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken c } finally { - _ = _writeGate.Release(); + ExitWriteGate(); } } @@ -341,31 +354,80 @@ private void ReadLoop() /// (Cisco/华为控制台、单片机 bootloader)粘一段配置进去,不节流就是丢字符 —— /// 而且丢在哪儿全看运气。两个延时默认都是 0,此时这条路径整个不进。 /// + /// + /// 跑在专用线程上(见 ),等待用 而不是 + /// :后者在 Windows 上的实际粒度约 15.6ms, + /// 用户填"每字节 1ms"会变成 15ms,一段粘贴慢十几倍。会话一关就停,不把剩下的字节写完。 + /// /// - /// 要写的字节。 + /// 要写的字节。 /// 取消令牌。 - private async Task WritePacedAsync(ReadOnlyMemory payload, CancellationToken cancellationToken) + private void WritePaced(byte[] data, CancellationToken cancellationToken) { byte[] one = new byte[1]; - ReadOnlyMemory data = payload; for (int i = 0; i < data.Length; i++) { - cancellationToken.ThrowIfCancellationRequested(); - one[0] = data.Span[i]; - // 第一次 await 之前先让出:WriteAsync 可能是在界面线程上被调用的, - // 而下面的 Write 是阻塞的。 - if (_config.TxDelayPerByte > TimeSpan.Zero || i == 0) + ThrowIfStopped(cancellationToken); + if (i > 0 && _config.TxDelayPerByte > TimeSpan.Zero) { - await Task.Delay(_config.TxDelayPerByte, cancellationToken).ConfigureAwait(false); + PacingWait(_config.TxDelayPerByte, cancellationToken); + ThrowIfStopped(cancellationToken); } + one[0] = data[i]; _port.Write(one, 0, 1); - if (_config.TxDelayPerLine > TimeSpan.Zero && one[0] is 0x0A or 0x0D) + if (_config.TxDelayPerLine > TimeSpan.Zero && EndsLine(data, i)) { - await Task.Delay(_config.TxDelayPerLine, cancellationToken).ConfigureAwait(false); + PacingWait(_config.TxDelayPerLine, cancellationToken); } } } + /// + /// 这个字节是否结束一行:LF,或者后面不跟 LF 的 CR。CR LF 只算一行 —— + /// 否则"回车发 CR LF"时每行要等两次行间隔。 + /// + internal static bool EndsLine(ReadOnlySpan data, int index) => + data[index] == 0x0A || (data[index] == 0x0D && (index + 1 >= data.Length || data[index + 1] != 0x0A)); + + private void ThrowIfStopped(CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (_closing) + { + throw new OperationCanceledException("The serial session is closing."); + } + } + + /// + /// 毫秒级精确等待:长的部分交给内核等(可被取消唤醒),最后不到一个系统定时器周期的那段自旋。 + /// 自旋只在用户开了节流、且正在发送时发生,总量不超过用户自己设的延时。 + /// + internal static void PacingWait(TimeSpan delay, CancellationToken cancellationToken) + { + // Windows 默认定时器周期约 15.6ms;留出一个周期的余量给自旋,别让内核等待睡过头。 + const long CoarseSleepMarginMs = 16; + long deadline = Stopwatch.GetTimestamp() + (long)(delay.TotalSeconds * Stopwatch.Frequency); + while (true) + { + long remainingMs = (deadline - Stopwatch.GetTimestamp()) * 1000 / Stopwatch.Frequency; + if (remainingMs <= CoarseSleepMarginMs) + { + break; + } + if (cancellationToken.WaitHandle.WaitOne((int)(remainingMs - CoarseSleepMarginMs))) + { + cancellationToken.ThrowIfCancellationRequested(); + } + } + var spinner = new SpinWait(); + while (Stopwatch.GetTimestamp() < deadline) + { + cancellationToken.ThrowIfCancellationRequested(); + // sleep1Threshold = -1:只让出不睡眠,Sleep(1) 本身在 Windows 上就会睡一个定时器周期。 + spinner.SpinOnce(sleep1Threshold: -1); + } + } + private void SetLine(SerialControlLine line, bool value) { if (line == SerialControlLine.Dtr) @@ -381,11 +443,10 @@ private void SetLine(SerialControlLine line, bool value) /// 控制线动作的公共外壳:与写共用同一把锁,关了就静默不做,异常只记日志。 private async Task OnLineAsync(Func action, CancellationToken cancellationToken) { - if (!IsOpen) + if (!IsOpen || !await EnterWriteGateAsync(cancellationToken).ConfigureAwait(false)) { return false; } - await _writeGate.WaitAsync(cancellationToken).ConfigureAwait(false); try { await action().ConfigureAwait(false); @@ -397,9 +458,38 @@ private async Task OnLineAsync(Func action, CancellationToken cancel return false; } finally + { + ExitWriteGate(); + } + } + + /// + /// 进写锁。会话关闭时锁会被释放掉,而关闭与写并发是常态(关标签时还有按键在路上): + /// 那时返回 false 让调用方静默放弃,而不是把 抛给宿主。 + /// + private async Task EnterWriteGateAsync(CancellationToken cancellationToken) + { + try + { + await _writeGate.WaitAsync(cancellationToken).ConfigureAwait(false); + return true; + } + catch (ObjectDisposedException) + { + return false; + } + } + + private void ExitWriteGate() + { + try { _ = _writeGate.Release(); } + catch (ObjectDisposedException) + { + // 会话在这次写进行期间关掉了。 + } } /// 把校验/停止位拼成 8N1 那种一眼能认的写法(日志用)。 diff --git a/plugins/VelaShell.Plugin.Serial/SerialTerminal.cs b/plugins/VelaShell.Plugin.Serial/SerialTerminal.cs index d6adae0..f487460 100644 --- a/plugins/VelaShell.Plugin.Serial/SerialTerminal.cs +++ b/plugins/VelaShell.Plugin.Serial/SerialTerminal.cs @@ -20,7 +20,13 @@ internal sealed class SerialTerminal( Func? open = null) : IProtocolTerminal, IProtocolChoiceSource { /// - public Task ConnectAsync( + /// + /// 打开端口放在线程池上做,而且可取消:SerialPort.Open 是阻塞调用, + /// Windows 上设备不在场的蓝牙虚拟串口一次要卡十几秒。它中途打断不了 —— + /// 取消时调用方立刻拿到 ,而那次打开等它自己返回后 + /// 再把端口关掉,免得一个没人要的会话占着 COM 口。 + /// + public async Task ConnectAsync( ProtocolConnectRequest request, ProtocolTerminalOptions options, CancellationToken cancellationToken = default) @@ -35,16 +41,39 @@ public Task ConnectAsync( // "PortName cannot be empty" 的英文 ArgumentException 给用户看。 throw new ProtocolConnectionException(loc["Serial_ErrNoPort"]); } + cancellationToken.ThrowIfCancellationRequested(); + Task opening = Task.Run(() => SerialSession.Connect(config, context.Log, open), CancellationToken.None); + SerialSession session; try { - var session = SerialSession.Connect(config, context.Log, open); - sessions.Add(session); - return Task.FromResult(session); + session = await opening.WaitAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + _ = opening.ContinueWith(CloseAbandoned, context.Log, CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + throw; } catch (Exception ex) { throw new ProtocolConnectionException(Explain(ex, config.PortName, loc), ex); } + sessions.Add(session); + return session; + } + + /// 用户已经取消、但端口后来才打开成功:关掉它。打开失败就只是观察掉那个异常。 + private static void CloseAbandoned(Task opening, object? state) + { + if (!opening.IsCompletedSuccessfully) + { + _ = opening.Exception; // 已经没人等这次打开了,别留成未观察的异常。 + return; + } + _ = opening.Result.DisposeAsync().AsTask().ContinueWith( + static (closing, log) => ((VelaShell.PluginSdk.Logging.IPluginLogger)log!).Warn( + $"Serial: closing an abandoned port failed — {closing.Exception?.GetBaseException().Message}"), + state, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); } /// diff --git a/plugins/VelaShell.Plugin.Serial/SystemSerialPortHandle.cs b/plugins/VelaShell.Plugin.Serial/SystemSerialPortHandle.cs index dbf0906..030f68e 100644 --- a/plugins/VelaShell.Plugin.Serial/SystemSerialPortHandle.cs +++ b/plugins/VelaShell.Plugin.Serial/SystemSerialPortHandle.cs @@ -71,7 +71,8 @@ public bool RtsEnable public static ISerialPortHandle Open(SerialConfig config) { ArgumentNullException.ThrowIfNull(config); - var port = new SerialPort(config.PortName, config.BaudRate, config.Parity, config.DataBits, config.StopBits) + string portName = PreferCallOutDevice(config.PortName, OperatingSystem.IsMacOS(), File.Exists); + var port = new SerialPort(portName, config.BaudRate, config.Parity, config.DataBits, config.StopBits) { Handshake = config.Handshake, ReadTimeout = ReadTimeoutMs, @@ -108,6 +109,30 @@ public static ISerialPortHandle Open(SerialConfig config) return new SystemSerialPortHandle(port); } + /// + /// macOS 上把 dial-in 设备 /dev/tty.xxx 换成对应的 call-out 设备 /dev/cu.xxx。 + /// + /// 下拉里只列 cu.*(见 ),但端口名允许手输, + /// 旧配置里也可能存着 tty.*:打开 dial-in 设备会**一直阻塞到 DCD 载波出现**, + /// 对着没接线的 USB 适配器就是"点了连接永远没反应"。两者是同一个硬件,换过去没有任何损失; + /// 找不到对应的 cu.* 时保持原样。 + /// + /// + /// 表单里的端口名。 + /// 是否 macOS(单测注入)。 + /// 设备文件是否存在(单测注入)。 + /// 实际要打开的端口名。 + internal static string PreferCallOutDevice(string portName, bool isMacOs, Func exists) + { + const string DialIn = "/dev/tty."; + if (!isMacOs || !portName.StartsWith(DialIn, StringComparison.Ordinal) || portName.Length == DialIn.Length) + { + return portName; + } + string callOut = "/dev/cu." + portName[DialIn.Length..]; + return exists(callOut) ? callOut : portName; + } + /// public int Read(byte[] buffer, int offset, int count) => _port.BaseStream.Read(buffer, offset, count); diff --git a/plugins/VelaShell.Plugin.Telnet/LocalEchoRenderer.cs b/plugins/VelaShell.Plugin.Telnet/LocalEchoRenderer.cs new file mode 100644 index 0000000..39f49ed --- /dev/null +++ b/plugins/VelaShell.Plugin.Telnet/LocalEchoRenderer.cs @@ -0,0 +1,160 @@ +namespace VelaShell.Plugin.Telnet; + +/// +/// 本地回显:把用户敲的键翻成"屏幕上该出现什么",而不是把原始按键字节原样喂回终端引擎。 +/// +/// 原样喂回的三个症状,都是"能用但看着不对": +/// +/// +/// 回车只是 CR —— 光标回到行首却不下移,对端的应答随即盖掉刚敲的那一行; +/// 退格是 DEL(0x7F)—— VT 引擎不画它,屏幕上的字删不掉; +/// 方向键是 ESC [ A 之类 —— 喂回去就是在本地真的移动光标。 +/// +/// +/// 这里做的是终端驱动在 ECHO + ICANON 下做的那部分显示:CR / LF / CR LF 一律显示成换行, +/// 退格擦掉本行上一个字符(擦不过行首,提示符不会被擦掉),控制序列与其余 C0 控制字符不显示。 +/// 线上的字节不受影响 —— 这只是显示。 +/// +/// +/// 宽字符按 UTF-8 首字节粗判(CJK、韩文、补充平面的 emoji 记两格):退格要擦几格只取决于它, +/// 判错的代价只是半个字残影,不值得为此带一张 Unicode 宽度表。 +/// +/// 状态跨调用保持(一个控制序列、一对 CR LF 都可能被切在两次写入之间),调用方须串行调用。 +/// +internal sealed class LocalEchoRenderer +{ + private const byte Cr = 0x0D; + private const byte Lf = 0x0A; + + /// 本行最多记这么多个字符的宽度;更长的行只是退格擦不回最早那部分。 + private const int MaxTrackedCells = 4096; + + private enum State + { + Text, + Escape, + ControlSequence, + SingleShift + } + + /// 本行已回显字符的显示宽度(1 或 2),退格按它擦。换行即清空。 + private readonly List _widths = []; + + private State _state; + private bool _afterCr; + + /// 把一次写入翻成要喂回终端的显示字节。 + /// 用户这次写入的字节。 + /// 要显示的字节;可能为空。 + public byte[] Render(ReadOnlySpan input) + { + var output = new List(input.Length + 8); + foreach (byte value in input) + { + switch (_state) + { + case State.Escape: + if (value == (byte)'[') + { + _state = State.ControlSequence; + continue; + } + if (value == (byte)'O') + { + _state = State.SingleShift; + continue; + } + // 单独按下的 ESC(或 Alt+键):ESC 本身不显示,这个字节照常处理。 + _state = State.Text; + break; + case State.ControlSequence: + // CSI 的参数与中间字节在 0x20–0x3F,终止字节在 0x40–0x7E。 + if (value is >= 0x40 and <= 0x7E) + { + _state = State.Text; + } + continue; + case State.SingleShift: + _state = State.Text; // ESC O x(小键盘、部分终端的方向键):x 是终止字节。 + continue; + } + RenderText(value, output); + } + return [.. output]; + } + + private void RenderText(byte value, List output) + { + bool afterCr = _afterCr; + _afterCr = false; + switch (value) + { + case 0x1B: + _state = State.Escape; + break; + case Cr: + NewLine(output); + _afterCr = true; + break; + case Lf: + if (!afterCr) + { + NewLine(output); // 裸 LF 也得回到行首,否则就是阶梯。 + } + break; + case 0x08 or 0x7F: + Erase(output); + break; + case 0x09: + output.Add(value); + Track(1); // 制表位的真实宽度不可知;按一格记,退格时最多少擦几格。 + break; + case < 0x20: + break; // Ctrl-C / Ctrl-D 之类没有字形。 + case >= 0x80 and < 0xC0: + output.Add(value); // UTF-8 续字节:属于前一个字符,不另占格。 + break; + default: + output.Add(value); + Track(value is >= 0xE3 and <= 0xED or >= 0xF0 ? (byte)2 : (byte)1); + break; + } + } + + private void NewLine(List output) + { + output.Add(Cr); + output.Add(Lf); + _widths.Clear(); + } + + private void Erase(List output) + { + if (_widths.Count == 0) + { + return; // 已在行首:别把提示符也擦了。 + } + int width = _widths[^1]; + _widths.RemoveAt(_widths.Count - 1); + for (int i = 0; i < width; i++) + { + output.Add(0x08); + } + for (int i = 0; i < width; i++) + { + output.Add((byte)' '); + } + for (int i = 0; i < width; i++) + { + output.Add(0x08); + } + } + + private void Track(byte width) + { + if (_widths.Count < MaxTrackedCells) + { + _widths.Add(width); + } + } +} diff --git a/plugins/VelaShell.Plugin.Telnet/README.md b/plugins/VelaShell.Plugin.Telnet/README.md index 327b617..dbba115 100644 --- a/plugins/VelaShell.Plugin.Telnet/README.md +++ b/plugins/VelaShell.Plugin.Telnet/README.md @@ -44,6 +44,16 @@ VT 引擎、回滚、搜索、会话日志、会话录制、ZMODEM 全部是宿 2. **子协商载荷里的 0xFF 同样要双写** —— NAWS 只在窗口宽或高**恰为 255** 时才触发。 3. **CR 改写的作用域** —— 谈成 BINARY 后一律不改写。改写只对"用户按的回车"成立, 而传输层看到的还有粘贴内容与 ZMODEM 帧,对整条出方向流改写会把它们打坏。 + 粘贴的 CRLF 被切在两次写入之间时也不会多发一个 LF(跨写入记着上一次是否以 CR 收尾)。 + +另外几条约束: + +- **对我们自己请求的确认不再应答**(RFC 1143)—— 握手里主动发过的 WILL / DO 记成"待确认", + 对端回来的 DO / WILL 是确认,DONT / WONT 是拒绝,都不回。否则每个选项都多刷一轮。 +- **子协商有上限** —— 载荷只存前 1KB(我们只处理 TERMINAL-TYPE SEND);超过 64KB 还没等到 + `IAC SE` 就当它坏了、回到数据态,不让一台固件有 bug 的设备把之后的输出全部吞掉。 +- **输出有背压** —— 读泵到终端引擎之间的通道约 1MB 封顶,满了就停读套接字, + 压力经 TCP 窗口顶回对端,而不是把对端按网速吐出的数据全部收进内存。 ## 连接表单 @@ -52,7 +62,7 @@ VT 引擎、回滚、搜索、会话日志、会话录制、ZMODEM 全部是宿 | 终端类型(TERM) | 跟随宿主设置 | 老设备可能只认 `vt100` | | 回车键发送 | CR LF | RFC 1123 §3.3.1 建议;可选 CR NUL / 裸 CR。BINARY 生效后此项不参与 | | 请求 8 位(BINARY) | 开 | 高级选项 | -| 本地回显 | 自动 | 高级选项。自动 = 对端未接管 ECHO 时本地回显,不会出现"打字看不见" | +| 本地回显 | 自动 | 高级选项。自动 = 对端未接管 ECHO 时本地回显,不会出现"打字看不见"。回显按屏幕该有的样子画:回车换行、退格擦字(不擦过行首)、方向键等控制序列不显示 | 用户名/口令两栏由 `ProtocolFeatures.NoCredentials` 收起:Telnet 的登录发生在带内 (对端打印 `login:`,用户直接在终端里敲),摆两个填了也发不出去的框只会误导。 diff --git a/plugins/VelaShell.Plugin.Telnet/TelnetNegotiator.cs b/plugins/VelaShell.Plugin.Telnet/TelnetNegotiator.cs index ad05d93..a12dde3 100644 --- a/plugins/VelaShell.Plugin.Telnet/TelnetNegotiator.cs +++ b/plugins/VelaShell.Plugin.Telnet/TelnetNegotiator.cs @@ -14,12 +14,30 @@ namespace VelaShell.Plugin.Telnet; /// 子协商载荷里的 0xFF 同样要双写 —— NAWS 只在窗口宽或高恰为 255 /// (或 65280+)时才踩到,几乎必然被漏掉。 /// 只在状态真的变化时回应 —— RFC 854 的要求。对已生效的选项再回一次 -/// WILL/DO 就是协商回环,两端能一直对着刷。 +/// WILL/DO 就是协商回环,两端能一直对着刷。我们**主动请求**过的选项还要记成"待确认" +/// (RFC 1143 的 WANTYES):对端的 DO/WILL 是对我们请求的确认,不是新请求,不再回应; +/// 对端的 DONT/WONT 是拒绝,同样不回应。 /// +/// +/// 线程:读泵调 ,写侧调 与 +/// ,界面线程读几个状态属性 —— 选项表是 , +/// 读写并发不安全,所以全部入口共用一把锁(每次持有的时间是微秒级)。 +/// /// /// 协商策略(TERM、回车模式、是否要 BINARY)。 internal sealed class TelnetNegotiator(TelnetConfig config) { + /// 子协商载荷最多保留这么多字节。我们只处理 TERMINAL-TYPE SEND(2 字节),更长的一律不关心。 + internal const int MaxStoredSubnegotiation = 1024; + + /// + /// 一段子协商超过这么多字节仍没等到 IAC SE,就当它坏了、回到数据态。 + /// 不设这道闸,一台发了 IAC SB 却永远不发 IAC SE 的设备(固件 bug) + /// 会让之后的全部输出都被当成子协商吞掉 —— 屏幕从此不动。 + /// 64KB 远大于任何正常的子协商(MUD 的 GMCP 之类 JSON 载荷也是 KB 级)。 + /// + internal const int MaxSubnegotiation = 64 * 1024; + /// 入方向解析状态。 private enum State { @@ -31,15 +49,30 @@ private enum State SubnegotiationIac } + private readonly Lock _gate = new(); + // 本端(我们 WILL 了什么)与对端(我们 DO 了什么)的启用状态。 private readonly HashSet _localEnabled = []; private readonly HashSet _remoteEnabled = []; + + // 我们主动发出、还没等到回音的请求(RFC 1143 的 WANTYES)。 + private readonly HashSet _localRequested = []; + private readonly HashSet _remoteRequested = []; + private readonly List _subnegotiation = []; + private int _subnegotiationLength; private State _state = State.Data; private byte _command; private bool _lastWasCarriageReturn; + /// + /// 上一次出方向写入以裸 CR 收尾,我们已经替它补了 LF / NUL。 + /// 下一次写入若正好以同一个字节开头(粘贴的 CRLF 恰好被切在两次写入之间),就吞掉它, + /// 否则线上会是 CR LF LF —— 多出一个空行。 + /// + private bool _outboundEndedWithCarriageReturn; + /// 当前窗口列数(NAWS 生效后每次变化都会重发)。 private int _columns = 80; @@ -47,26 +80,26 @@ private enum State private int _rows = 24; /// 对端是否已启用 ECHO(它负责回显我们的输入)。 - public bool RemoteEcho => _remoteEnabled.Contains(TelnetProtocol.OptionEcho); + public bool RemoteEcho => IsEnabled(_remoteEnabled, TelnetProtocol.OptionEcho); /// 对端是否已启用 SUPPRESS-GO-AHEAD。 - public bool RemoteSuppressGoAhead => _remoteEnabled.Contains(TelnetProtocol.OptionSuppressGoAhead); + public bool RemoteSuppressGoAhead => IsEnabled(_remoteEnabled, TelnetProtocol.OptionSuppressGoAhead); /// 出方向是否已进入 BINARY(8 位透明:不再改写回车)。 - public bool BinaryOutbound => _localEnabled.Contains(TelnetProtocol.OptionBinary); + public bool BinaryOutbound => IsEnabled(_localEnabled, TelnetProtocol.OptionBinary); /// 入方向是否已进入 BINARY(不再做 CR NUL → CR 归一)。 - public bool BinaryInbound => _remoteEnabled.Contains(TelnetProtocol.OptionBinary); + public bool BinaryInbound => IsEnabled(_remoteEnabled, TelnetProtocol.OptionBinary); /// NAWS 是否已启用(对端 DO 过)。 - public bool NawsEnabled => _localEnabled.Contains(TelnetProtocol.OptionNaws); + public bool NawsEnabled => IsEnabled(_localEnabled, TelnetProtocol.OptionNaws); /// /// 连接建立后主动发出的第一批协商。 /// /// 只发**我们真正想要**的四项(+ 可选 BINARY):TERMINAL-TYPE 与 NAWS 由我们提供, /// ECHO 与 SGA 要对端提供 —— RFC 858 明确这两项同时生效才是"逐字符回显", - /// 也就是 vim/htop 能工作的前提。 + /// 也就是 vim/htop 能工作的前提。每一项都记成"待确认",对端的应答据此识别为确认而非新请求。 /// /// /// 初始列数。 @@ -74,21 +107,24 @@ private enum State /// 要发给对端的字节。 public byte[] BuildInitialRequests(int columns, int rows) { - _columns = Normalize(columns, 80); - _rows = Normalize(rows, 24); - List output = []; - Command(output, TelnetProtocol.Will, TelnetProtocol.OptionTerminalType); - Command(output, TelnetProtocol.Will, TelnetProtocol.OptionNaws); - Command(output, TelnetProtocol.Will, TelnetProtocol.OptionSuppressGoAhead); - Command(output, TelnetProtocol.Do, TelnetProtocol.OptionSuppressGoAhead); - Command(output, TelnetProtocol.Do, TelnetProtocol.OptionEcho); - if (config.RequestBinary) + lock (_gate) { - // 按方向分别协商:我们要发 8 位透明(WILL),也要能收 8 位透明(DO)。 - Command(output, TelnetProtocol.Will, TelnetProtocol.OptionBinary); - Command(output, TelnetProtocol.Do, TelnetProtocol.OptionBinary); + _columns = Normalize(columns, 80); + _rows = Normalize(rows, 24); + List output = []; + RequestLocal(output, TelnetProtocol.OptionTerminalType); + RequestLocal(output, TelnetProtocol.OptionNaws); + RequestLocal(output, TelnetProtocol.OptionSuppressGoAhead); + RequestRemote(output, TelnetProtocol.OptionSuppressGoAhead); + RequestRemote(output, TelnetProtocol.OptionEcho); + if (config.RequestBinary) + { + // 按方向分别协商:我们要发 8 位透明(WILL),也要能收 8 位透明(DO)。 + RequestLocal(output, TelnetProtocol.OptionBinary); + RequestRemote(output, TelnetProtocol.OptionBinary); + } + return [.. output]; } - return [.. output]; } /// @@ -102,81 +138,111 @@ public void Process(ReadOnlySpan input, List data, List respon { ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(responses); - foreach (byte current in input) + lock (_gate) { - switch (_state) + foreach (byte current in input) { - case State.Data: - if (current == TelnetProtocol.Iac) - { - _state = State.Iac; - break; - } - Emit(data, current); - break; + Step(current, data, responses); + } + } + } - case State.Iac: - if (current == TelnetProtocol.Iac) - { - // IAC IAC = 一个字面的 0xFF。 - _state = State.Data; - Emit(data, TelnetProtocol.Iac); - break; - } - if (current is TelnetProtocol.Will or TelnetProtocol.Wont - or TelnetProtocol.Do or TelnetProtocol.Dont) - { - _command = current; - _state = State.Negotiate; - break; - } - if (current == TelnetProtocol.Sb) - { - _state = State.SubnegotiationStart; - break; - } - // 其余单字节命令(GA / NOP / DM…)对全屏终端没有意义,吃掉即可。 - _state = State.Data; + private void Step(byte current, List data, List responses) + { + switch (_state) + { + case State.Data: + if (current == TelnetProtocol.Iac) + { + _state = State.Iac; break; + } + Emit(data, current); + break; - case State.Negotiate: - Negotiate(_command, current, responses); + case State.Iac: + if (current == TelnetProtocol.Iac) + { + // IAC IAC = 一个字面的 0xFF。 _state = State.Data; + Emit(data, TelnetProtocol.Iac); break; - - case State.SubnegotiationStart: - _subnegotiation.Clear(); - _subnegotiation.Add(current); // 选项码 - _state = State.Subnegotiation; + } + if (current is TelnetProtocol.Will or TelnetProtocol.Wont + or TelnetProtocol.Do or TelnetProtocol.Dont) + { + _command = current; + _state = State.Negotiate; break; + } + if (current == TelnetProtocol.Sb) + { + _state = State.SubnegotiationStart; + break; + } + // 其余单字节命令(GA / NOP / DM…)对全屏终端没有意义,吃掉即可。 + _state = State.Data; + break; - case State.Subnegotiation: - if (current == TelnetProtocol.Iac) - { - _state = State.SubnegotiationIac; - break; - } - _subnegotiation.Add(current); + case State.Negotiate: + Negotiate(_command, current, responses); + _state = State.Data; + break; + + case State.SubnegotiationStart: + _subnegotiation.Clear(); + _subnegotiation.Add(current); // 选项码 + _subnegotiationLength = 1; + _state = State.Subnegotiation; + break; + + case State.Subnegotiation: + if (current == TelnetProtocol.Iac) + { + _state = State.SubnegotiationIac; break; + } + AppendSubnegotiation(current, data); + break; - case State.SubnegotiationIac: - if (current == TelnetProtocol.Iac) - { - // 载荷里的字面 0xFF(对端按规范双写过)。 - _subnegotiation.Add(TelnetProtocol.Iac); - _state = State.Subnegotiation; - break; - } - if (current == TelnetProtocol.Se) - { - HandleSubnegotiation(responses); - _state = State.Data; - break; - } - // 规范外的写法:当作子协商被打断,回到数据态重新同步。 + case State.SubnegotiationIac: + if (current == TelnetProtocol.Iac) + { + // 载荷里的字面 0xFF(对端按规范双写过)。 + _state = State.Subnegotiation; + AppendSubnegotiation(TelnetProtocol.Iac, data); + break; + } + if (current == TelnetProtocol.Se) + { + HandleSubnegotiation(responses); + _subnegotiation.Clear(); _state = State.Data; break; - } + } + // 规范外的写法:当作子协商被打断,回到数据态重新同步。 + _subnegotiation.Clear(); + _state = State.Data; + break; + } + } + + /// + /// 收一个子协商载荷字节。超过 的部分不再保存(内存有界), + /// 超过 还没结束就放弃这段子协商,当前字节起按数据处理。 + /// + private void AppendSubnegotiation(byte value, List data) + { + if (++_subnegotiationLength > MaxSubnegotiation) + { + _subnegotiation.Clear(); + _state = State.Data; + Emit(data, value); + return; + } + if (_subnegotiation.Count < MaxStoredSubnegotiation) + { + _subnegotiation.Add(value); } } @@ -187,35 +253,54 @@ public void Process(ReadOnlySpan input, List data, List respon /// 而这个方法看到的还有粘贴内容与 ZMODEM 帧 —— 对整条出方向流改写会把它们打坏。 /// BINARY 谈成时按 8 位透明原样发;没谈成才退回 NVT 的 CR 规则(那种对端本来也跑不了 ZMODEM)。 /// + /// + /// 调用方必须串行调用(会话在写锁里调):跨调用记着"上一次是否以裸 CR 收尾"。 + /// /// /// 用户数据。 /// 线上字节。 public byte[] EncodeOutbound(ReadOnlySpan data) { - List output = [with(data.Length + 8)]; - bool rewriteCarriageReturn = !BinaryOutbound && config.EnterMode != TelnetEnterMode.Cr; - for (int index = 0; index < data.Length; index++) + lock (_gate) { - byte current = data[index]; - if (current == TelnetProtocol.Iac) - { - output.Add(TelnetProtocol.Iac); - output.Add(TelnetProtocol.Iac); - continue; - } - output.Add(current); - if (!rewriteCarriageReturn || current != 0x0D) + List output = [with(data.Length + 8)]; + bool rewriteCarriageReturn = !_localEnabled.Contains(TelnetProtocol.OptionBinary) + && config.EnterMode != TelnetEnterMode.Cr; + byte filler = config.EnterMode == TelnetEnterMode.CrLf ? (byte)0x0A : (byte)0x00; + int start = 0; + if (_outboundEndedWithCarriageReturn) { - continue; + _outboundEndedWithCarriageReturn = false; + // 上一次已经替那个 CR 补过 filler:本次若正以它开头,就是同一个换行的后半截。 + if (rewriteCarriageReturn && data.Length > 0 && data[0] == filler) + { + start = 1; + } } - // 已经是 CR LF 就别再补:补了会变成两行。 - if (index + 1 < data.Length && data[index + 1] is 0x0A or 0x00) + for (int index = start; index < data.Length; index++) { - continue; + byte current = data[index]; + if (current == TelnetProtocol.Iac) + { + output.Add(TelnetProtocol.Iac); + output.Add(TelnetProtocol.Iac); + continue; + } + output.Add(current); + if (!rewriteCarriageReturn || current != 0x0D) + { + continue; + } + // 已经是 CR LF 就别再补:补了会变成两行。 + if (index + 1 < data.Length && data[index + 1] is 0x0A or 0x00) + { + continue; + } + output.Add(filler); + _outboundEndedWithCarriageReturn = index == data.Length - 1; } - output.Add(config.EnterMode == TelnetEnterMode.CrLf ? (byte)0x0A : (byte)0x00); + return [.. output]; } - return [.. output]; } /// @@ -227,12 +312,17 @@ public byte[] EncodeOutbound(ReadOnlySpan data) /// 要发送的字节;无需发送时为 null。 public byte[]? BuildWindowSize(int columns, int rows) { - int normalizedColumns = Normalize(columns, _columns); - int normalizedRows = Normalize(rows, _rows); - bool unchanged = normalizedColumns == _columns && normalizedRows == _rows; - _columns = normalizedColumns; - _rows = normalizedRows; - return !NawsEnabled || unchanged ? null : BuildWindowSizeFrame(normalizedColumns, normalizedRows); + lock (_gate) + { + int normalizedColumns = Normalize(columns, _columns); + int normalizedRows = Normalize(rows, _rows); + bool unchanged = normalizedColumns == _columns && normalizedRows == _rows; + _columns = normalizedColumns; + _rows = normalizedRows; + return !_localEnabled.Contains(TelnetProtocol.OptionNaws) || unchanged + ? null + : BuildWindowSizeFrame(normalizedColumns, normalizedRows); + } } private static byte[] BuildWindowSizeFrame(int columns, int rows) @@ -260,18 +350,24 @@ private void Negotiate(byte command, byte option, List responses) case TelnetProtocol.Will: if (WantRemote(option)) { - if (_remoteEnabled.Add(option)) + bool requested = _remoteRequested.Remove(option); + // 状态变了才回;是对我们 DO 的确认时也不回(RFC 1143),否则两端对刷。 + if (_remoteEnabled.Add(option) && !requested) { Command(responses, TelnetProtocol.Do, option); } - // 已启用:不再回应(RFC 854:状态没变就不回,否则两端对刷)。 break; } Command(responses, TelnetProtocol.Dont, option); break; - // 对端说"我不启用 x":状态变了才回 DONT。 + // 对端说"我不启用 x":拒绝我们的请求时不回,撤销已生效的选项时回 DONT。 case TelnetProtocol.Wont: + if (_remoteRequested.Remove(option)) + { + _ = _remoteEnabled.Remove(option); + break; + } if (_remoteEnabled.Remove(option)) { Command(responses, TelnetProtocol.Dont, option); @@ -282,7 +378,8 @@ private void Negotiate(byte command, byte option, List responses) case TelnetProtocol.Do: if (WantLocal(option)) { - if (_localEnabled.Add(option)) + bool requested = _localRequested.Remove(option); + if (_localEnabled.Add(option) && !requested) { Command(responses, TelnetProtocol.Will, option); } @@ -299,6 +396,11 @@ private void Negotiate(byte command, byte option, List responses) // 对端说"请你别启用 x"。 case TelnetProtocol.Dont: + if (_localRequested.Remove(option)) + { + _ = _localEnabled.Remove(option); + break; + } if (_localEnabled.Remove(option)) { Command(responses, TelnetProtocol.Wont, option); @@ -368,7 +470,7 @@ private string TerminalTypeName() /// private void Emit(List data, byte value) { - if (!BinaryInbound && _lastWasCarriageReturn && value == 0x00) + if (!_remoteEnabled.Contains(TelnetProtocol.OptionBinary) && _lastWasCarriageReturn && value == 0x00) { _lastWasCarriageReturn = false; return; @@ -377,6 +479,30 @@ private void Emit(List data, byte value) data.Add(value); } + private bool IsEnabled(HashSet options, byte option) + { + lock (_gate) + { + return options.Contains(option); + } + } + + private void RequestLocal(List output, byte option) + { + if (!_localEnabled.Contains(option) && _localRequested.Add(option)) + { + Command(output, TelnetProtocol.Will, option); + } + } + + private void RequestRemote(List output, byte option) + { + if (!_remoteEnabled.Contains(option) && _remoteRequested.Add(option)) + { + Command(output, TelnetProtocol.Do, option); + } + } + private static void AppendEscaped(List output, byte value) { output.Add(value); diff --git a/plugins/VelaShell.Plugin.Telnet/TelnetPlugin.cs b/plugins/VelaShell.Plugin.Telnet/TelnetPlugin.cs index 7bd8fe8..abffbf0 100644 --- a/plugins/VelaShell.Plugin.Telnet/TelnetPlugin.cs +++ b/plugins/VelaShell.Plugin.Telnet/TelnetPlugin.cs @@ -31,13 +31,18 @@ public Task ActivateAsync(IPluginContext context, CancellationToken cancellation _terminal = new(context); _registration = context.Protocols.Register(BuildDescriptor(context), _terminal); // 语言切换后重注册:表单标签是插件自己的文案,宿主不会替我们翻。 - context.Events.LocaleChanged += _ => Reregister(); + context.Events.LocaleChanged += OnLocaleChanged; return Task.CompletedTask; } /// public Task DeactivateAsync(CancellationToken cancellationToken) { + // 不退订的话宿主的事件表一直握着本插件实例,可收集 ALC 就卸不掉这份程序集。 + if (_context is { } context) + { + context.Events.LocaleChanged -= OnLocaleChanged; + } _registration?.Dispose(); _registration = null; _terminal = null; @@ -45,6 +50,9 @@ public Task DeactivateAsync(CancellationToken cancellationToken) return Task.CompletedTask; } + /// 语言切换:按新语言重注册。命名方法而不是 lambda —— 停用时要能退订。 + private void OnLocaleChanged(string locale) => Reregister(); + private void Reregister() { if (_context is not { } context || _terminal is not { } terminal) diff --git a/plugins/VelaShell.Plugin.Telnet/TelnetSession.cs b/plugins/VelaShell.Plugin.Telnet/TelnetSession.cs index 94eba49..1d40359 100644 --- a/plugins/VelaShell.Plugin.Telnet/TelnetSession.cs +++ b/plugins/VelaShell.Plugin.Telnet/TelnetSession.cs @@ -15,24 +15,41 @@ namespace VelaShell.Plugin.Telnet; /// (若把回显攒在旁路缓冲里,阻塞在套接字读上的读取方根本不会醒)。 /// /// +/// 通道**有上限**:对端可以按网速往外吐(cat 一个大文件),宿主的终端引擎未必跟得上。 +/// 满了就让泵停下来不读套接字,压力经 TCP 窗口顶回对端;不设上限的话,这些数据只会全部堆在内存里。 +/// +/// /// 写侧串行化():用户按键、NAWS 子协商、协商应答都是写, -/// 交织会把一个帧撕成两半 —— 对端看到的就是半个 IAC 序列。 +/// 交织会把一个帧撕成两半 —— 对端看到的就是半个 IAC 序列。编码(跨写入记着 CR 状态)与 +/// 本地回显(跨写入记着控制序列状态)也在这把锁里做,顺序才对得上。 /// /// internal sealed class TelnetSession : IProtocolTerminalSession { + /// 读泵一次最多读的字节数。 + private const int ReadChunkSize = 16384; + + /// 输出通道最多积压的块数:最坏约 64 × 16KB = 1MB。 + private const int OutputCapacity = 64; + private readonly Stream _stream; private readonly TelnetNegotiator _negotiator; private readonly TelnetConfig _config; private readonly IPluginLogger _log; + private readonly LocalEchoRenderer _echo = new(); private readonly CancellationTokenSource _lifetime = new(); private readonly SemaphoreSlim _writeGate = new(1, 1); - private readonly Channel _output = Channel.CreateUnbounded( - new UnboundedChannelOptions { SingleReader = true, SingleWriter = false }); + private readonly Channel _output = Channel.CreateBounded( + new BoundedChannelOptions(OutputCapacity) + { + SingleReader = true, + SingleWriter = false, + FullMode = BoundedChannelFullMode.Wait + }); private ReadOnlyMemory _carry; private Task? _pump; - private volatile bool _disposed; + private int _disposed; private TelnetSession(Stream stream, TelnetConfig config, IPluginLogger log) { @@ -42,6 +59,8 @@ private TelnetSession(Stream stream, TelnetConfig config, IPluginLogger log) _negotiator = new(config); } + private bool IsDisposed => Volatile.Read(ref _disposed) != 0; + /// 建立连接并发出第一批协商;端点不可达时抛 。 /// 主机名或 IP。 /// 端口。 @@ -89,9 +108,14 @@ public static async Task ConnectAsync( await stream.WriteAsync(hello, cancellationToken).ConfigureAwait(false); await stream.FlushAsync(cancellationToken).ConfigureAwait(false); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (Exception ex) { + // 取消也一样要关:连接已经建立,不关就是一条没人要的 TCP 连接一直挂着。 await session.DisposeAsync().ConfigureAwait(false); + if (ex is OperationCanceledException) + { + throw; + } throw new ProtocolConnectionException($"{host}:{port} — {ex.Message}", ex); } session._pump = Task.Run(() => session.PumpAsync(), CancellationToken.None); @@ -124,44 +148,46 @@ public async ValueTask ReadAsync(Memory buffer, CancellationToken can } /// - public async ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken cancellationToken = default) + public ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken cancellationToken = default) { - if (_disposed || data.IsEmpty) + if (IsDisposed || data.IsEmpty) { - return; + return ValueTask.CompletedTask; } - byte[] encoded = _negotiator.EncodeOutbound(data.Span); - await SendAsync(encoded, cancellationToken).ConfigureAwait(false); - - // 本地回显:对端没接管回显时,用户敲的字得由我们显示出来,否则就是"打字看不见"。 - // 回显的是**用户原始字节**,不是编码后的线上字节(那里可能刚补过 LF、双写过 0xFF)。 - if (ShouldEchoLocally()) + return new(UnderWriteGateAsync(async token => { - _ = _output.Writer.TryWrite(data.ToArray()); - } + await WriteWireAsync(_negotiator.EncodeOutbound(data.Span), token).ConfigureAwait(false); + + // 本地回显:对端没接管回显时,用户敲的字得由我们显示出来,否则就是"打字看不见"。 + // 回显的是**用户原始字节**翻成的显示内容,不是编码后的线上字节(那里可能刚补过 LF、双写过 0xFF)。 + if (ShouldEchoLocally() && _echo.Render(data.Span) is { Length: > 0 } echo) + { + await DeliverAsync(echo, token).ConfigureAwait(false); + } + }, cancellationToken)); } /// - public async ValueTask ResizeAsync(int columns, int rows, CancellationToken cancellationToken = default) + public ValueTask ResizeAsync(int columns, int rows, CancellationToken cancellationToken = default) { - if (_disposed) - { - return; - } - if (_negotiator.BuildWindowSize(columns, rows) is { Length: > 0 } frame) + if (IsDisposed) { - await SendAsync(frame, cancellationToken).ConfigureAwait(false); + return ValueTask.CompletedTask; } + // 在写锁里取帧:两次并发的尺寸变化按取帧的顺序上线,对端最后看到的就是最后一次。 + return new(UnderWriteGateAsync(token => + _negotiator.BuildWindowSize(columns, rows) is { Length: > 0 } frame + ? WriteWireAsync(frame, token) + : Task.CompletedTask, cancellationToken)); } /// public async ValueTask DisposeAsync() { - if (_disposed) + if (Interlocked.Exchange(ref _disposed, 1) != 0) { return; } - _disposed = true; await _lifetime.CancelAsync().ConfigureAwait(false); try { @@ -201,51 +227,92 @@ public async ValueTask DisposeAsync() _ => !_negotiator.RemoteEcho }; - private async Task SendAsync(byte[] payload, CancellationToken cancellationToken) + /// + /// 在写锁里执行一次写侧动作。会话正在关或已关时静默放弃:关闭与写并发是常态 + /// (用户关标签的同时还有按键、尺寸变化在路上),那时抛出的 + /// 或取消异常只会变成宿主日志里的噪声。调用方自己的令牌被取消时照常抛出。 + /// + private async Task UnderWriteGateAsync(Func action, CancellationToken cancellationToken) { - if (payload.Length == 0) - { - return; - } - using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _lifetime.Token); - await _writeGate.WaitAsync(linked.Token).ConfigureAwait(false); + CancellationTokenSource linked; try { - await _stream.WriteAsync(payload, linked.Token).ConfigureAwait(false); - await _stream.FlushAsync(linked.Token).ConfigureAwait(false); + linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _lifetime.Token); } - catch (Exception ex) when (ex is IOException or ObjectDisposedException or SocketException) + catch (ObjectDisposedException) { - // 连接已断:读侧的 EOF 才是权威结论,这里只丢弃这一次写。 - _log.Debug($"Telnet write failed: {ex.Message}"); + return; // 已关。 } - finally + using (linked) { - // Dispose 与写并发时信号量可能已释放,吞掉这一次。 try { - _ = _writeGate.Release(); + await _writeGate.WaitAsync(linked.Token).ConfigureAwait(false); } catch (ObjectDisposedException) { + return; + } + catch (OperationCanceledException) when (_lifetime.IsCancellationRequested && !cancellationToken.IsCancellationRequested) + { + return; + } + try + { + await action(linked.Token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or ObjectDisposedException or SocketException or ChannelClosedException) + { + // 连接已断:读侧的 EOF 才是权威结论,这里只丢弃这一次写。 + _log.Debug($"Telnet write failed: {ex.Message}"); + } + catch (OperationCanceledException) when (_lifetime.IsCancellationRequested && !cancellationToken.IsCancellationRequested) + { + // 会话正在关。 + } + finally + { + // Dispose 与写并发时信号量可能已释放,吞掉这一次。 + try + { + _ = _writeGate.Release(); + } + catch (ObjectDisposedException) + { + } } } } + private async Task WriteWireAsync(byte[] payload, CancellationToken cancellationToken) + { + if (payload.Length == 0) + { + return; + } + await _stream.WriteAsync(payload, cancellationToken).ConfigureAwait(false); + await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + /// 把一块显示数据交给读取方;通道满时等(而不是丢)。 + private ValueTask DeliverAsync(byte[] chunk, CancellationToken cancellationToken) => + _output.Writer.TryWrite(chunk) ? ValueTask.CompletedTask : _output.Writer.WriteAsync(chunk, cancellationToken); + /// /// 读泵:套接字 → 协商状态机 → 净数据进通道。任何异常都归一化成"结束" /// (完成通道即 EOF),掉线不该以异常形式冒到宿主的读循环里。 /// private async Task PumpAsync() { - byte[] buffer = new byte[16384]; + byte[] buffer = new byte[ReadChunkSize]; List data = []; List responses = []; try { - while (!_lifetime.IsCancellationRequested) + CancellationToken token = _lifetime.Token; + while (!token.IsCancellationRequested) { - int read = await _stream.ReadAsync(buffer, _lifetime.Token).ConfigureAwait(false); + int read = await _stream.ReadAsync(buffer, token).ConfigureAwait(false); if (read <= 0) { break; // 对端关闭。 @@ -255,16 +322,18 @@ private async Task PumpAsync() _negotiator.Process(buffer.AsSpan(0, read), data, responses); if (responses.Count > 0) { - await SendAsync([.. responses], _lifetime.Token).ConfigureAwait(false); + byte[] reply = [.. responses]; + await UnderWriteGateAsync(ct => WriteWireAsync(reply, ct), token).ConfigureAwait(false); } if (data.Count > 0) { - _ = _output.Writer.TryWrite([.. data]); + // 满了就在这里等:泵不再读套接字,TCP 窗口把压力顶回对端。 + await DeliverAsync([.. data], token).ConfigureAwait(false); } } } catch (Exception ex) when (ex is OperationCanceledException or IOException - or ObjectDisposedException or SocketException) + or ObjectDisposedException or SocketException or ChannelClosedException) { // 正常收尾路径:关标签、对端 RST、进程退出。 } diff --git a/src/VelaShell.Vnc/Audio/AudioOutput.cs b/src/VelaShell.Vnc/Audio/AudioOutput.cs index fd67cf3..cff30d0 100644 --- a/src/VelaShell.Vnc/Audio/AudioOutput.cs +++ b/src/VelaShell.Vnc/Audio/AudioOutput.cs @@ -54,6 +54,7 @@ internal sealed class NativeAudioOutput : IAudioOutput private int _queuedCount; private long _queuedBytes; private double _queuedMilliseconds; + private TaskCompletionSource _budgetChanged = NewPulse(); private readonly Action? _log; @@ -84,41 +85,63 @@ format.BitsPerSample is not (8 or 16) || data.Length % format.BlockAlign != 0) var command = new Command(Volatile.Read(ref _generation), format, data, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously), Stopwatch.GetTimestamp(), ct); - lock (_budgetGate) + return EnqueueAsync(command); + } + + private async Task EnqueueAsync(Command command) + { + while (true) { - double duration = DurationMilliseconds(command); - if (_queuedCount >= 128 || _queuedBytes + data.Length > 1024 * 1024 || - (_queuedCount > 0 && _queuedMilliseconds + duration > 2000)) + Task wait; + lock (_budgetGate) { - return Task.FromException(new IOException("VNC audio output queue capacity exceeded.")); - } + if (command.Generation != Volatile.Read(ref _generation)) + { + throw new OperationCanceledException("VNC audio playback was closed.", command.Cancellation); + } - _queuedCount++; - _queuedBytes += data.Length; - _queuedMilliseconds += duration; - command.QueueAllowance = TimeSpan.FromMilliseconds(_queuedMilliseconds + 100); - if (!_commands.Writer.TryWrite(command)) - { - ReleaseBudget(command); - command.Result!.SetException(new IOException("VNC audio output queue is closed.")); + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, nameof(NativeAudioOutput)); + double duration = DurationMilliseconds(command); + if (_queuedCount < 128 && _queuedBytes + command.Data!.Length <= 1024 * 1024 && + (_queuedCount == 0 || _queuedMilliseconds + duration <= 2000)) + { + _queuedCount++; + _queuedBytes += command.Data.Length; + _queuedMilliseconds += duration; + command._queueAllowance = TimeSpan.FromMilliseconds(_queuedMilliseconds + 100); + command._admittedAt = Stopwatch.GetTimestamp(); + if (!_commands.Writer.TryWrite(command)) + { + ReleaseBudget(command); + throw new IOException("VNC audio output queue is closed."); + } + break; + } + + wait = _budgetChanged.Task; } + + // A burst of server audio must apply backpressure instead of permanently stopping + // playback. The worker releases budget as native buffers finish. + await wait.WaitAsync(command.Cancellation).ConfigureAwait(false); } + // Keep the caller cancellable even if a system driver stalls inside a native call. Native // buffers remain owned by the worker until that call returns and cleanup is safe. - return WaitForPlaybackAsync(command); + await WaitForPlaybackAsync(command).ConfigureAwait(false); } private async Task WaitForPlaybackAsync(Command command) { try { - await command.Result!.Task.WaitAsync(_stallAllowance + command.QueueAllowance, command.Cancellation).ConfigureAwait(false); + await command.Result!.Task.WaitAsync(_stallAllowance + command._queueAllowance, command.Cancellation).ConfigureAwait(false); } catch (TimeoutException) { // The timer can expire just before the stopwatch deadline due to millisecond rounding. // Invalidate the command before the caller can unblock a stalled native operation. - Volatile.Write(ref command.TimedOut, 1); + Volatile.Write(ref command._timedOut, 1); throw; } } @@ -131,6 +154,7 @@ public void Close() } int generation = Interlocked.Increment(ref _generation); + PulseBudget(); // A full queue already wakes the worker, which also observes the generation change. _ = _commands.Writer.TryWrite(new Command(generation, default, null, null, 0, default)); } @@ -143,6 +167,7 @@ public void Dispose() } _ = Interlocked.Increment(ref _generation); + PulseBudget(); _ = _commands.Writer.TryComplete(); } @@ -155,11 +180,15 @@ private async Task RunAsync() var timing = new AudioPlayoutTiming(); double waitingMilliseconds = 0; long bufferingSince = 0; - long lastReport = 0; + long lastReport = 0, previousActivePoll = 0; + double maxPollGap = 0; + int drains = 0; + Task? readable = null; try { while (true) { + if (readable is { IsCompleted: true }) { readable = null; } while (_commands.Reader.TryRead(out Command? incoming)) { if (incoming.Result is null) @@ -184,6 +213,12 @@ private async Task RunAsync() opened = null; timing = new AudioPlayoutTiming(); } + long poll = Stopwatch.GetTimestamp(); + bool hadActive = active.Count != 0; + if (previousActivePoll != 0) + { + maxPollGap = Math.Max(maxPollGap, Stopwatch.GetElapsedTime(previousActivePoll, poll).TotalMilliseconds); + } // Reap completed buffers without draining the device. Later buffers keep playing. while (active.Count > 0 && _device.IsComplete()) { @@ -194,6 +229,7 @@ private async Task RunAsync() } if (active.Count == 0 && bufferingSince == 0) { + if (hadActive) { drains++; } bufferingSince = Stopwatch.GetTimestamp(); timing.ResetDrift(); } @@ -229,23 +265,26 @@ private async Task RunAsync() bufferingSince = Stopwatch.GetTimestamp(); CheckCancellation(next); } - if (!next.Observed) + if (!next._observed) { timing.ObserveArrival(next.EnqueuedAt * 1000.0 / Stopwatch.Frequency, DurationMilliseconds(next)); - next.Observed = true; + next._observed = true; } - if (active.Count == 0 && Stopwatch.GetElapsedTime(bufferingSince).TotalMilliseconds < timing.TargetMilliseconds) + double duration = DurationMilliseconds(next); + if (active.Count == 0 && duration < timing.TargetMilliseconds && + Stopwatch.GetElapsedTime(bufferingSince).TotalMilliseconds < timing.TargetMilliseconds) { break; } double deviceMilliseconds = _device.PendingFrames * 1000.0 / next.Format.SampleRate; - if (active.Count > 0 && deviceMilliseconds >= 120) + // Keep a successor ready for long server blocks, even with a coarse device clock. + double refillThreshold = Math.Clamp(duration + timing.TargetMilliseconds, 120, 250); + if (active.Count > 0 && deviceMilliseconds >= refillThreshold) { break; } - double duration = DurationMilliseconds(next); _ = timing.UpdateRate(deviceMilliseconds + waitingMilliseconds - duration, duration); _device.Start(timing.Resample(next.Format, next.Data)); _ = waiting.Dequeue(); @@ -256,13 +295,16 @@ private async Task RunAsync() lastReport = Stopwatch.GetTimestamp(); try { - _log($"playout; targetMs={timing.TargetMilliseconds:F1}; bufferedMs={deviceMilliseconds + waitingMilliseconds + duration:F1}; correctionPpm={timing.RateCorrection * 1000000:F0}; inFlight={active.Count}"); + _log($"playout; targetMs={timing.TargetMilliseconds:F1}; bufferedMs={deviceMilliseconds + waitingMilliseconds + duration:F1}; driftTargetMs={timing.DriftTarget(duration):F1}; correctionPpm={timing.RateCorrection * 1000000:F0}; inFlight={active.Count}; deviceBeforeWriteMs={deviceMilliseconds:F1}; drains={drains}; maxActivePollGapMs={maxPollGap:F1}; at={DateTimeOffset.Now:HH:mm:ss.fff}"); + drains = 0; + maxPollGap = 0; } catch { /* Diagnostics cannot interrupt native buffer ownership. */ } } bufferingSince = 0; submitting = null; } + previousActivePoll = active.Count == 0 ? 0 : poll; } catch (Exception error) { @@ -288,15 +330,23 @@ private async Task RunAsync() if (active.Count == 0 && waiting.Count == 0) { bufferingSince = 0; - if (!await _commands.Reader.WaitToReadAsync().ConfigureAwait(false)) + readable ??= _commands.Reader.WaitToReadAsync().AsTask(); + if (!await readable.ConfigureAwait(false)) { break; } } else { - // Only active playback needs clock checks; idle outputs sleep on the channel. - await Task.Delay(5).ConfigureAwait(false); + // A successor arriving just before the device drains should wake the worker without + // waiting for a (sometimes coarse) OS timer. Keep at most one pending channel read. + var pollDelay = Task.Delay(5); + if (waiting.Count == 0 && !_commands.Reader.Completion.IsCompleted) + { + readable ??= _commands.Reader.WaitToReadAsync().AsTask(); + await Task.WhenAny(readable, pollDelay).ConfigureAwait(false); + } + else { await pollDelay.ConfigureAwait(false); } } } } @@ -316,9 +366,20 @@ private void ReleaseBudget(Command command) _queuedCount--; _queuedBytes -= command.Data!.Length; _queuedMilliseconds -= DurationMilliseconds(command); + PulseBudget(); } } + private void PulseBudget() + { + TaskCompletionSource changed = _budgetChanged; + _budgetChanged = NewPulse(); + _ = changed.TrySetResult(); + } + + private static TaskCompletionSource NewPulse() => + new(TaskCreationOptions.RunContinuationsAsynchronously); + private void Finish(Command command, Exception? error = null) { ReleaseBudget(command); @@ -344,8 +405,8 @@ private void CheckCancellation(Command command) throw new OperationCanceledException("VNC audio playback was closed."); } - TimeSpan deadline = _stallAllowance + command.QueueAllowance; - if (Volatile.Read(ref command.TimedOut) != 0 || Stopwatch.GetElapsedTime(command.EnqueuedAt) >= deadline) + TimeSpan deadline = _stallAllowance + command._queueAllowance; + if (Volatile.Read(ref command._timedOut) != 0 || Stopwatch.GetElapsedTime(command._admittedAt) >= deadline) { throw new TimeoutException($"VNC audio device stalled for {deadline.TotalSeconds:F1} seconds."); } @@ -364,8 +425,9 @@ private void CloseDevice() private sealed record Command(int Generation, AudioFormat Format, byte[]? Data, TaskCompletionSource? Result, long EnqueuedAt, CancellationToken Cancellation) { - internal int TimedOut; - internal TimeSpan QueueAllowance; - internal bool Observed; + internal int _timedOut; + internal TimeSpan _queueAllowance; + internal long _admittedAt; + internal bool _observed; } } diff --git a/src/VelaShell.Vnc/Audio/AudioPlayoutTiming.cs b/src/VelaShell.Vnc/Audio/AudioPlayoutTiming.cs index 042e92a..2db0273 100644 --- a/src/VelaShell.Vnc/Audio/AudioPlayoutTiming.cs +++ b/src/VelaShell.Vnc/Audio/AudioPlayoutTiming.cs @@ -30,11 +30,30 @@ internal void ObserveArrival(double arrivalMilliseconds, double durationMillisec internal void ResetDrift() => _filteredError = _integral = _fractionalFrames = RateCorrection = 0; + // Occupancy is measured BEFORE the next block is submitted. Do not speed through + // the last fraction of a long server block just to reach a short startup target. + internal double DriftTarget(double durationMilliseconds) => + Math.Max(TargetMilliseconds, Math.Min(180, 0.95 * durationMilliseconds)); + internal double UpdateRate(double bufferedMilliseconds, double durationMilliseconds) { // Device-clock occupancy is filtered over seconds: packet jitter must not modulate pitch. double seconds = Math.Min(durationMilliseconds / 1000, 0.25); - double error = Math.Clamp(bufferedMilliseconds - TargetMilliseconds, -100, 100); + double target = DriftTarget(durationMilliseconds); + double error = Math.Clamp(bufferedMilliseconds - target, -100, 100); + if (bufferedMilliseconds < target / 2) + { + // A previous burst may have saturated the controller. Its positive bias must not + // keep draining an already thin reserve while the slow filter catches up. + _filteredError = Math.Min(0, _filteredError); + _integral = Math.Min(0, _integral); + } + else if (target > TargetMilliseconds && bufferedMilliseconds >= 0.98 * durationMilliseconds) + { + // At almost a whole block of reserve the two-block window cannot absorb further slowdown. + _filteredError = Math.Max(0, _filteredError); + _integral = Math.Max(0, _integral); + } _filteredError += (error - _filteredError) * (1 - Math.Exp(-seconds / 5)); _integral = Math.Clamp(_integral + _filteredError * seconds * 0.000002, -0.004, 0.004); RateCorrection = Math.Clamp(_filteredError * 0.00005 + _integral, -0.005, 0.005); diff --git a/src/VelaShell.Vnc/Audio/VncAudioPlayer.cs b/src/VelaShell.Vnc/Audio/VncAudioPlayer.cs index 842c58e..cd4cb7a 100644 --- a/src/VelaShell.Vnc/Audio/VncAudioPlayer.cs +++ b/src/VelaShell.Vnc/Audio/VncAudioPlayer.cs @@ -5,9 +5,11 @@ namespace VelaShell.Vnc.Audio; /// /// Plays the QEMU Audio stream. The receive loop only hands data over ( never blocks): a worker gathers -/// it into 40 ms buffers and keeps at most of them queued at the output, so latency stays -/// bounded. When the network delivers faster than the device plays (clock drift, a burst after a stall), the newest data -/// is dropped — QEMU itself drops audio under back-pressure. A device failure stops audio only. +/// it into 40 ms buffers and keeps at most of them queued at the output. Latency is bounded +/// in time, not just in bytes: data that waited longer than since it was received (a burst after a +/// network stall, a device that fell behind) is skipped, so playback catches up with the server instead of carrying the +/// backlog for the rest of the session. QEMU keeps capturing in real time, so late audio is never worth playing. Only when +/// the hand-over queue itself is full is the newest data dropped. A device failure stops audio only. /// internal sealed class VncAudioPlayer : IAsyncDisposable { @@ -16,13 +18,16 @@ internal sealed class VncAudioPlayer : IAsyncDisposable internal const int ChunkBytes = 44100 * 4 / 25; // 40 ms of S16 stereo: 7056 bytes, frame-aligned internal const int MaxOutstanding = 8; // 320 ms queued at the device at most + /// Received data older than this when the worker reaches it is skipped (the RDP client uses the same bound). + internal const long StaleMs = 600; private const int QueueCapacity = 256; - private const long MaxQueuedBytes = 4 * 1024 * 1024; // about 24 s of audio: a stalled device, not a backlog to keep + private const long MaxQueuedBytes = 1024 * 1024; // about 6 s: only a stalled device fills it, stale data is skipped first private readonly Func _createOutput; private readonly Action _failed; private readonly Action? _log; - private readonly Channel _queue = Channel.CreateBounded(new BoundedChannelOptions(QueueCapacity) + private readonly Func _now; + private readonly Channel<(byte[]? Data, long ReceivedAt)> _queue = Channel.CreateBounded<(byte[]?, long)>(new BoundedChannelOptions(QueueCapacity) { SingleReader = true, FullMode = BoundedChannelFullMode.Wait @@ -30,25 +35,31 @@ internal sealed class VncAudioPlayer : IAsyncDisposable private readonly CancellationTokenSource _stop = new(); private readonly Task _worker; private long _dropped; + private long _skipped; private long _queuedBytes; private int _stopped; - internal VncAudioPlayer(Func createOutput, Action failed, Action? log) + // now: test seam, a millisecond clock (default Environment.TickCount64). + internal VncAudioPlayer(Func createOutput, Action failed, Action? log, Func? now = null) { _createOutput = createOutput; _failed = failed; _log = log; + _now = now ?? (static () => Environment.TickCount64); _worker = Task.Run(RunAsync); } - /// Bytes discarded because the output fell behind. + /// Bytes discarded because the hand-over queue was full. internal long Dropped => Interlocked.Read(ref _dropped); + /// Bytes skipped because they arrived or waited too long to be played in time. + internal long Skipped => Interlocked.Read(ref _skipped); + /// Queues PCM data (frame-aligned S16 stereo). Never blocks. internal void Push(byte[] data) { if (Volatile.Read(ref _stopped) != 0 || data.Length == 0) { return; } - bool queued = Interlocked.Add(ref _queuedBytes, data.Length) <= MaxQueuedBytes && _queue.Writer.TryWrite(data); + bool queued = Interlocked.Add(ref _queuedBytes, data.Length) <= MaxQueuedBytes && _queue.Writer.TryWrite((data, _now())); if (!queued) { _ = Interlocked.Add(ref _queuedBytes, -data.Length); @@ -62,7 +73,7 @@ internal void Push(byte[] data) /// The server ended the stream: play what is gathered without waiting for a full buffer. internal void Flush() { - if (Volatile.Read(ref _stopped) == 0) { _ = _queue.Writer.TryWrite(null); } + if (Volatile.Read(ref _stopped) == 0) { _ = _queue.Writer.TryWrite((null, 0)); } } private async Task RunAsync() @@ -71,13 +82,26 @@ private async Task RunAsync() IAudioOutput? output = null; var pending = new Queue(); var gathered = new ArrayBufferWriter(ChunkBytes * 2); + long skippedRun = 0; try { - await foreach (byte[]? item in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false)) + await foreach ((byte[]? item, long receivedAt) in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false)) { if (item is not null) { _ = Interlocked.Add(ref _queuedBytes, -item.Length); + if (_now() - receivedAt > StaleMs) + { + // Catch up with the server: late audio would add its delay to everything after it. + _ = Interlocked.Add(ref _skipped, item.Length); + skippedRun += item.Length; + continue; + } + if (skippedRun != 0) + { + _log?.Invoke($"VNC audio fell behind; skipped {skippedRun * 1000 / (Format.BlockAlign * Format.SampleRate)} ms of late audio."); + skippedRun = 0; + } gathered.Write(item); } while (gathered.WrittenCount >= ChunkBytes || (item is null && gathered.WrittenCount >= Format.BlockAlign)) diff --git a/tests/VelaShell.Plugin.S3.Tests/S3PluginActivationTests.cs b/tests/VelaShell.Plugin.S3.Tests/S3PluginActivationTests.cs index b4fc8c6..9092fc2 100644 --- a/tests/VelaShell.Plugin.S3.Tests/S3PluginActivationTests.cs +++ b/tests/VelaShell.Plugin.S3.Tests/S3PluginActivationTests.cs @@ -26,6 +26,31 @@ private static async Task ActivateAsync(TestPluginContext co return context.RecordingProtocols.Registered.Single(); } + [TestMethod] + public void Deactivate_ReleasesThePluginFromTheHostEvents() + { + // 语言切换的订阅不退订,宿主的事件表就一直握着插件实例,可收集 ALC 卸不掉这份程序集。 + using TestPluginContext context = NewContext(); + WeakReference plugin = ActivateThenDeactivate(context); + + for (int i = 0; i < 5 && plugin.IsAlive; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + + Assert.IsFalse(plugin.IsAlive, "停用后插件实例仍被宿主对象引用着"); + } + + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + private static WeakReference ActivateThenDeactivate(TestPluginContext context) + { + var plugin = new S3Plugin(); + plugin.ActivateAsync(context, CancellationToken.None).GetAwaiter().GetResult(); + plugin.DeactivateAsync(CancellationToken.None).GetAwaiter().GetResult(); + return new WeakReference(plugin); + } + [TestMethod] public async Task Activate_RegistersAFileProtocolUnderThePluginId() { diff --git a/tests/VelaShell.Plugin.Serial.Tests/LocalEchoRendererTests.cs b/tests/VelaShell.Plugin.Serial.Tests/LocalEchoRendererTests.cs new file mode 100644 index 0000000..4095f96 --- /dev/null +++ b/tests/VelaShell.Plugin.Serial.Tests/LocalEchoRendererTests.cs @@ -0,0 +1,95 @@ +using System.Text; + +namespace VelaShell.Plugin.Serial.Tests; + +/// +/// 本地回显的显示规则:按键 → 屏幕上该出现的字节。期望值按字节手写。 +/// Telnet 插件里有一份相同的实现与相同的用例,改一边请同步另一边。 +/// +[TestClass] +public sealed class LocalEchoRendererTests +{ + private static string Render(LocalEchoRenderer renderer, string input) => + Encoding.UTF8.GetString(renderer.Render(Encoding.UTF8.GetBytes(input))); + + [TestMethod] + public void BareCr_IsShownAsANewLine() + { + // 只回行首不下移的话,对端的应答会盖掉刚敲的那一行。 + Assert.AreEqual("hi\r\n", Render(new(), "hi\r")); + } + + [TestMethod] + public void BareLf_IsShownAsANewLine_NotAStaircase() + { + // "回车发 LF" 模式下上线的是裸 LF:只下移不回行首就是阶梯。 + Assert.AreEqual("hi\r\n", Render(new(), "hi\n")); + } + + [TestMethod] + public void CrLf_IsOneNewLine_EvenWhenSplitAcrossWrites() + { + var renderer = new LocalEchoRenderer(); + Assert.AreEqual("\r\n", Render(renderer, "\r\n")); + Assert.AreEqual("a\r\n", Render(renderer, "a\r")); + Assert.AreEqual("b", Render(renderer, "\nb")); + } + + [TestMethod] + public void Backspace_ErasesTheLastCharacter_ButNeverThePrompt() + { + var renderer = new LocalEchoRenderer(); + // DEL(0x7F,多数终端的退格键)与 BS(0x08)都擦一格:退格、空格盖掉、再退格。 + Assert.AreEqual("ab\b \b", Render(renderer, "ab\x7f")); + Assert.AreEqual("\b \b", Render(renderer, "\b")); + // 本行敲的字已经擦完,再退格不能吃到行首前面的提示符。 + Assert.AreEqual(string.Empty, Render(renderer, "\x7f\x7f")); + } + + [TestMethod] + public void Backspace_DoesNotCrossANewLine() + { + var renderer = new LocalEchoRenderer(); + _ = Render(renderer, "abc\r"); + Assert.AreEqual(string.Empty, Render(renderer, "\x7f")); + } + + [TestMethod] + public void Backspace_ErasesBothCellsOfAWideCharacter() + { + var renderer = new LocalEchoRenderer(); + Assert.AreEqual("中", Render(renderer, "中")); + Assert.AreEqual("\b\b \b\b", Render(renderer, "\x7f")); + Assert.AreEqual("é\b \b", Render(new(), "é\x7f")); + } + + [TestMethod] + public void CursorKeys_AreNotEchoed() + { + // 方向键喂回去就是在本地真的移动光标。CSI(ESC [)与 SS3(ESC O)两种写法都要吞。 + Assert.AreEqual("ab", Render(new(), "a\x1b[Ab\x1bOD")); + Assert.AreEqual("x", Render(new(), "\x1b[1;5Cx")); + } + + [TestMethod] + public void ControlSequence_SplitAcrossWrites_IsStillSwallowed() + { + var renderer = new LocalEchoRenderer(); + Assert.AreEqual(string.Empty, Render(renderer, "\x1b[")); + Assert.AreEqual("z", Render(renderer, "Az")); + } + + [TestMethod] + public void LoneEscape_DoesNotEatTheNextCharacter() + { + // vi 用户按一下 ESC 再敲 i:ESC 本身不显示,i 必须显示。 + Assert.AreEqual("i", Render(new(), "\x1bi")); + } + + [TestMethod] + public void OtherControlCharacters_HaveNoGlyph() + { + Assert.AreEqual("ab", Render(new(), "a\u0003\u0004b")); + Assert.AreEqual("a\tb", Render(new(), "a\tb")); + } +} diff --git a/tests/VelaShell.Plugin.Serial.Tests/SerialLineDisciplineTests.cs b/tests/VelaShell.Plugin.Serial.Tests/SerialLineDisciplineTests.cs index 061d5e3..94f16d0 100644 --- a/tests/VelaShell.Plugin.Serial.Tests/SerialLineDisciplineTests.cs +++ b/tests/VelaShell.Plugin.Serial.Tests/SerialLineDisciplineTests.cs @@ -180,23 +180,43 @@ public void Transmit_Lf_ReplacesCrAndCollapsesCrLf() Assert.AreSequenceEqual([(byte)'a', Lf], discipline.Transmit("a\r\n"u8.ToArray()).ToArray()); } - // ── 本地回显 ──────────────────────────────────────────────────────────── + [TestMethod] + public void Transmit_CrLf_DoesNotDoubleACrLfSplitAcrossWrites() + { + // 宿主分块写入一段粘贴时,CRLF 可能正好切在两块之间:前一块的 CR 已经发成 CR LF, + // 后一块开头那个 LF 是同一个换行的后半截,再发就多出一个空行。 + var discipline = new SerialLineDiscipline(Config(enterMode: SerialEnterMode.CrLf)); + + byte[] first = discipline.Transmit("a\r"u8.ToArray()).ToArray(); + byte[] second = discipline.Transmit("\nb"u8.ToArray()).ToArray(); + + Assert.AreSequenceEqual([(byte)'a', Cr, Lf], first); + Assert.AreSequenceEqual([(byte)'b'], second); + } [TestMethod] - public void BuildEcho_TurnsABareCrIntoCrLfSoTheCursorAdvances() + public void Transmit_Lf_DoesNotDoubleACrLfSplitAcrossWrites() { - // 屏幕上的"回车"必须同时回行首并下移;只回不移的话用户敲的下一行会盖住上一行。 - byte[] echo = SerialLineDiscipline.BuildEcho("hi\r"u8.ToArray()).ToArray(); + var discipline = new SerialLineDiscipline(Config(enterMode: SerialEnterMode.Lf)); + + byte[] first = discipline.Transmit("a\r"u8.ToArray()).ToArray(); + byte[] second = discipline.Transmit("\nb"u8.ToArray()).ToArray(); - Assert.AreSequenceEqual([(byte)'h', (byte)'i', Cr, Lf], echo); + Assert.AreSequenceEqual([(byte)'a', Lf], first); + Assert.AreSequenceEqual([(byte)'b'], second); } [TestMethod] - public void BuildEcho_LeavesAnExistingCrLfAlone() + public void Transmit_OnlySwallowsTheLfImmediatelyAfterASplitCr() { - byte[] echo = SerialLineDiscipline.BuildEcho("\r\n"u8.ToArray()).ToArray(); + // 前一块不是以 CR 收尾时,下一块开头的 LF 是真的换行,必须照发。 + var discipline = new SerialLineDiscipline(Config(enterMode: SerialEnterMode.CrLf)); + + _ = discipline.Transmit("a\r"u8.ToArray()); + _ = discipline.Transmit("b"u8.ToArray()); + byte[] third = discipline.Transmit("\n"u8.ToArray()).ToArray(); - Assert.AreSequenceEqual([Cr, Lf], echo); + Assert.AreSequenceEqual([Lf], third); } [TestMethod] diff --git a/tests/VelaShell.Plugin.Serial.Tests/SerialPluginActivationTests.cs b/tests/VelaShell.Plugin.Serial.Tests/SerialPluginActivationTests.cs index cb1b6a0..94ce1ee 100644 --- a/tests/VelaShell.Plugin.Serial.Tests/SerialPluginActivationTests.cs +++ b/tests/VelaShell.Plugin.Serial.Tests/SerialPluginActivationTests.cs @@ -186,6 +186,58 @@ public async Task Connect_WithoutADeviceName_SaysSoInPlainLanguage() Assert.Contains("串口设备", error.Message); } + [TestMethod] + public async Task Connect_CanBeCancelledWhileTheOpenHangs_AndTheLateOpenIsClosed() + { + // SerialPort.Open 是阻塞调用(设备不在场的蓝牙 COM 口能卡十几秒),中途打断不了: + // 取消必须立刻生效,而那次迟到的打开在返回后由我们关掉,不能占着端口。 + using TestPluginContext context = NewContext(); + using var release = new ManualResetEventSlim(); + var port = new FakeSerialPort(); + var terminal = new SerialTerminal(context, new SerialSessionRegistry(), _ => + { + release.Wait(TimeSpan.FromSeconds(10)); + return port; + }); + using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); + + _ = await Assert.ThrowsAsync( + () => terminal.ConnectAsync(new() { Host = "COM9", Port = 0 }, new("xterm-256color", 80, 24), cancel.Token)); + Assert.IsFalse(port.IsDisposed); + + release.Set(); + for (int i = 0; i < 200 && !port.IsDisposed; i++) + { + await Task.Delay(25); + } + Assert.IsTrue(port.IsDisposed, "取消之后才打开成功的端口必须被关掉"); + } + + [TestMethod] + public void Deactivate_ReleasesThePluginFromTheHostEvents() + { + // 语言切换的订阅不退订,宿主的事件表就一直握着插件实例,可收集 ALC 卸不掉这份程序集。 + using TestPluginContext context = NewContext(); + WeakReference plugin = ActivateThenDeactivate(context); + + for (int i = 0; i < 5 && plugin.IsAlive; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + + Assert.IsFalse(plugin.IsAlive, "停用后插件实例仍被宿主对象引用着"); + } + + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + private static WeakReference ActivateThenDeactivate(TestPluginContext context) + { + var plugin = new SerialPlugin(); + plugin.ActivateAsync(context, CancellationToken.None).GetAwaiter().GetResult(); + plugin.DeactivateAsync(CancellationToken.None).GetAwaiter().GetResult(); + return new WeakReference(plugin); + } + [TestMethod] public async Task Deactivate_RemovesEverythingItRegistered() { diff --git a/tests/VelaShell.Plugin.Serial.Tests/SerialPortEnumeratorTests.cs b/tests/VelaShell.Plugin.Serial.Tests/SerialPortEnumeratorTests.cs index f0f8217..879da91 100644 --- a/tests/VelaShell.Plugin.Serial.Tests/SerialPortEnumeratorTests.cs +++ b/tests/VelaShell.Plugin.Serial.Tests/SerialPortEnumeratorTests.cs @@ -112,4 +112,23 @@ public void Label_FallsBackToThePortNameWhenThereIsNoDescription() Assert.AreEqual("COM3", new SerialPortInfo("COM3", string.Empty).Label); Assert.AreEqual("CH340 (COM3)", new SerialPortInfo("COM3", "CH340").Label); } + + [TestMethod] + public void PreferCallOutDevice_SwapsAMacDialInDeviceForItsCallOutTwin() + { + // /dev/tty.* 打开时会一直等 DCD 载波:手输或旧配置里的 tty.* 换成同一硬件的 cu.*。 + Assert.AreEqual("/dev/cu.usbserial-A50285BI", + SystemSerialPortHandle.PreferCallOutDevice("/dev/tty.usbserial-A50285BI", isMacOs: true, static _ => true)); + } + + [TestMethod] + public void PreferCallOutDevice_LeavesEverythingElseAlone() + { + Assert.AreEqual("/dev/tty.usbserial", SystemSerialPortHandle.PreferCallOutDevice("/dev/tty.usbserial", isMacOs: true, static _ => false), + "没有对应的 cu.* 时保持原样"); + Assert.AreEqual("/dev/tty.usbserial", SystemSerialPortHandle.PreferCallOutDevice("/dev/tty.usbserial", isMacOs: false, static _ => true), + "只有 macOS 有 dial-in / call-out 之分"); + Assert.AreEqual("/dev/ttyUSB0", SystemSerialPortHandle.PreferCallOutDevice("/dev/ttyUSB0", isMacOs: true, static _ => true)); + Assert.AreEqual("COM3", SystemSerialPortHandle.PreferCallOutDevice("COM3", isMacOs: true, static _ => true)); + } } diff --git a/tests/VelaShell.Plugin.Serial.Tests/SerialSessionTests.cs b/tests/VelaShell.Plugin.Serial.Tests/SerialSessionTests.cs index 1cc40e2..212b8fe 100644 --- a/tests/VelaShell.Plugin.Serial.Tests/SerialSessionTests.cs +++ b/tests/VelaShell.Plugin.Serial.Tests/SerialSessionTests.cs @@ -322,4 +322,136 @@ public async Task Write_RaisesActivitySoCommandsCanFindTheSession() Assert.AreSame(session, seen); } + + // ── 本地回显的显示 ────────────────────────────────────────────────────── + + [TestMethod] + public async Task Write_LfMode_EchoesANewLine_NotAStaircase() + { + // "回车发 LF" 时上线的是裸 LF;原样回显只下移不回行首,每敲一行就往右挪一截。 + var port = new FakeSerialPort(); + await using SerialSession session = Open(port, Config(SerialEnterMode.Lf, localEcho: true)); + + await session.WriteAsync("AT\r"u8.ToArray(), CancellationToken.None); + byte[] echoed = await ReadExactAsync(session, 4); + + Assert.AreSequenceEqual("AT\r\n"u8.ToArray(), echoed); + Assert.AreSequenceEqual("AT\n"u8.ToArray(), port.Written); + } + + [TestMethod] + public async Task Write_EchoesBackspaceAsAnErase() + { + var port = new FakeSerialPort(); + await using SerialSession session = Open(port, Config(localEcho: true)); + + await session.WriteAsync("ab\x7f"u8.ToArray(), CancellationToken.None); + byte[] echoed = await ReadExactAsync(session, 5); + + Assert.AreSequenceEqual("ab\b \b"u8.ToArray(), echoed); + Assert.AreSequenceEqual("ab\x7f"u8.ToArray(), port.Written, "线上照发 DEL,擦字只是显示"); + } + + // ── 发送节流 ──────────────────────────────────────────────────────────── + + [TestMethod] + public async Task PacedWrite_NeverRunsOnTheCallersThread() + { + // 只设了行间隔时,以前的第一次 Task.Delay(0) 会同步完成:整行的阻塞写跑在调用方(可能是界面线程)上。 + var port = new ThreadRecordingPort(); + SerialConfig config = Config() with { TxDelayPerLine = TimeSpan.FromMilliseconds(5) }; + await using var session = SerialSession.Connect(config, new CollectingLogger(), _ => port); + int caller = Environment.CurrentManagedThreadId; + + await session.WriteAsync("ab\r"u8.ToArray(), CancellationToken.None); + + Assert.AreSequenceEqual("ab\r"u8.ToArray(), port.Inner.Written); + Assert.DoesNotContain(caller, port.WriterThreads); + } + + [TestMethod] + public async Task Dispose_StopsAPacedWriteInProgress() + { + // 50ms/字节 × 100 字节 = 5 秒。关标签不能等它写完,也不能让关闭路径抛异常。 + var port = new FakeSerialPort(); + SerialSession session = Open(port, Config(delayPerByteMs: 50)); + Task writing = session.WriteAsync(new byte[100], CancellationToken.None).AsTask(); + await Task.Delay(200); + + await session.DisposeAsync(); + await writing.WaitAsync(TimeSpan.FromSeconds(2)); + + Assert.IsLessThan(100, port.Written.Length); + } + + [TestMethod] + [DataRow("a\r\nb", 1, false, DisplayName = "CR followed by LF")] + [DataRow("a\r\nb", 2, true, DisplayName = "LF after CR")] + [DataRow("a\rb", 1, true, DisplayName = "bare CR")] + [DataRow("a\r", 1, true, DisplayName = "CR at the end")] + [DataRow("a\nb", 1, true, DisplayName = "bare LF")] + [DataRow("ab", 0, false, DisplayName = "text")] + public void EndsLine_CountsCrLfAsOneLine(string text, int index, bool expected) + { + // CR LF 只算一行:"回车发 CR LF" 时每行只等一次行间隔。 + Assert.AreEqual(expected, SerialSession.EndsLine(Encoding.ASCII.GetBytes(text), index)); + } + + [TestMethod] + public void PacingWait_IsFinerThanTheSystemTimer() + { + // Task.Delay(1ms) 在 Windows 上实际约 15.6ms:十次就是 150ms 以上。上界放宽到 100ms, + // 只钉"不是定时器粒度",不在繁忙的 CI 上赌精确值。 + var clock = System.Diagnostics.Stopwatch.StartNew(); + for (int i = 0; i < 10; i++) + { + SerialSession.PacingWait(TimeSpan.FromMilliseconds(2), CancellationToken.None); + } + clock.Stop(); + + Assert.IsGreaterThanOrEqualTo(20L, clock.ElapsedMilliseconds); + Assert.IsLessThan(100L, clock.ElapsedMilliseconds); + } + + [TestMethod] + public void PacingWait_WakesUpWhenCancelled() + { + using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); + var clock = System.Diagnostics.Stopwatch.StartNew(); + + _ = Assert.ThrowsExactly( + () => SerialSession.PacingWait(TimeSpan.FromSeconds(30), cancel.Token)); + + Assert.IsLessThan(5000L, clock.ElapsedMilliseconds); + } + + /// 记下每次写发生在哪条线程上的端口。 + private sealed class ThreadRecordingPort : ISerialPortHandle + { + private readonly System.Collections.Concurrent.ConcurrentBag _threads = []; + + public FakeSerialPort Inner { get; } = new(); + + public int[] WriterThreads => [.. _threads]; + + public string PortName => Inner.PortName; + + public bool CanControlRts => Inner.CanControlRts; + + public bool DtrEnable { get => Inner.DtrEnable; set => Inner.DtrEnable = value; } + + public bool RtsEnable { get => Inner.RtsEnable; set => Inner.RtsEnable = value; } + + public int Read(byte[] buffer, int offset, int count) => Inner.Read(buffer, offset, count); + + public void Write(byte[] buffer, int offset, int count) + { + _threads.Add(Environment.CurrentManagedThreadId); + Inner.Write(buffer, offset, count); + } + + public void SetBreak(bool on) => Inner.SetBreak(on); + + public void Dispose() => Inner.Dispose(); + } } diff --git a/tests/VelaShell.Plugin.Telnet.Tests/LocalEchoRendererTests.cs b/tests/VelaShell.Plugin.Telnet.Tests/LocalEchoRendererTests.cs new file mode 100644 index 0000000..e33b494 --- /dev/null +++ b/tests/VelaShell.Plugin.Telnet.Tests/LocalEchoRendererTests.cs @@ -0,0 +1,95 @@ +using System.Text; + +namespace VelaShell.Plugin.Telnet.Tests; + +/// +/// 本地回显的显示规则:按键 → 屏幕上该出现的字节。期望值按字节手写。 +/// Serial 插件里有一份相同的实现与相同的用例,改一边请同步另一边。 +/// +[TestClass] +public sealed class LocalEchoRendererTests +{ + private static string Render(LocalEchoRenderer renderer, string input) => + Encoding.UTF8.GetString(renderer.Render(Encoding.UTF8.GetBytes(input))); + + [TestMethod] + public void BareCr_IsShownAsANewLine() + { + // 只回行首不下移的话,对端的应答会盖掉刚敲的那一行。 + Assert.AreEqual("hi\r\n", Render(new(), "hi\r")); + } + + [TestMethod] + public void BareLf_IsShownAsANewLine_NotAStaircase() + { + // "回车发 LF" 模式下上线的是裸 LF:只下移不回行首就是阶梯。 + Assert.AreEqual("hi\r\n", Render(new(), "hi\n")); + } + + [TestMethod] + public void CrLf_IsOneNewLine_EvenWhenSplitAcrossWrites() + { + var renderer = new LocalEchoRenderer(); + Assert.AreEqual("\r\n", Render(renderer, "\r\n")); + Assert.AreEqual("a\r\n", Render(renderer, "a\r")); + Assert.AreEqual("b", Render(renderer, "\nb")); + } + + [TestMethod] + public void Backspace_ErasesTheLastCharacter_ButNeverThePrompt() + { + var renderer = new LocalEchoRenderer(); + // DEL(0x7F,多数终端的退格键)与 BS(0x08)都擦一格:退格、空格盖掉、再退格。 + Assert.AreEqual("ab\b \b", Render(renderer, "ab\x7f")); + Assert.AreEqual("\b \b", Render(renderer, "\b")); + // 本行敲的字已经擦完,再退格不能吃到行首前面的提示符。 + Assert.AreEqual(string.Empty, Render(renderer, "\x7f\x7f")); + } + + [TestMethod] + public void Backspace_DoesNotCrossANewLine() + { + var renderer = new LocalEchoRenderer(); + _ = Render(renderer, "abc\r"); + Assert.AreEqual(string.Empty, Render(renderer, "\x7f")); + } + + [TestMethod] + public void Backspace_ErasesBothCellsOfAWideCharacter() + { + var renderer = new LocalEchoRenderer(); + Assert.AreEqual("中", Render(renderer, "中")); + Assert.AreEqual("\b\b \b\b", Render(renderer, "\x7f")); + Assert.AreEqual("é\b \b", Render(new(), "é\x7f")); + } + + [TestMethod] + public void CursorKeys_AreNotEchoed() + { + // 方向键喂回去就是在本地真的移动光标。CSI(ESC [)与 SS3(ESC O)两种写法都要吞。 + Assert.AreEqual("ab", Render(new(), "a\x1b[Ab\x1bOD")); + Assert.AreEqual("x", Render(new(), "\x1b[1;5Cx")); + } + + [TestMethod] + public void ControlSequence_SplitAcrossWrites_IsStillSwallowed() + { + var renderer = new LocalEchoRenderer(); + Assert.AreEqual(string.Empty, Render(renderer, "\x1b[")); + Assert.AreEqual("z", Render(renderer, "Az")); + } + + [TestMethod] + public void LoneEscape_DoesNotEatTheNextCharacter() + { + // vi 用户按一下 ESC 再敲 i:ESC 本身不显示,i 必须显示。 + Assert.AreEqual("i", Render(new(), "\x1bi")); + } + + [TestMethod] + public void OtherControlCharacters_HaveNoGlyph() + { + Assert.AreEqual("ab", Render(new(), "a\u0003\u0004b")); + Assert.AreEqual("a\tb", Render(new(), "a\tb")); + } +} diff --git a/tests/VelaShell.Plugin.Telnet.Tests/TelnetNegotiatorTests.cs b/tests/VelaShell.Plugin.Telnet.Tests/TelnetNegotiatorTests.cs index e001598..8909dff 100644 --- a/tests/VelaShell.Plugin.Telnet.Tests/TelnetNegotiatorTests.cs +++ b/tests/VelaShell.Plugin.Telnet.Tests/TelnetNegotiatorTests.cs @@ -112,17 +112,71 @@ public void DoEcho_IsRefused_BecauseEchoingIsTheServersJob() } [TestMethod] - public void DoNaws_AnswersWillAndImmediatelyReportsTheCurrentSize() + public void DoNaws_AfterOurWill_IsAnAcknowledgement_AndImmediatelyReportsTheCurrentSize() { // NAWS 启用后不立刻上报,对端会一直按 80x24 画,直到用户碰巧拉一下窗口。 + // 这个 DO 是对我们握手里 WILL NAWS 的确认(RFC 1143),不是新请求:不再回 WILL。 TelnetNegotiator negotiator = Create(); _ = negotiator.BuildInitialRequests(120, 32); (_, byte[] responses) = Process(negotiator, Iac, Do, 31); Assert.AreSequenceEqual( - new byte[] { Iac, Will, 31, Iac, Sb, 31, 0, 120, 0, 32, Iac, Se }, responses); + new byte[] { Iac, Sb, 31, 0, 120, 0, 32, Iac, Se }, responses); Assert.IsTrue(negotiator.NawsEnabled); } + [TestMethod] + public void DoNaws_Unsolicited_AnswersWillAndReportsTheSize() + { + // 对端先开口(我们还没 WILL 过):这才是一个请求,要回 WILL。 + (_, byte[] responses) = Process(Create(), Iac, Do, 31); + Assert.AreSequenceEqual( + new byte[] { Iac, Will, 31, Iac, Sb, 31, 0, 80, 0, 24, Iac, Se }, responses); + } + + [TestMethod] + public void AcknowledgementsOfOurRequests_AreNotAnsweredAgain() + { + // RFC 1143:握手里的 WILL / DO 得到对端的 DO / WILL 是确认。再回一次虽然合规的对端会忽略, + // 但不合规的设备会再确认一次,两边就多刷一轮 —— 而且每一条都是线上的噪声。 + TelnetNegotiator negotiator = Create(); + _ = negotiator.BuildInitialRequests(80, 24); + (_, byte[] responses) = Process(negotiator, + Iac, Will, 1, Iac, Will, 3, Iac, Will, 0, // 对端确认 ECHO / SGA / BINARY + Iac, Do, 24, Iac, Do, 3, Iac, Do, 0); // 对端确认 TERMINAL-TYPE / SGA / BINARY + Assert.IsEmpty(responses); + Assert.IsTrue(negotiator.RemoteEcho); + Assert.IsTrue(negotiator.RemoteSuppressGoAhead); + Assert.IsTrue(negotiator.BinaryOutbound); + Assert.IsTrue(negotiator.BinaryInbound); + } + + [TestMethod] + public void RefusalOfOurRequest_IsNotAnswered() + { + // 对端拒绝我们的请求时选项本来就没开:状态没变,不回应。 + TelnetNegotiator negotiator = Create(); + _ = negotiator.BuildInitialRequests(80, 24); + (_, byte[] responses) = Process(negotiator, Iac, Wont, 1, Iac, Dont, 0); + Assert.IsEmpty(responses); + Assert.IsFalse(negotiator.RemoteEcho); + Assert.IsFalse(negotiator.BinaryOutbound); + } + + [TestMethod] + public void RemoteEcho_CanBeTurnedOffAndOnAgainAfterTheHandshake() + { + // 典型的口令提示:对端 WILL ECHO(由它"回显",实际不回 = 隐藏口令),输完再 WONT ECHO。 + // 握手之后的这些都是新请求,必须照常应答。 + TelnetNegotiator negotiator = Create(); + _ = negotiator.BuildInitialRequests(80, 24); + _ = Process(negotiator, Iac, Will, 1); + (_, byte[] off) = Process(negotiator, Iac, Wont, 1); + (_, byte[] on) = Process(negotiator, Iac, Will, 1); + Assert.AreSequenceEqual(new byte[] { Iac, Dont, 1 }, off); + Assert.AreSequenceEqual(new byte[] { Iac, Do, 1 }, on); + Assert.IsTrue(negotiator.RemoteEcho); + } + [TestMethod] public void Naws_DoublesPayloadBytesThatEqual255() { @@ -168,6 +222,39 @@ public void Subnegotiation_WithEscapedPayload_IsParsedAndDoesNotLeakIntoData() Assert.AreSequenceEqual("k"u8.ToArray(), data); } + [TestMethod] + public void Subnegotiation_ThatNeverEnds_IsAbandoned_SoOutputIsNotSwallowedForever() + { + // 发了 IAC SB 却永远不发 IAC SE 的设备(固件 bug):不设上限的话之后的全部输出都被当成 + // 子协商吞掉,屏幕从此不动,内存一直涨。 + TelnetNegotiator negotiator = Create(); + _ = Process(negotiator, Iac, Sb, 24); + _ = Process(negotiator, [.. Enumerable.Repeat((byte)'x', TelnetNegotiator.MaxSubnegotiation)]); + (byte[] data, _) = Process(negotiator, "hello"u8.ToArray()); + Assert.AreSequenceEqual("hello"u8.ToArray(), data); + } + + [TestMethod] + public void Subnegotiation_ThatIsLargeButTerminated_DoesNotLeakIntoData() + { + // 超过保存上限的载荷不再存,但仍要找到它的 IAC SE —— 后面的数据一个字节都不能少。 + TelnetNegotiator negotiator = Create(); + byte[] large = [Iac, Sb, 201, .. Enumerable.Repeat((byte)'j', TelnetNegotiator.MaxStoredSubnegotiation * 4), Iac, Se, (byte)'k']; + (byte[] data, byte[] responses) = Process(negotiator, large); + Assert.AreSequenceEqual("k"u8.ToArray(), data); + Assert.IsEmpty(responses); + } + + [TestMethod] + public void EncodeOutbound_CrLfSplitAcrossWrites_IsNotDoubled() + { + // 粘贴的 CRLF 恰好被切在两次写入之间:前一次已经替裸 CR 补了 LF,后一次开头的 LF 要吞掉。 + TelnetNegotiator negotiator = Create(binary: false); + Assert.AreSequenceEqual("a\r\n"u8.ToArray(), negotiator.EncodeOutbound("a\r"u8)); + Assert.AreSequenceEqual("b"u8.ToArray(), negotiator.EncodeOutbound("\nb"u8)); + Assert.AreSequenceEqual("\n"u8.ToArray(), negotiator.EncodeOutbound("\n"u8), "只吞紧跟在那个 CR 后面的一个 LF"); + } + [TestMethod] public void EncodeOutbound_EscapesIac_AndAppendsLineFeedAfterBareCarriageReturn() { diff --git a/tests/VelaShell.Plugin.Telnet.Tests/TelnetPluginActivationTests.cs b/tests/VelaShell.Plugin.Telnet.Tests/TelnetPluginActivationTests.cs index eeab3ff..1404dbe 100644 --- a/tests/VelaShell.Plugin.Telnet.Tests/TelnetPluginActivationTests.cs +++ b/tests/VelaShell.Plugin.Telnet.Tests/TelnetPluginActivationTests.cs @@ -26,6 +26,31 @@ private static async Task ActivateAsync(TestPluginContext co return context.RecordingProtocols.Registered.Single(); } + [TestMethod] + public void Deactivate_ReleasesThePluginFromTheHostEvents() + { + // 语言切换的订阅不退订,宿主的事件表就一直握着插件实例,可收集 ALC 卸不掉这份程序集。 + using TestPluginContext context = NewContext(); + WeakReference plugin = ActivateThenDeactivate(context); + + for (int i = 0; i < 5 && plugin.IsAlive; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + + Assert.IsFalse(plugin.IsAlive, "停用后插件实例仍被宿主对象引用着"); + } + + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + private static WeakReference ActivateThenDeactivate(TestPluginContext context) + { + var plugin = new TelnetPlugin(); + plugin.ActivateAsync(context, CancellationToken.None).GetAwaiter().GetResult(); + plugin.DeactivateAsync(CancellationToken.None).GetAwaiter().GetResult(); + return new WeakReference(plugin); + } + [TestMethod] public async Task Activate_RegistersATerminalProtocolUnderThePluginId() { diff --git a/tests/VelaShell.Plugin.Telnet.Tests/TelnetSessionTests.cs b/tests/VelaShell.Plugin.Telnet.Tests/TelnetSessionTests.cs index 11be6eb..0b2d215 100644 --- a/tests/VelaShell.Plugin.Telnet.Tests/TelnetSessionTests.cs +++ b/tests/VelaShell.Plugin.Telnet.Tests/TelnetSessionTests.cs @@ -136,11 +136,12 @@ public async ValueTask DisposeAsync() private static async Task ConnectAsync( LoopbackServer server, - Dictionary? settings = null) + Dictionary? settings = null, + Func? network = null) { var context = new TestPluginContext { PluginId = "velashell.telnet" }; // 宿主的出站拨号在测试里就是一条真实的环回连接:会话行为照旧跑在真实 TCP 上。 - context.FakeNetwork.Handler = static (host, port) => new TcpClient(host, port) { NoDelay = true }.GetStream(); + context.FakeNetwork.Handler = network ?? (static (host, port) => new TcpClient(host, port) { NoDelay = true }.GetStream()); var terminal = new TelnetTerminal(context); var request = new ProtocolConnectRequest { @@ -232,12 +233,12 @@ public async Task Write_AfterServerTakesOverEcho_DoesNotEchoLocally() // 对端 WILL ECHO 之后本地不能再回显,否则用户看到的是双份字符("llss")。 // - // 等**第二份** IAC DO ECHO:第一份在握手里(BuildInitialRequests 主动请求过对端回显), - // 只等第一份等于什么都没等,写入就成了在赌"读泵已经处理完 WILL"。第二份是对这次 WILL - // 的应答,而应答是在 Negotiate() 里 _remoteEnabled.Add(ECHO) **之后**才生成的 —— - // 所以它到达即意味着 RemoteEcho 已翻转、本地回显已关,下面的写入不会再被本地回显。 - await server.SendAsync(255, 251, 1); - await server.WaitForBytesAsync([255, 253, 1], "对端 WILL ECHO 后应回 DO ECHO", occurrences: 2); + // 这个 WILL 是对握手里 DO ECHO 的确认(RFC 1143),客户端不会再应答,没有线上字节可等。 + // 改用紧跟在它后面的一个数据字节同步:泵对同一块数据先做协商、再把净数据交出去, + // 读到 'Z' 即意味着 RemoteEcho 已翻转、本地回显已关,下面的写入不会再被本地回显。 + await server.SendAsync(255, 251, 1, (byte)'Z'); + string marker = await ReadTextAsync(session, 1); + Assert.AreEqual("Z", marker); await session.WriteAsync(Encoding.ASCII.GetBytes("ls"), TestContext.CancellationToken); await server.SendAsync("X"u8.ToArray()); @@ -273,4 +274,183 @@ public async Task EnterKey_IsRewrittenPerSettings_WhenBinaryIsRefused() await session.WriteAsync("\r"u8.ToArray(), TestContext.CancellationToken); await server.WaitForBytesAsync([0x0D, 0x00], "非 BINARY + CR NUL 模式下回车应发 CR NUL"); } + + [TestMethod] + public async Task LocalEcho_ShowsEnterAsANewLine_AndBackspaceAsAnErase() + { + // 原样回显的话:回车只回行首(对端的应答随即盖掉这一行),退格(DEL)屏幕上什么都不发生。 + await using var server = new LoopbackServer(); + await using IProtocolTerminalSession session = await ConnectAsync(server); + await server.WaitForClientAsync(); + + await session.WriteAsync("ab\x7f\r"u8.ToArray(), TestContext.CancellationToken); + + string echoed = await ReadTextAsync(session, 7); + Assert.AreEqual("ab\b \b\r\n", echoed); + await server.WaitForBytesAsync("ab\x7f\r"u8.ToArray(), "线上照发用户的原始按键"); + } + + [TestMethod] + public async Task Output_AppliesBackpressure_InsteadOfBufferingWithoutLimit() + { + // 对端按网速吐数据、宿主暂时不读:泵必须停下来,让 TCP 窗口把压力顶回对端, + // 而不是把几十 MB 全部收进内存。 + // + // 量的是**会话从套接字读走了多少**,不是"对端的写完成没有":Windows 环回上一次大块 send + // 在接收方停读之后照样会完成(实测 64MB),拿它当信号在 Windows 上永远是假阴性。 + const int total = 32 * 1024 * 1024; + await using var server = new LoopbackServer(); + CountingStream? counted = null; + await using IProtocolTerminalSession session = await ConnectAsync(server, network: (host, port) => + counted = new CountingStream(new TcpClient(host, port) { NoDelay = true }.GetStream())); + await server.WaitForClientAsync(); + + Task sending = server.SendAsync([.. Enumerable.Repeat((byte)'a', total)]); + await Task.Delay(1000, TestContext.CancellationToken); + long readBeforeDraining = counted!.BytesRead; + // 输出通道上限约 1MB,再加上泵手里的一块:远小于 32MB。 + Assert.IsLessThan(4L * 1024 * 1024, readBeforeDraining, "宿主不读时,会话不该继续从套接字往内存里收"); + + byte[] buffer = new byte[64 * 1024]; + long received = 0; + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + while (received < total) + { + int read = await session.ReadAsync(buffer, timeout.Token); + Assert.IsGreaterThan(0, read); + received += read; + } + await sending.WaitAsync(TimeSpan.FromSeconds(10), TestContext.CancellationToken); + Assert.AreEqual(total, received); + } + + [TestMethod] + public async Task Connect_CancelledWhileSendingTheHandshake_ClosesTheConnection() + { + // 连接已经建立、握手写到一半被取消:不关的话就是一条没人要的 TCP 连接一直挂着。 + var stream = new HangingStream(); + var context = new TestPluginContext { PluginId = "velashell.telnet" }; + context.FakeNetwork.Handler = (_, _) => stream; + var terminal = new TelnetTerminal(context); + using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); + + _ = await Assert.ThrowsAsync(() => terminal.ConnectAsync( + new ProtocolConnectRequest { Host = "127.0.0.1", Port = 23 }, + new("xterm-256color", 80, 24), + cancel.Token)); + + Assert.IsTrue(stream.Disposed); + } + + [TestMethod] + public async Task WriteAndResize_AfterDispose_AreSilent() + { + await using var server = new LoopbackServer(); + IProtocolTerminalSession session = await ConnectAsync(server); + await server.WaitForClientAsync(); + await Task.WhenAll(session.DisposeAsync().AsTask(), session.DisposeAsync().AsTask()); + + await session.WriteAsync("x"u8.ToArray(), TestContext.CancellationToken); + await session.ResizeAsync(100, 40, TestContext.CancellationToken); + } + + /// 数一数被测会话从套接字读走了多少字节的透传流。 + private sealed class CountingStream(Stream inner) : Stream + { + private long _read; + + public long BytesRead => Interlocked.Read(ref _read); + + public override bool CanRead => inner.CanRead; + + public override bool CanSeek => false; + + public override bool CanWrite => inner.CanWrite; + + public override long Length => throw new NotSupportedException(); + + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + int read = await inner.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + _ = Interlocked.Add(ref _read, read); + return read; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override int Read(byte[] buffer, int offset, int count) + { + int read = inner.Read(buffer, offset, count); + _ = Interlocked.Add(ref _read, read); + return read; + } + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => + inner.WriteAsync(buffer, cancellationToken); + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + inner.WriteAsync(buffer, offset, count, cancellationToken); + + public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count); + + public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken); + + public override void Flush() => inner.Flush(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + inner.Dispose(); + } + base.Dispose(disposing); + } + } + + /// 写入永远不完成(直到被取消)的流:模拟握手发到一半网络卡住。 + private sealed class HangingStream : Stream + { + public bool Disposed { get; private set; } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + public override long Length => throw new NotSupportedException(); + + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + Task.Delay(Timeout.Infinite, cancellationToken); + + public override void Flush() + { + } + + public override int Read(byte[] buffer, int offset, int count) => 0; + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + Disposed = true; + base.Dispose(disposing); + } + } } diff --git a/tests/VelaShell.Plugin.Vnc.Tests/VncAudioTests.cs b/tests/VelaShell.Plugin.Vnc.Tests/VncAudioTests.cs index 4c294b9..02b2e57 100644 --- a/tests/VelaShell.Plugin.Vnc.Tests/VncAudioTests.cs +++ b/tests/VelaShell.Plugin.Vnc.Tests/VncAudioTests.cs @@ -1,3 +1,4 @@ +using System.Runtime.CompilerServices; using VelaShell.Vnc; using VelaShell.Vnc.Audio; using static VelaShell.Plugin.Vnc.Tests.ServerConnection; @@ -210,6 +211,29 @@ public async Task ThePlayerDropsRatherThanBlocksWhenTheOutputFallsBehind() Assert.IsNull(failed); } + [TestMethod] + public async Task ThePlayerSkipsLateAudioToCatchUpAfterAStall() + { + var gate = new TaskCompletionSource(); + var blocked = new BlockingOutput(gate.Task); + var clock = new StrongBox(0); + Exception? failed = null; + await using var player = new VncAudioPlayer(() => blocked, e => failed = e, null, () => Interlocked.Read(ref clock.Value)); + // Fill the device, then queue a backlog behind it while the output is stalled. + for (int i = 0; i < VncAudioPlayer.MaxOutstanding + 10; i++) { player.Push(new byte[VncAudioPlayer.ChunkBytes]); } + await Until(() => blocked.Started == VncAudioPlayer.MaxOutstanding, "the device filled"); + _ = Interlocked.Exchange(ref clock.Value, VncAudioPlayer.StaleMs + 1); + gate.SetResult(); + // At most one chunk was taken before the stall; the rest is late and skipped, not played. + await Until(() => player.Skipped >= 9L * VncAudioPlayer.ChunkBytes, "the backlog skipped"); + Assert.AreEqual(0L, player.Dropped); + int before = blocked.Started; + player.Push(new byte[VncAudioPlayer.ChunkBytes]); // fresh audio plays at once + await Until(() => blocked.Started > before, "fresh audio played"); + Assert.IsLessThanOrEqualTo(VncAudioPlayer.MaxOutstanding + 2, blocked.Started); + Assert.IsNull(failed); + } + private sealed class BlockingOutput(Task release) : IAudioOutput { private int _started;