132 lines
4.8 KiB
C#
132 lines
4.8 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Threading.Channels;
|
|
using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol;
|
|
using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Tools;
|
|
|
|
namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Protocol;
|
|
|
|
internal sealed class ProtocolTestConnection : IAsyncDisposable
|
|
{
|
|
public const string Initialization = """
|
|
{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"unit-tests","version":"1"}}
|
|
""";
|
|
private readonly ChannelStream _input = new();
|
|
private readonly ChannelStream _output = new();
|
|
private readonly CancellationTokenSource _stopping = new();
|
|
private readonly StdioTransport _transport;
|
|
private readonly StreamReader _reader;
|
|
private readonly Task _running;
|
|
public StringWriter Diagnostics { get; } = new();
|
|
|
|
public ProtocolTestConnection(McpToolRegistry? registry = null)
|
|
{
|
|
_transport = new(_input, _output);
|
|
_reader = new(_output, new UTF8Encoding(false, true), leaveOpen: true);
|
|
_running = new JsonRpcDispatcher(_transport, new McpSession(registry ?? new()), Diagnostics)
|
|
.RunAsync(_stopping.Token);
|
|
}
|
|
|
|
public static JsonElement Json(string value)
|
|
{
|
|
using var document = JsonDocument.Parse(value);
|
|
return document.RootElement.Clone();
|
|
}
|
|
|
|
public async Task SendAsync(string json) =>
|
|
await _input.WriteAsync(Encoding.UTF8.GetBytes(json + "\n"));
|
|
|
|
public async Task<JsonElement> ReadAsync()
|
|
{
|
|
var line = await _reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(5));
|
|
Assert.NotNull(line);
|
|
var result = Json(line);
|
|
Assert.Equal("2.0", result.GetProperty("jsonrpc").GetString());
|
|
return result;
|
|
}
|
|
|
|
public async Task ReadyAsync()
|
|
{
|
|
await SendAsync($$"""{"jsonrpc":"2.0","id":"init","method":"initialize","params":{{Initialization}}}""");
|
|
Assert.True((await ReadAsync()).TryGetProperty("result", out _));
|
|
await SendAsync("""{"jsonrpc":"2.0","method":"notifications/initialized"}""");
|
|
}
|
|
|
|
public async Task CompleteAsync()
|
|
{
|
|
_input.Complete();
|
|
await _running.WaitAsync(TimeSpan.FromSeconds(5));
|
|
_output.Complete();
|
|
}
|
|
|
|
public async Task CancelAsync()
|
|
{
|
|
_stopping.Cancel();
|
|
await _running.WaitAsync(TimeSpan.FromSeconds(5));
|
|
_output.Complete();
|
|
}
|
|
|
|
public async Task AssertNoMoreResponsesAsync()
|
|
{
|
|
await CompleteAsync();
|
|
Assert.Null(await _reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(5)));
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
_stopping.Cancel();
|
|
_input.Complete();
|
|
await _running.WaitAsync(TimeSpan.FromSeconds(5));
|
|
_output.Complete();
|
|
_reader.Dispose();
|
|
_transport.Dispose();
|
|
_stopping.Dispose();
|
|
_input.Dispose();
|
|
_output.Dispose();
|
|
Diagnostics.Dispose();
|
|
}
|
|
}
|
|
|
|
internal sealed class ChannelStream : Stream
|
|
{
|
|
private readonly Channel<byte[]> _chunks = Channel.CreateUnbounded<byte[]>();
|
|
private byte[]? _current;
|
|
private int _offset;
|
|
|
|
public void Complete() => _chunks.Writer.TryComplete();
|
|
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 void Flush() { }
|
|
public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
|
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
|
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) =>
|
|
_chunks.Writer.TryWrite(buffer.AsSpan(offset, count).ToArray());
|
|
|
|
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
|
{
|
|
if (_current is null || _offset == _current.Length)
|
|
{
|
|
if (!await _chunks.Reader.WaitToReadAsync(cancellationToken))
|
|
{
|
|
return 0;
|
|
}
|
|
|
|
_current = await _chunks.Reader.ReadAsync(cancellationToken);
|
|
_offset = 0;
|
|
}
|
|
|
|
var count = Math.Min(buffer.Length, _current.Length - _offset);
|
|
_current.AsMemory(_offset, count).CopyTo(buffer);
|
|
_offset += count;
|
|
return count;
|
|
}
|
|
|
|
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) =>
|
|
_chunks.Writer.WriteAsync(buffer.ToArray(), cancellationToken);
|
|
}
|