Public Access
Add the SSH session layer and the terminal data plane
The throughput harness the plan requires before any UI, plus the SSH plumbing under it. 94 new tests, no WebView involved. Credit-based flow control is what makes `yes` survivable. A terminal renders at 60 Hz at best while a remote produces output as fast as the network allows, and the difference has to accumulate somewhere or be refused. Credit is reserved *before* reading, never after: because the pump cannot read more than the renderer has room for, the coalescing buffer is bounded by the window rather than by how fast the remote can talk. When credit runs out the pump stops reading, SSH's own receive window closes, and the remote sshd blocks -- backpressure to the source with no custom protocol. Verified by falsification, not just by passing: with the credit gate removed three tests fail, including the throughput harness's bounded-memory assertion. Acknowledgements are clamped because they cross into JavaScript, where a buggy or hostile page could otherwise claim to have rendered a gigabyte and talk the host into an unbounded read. Host key trust is enforced by *failing* the connection rather than prompting inside the handshake. SSH.NET raises verification synchronously, so consulting the user there would block the handshake on a UI round trip and deadlock the first time the prompt needed the UI thread. Unknown host and changed key become distinct exceptions the caller resolves asynchronously. A mismatch has no retry path at all: a dialog offering to continue is how users are trained to click through the one warning that actually indicates interception. A legitimately rebuilt server is handled by removing the pin in settings, away from the moment of connecting. The data plane serves the renderer page from the same loopback listener as the socket, which makes Origin predictable -- always http://127.0.0.1:{port} -- where a WebView virtual-host mapping would give a different origin per backend and nothing to validate. The token is substituted at serve time, so it never touches disk and never appears in a URL. Being clear about what that buys: not protection from a process running as this user, which can read our memory anyway, but from a page in the user's browser attempting WebSocket connections to loopback ports, which is a real and routine thing. Two bugs the tests caught. The accept loop handled connections serially, so an upgraded WebSocket parked it inside the receive loop and every later request went unanswered -- the page's own script among them. The suite hung rather than failed, which is how I found it. And SHA-1 is unavoidable here: RFC 6455 mandates it for Sec-WebSocket-Accept, where it authenticates nothing. Suppressed narrowly with that reasoning; the alternative, HttpListener.AcceptWebSocketAsync, throws PlatformNotSupportedException off Windows.
This commit is contained in:
@@ -0,0 +1,181 @@
|
||||
namespace DodoSSH.Client.Terminal.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The flow-control accounting.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Worth testing on its own, ahead of the pump, because everything else about the terminal depends on
|
||||
/// this arithmetic being right. An off-by-one that leaks credit shows up as a session that stalls
|
||||
/// after several minutes of heavy output — a symptom nobody would trace back to here.
|
||||
/// </remarks>
|
||||
public sealed class CreditWindowTests
|
||||
{
|
||||
[Fact]
|
||||
public void AFreshWindow_OffersItsWholeSize()
|
||||
{
|
||||
var window = new CreditWindow(1024);
|
||||
|
||||
window.Available.ShouldBe(1024);
|
||||
window.Outstanding.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reserving_ReducesWhatIsAvailable()
|
||||
{
|
||||
var window = new CreditWindow(1024);
|
||||
|
||||
window.TryReserve(400).ShouldBe(400);
|
||||
|
||||
window.Outstanding.ShouldBe(400);
|
||||
window.Available.ShouldBe(624);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReservingMoreThanRemains_GrantsAPartialAmount()
|
||||
{
|
||||
// All-or-nothing would stall a session that could have made progress with what was left, and
|
||||
// the caller has to cope with a short read regardless.
|
||||
var window = new CreditWindow(1024);
|
||||
window.TryReserve(900);
|
||||
|
||||
window.TryReserve(400).ShouldBe(124);
|
||||
window.Available.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFullWindow_GrantsNothing()
|
||||
{
|
||||
var window = new CreditWindow(1024);
|
||||
window.TryReserve(1024);
|
||||
|
||||
window.TryReserve(1).ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Returning_RestoresCredit()
|
||||
{
|
||||
var window = new CreditWindow(1024);
|
||||
window.TryReserve(1024);
|
||||
|
||||
window.Return(512);
|
||||
|
||||
window.Available.ShouldBe(512);
|
||||
window.Outstanding.ShouldBe(512);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReturningMoreThanWasReserved_IsClamped()
|
||||
{
|
||||
// The acknowledgement crosses into JavaScript, so a buggy or tampered page can claim to have
|
||||
// rendered more than it was sent. Letting that drive outstanding negative would hand it an
|
||||
// unbounded window, which is precisely what this class exists to prevent.
|
||||
var window = new CreditWindow(1024);
|
||||
window.TryReserve(100);
|
||||
|
||||
window.Return(100_000);
|
||||
|
||||
window.Outstanding.ShouldBe(0);
|
||||
window.Available.ShouldBe(1024);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReturningWithNothingOutstanding_ChangesNothing()
|
||||
{
|
||||
var window = new CreditWindow(1024);
|
||||
|
||||
window.Return(500);
|
||||
|
||||
window.Available.ShouldBe(1024);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WaitingWithCreditAvailable_ReturnsImmediately()
|
||||
{
|
||||
var window = new CreditWindow(1024);
|
||||
|
||||
await window.WaitForCreditAsync(TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WaitingOnAFullWindow_BlocksUntilCreditIsReturned()
|
||||
{
|
||||
var window = new CreditWindow(1024);
|
||||
window.TryReserve(1024);
|
||||
|
||||
var wait = window.WaitForCreditAsync(TestContext.Current.CancellationToken).AsTask();
|
||||
|
||||
wait.IsCompleted.ShouldBeFalse("A full window must not let a reader proceed.");
|
||||
|
||||
window.Return(1);
|
||||
|
||||
await wait;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Reset_UnblocksAWaiter()
|
||||
{
|
||||
// A session being torn down must not leave its reader parked forever on credit that will
|
||||
// never be acknowledged.
|
||||
var window = new CreditWindow(1024);
|
||||
window.TryReserve(1024);
|
||||
|
||||
var wait = window.WaitForCreditAsync(TestContext.Current.CancellationToken).AsTask();
|
||||
wait.IsCompleted.ShouldBeFalse();
|
||||
|
||||
window.Reset();
|
||||
|
||||
await wait;
|
||||
window.Outstanding.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Waiting_ObservesCancellation()
|
||||
{
|
||||
var window = new CreditWindow(1024);
|
||||
window.TryReserve(1024);
|
||||
|
||||
using var cts = new CancellationTokenSource();
|
||||
var wait = window.WaitForCreditAsync(cts.Token).AsTask();
|
||||
|
||||
await cts.CancelAsync();
|
||||
|
||||
await Should.ThrowAsync<OperationCanceledException>(async () => await wait);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConcurrentReservesAndReturns_KeepTheAccountingConsistent()
|
||||
{
|
||||
// The pump reserves on one task and returns on another, so the arithmetic has to hold under
|
||||
// real contention rather than only in a single-threaded walkthrough.
|
||||
const int Window = 64 * 1024;
|
||||
var window = new CreditWindow(Window);
|
||||
|
||||
var reserved = 0;
|
||||
var returned = 0;
|
||||
|
||||
var workers = Enumerable.Range(0, 8).Select(_ => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < 2_000; i++)
|
||||
{
|
||||
var granted = window.TryReserve(97);
|
||||
Interlocked.Add(ref reserved, granted);
|
||||
|
||||
window.Return(granted);
|
||||
Interlocked.Add(ref returned, granted);
|
||||
}
|
||||
}, TestContext.Current.CancellationToken));
|
||||
|
||||
await Task.WhenAll(workers);
|
||||
|
||||
reserved.ShouldBe(returned);
|
||||
window.Outstanding.ShouldBe(0);
|
||||
window.Available.ShouldBe(Window);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWindowOfZeroOrLess_IsRejected()
|
||||
{
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => new CreditWindow(0));
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => new CreditWindow(-1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
The throughput and backpressure harness the plan requires before any UI exists. Nothing
|
||||
here needs a WebView: the flow control is what is most likely to be wrong, and it is pure
|
||||
logic once ITerminalTransport is a seam.
|
||||
-->
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../src/DodoSSH.Client.Terminal/DodoSSH.Client.Terminal.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,167 @@
|
||||
using DodoSSH.Client.Ssh;
|
||||
|
||||
namespace DodoSSH.Client.Terminal.Tests;
|
||||
|
||||
/// <summary>A shell session that produces output on demand, for exercising the pump.</summary>
|
||||
internal sealed class FakeShellSession : ISshShellSession
|
||||
{
|
||||
private readonly List<byte> written = [];
|
||||
private readonly Lock gate = new();
|
||||
|
||||
private long remaining;
|
||||
private byte pattern;
|
||||
|
||||
/// <param name="bytesToProduce">
|
||||
/// How many bytes to emit before reporting end of stream. <see cref="long.MaxValue"/> for an
|
||||
/// endless producer, which is what a runaway remote process looks like — those sessions are ended
|
||||
/// by disposing the pump rather than by running out of data.
|
||||
/// </param>
|
||||
internal FakeShellSession(long bytesToProduce = 0) => remaining = bytesToProduce;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsOpen { get; private set; } = true;
|
||||
|
||||
/// <summary>Reads issued against this session, to detect a pump that kept reading.</summary>
|
||||
public int ReadCount { get; private set; }
|
||||
|
||||
/// <summary>Bytes the pump wrote toward the remote.</summary>
|
||||
public byte[] Written
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
return [.. written];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The last size the pump forwarded, or null if it forwarded none.</summary>
|
||||
public TerminalSize? LastResize { get; private set; }
|
||||
|
||||
/// <summary>How many resizes were forwarded, so a dropped one is observable.</summary>
|
||||
public int ResizeCount { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// Returns 0 once the configured budget is spent, which is what a remote closing the channel looks
|
||||
/// like. Not synchronous: a fake that never yields would let the pump's read loop monopolise the
|
||||
/// thread and hide any ordering problem between reading and flushing.
|
||||
/// </remarks>
|
||||
public async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
|
||||
{
|
||||
ReadCount++;
|
||||
|
||||
await Task.Yield();
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
if (remaining <= 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var count = (int)Math.Min(buffer.Length, remaining);
|
||||
buffer.Span[..count].Fill(unchecked(pattern++));
|
||||
remaining -= count;
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
written.AddRange(data.ToArray());
|
||||
}
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Resize(TerminalSize size)
|
||||
{
|
||||
// Mirrors the real session: an unusable size is dropped rather than forwarded.
|
||||
if (!size.IsUsable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ResizeCount++;
|
||||
LastResize = size;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
IsOpen = false;
|
||||
remaining = 0;
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Records frames, and can acknowledge them to keep credit flowing.</summary>
|
||||
internal sealed class RecordingTransport : ITerminalTransport
|
||||
{
|
||||
private readonly List<byte[]> frames = [];
|
||||
private readonly Lock gate = new();
|
||||
|
||||
/// <summary>Set to acknowledge every output frame immediately, as a keeping-up renderer would.</summary>
|
||||
internal TerminalSessionPump? AutoAcknowledge { get; set; }
|
||||
|
||||
/// <summary>Frames sent so far.</summary>
|
||||
internal IReadOnlyList<byte[]> Frames
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
return [.. frames];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask SendAsync(ReadOnlyMemory<byte> frame, CancellationToken cancellationToken)
|
||||
{
|
||||
var copy = frame.ToArray();
|
||||
|
||||
lock (gate)
|
||||
{
|
||||
frames.Add(copy);
|
||||
}
|
||||
|
||||
if (AutoAcknowledge is { } pump
|
||||
&& TerminalFrame.TryRead(copy, out var opcode, out _, out var payload)
|
||||
&& opcode == (byte)TerminalServerOpcode.Output)
|
||||
{
|
||||
pump.Acknowledge((uint)payload.Length);
|
||||
}
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Concatenated payloads of every output frame.</summary>
|
||||
internal byte[] OutputBytes()
|
||||
{
|
||||
var output = new List<byte>();
|
||||
|
||||
foreach (var frame in Frames)
|
||||
{
|
||||
if (TerminalFrame.TryRead(frame, out var opcode, out _, out var payload)
|
||||
&& opcode == (byte)TerminalServerOpcode.Output)
|
||||
{
|
||||
output.AddRange(payload);
|
||||
}
|
||||
}
|
||||
|
||||
return [.. output];
|
||||
}
|
||||
|
||||
/// <summary>Counts frames of one opcode.</summary>
|
||||
internal int CountOf(TerminalServerOpcode opcode) =>
|
||||
Frames.Count(frame =>
|
||||
TerminalFrame.TryRead(frame, out var actual, out _, out _)
|
||||
&& actual == (byte)opcode);
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using DodoSSH.Client.Ssh;
|
||||
|
||||
namespace DodoSSH.Client.Terminal.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The loopback transport end to end, with a real WebSocket client.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Uses <see cref="ClientWebSocket"/> against the real listener rather than a stubbed transport,
|
||||
/// because the hand-rolled HTTP upgrade is the part that could be subtly wrong — and a handshake that
|
||||
/// no real client accepts would pass any test that skipped it.
|
||||
/// </remarks>
|
||||
public sealed class TerminalDataPlaneTests : IAsyncDisposable
|
||||
{
|
||||
private const uint SessionId = 3;
|
||||
|
||||
private static readonly byte[] PageTemplate = Encoding.UTF8.GetBytes(
|
||||
$"<html><body data-token=\"{TerminalDataPlane.TokenPlaceholder}\" "
|
||||
+ $"data-socket=\"{TerminalDataPlane.SocketUrlPlaceholder}\"></body></html>");
|
||||
|
||||
private readonly TerminalDataPlane plane = new(new InMemoryTerminalAssetProvider(
|
||||
new Dictionary<string, TerminalAsset>(StringComparer.Ordinal)
|
||||
{
|
||||
[TerminalDataPlane.PagePath] = new("text/html; charset=utf-8", PageTemplate),
|
||||
["/xterm.js"] = new("text/javascript; charset=utf-8", "console.log(1)"u8.ToArray()),
|
||||
}));
|
||||
|
||||
private readonly CancellationTokenSource lifetime = new();
|
||||
private Task? server;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await lifetime.CancelAsync();
|
||||
await plane.DisposeAsync();
|
||||
|
||||
if (server is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await server;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Expected: the accept loop is stopped by cancelling it.
|
||||
}
|
||||
}
|
||||
|
||||
lifetime.Dispose();
|
||||
}
|
||||
|
||||
// ---- Serving the page ----
|
||||
|
||||
[Fact]
|
||||
public async Task ThePage_IsServedWithTheTokenAndSocketUrlSubstituted()
|
||||
{
|
||||
// Substituted at serve time rather than written into the file, so the token never touches disk
|
||||
// and never appears in a URL that a log or a browser history could keep.
|
||||
Start();
|
||||
|
||||
using var client = new HttpClient();
|
||||
var body = await client.GetStringAsync(plane.PageUrl, TestContext.Current.CancellationToken);
|
||||
|
||||
body.ShouldContain(plane.Token);
|
||||
body.ShouldContain(
|
||||
string.Create(CultureInfo.InvariantCulture, $"ws://127.0.0.1:{plane.Port}/socket"));
|
||||
|
||||
body.ShouldNotContain(TerminalDataPlane.TokenPlaceholder);
|
||||
body.ShouldNotContain(TerminalDataPlane.SocketUrlPlaceholder);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThePage_IsNotCached()
|
||||
{
|
||||
// It carries a connection token.
|
||||
Start();
|
||||
|
||||
using var client = new HttpClient();
|
||||
using var response = await client.GetAsync(plane.PageUrl, TestContext.Current.CancellationToken);
|
||||
|
||||
response.Headers.CacheControl!.NoStore.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnUnknownPath_Is404()
|
||||
{
|
||||
Start();
|
||||
|
||||
using var client = new HttpClient();
|
||||
using var response = await client.GetAsync(
|
||||
new Uri($"http://127.0.0.1:{plane.Port}/nope"),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
// ---- Attaching ----
|
||||
|
||||
[Fact]
|
||||
public async Task TheRenderer_Attaches()
|
||||
{
|
||||
Start();
|
||||
|
||||
using var socket = await ConnectAsync();
|
||||
|
||||
socket.State.ShouldBe(WebSocketState.Open);
|
||||
socket.SubProtocol.ShouldBe(TerminalDataPlane.SubProtocol);
|
||||
|
||||
await plane.RendererAttached;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AConnectionWithoutTheToken_IsRejected()
|
||||
{
|
||||
Start();
|
||||
|
||||
await Should.ThrowAsync<WebSocketException>(async () =>
|
||||
await ConnectAsync(token: null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AConnectionWithTheWrongToken_IsRejected()
|
||||
{
|
||||
Start();
|
||||
|
||||
await Should.ThrowAsync<WebSocketException>(async () =>
|
||||
await ConnectAsync(token: "not-the-token"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AConnectionFromAnotherOrigin_IsRejected()
|
||||
{
|
||||
// The threat this actually addresses: a page open in the user's browser can attempt WebSocket
|
||||
// connections to loopback ports, and would otherwise reach a terminal.
|
||||
Start();
|
||||
|
||||
await Should.ThrowAsync<WebSocketException>(async () =>
|
||||
await ConnectAsync(origin: "https://evil.example"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASecondRenderer_IsRejected()
|
||||
{
|
||||
Start();
|
||||
|
||||
using var first = await ConnectAsync();
|
||||
first.State.ShouldBe(WebSocketState.Open);
|
||||
|
||||
await Should.ThrowAsync<WebSocketException>(async () => await ConnectAsync());
|
||||
}
|
||||
|
||||
// ---- Frames ----
|
||||
|
||||
[Fact]
|
||||
public async Task Output_ReachesTheRenderer()
|
||||
{
|
||||
Start();
|
||||
|
||||
using var socket = await ConnectAsync();
|
||||
|
||||
await using var session = new FakeShellSession(bytesToProduce: 128);
|
||||
await using var pump = CreatePump(session);
|
||||
plane.Register(SessionId, pump);
|
||||
|
||||
var run = pump.RunAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
// SessionOpened first, then the output.
|
||||
var opened = await ReceiveAsync(socket);
|
||||
opened.Opcode.ShouldBe((byte)TerminalServerOpcode.SessionOpened);
|
||||
opened.SessionId.ShouldBe(SessionId);
|
||||
|
||||
var output = await ReceiveAsync(socket);
|
||||
output.Opcode.ShouldBe((byte)TerminalServerOpcode.Output);
|
||||
output.Payload.Length.ShouldBe(128);
|
||||
|
||||
// Acknowledge it, exactly as the page does from term.write's callback.
|
||||
await SendAsync(
|
||||
socket,
|
||||
(byte)TerminalClientOpcode.Acknowledge,
|
||||
TerminalFrame.CreateAcknowledgementPayload((uint)output.Payload.Length));
|
||||
|
||||
await run;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Input_ReachesTheRemote()
|
||||
{
|
||||
Start();
|
||||
|
||||
using var socket = await ConnectAsync();
|
||||
|
||||
await using var session = new FakeShellSession();
|
||||
await using var pump = CreatePump(session);
|
||||
plane.Register(SessionId, pump);
|
||||
|
||||
await SendAsync(socket, (byte)TerminalClientOpcode.Input, "whoami\r"u8.ToArray());
|
||||
|
||||
await WaitUntilAsync(() => session.Written.Length > 0);
|
||||
|
||||
Encoding.UTF8.GetString(session.Written).ShouldBe("whoami\r");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AResize_ReachesTheRemote()
|
||||
{
|
||||
Start();
|
||||
|
||||
using var socket = await ConnectAsync();
|
||||
|
||||
await using var session = new FakeShellSession();
|
||||
await using var pump = CreatePump(session);
|
||||
plane.Register(SessionId, pump);
|
||||
|
||||
await SendAsync(
|
||||
socket,
|
||||
(byte)TerminalClientOpcode.Resize,
|
||||
TerminalFrame.CreateResizePayload(new TerminalSize(132, 43, 1320, 1075)));
|
||||
|
||||
await WaitUntilAsync(() => session.ResizeCount > 0);
|
||||
|
||||
session.LastResize.ShouldBe(new TerminalSize(132, 43, 1320, 1075));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnAcknowledgement_ReturnsCredit()
|
||||
{
|
||||
Start();
|
||||
|
||||
using var socket = await ConnectAsync();
|
||||
|
||||
await using var session = new FakeShellSession();
|
||||
await using var pump = CreatePump(session);
|
||||
plane.Register(SessionId, pump);
|
||||
|
||||
pump.Credits.TryReserve(1024);
|
||||
pump.Credits.Outstanding.ShouldBe(1024);
|
||||
|
||||
await SendAsync(
|
||||
socket,
|
||||
(byte)TerminalClientOpcode.Acknowledge,
|
||||
TerminalFrame.CreateAcknowledgementPayload(1024));
|
||||
|
||||
await WaitUntilAsync(() => pump.Credits.Outstanding == 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AFrameForAnUnregisteredSession_IsIgnored()
|
||||
{
|
||||
// Ordinary during teardown: the page can still have frames in flight for a session that just
|
||||
// ended. Dropping them must not disturb anything else.
|
||||
Start();
|
||||
|
||||
using var socket = await ConnectAsync();
|
||||
|
||||
await using var session = new FakeShellSession();
|
||||
await using var pump = CreatePump(session);
|
||||
plane.Register(SessionId, pump);
|
||||
|
||||
// A session id that is never registered. Using the registered one and relying on ordering
|
||||
// would be a race: frames are dispatched on the receive loop, so the orphan can land after
|
||||
// registration and legitimately be delivered.
|
||||
await SendAsync(socket, (byte)TerminalClientOpcode.Input, "orphan"u8.ToArray(), sessionId: 999);
|
||||
|
||||
await SendAsync(socket, (byte)TerminalClientOpcode.Input, "real"u8.ToArray());
|
||||
await WaitUntilAsync(() => session.Written.Length > 0);
|
||||
|
||||
Encoding.UTF8.GetString(session.Written).ShouldBe("real");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AMalformedFrame_IsIgnored()
|
||||
{
|
||||
Start();
|
||||
|
||||
using var socket = await ConnectAsync();
|
||||
|
||||
// Shorter than the header.
|
||||
await socket.SendAsync(
|
||||
new byte[] { 1, 2 },
|
||||
WebSocketMessageType.Binary,
|
||||
endOfMessage: true,
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
await using var session = new FakeShellSession();
|
||||
await using var pump = CreatePump(session);
|
||||
plane.Register(SessionId, pump);
|
||||
|
||||
await SendAsync(socket, (byte)TerminalClientOpcode.Input, "still here"u8.ToArray());
|
||||
await WaitUntilAsync(() => session.Written.Length > 0);
|
||||
|
||||
Encoding.UTF8.GetString(session.Written).ShouldBe("still here");
|
||||
}
|
||||
|
||||
// ---- Helpers ----
|
||||
|
||||
private void Start() => server = plane.RunAsync(lifetime.Token);
|
||||
|
||||
private TerminalSessionPump CreatePump(FakeShellSession session) =>
|
||||
new(
|
||||
SessionId,
|
||||
session,
|
||||
plane,
|
||||
TimeProvider.System,
|
||||
new TerminalPumpOptions { FlushInterval = TimeSpan.FromMilliseconds(10) });
|
||||
|
||||
private async Task<ClientWebSocket> ConnectAsync(
|
||||
string? token = "",
|
||||
string? origin = null)
|
||||
{
|
||||
var socket = new ClientWebSocket();
|
||||
|
||||
socket.Options.AddSubProtocol(TerminalDataPlane.SubProtocol);
|
||||
|
||||
if (token is not null)
|
||||
{
|
||||
socket.Options.AddSubProtocol($"token.{(token.Length == 0 ? plane.Token : token)}");
|
||||
}
|
||||
|
||||
socket.Options.SetRequestHeader(
|
||||
"Origin",
|
||||
origin ?? string.Create(CultureInfo.InvariantCulture, $"http://127.0.0.1:{plane.Port}"));
|
||||
|
||||
try
|
||||
{
|
||||
await socket.ConnectAsync(
|
||||
new Uri($"ws://127.0.0.1:{plane.Port}{TerminalDataPlane.SocketPath}"),
|
||||
TestContext.Current.CancellationToken);
|
||||
}
|
||||
catch
|
||||
{
|
||||
socket.Dispose();
|
||||
throw;
|
||||
}
|
||||
|
||||
return socket;
|
||||
}
|
||||
|
||||
private static async Task SendAsync(
|
||||
ClientWebSocket socket,
|
||||
byte opcode,
|
||||
byte[] payload,
|
||||
uint sessionId = SessionId) =>
|
||||
await socket.SendAsync(
|
||||
TerminalFrame.Create(opcode, sessionId, payload),
|
||||
WebSocketMessageType.Binary,
|
||||
endOfMessage: true,
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
private static async Task<(byte Opcode, uint SessionId, byte[] Payload)> ReceiveAsync(
|
||||
ClientWebSocket socket)
|
||||
{
|
||||
var buffer = new byte[64 * 1024];
|
||||
|
||||
var result = await socket.ReceiveAsync(
|
||||
buffer.AsMemory(),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
TerminalFrame.TryRead(buffer.AsSpan(0, result.Count), out var opcode, out var sessionId, out var payload)
|
||||
.ShouldBeTrue();
|
||||
|
||||
return (opcode, sessionId, payload.ToArray());
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// Polls rather than awaiting a signal: inbound frames are dispatched on the transport's receive
|
||||
/// loop, which has no completion for the caller to await. The bound keeps a genuine failure a
|
||||
/// failure rather than a hang.
|
||||
/// </remarks>
|
||||
private static async Task WaitUntilAsync(Func<bool> condition)
|
||||
{
|
||||
var deadline = TimeProvider.System.GetUtcNow() + TimeSpan.FromSeconds(5);
|
||||
|
||||
while (TimeProvider.System.GetUtcNow() < deadline)
|
||||
{
|
||||
if (condition())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Delay(10, TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
throw new TimeoutException("The expected state was not reached within 5 seconds.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using DodoSSH.Client.Ssh;
|
||||
|
||||
namespace DodoSSH.Client.Terminal.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The wire format between the host and the renderer page.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Byte order is asserted explicitly rather than only round-tripped. Both ends of this protocol are
|
||||
/// ours today, but the JavaScript side reads the header with a <c>DataView</c>, whose default is
|
||||
/// big-endian — a round-trip-only test would pass just as happily with a little-endian header that the
|
||||
/// page then misreads.
|
||||
/// </remarks>
|
||||
public sealed class TerminalFrameTests
|
||||
{
|
||||
[Fact]
|
||||
public void AFrame_RoundTrips()
|
||||
{
|
||||
var frame = TerminalFrame.Create((byte)TerminalServerOpcode.Output, 42, "hello"u8);
|
||||
|
||||
TerminalFrame.TryRead(frame, out var opcode, out var sessionId, out var payload).ShouldBeTrue();
|
||||
|
||||
opcode.ShouldBe((byte)TerminalServerOpcode.Output);
|
||||
sessionId.ShouldBe(42u);
|
||||
payload.ToArray().ShouldBe("hello"u8.ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSessionId_IsBigEndian()
|
||||
{
|
||||
var frame = TerminalFrame.Create((byte)TerminalServerOpcode.Output, 0x01020304, []);
|
||||
|
||||
frame[1].ShouldBe((byte)0x01);
|
||||
frame[2].ShouldBe((byte)0x02);
|
||||
frame[3].ShouldBe((byte)0x03);
|
||||
frame[4].ShouldBe((byte)0x04);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnEmptyPayload_IsLegal()
|
||||
{
|
||||
// SessionOpened carries nothing.
|
||||
var frame = TerminalFrame.Create((byte)TerminalServerOpcode.SessionOpened, 1, []);
|
||||
|
||||
frame.Length.ShouldBe(TerminalFrame.HeaderLength);
|
||||
TerminalFrame.TryRead(frame, out _, out _, out var payload).ShouldBeTrue();
|
||||
payload.Length.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(1)]
|
||||
[InlineData(4)]
|
||||
public void AFrameShorterThanTheHeader_IsRejected(int length)
|
||||
{
|
||||
// These arrive from a WebView page, so a malformed frame is untrusted input to drop rather
|
||||
// than an exceptional condition.
|
||||
TerminalFrame.TryRead(new byte[length], out _, out _, out _).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Write_RejectsATooSmallDestination()
|
||||
{
|
||||
Should.Throw<ArgumentException>(() =>
|
||||
TerminalFrame.Write(new byte[4], 1, 1, "payload"u8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnAcknowledgement_RoundTrips()
|
||||
{
|
||||
var payload = TerminalFrame.CreateAcknowledgementPayload(123_456);
|
||||
|
||||
TerminalFrame.TryReadAcknowledgement(payload, out var rendered).ShouldBeTrue();
|
||||
rendered.ShouldBe(123_456u);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(3)]
|
||||
[InlineData(5)]
|
||||
public void AnAcknowledgementOfTheWrongLength_IsRejected(int length)
|
||||
{
|
||||
TerminalFrame.TryReadAcknowledgement(new byte[length], out _).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AResize_RoundTrips()
|
||||
{
|
||||
var size = new TerminalSize(132, 43, 1320, 1075);
|
||||
var payload = TerminalFrame.CreateResizePayload(size);
|
||||
|
||||
TerminalFrame.TryReadResize(payload, out var decoded).ShouldBeTrue();
|
||||
decoded.ShouldBe(size);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(7)]
|
||||
[InlineData(9)]
|
||||
public void AResizeOfTheWrongLength_IsRejected(int length)
|
||||
{
|
||||
TerminalFrame.TryReadResize(new byte[length], out _).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AResizePayload_OrdersColumnsBeforeRows()
|
||||
{
|
||||
// The page builds this by hand, and columns-before-rows is the SSH convention. Swapping them
|
||||
// produces a terminal that is 24 columns by 80 rows, which looks like a rendering bug.
|
||||
var payload = TerminalFrame.CreateResizePayload(new TerminalSize(80, 24));
|
||||
|
||||
payload[0].ShouldBe((byte)0);
|
||||
payload[1].ShouldBe((byte)80);
|
||||
payload[2].ShouldBe((byte)0);
|
||||
payload[3].ShouldBe((byte)24);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using DodoSSH.Client.Ssh;
|
||||
|
||||
namespace DodoSSH.Client.Terminal.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The output path under load: coalescing, backpressure, and shutdown.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The plan calls for a throughput harness built before any UI, and this is it. Terminal throughput is
|
||||
/// where a client like this usually fails — <c>cat</c> on a large file either freezes the UI or grows
|
||||
/// memory until the process dies — and neither symptom is diagnosable once a WebView is in the picture.
|
||||
/// </remarks>
|
||||
public sealed class TerminalSessionPumpTests
|
||||
{
|
||||
private const uint SessionId = 7;
|
||||
|
||||
[Fact]
|
||||
public async Task Output_ReachesTheTransportTaggedWithItsSession()
|
||||
{
|
||||
await using var session = new FakeShellSession(bytesToProduce: 64);
|
||||
var transport = new RecordingTransport();
|
||||
|
||||
await using var pump = CreatePump(session, transport);
|
||||
transport.AutoAcknowledge = pump;
|
||||
|
||||
await pump.RunAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
transport.OutputBytes().Length.ShouldBe(64);
|
||||
|
||||
foreach (var frame in transport.Frames)
|
||||
{
|
||||
TerminalFrame.TryRead(frame, out _, out var sessionId, out _).ShouldBeTrue();
|
||||
sessionId.ShouldBe(SessionId);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASessionOpenedFrame_PrecedesAnyOutput()
|
||||
{
|
||||
// The renderer has to attach a terminal before bytes arrive for it, or the first screenful is
|
||||
// written into nothing.
|
||||
await using var session = new FakeShellSession(bytesToProduce: 16);
|
||||
var transport = new RecordingTransport();
|
||||
|
||||
await using var pump = CreatePump(session, transport);
|
||||
transport.AutoAcknowledge = pump;
|
||||
|
||||
await pump.RunAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
TerminalFrame.TryRead(transport.Frames[0], out var opcode, out _, out _).ShouldBeTrue();
|
||||
opcode.ShouldBe((byte)TerminalServerOpcode.SessionOpened);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeveralReadsWithinOneInterval_BecomeASingleFrame()
|
||||
{
|
||||
// A terminal cannot render faster than the display refreshes, so sending each read separately
|
||||
// is work whose result is overwritten before anyone sees it.
|
||||
await using var session = new FakeShellSession(bytesToProduce: 8 * 1024);
|
||||
var transport = new RecordingTransport();
|
||||
|
||||
await using var pump = CreatePump(
|
||||
session,
|
||||
transport,
|
||||
new TerminalPumpOptions
|
||||
{
|
||||
ReadBufferBytes = 512,
|
||||
FlushInterval = TimeSpan.FromMilliseconds(400),
|
||||
});
|
||||
|
||||
transport.AutoAcknowledge = pump;
|
||||
|
||||
var run = pump.RunAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
// Long enough for one flush, short enough that a second cannot have happened.
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(600), TestContext.Current.CancellationToken);
|
||||
|
||||
// 8 KiB arrived as sixteen 512-byte reads and left as one frame.
|
||||
transport.CountOf(TerminalServerOpcode.Output).ShouldBe(1);
|
||||
transport.OutputBytes().Length.ShouldBe(8 * 1024);
|
||||
|
||||
await run;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhenCreditRunsOut_ThePumpStopsReading()
|
||||
{
|
||||
// The property the whole design rests on. With no acknowledgement the pump must read exactly
|
||||
// the window and then stop, so nothing accumulates between the socket and the screen. Left
|
||||
// unbounded, a remote running `yes` grows the client's memory until it dies.
|
||||
const int Window = 4 * 1024;
|
||||
|
||||
await using var session = new FakeShellSession(bytesToProduce: long.MaxValue);
|
||||
var transport = new RecordingTransport();
|
||||
|
||||
// Deliberately no AutoAcknowledge: this models a renderer that has stopped keeping up.
|
||||
await using var pump = CreatePump(
|
||||
session,
|
||||
transport,
|
||||
new TerminalPumpOptions
|
||||
{
|
||||
ReadBufferBytes = 1024,
|
||||
FlushInterval = TimeSpan.FromMilliseconds(5),
|
||||
WindowBytes = Window,
|
||||
});
|
||||
|
||||
var run = pump.RunAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(300), TestContext.Current.CancellationToken);
|
||||
|
||||
pump.BytesRead.ShouldBe(
|
||||
Window,
|
||||
"The pump read past its credit window, so output accumulates without bound.");
|
||||
|
||||
// Still stalled a moment later, rather than merely slow.
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||
pump.BytesRead.ShouldBe(Window);
|
||||
|
||||
pump.Credits.Available.ShouldBe(0);
|
||||
|
||||
await pump.DisposeAsync();
|
||||
await run;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AcknowledgingCredit_LetsThePumpResume()
|
||||
{
|
||||
const int Window = 4 * 1024;
|
||||
|
||||
await using var session = new FakeShellSession(bytesToProduce: long.MaxValue);
|
||||
var transport = new RecordingTransport();
|
||||
|
||||
await using var pump = CreatePump(
|
||||
session,
|
||||
transport,
|
||||
new TerminalPumpOptions
|
||||
{
|
||||
ReadBufferBytes = 1024,
|
||||
FlushInterval = TimeSpan.FromMilliseconds(5),
|
||||
WindowBytes = Window,
|
||||
});
|
||||
|
||||
var run = pump.RunAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||
pump.BytesRead.ShouldBe(Window);
|
||||
|
||||
pump.Acknowledge(2048);
|
||||
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||
|
||||
pump.BytesRead.ShouldBe(Window + 2048);
|
||||
|
||||
await pump.DisposeAsync();
|
||||
await run;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnOverLargeAcknowledgement_DoesNotWidenTheWindow()
|
||||
{
|
||||
// The acknowledgement comes from JavaScript. A page claiming to have rendered a gigabyte must
|
||||
// not be able to talk the host into an unbounded read.
|
||||
const int Window = 4 * 1024;
|
||||
|
||||
await using var session = new FakeShellSession(bytesToProduce: long.MaxValue);
|
||||
var transport = new RecordingTransport();
|
||||
|
||||
await using var pump = CreatePump(
|
||||
session,
|
||||
transport,
|
||||
new TerminalPumpOptions
|
||||
{
|
||||
ReadBufferBytes = 1024,
|
||||
FlushInterval = TimeSpan.FromMilliseconds(5),
|
||||
WindowBytes = Window,
|
||||
});
|
||||
|
||||
var run = pump.RunAsync(TestContext.Current.CancellationToken);
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||
|
||||
pump.Acknowledge(uint.MaxValue);
|
||||
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||
|
||||
// One further window's worth at most, never everything the endless producer could offer.
|
||||
pump.BytesRead.ShouldBeLessThanOrEqualTo(Window * 2);
|
||||
|
||||
await pump.DisposeAsync();
|
||||
await run;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhenTheRemoteCloses_ASessionClosedFrameFollowsTheLastOutput()
|
||||
{
|
||||
// The last thing a remote writes is often the most important — an error, an exit code — and
|
||||
// dropping it makes a clean exit look like a crash.
|
||||
await using var session = new FakeShellSession(bytesToProduce: 4096);
|
||||
var transport = new RecordingTransport();
|
||||
|
||||
await using var pump = CreatePump(
|
||||
session,
|
||||
transport,
|
||||
new TerminalPumpOptions { FlushInterval = TimeSpan.FromMilliseconds(20) });
|
||||
|
||||
transport.AutoAcknowledge = pump;
|
||||
|
||||
await pump.RunAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
transport.OutputBytes().Length.ShouldBe(4096);
|
||||
|
||||
TerminalFrame.TryRead(transport.Frames[^1], out var opcode, out _, out var payload)
|
||||
.ShouldBeTrue();
|
||||
|
||||
opcode.ShouldBe((byte)TerminalServerOpcode.SessionClosed);
|
||||
System.Text.Encoding.UTF8.GetString(payload).ShouldNotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Input_ReachesTheRemote()
|
||||
{
|
||||
await using var session = new FakeShellSession();
|
||||
var transport = new RecordingTransport();
|
||||
|
||||
await using var pump = CreatePump(session, transport);
|
||||
|
||||
await pump.WriteInputAsync("ls -la\r"u8.ToArray(), TestContext.Current.CancellationToken);
|
||||
|
||||
System.Text.Encoding.UTF8.GetString(session.Written).ShouldBe("ls -la\r");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AResize_ReachesTheRemote()
|
||||
{
|
||||
await using var session = new FakeShellSession();
|
||||
var transport = new RecordingTransport();
|
||||
|
||||
await using var pump = CreatePump(session, transport);
|
||||
|
||||
pump.Resize(new TerminalSize(132, 43, 1320, 1075));
|
||||
|
||||
session.ResizeCount.ShouldBe(1);
|
||||
session.LastResize.ShouldBe(new TerminalSize(132, 43, 1320, 1075));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AZeroSizedResize_IsDropped()
|
||||
{
|
||||
// Arrives naturally when a pane collapses or a window minimises. Forwarding it leaves the
|
||||
// remote's idea of the terminal nonsensical until the next resize.
|
||||
await using var session = new FakeShellSession();
|
||||
var transport = new RecordingTransport();
|
||||
|
||||
await using var pump = CreatePump(session, transport);
|
||||
|
||||
pump.Resize(new TerminalSize(0, 0));
|
||||
|
||||
session.ResizeCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThroughputHarness_SustainsTenMegabytesPerSecondWithBoundedMemory()
|
||||
{
|
||||
// The plan's target: `yes` at full tilt must hold a fixed memory ceiling. Throughput is
|
||||
// asserted well below what the machine manages, because a CI runner under load is slower than
|
||||
// a desktop and a flaky performance test gets deleted rather than fixed. The bounded-memory
|
||||
// assertion is the one that carries the real meaning.
|
||||
const long Target = 32L * 1024 * 1024;
|
||||
const int Window = CreditWindow.DefaultWindowBytes;
|
||||
|
||||
await using var session = new FakeShellSession(bytesToProduce: Target);
|
||||
var transport = new RecordingTransport();
|
||||
|
||||
await using var pump = CreatePump(
|
||||
session,
|
||||
transport,
|
||||
new TerminalPumpOptions
|
||||
{
|
||||
ReadBufferBytes = 32 * 1024,
|
||||
FlushInterval = TimeSpan.FromMilliseconds(1),
|
||||
WindowBytes = Window,
|
||||
});
|
||||
|
||||
transport.AutoAcknowledge = pump;
|
||||
|
||||
using var monitor = new CancellationTokenSource();
|
||||
var sampler = SamplePeakOutstandingAsync(pump, monitor.Token);
|
||||
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
await pump.RunAsync(TestContext.Current.CancellationToken);
|
||||
stopwatch.Stop();
|
||||
|
||||
await monitor.CancelAsync();
|
||||
var peakOutstanding = await sampler;
|
||||
|
||||
pump.BytesRead.ShouldBe(Target);
|
||||
transport.OutputBytes().Length.ShouldBe((int)Target);
|
||||
|
||||
var megabytesPerSecond = Target / 1024d / 1024d / stopwatch.Elapsed.TotalSeconds;
|
||||
|
||||
megabytesPerSecond.ShouldBeGreaterThan(
|
||||
10,
|
||||
string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"Sustained {megabytesPerSecond:F1} MB/s, below the 10 MB/s target."));
|
||||
|
||||
// The real assertion: in-flight bytes never exceeded the window, however fast the producer ran.
|
||||
peakOutstanding.ShouldBeLessThanOrEqualTo(
|
||||
Window,
|
||||
string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"Peak in-flight was {peakOutstanding} bytes against a {Window}-byte window."));
|
||||
}
|
||||
|
||||
/// <summary>Watches in-flight bytes for the duration of a run, returning the highest seen.</summary>
|
||||
private static async Task<int> SamplePeakOutstandingAsync(
|
||||
TerminalSessionPump pump,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var peak = 0;
|
||||
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
peak = Math.Max(peak, pump.Credits.Outstanding);
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(1, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return peak;
|
||||
}
|
||||
|
||||
private static TerminalSessionPump CreatePump(
|
||||
FakeShellSession session,
|
||||
ITerminalTransport transport,
|
||||
TerminalPumpOptions? options = null) =>
|
||||
new(
|
||||
SessionId,
|
||||
session,
|
||||
transport,
|
||||
TimeProvider.System,
|
||||
options ?? new TerminalPumpOptions { FlushInterval = TimeSpan.FromMilliseconds(10) });
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"Meziantou.Analyzer": {
|
||||
"type": "Direct",
|
||||
"requested": "[3.0.134, )",
|
||||
"resolved": "3.0.134",
|
||||
"contentHash": "tTYCcYKyOko3TMNxmxmA9nakbcHVUgglENmCMIhzIjl9y9FBZO/0tWSxTGC74Sp198FmWih5S5KkjQRBg5ePkQ=="
|
||||
},
|
||||
"Microsoft.CodeAnalysis.BannedApiAnalyzers": {
|
||||
"type": "Direct",
|
||||
"requested": "[5.6.0, )",
|
||||
"resolved": "5.6.0",
|
||||
"contentHash": "Kcobt3pnOdO0A+6CKiMHZdTEluJpsfxiV20axtZdmfBQnDmiWTKPJADlgAfdTuKNAnVarrkJa0UEGwuOo91muw=="
|
||||
},
|
||||
"NSubstitute": {
|
||||
"type": "Direct",
|
||||
"requested": "[6.0.0, )",
|
||||
"resolved": "6.0.0",
|
||||
"contentHash": "0gvKMbiJ+/WrfbcfBfqRZZrvfLJcd3rqkqVMjjlY5dtmLRVzMY+o/K/rJUStofQ2haSr9Vd04YDfvZtVVGS3/A==",
|
||||
"dependencies": {
|
||||
"Castle.Core": "5.1.1"
|
||||
}
|
||||
},
|
||||
"Shouldly": {
|
||||
"type": "Direct",
|
||||
"requested": "[4.3.0, )",
|
||||
"resolved": "4.3.0",
|
||||
"contentHash": "sDetrWXrl6YXZ4HeLsdBoNk3uIa7K+V4uvIJ+cqdRa5DrFxeTED7VkjoxCuU1kJWpUuBDZz2QXFzSxBtVXLwRQ==",
|
||||
"dependencies": {
|
||||
"DiffEngine": "11.3.0",
|
||||
"EmptyFiles": "4.4.0"
|
||||
}
|
||||
},
|
||||
"xunit.v3": {
|
||||
"type": "Direct",
|
||||
"requested": "[3.2.2, )",
|
||||
"resolved": "3.2.2",
|
||||
"contentHash": "L+4/4y0Uqcg8/d6hfnxhnwh4j9FaeULvefTwrk30rr1o4n/vdPfyUQ8k0yzH8VJx7bmFEkDdcRfbtbjEHlaYcA==",
|
||||
"dependencies": {
|
||||
"xunit.v3.mtp-v1": "[3.2.2]"
|
||||
}
|
||||
},
|
||||
"Castle.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "5.1.1",
|
||||
"contentHash": "rpYtIczkzGpf+EkZgDr9CClTdemhsrwA/W5hMoPjLkRFnXzH44zDLoovXeKtmxb1ykXK9aJVODSpiJml8CTw2g==",
|
||||
"dependencies": {
|
||||
"System.Diagnostics.EventLog": "6.0.0"
|
||||
}
|
||||
},
|
||||
"DiffEngine": {
|
||||
"type": "Transitive",
|
||||
"resolved": "11.3.0",
|
||||
"contentHash": "k0ZgZqd09jLZQjR8FyQbSQE86Q7QZnjEzq1LPHtj1R2AoWO8sjV5x+jlSisL7NZAbUOI4y+7Bog8gkr9WIRBGw==",
|
||||
"dependencies": {
|
||||
"EmptyFiles": "4.4.0",
|
||||
"System.Management": "6.0.1"
|
||||
}
|
||||
},
|
||||
"EmptyFiles": {
|
||||
"type": "Transitive",
|
||||
"resolved": "4.4.0",
|
||||
"contentHash": "gwJEfIGS7FhykvtZoscwXj/XwW+mJY6UbAZk+qtLKFUGWC95kfKXnj8VkxsZQnWBxJemM/q664rGLN5nf+OHZw=="
|
||||
},
|
||||
"Microsoft.ApplicationInsights": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.23.0",
|
||||
"contentHash": "nWArUZTdU7iqZLycLKWe0TDms48KKGE6pONH2terYNa8REXiqixrMOkf1sk5DHGMaUTqONU2YkS4SAXBhLStgw=="
|
||||
},
|
||||
"Microsoft.Bcl.AsyncInterfaces": {
|
||||
"type": "Transitive",
|
||||
"resolved": "6.0.0",
|
||||
"contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg=="
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.0.2",
|
||||
"contentHash": "3iE7UF7MQkCv1cxzCahz+Y/guQbTqieyxyaWKhrRO91itI9cOKO76OHeQDahqG4MmW5umr3CcCvGmK92lWNlbg=="
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.0.3",
|
||||
"contentHash": "dL0QGToTxggRLMYY4ZYX5AMwBb+byQBd/5dMiZE07Nv73o6I5Are3C7eQTh7K2+A4ct0PVISSr7TZANbiNb2yQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Testing.Extensions.Telemetry": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.9.1",
|
||||
"contentHash": "No5AudZMmSb+uNXjlgL2y3/stHD2IT4uxqc5yHwkE+/nNux9jbKcaJMvcp9SwgP4DVD8L9/P3OUz8mmmcvEIdQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.ApplicationInsights": "2.23.0",
|
||||
"Microsoft.Testing.Platform": "1.9.1"
|
||||
}
|
||||
},
|
||||
"Microsoft.Testing.Extensions.TrxReport.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.9.1",
|
||||
"contentHash": "AL46Xe1WBi85Ntd4mNPvat5ZSsZ2uejiVqoKCypr8J3wK0elA5xJ3AN4G/Q4GIwzUFnggZoH/DBjnr9J18IO/g==",
|
||||
"dependencies": {
|
||||
"Microsoft.Testing.Platform": "1.9.1"
|
||||
}
|
||||
},
|
||||
"Microsoft.Testing.Platform": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.9.1",
|
||||
"contentHash": "QafNtNSmEI0zazdebnsIkDKmFtTSpmx/5PLOjURWwozcPb3tvRxzosQSL8xwYNM1iPhhKiBksXZyRSE2COisrA=="
|
||||
},
|
||||
"Microsoft.Testing.Platform.MSBuild": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.9.1",
|
||||
"contentHash": "oTUtyR4X/s9ytuiNA29FGsNCCH0rNmY5Wdm14NCKLjTM1cT9edVSlA+rGS/mVmusPqcP0l/x9qOnMXg16v87RQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Testing.Platform": "1.9.1"
|
||||
}
|
||||
},
|
||||
"Microsoft.Win32.Registry": {
|
||||
"type": "Transitive",
|
||||
"resolved": "5.0.0",
|
||||
"contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg=="
|
||||
},
|
||||
"System.CodeDom": {
|
||||
"type": "Transitive",
|
||||
"resolved": "6.0.0",
|
||||
"contentHash": "CPc6tWO1LAer3IzfZufDBRL+UZQcj5uS207NHALQzP84Vp/z6wF0Aa0YZImOQY8iStY0A2zI/e3ihKNPfUm8XA=="
|
||||
},
|
||||
"System.Diagnostics.EventLog": {
|
||||
"type": "Transitive",
|
||||
"resolved": "6.0.0",
|
||||
"contentHash": "lcyUiXTsETK2ALsZrX+nWuHSIQeazhqPphLfaRxzdGaG93+0kELqpgEHtwWOlQe7+jSFnKwaCAgL4kjeZCQJnw=="
|
||||
},
|
||||
"System.Management": {
|
||||
"type": "Transitive",
|
||||
"resolved": "6.0.1",
|
||||
"contentHash": "10J1D0h/lioojphfJ4Fuh5ZUThT/xOVHdV9roGBittKKNP2PMjrvibEdbVTGZcPra1399Ja3tqIJLyQrc5Wmhg==",
|
||||
"dependencies": {
|
||||
"System.CodeDom": "6.0.0"
|
||||
}
|
||||
},
|
||||
"xunit.analyzers": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.27.0",
|
||||
"contentHash": "y/pxIQaLvk/kxAoDkZW9GnHLCEqzwl5TW0vtX3pweyQpjizB9y3DXhb9pkw2dGeUqhLjsxvvJM1k89JowU6z3g=="
|
||||
},
|
||||
"xunit.v3.assert": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.2.2",
|
||||
"contentHash": "BPciBghgEEaJN/JG00QfCYDfEfnLgQhfnYEy+j1izoeHVNYd5+3Wm8GJ6JgYysOhpBPYGE+sbf75JtrRc7jrdA=="
|
||||
},
|
||||
"xunit.v3.common": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.2.2",
|
||||
"contentHash": "Hj775PEH6GTbbg0wfKRvG2hNspDCvTH9irXhH4qIWgdrOSV1sQlqPie+DOvFeigsFg2fxSM3ZAaaCDQs+KreFA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Bcl.AsyncInterfaces": "6.0.0"
|
||||
}
|
||||
},
|
||||
"xunit.v3.core.mtp-v1": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.2.2",
|
||||
"contentHash": "Ga5aA2Ca9ktz+5k3g5ukzwfexwoqwDUpV6z7atSEUvqtd6JuybU1XopHqg1oFd78QdTfZgZE9h5sHpO4qYIi5w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Testing.Extensions.Telemetry": "1.9.1",
|
||||
"Microsoft.Testing.Extensions.TrxReport.Abstractions": "1.9.1",
|
||||
"Microsoft.Testing.Platform": "1.9.1",
|
||||
"Microsoft.Testing.Platform.MSBuild": "1.9.1",
|
||||
"xunit.v3.extensibility.core": "[3.2.2]",
|
||||
"xunit.v3.runner.inproc.console": "[3.2.2]"
|
||||
}
|
||||
},
|
||||
"xunit.v3.extensibility.core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.2.2",
|
||||
"contentHash": "srY8z/oMPvh/t8axtO2DwrHajhFMH7tnqKildvYrVQIfICi8fOn3yIBWkVPAcrKmHMwvXRJ/XsQM3VMR6DOYfQ==",
|
||||
"dependencies": {
|
||||
"xunit.v3.common": "[3.2.2]"
|
||||
}
|
||||
},
|
||||
"xunit.v3.mtp-v1": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.2.2",
|
||||
"contentHash": "O41aAzYKBT5PWqATa1oEWVNCyEUypFQ4va6K0kz37dduV3EKzXNMaV2UnEhufzU4Cce1I33gg0oldS8tGL5I0A==",
|
||||
"dependencies": {
|
||||
"xunit.analyzers": "1.27.0",
|
||||
"xunit.v3.assert": "[3.2.2]",
|
||||
"xunit.v3.core.mtp-v1": "[3.2.2]"
|
||||
}
|
||||
},
|
||||
"xunit.v3.runner.common": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.2.2",
|
||||
"contentHash": "/hkHkQCzGrugelOAehprm7RIWdsUFVmIVaD6jDH/8DNGCymTlKKPTbGokD5czbAfqfex47mBP0sb0zbHYwrO/g==",
|
||||
"dependencies": {
|
||||
"Microsoft.Win32.Registry": "[5.0.0]",
|
||||
"xunit.v3.common": "[3.2.2]"
|
||||
}
|
||||
},
|
||||
"xunit.v3.runner.inproc.console": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.2.2",
|
||||
"contentHash": "ulWOdSvCk+bPXijJZ73bth9NyoOHsAs1ZOvamYbCkD4DNLX/Bd29Ve2ZNUwBbK0MqfIYWXHZViy/HKrdEC/izw==",
|
||||
"dependencies": {
|
||||
"xunit.v3.extensibility.core": "[3.2.2]",
|
||||
"xunit.v3.runner.common": "[3.2.2]"
|
||||
}
|
||||
},
|
||||
"dodossh.client.ssh": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"SSH.NET": "[2025.1.0, )"
|
||||
}
|
||||
},
|
||||
"dodossh.client.terminal": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"DodoSSH.Client.Ssh": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"BouncyCastle.Cryptography": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2.6.2, )",
|
||||
"resolved": "2.6.2",
|
||||
"contentHash": "7oWOcvnntmMKNzDLsdxAYqApt+AjpRpP2CShjMfIa3umZ42UQMvH0tl1qAliYPNYO6vTdcGMqnRrCPmsfzTI1w=="
|
||||
},
|
||||
"SSH.NET": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2025.1.0, )",
|
||||
"resolved": "2025.1.0",
|
||||
"contentHash": "jrnbtf0ItVaXAe6jE8X/kSLa6uC+0C+7W1vepcnRQB/rD88qy4IxG7Lf1FIbWmkoc4iVXv0pKrz+Wc6J4ngmHw==",
|
||||
"dependencies": {
|
||||
"BouncyCastle.Cryptography": "2.6.2",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "8.0.3"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user