diff --git a/src/Orleans.Connections.Security/Hosting/HostingExtensions.cs b/src/Orleans.Connections.Security/Hosting/HostingExtensions.cs index ecda5bcd286..1cb3868b223 100644 --- a/src/Orleans.Connections.Security/Hosting/HostingExtensions.cs +++ b/src/Orleans.Connections.Security/Hosting/HostingExtensions.cs @@ -19,11 +19,7 @@ public static void UseServerTls( } var loggerFactory = builder.ApplicationServices.GetService(typeof(ILoggerFactory)) as ILoggerFactory ?? NullLoggerFactory.Instance; - builder.Use(next => - { - var middleware = new TlsServerConnectionMiddleware(next, options, loggerFactory); - return middleware.OnConnectionAsync; - }); + builder.UseMiddleware(new TlsServerConnectionMiddleware(options, loggerFactory)); } public static void UseClientTls( @@ -36,11 +32,7 @@ public static void UseClientTls( } var loggerFactory = builder.ApplicationServices.GetService(typeof(ILoggerFactory)) as ILoggerFactory ?? NullLoggerFactory.Instance; - builder.Use(next => - { - var middleware = new TlsClientConnectionMiddleware(next, options, loggerFactory); - return middleware.OnConnectionAsync; - }); + builder.UseMiddleware(new TlsClientConnectionMiddleware(options, loggerFactory)); } internal static void ThrowNoPrivateKey(X509Certificate2 certificate, string parameterName) diff --git a/src/Orleans.Connections.Security/Security/TlsClientConnectionMiddleware.cs b/src/Orleans.Connections.Security/Security/TlsClientConnectionMiddleware.cs index 31f8f91ad52..e85be5b1446 100644 --- a/src/Orleans.Connections.Security/Security/TlsClientConnectionMiddleware.cs +++ b/src/Orleans.Connections.Security/Security/TlsClientConnectionMiddleware.cs @@ -8,26 +8,24 @@ using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections.Features; using Microsoft.Extensions.Logging; +using Orleans.Runtime.Messaging; namespace Orleans.Connections.Security { - internal partial class TlsClientConnectionMiddleware + internal partial class TlsClientConnectionMiddleware : IConnectionMiddleware { - private readonly ConnectionDelegate _next; private readonly TlsOptions _options; private readonly ILogger? _logger; private readonly X509Certificate2? _certificate; private readonly Func? _certificateSelector; - public TlsClientConnectionMiddleware(ConnectionDelegate next, TlsOptions options, ILoggerFactory? loggerFactory) + public TlsClientConnectionMiddleware(TlsOptions options, ILoggerFactory? loggerFactory) { if (options == null) { throw new ArgumentNullException(nameof(options)); } - _next = next; - // capture the certificate now so it can't be switched after validation _certificate = ValidateCertificate(options.LocalCertificate, options.ClientCertificateMode); _certificateSelector = options.LocalClientCertificateSelector; @@ -37,12 +35,12 @@ public TlsClientConnectionMiddleware(ConnectionDelegate next, TlsOptions options _logger = loggerFactory?.CreateLogger(); } - public Task OnConnectionAsync(ConnectionContext context) + public Task OnConnectionAsync(ConnectionContext context, ConnectionDelegate next) { - return InnerOnConnectionAsync(context); + return InnerOnConnectionAsync(context, next); } - private async Task InnerOnConnectionAsync(ConnectionContext context) + private async Task InnerOnConnectionAsync(ConnectionContext context, ConnectionDelegate next) { var feature = new TlsConnectionFeature(); context.Features.Set(feature); @@ -195,7 +193,7 @@ private async Task InnerOnConnectionAsync(ConnectionContext context) await using (sslStream) await using (tlsDuplexPipe) { - await _next(context); + await next(context); // Dispose the inner stream (tlsDuplexPipe) before disposing the SslStream // as the duplex pipe can hit an ODE as it still may be writing. } diff --git a/src/Orleans.Connections.Security/Security/TlsServerConnectionMiddleware.cs b/src/Orleans.Connections.Security/Security/TlsServerConnectionMiddleware.cs index c200dc1f4f7..bdbb0c1a454 100644 --- a/src/Orleans.Connections.Security/Security/TlsServerConnectionMiddleware.cs +++ b/src/Orleans.Connections.Security/Security/TlsServerConnectionMiddleware.cs @@ -7,26 +7,24 @@ using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections.Features; using Microsoft.Extensions.Logging; +using Orleans.Runtime.Messaging; namespace Orleans.Connections.Security { - internal partial class TlsServerConnectionMiddleware + internal partial class TlsServerConnectionMiddleware : IConnectionMiddleware { - private readonly ConnectionDelegate _next; private readonly TlsOptions _options; private readonly ILogger? _logger; private readonly X509Certificate2? _certificate; private readonly Func? _certificateSelector; - public TlsServerConnectionMiddleware(ConnectionDelegate next, TlsOptions options, ILoggerFactory? loggerFactory) + public TlsServerConnectionMiddleware(TlsOptions options, ILoggerFactory? loggerFactory) { if (options == null) { throw new ArgumentNullException(nameof(options)); } - _next = next; - // capture the certificate now so it can't be switched after validation _certificate = options.LocalCertificate; _certificateSelector = options.LocalServerCertificateSelector; @@ -50,12 +48,12 @@ public TlsServerConnectionMiddleware(ConnectionDelegate next, TlsOptions options _logger = loggerFactory?.CreateLogger(); } - public Task OnConnectionAsync(ConnectionContext context) + public Task OnConnectionAsync(ConnectionContext context, ConnectionDelegate next) { - return InnerOnConnectionAsync(context); + return InnerOnConnectionAsync(context, next); } - private async Task InnerOnConnectionAsync(ConnectionContext context) + private async Task InnerOnConnectionAsync(ConnectionContext context, ConnectionDelegate next) { bool certificateRequired; var feature = new TlsConnectionFeature(); @@ -222,7 +220,7 @@ private async Task InnerOnConnectionAsync(ConnectionContext context) await using (sslStream) await using (tlsDuplexPipe) { - await _next(context); + await next(context); // Dispose the inner stream (TlsDuplexPipe) before disposing the SslStream // as the duplex pipe can hit an ODE as it still may be writing. } diff --git a/src/Orleans.Core/Networking/ConnectionFrameHelper.cs b/src/Orleans.Core/Networking/ConnectionFrameHelper.cs new file mode 100644 index 00000000000..061b9abeea2 --- /dev/null +++ b/src/Orleans.Core/Networking/ConnectionFrameHelper.cs @@ -0,0 +1,242 @@ +using System; +using System.Buffers; +using System.Buffers.Binary; +using System.IO.Pipelines; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Connections; + +namespace Orleans.Runtime.Messaging +{ + /// + /// Provides framing utilities for connection middleware authors. + /// + /// Wire format per frame: [4-byte LE length] [1-byte frame type] [payload]. + /// The length field equals 1 + payload.Length. + /// + /// + /// Connection middlewares should follow the pipeline pattern + /// (like TLS) and register via SiloConnectionOptions or ClientConnectionOptions. + /// Use these helpers for structured frame I/O within your middleware. + /// + /// + /// This helper is optional. Middleware authors who need custom protocols can read/write + /// directly from context.Transport.Input (PipeReader) and context.Transport.Output + /// (PipeWriter) without using this class. + /// + /// + public static class ConnectionFrameHelper + { + /// + /// Default maximum frame length (1 MB). + /// + public const int DefaultMaxFrameLength = 1024 * 1024; + + /// + /// Prefix size: 4 bytes (LE length) + 1 byte (frame type) = 5 bytes. + /// + public const int FramePrefixSize = 5; + + /// + /// Reads a single frame from the connection. + /// + public static async ValueTask<(byte FrameType, byte[] Payload)> ReadFrameAsync( + ConnectionContext connection, + CancellationToken cancellationToken, + int maxFrameLength = DefaultMaxFrameLength) + { + var input = connection.Transport.Input; + + var readResult = await input.ReadAsync(cancellationToken); + var buffer = readResult.Buffer; + CheckCompletionWithData(ref readResult, 4); + + while (buffer.Length < 4) + { + input.AdvanceTo(buffer.Start, buffer.End); + readResult = await input.ReadAsync(cancellationToken); + buffer = readResult.Buffer; + CheckCompletionWithData(ref readResult, 4); + } + + var lengthBytes = new byte[4]; + buffer.Slice(0, 4).CopyTo(lengthBytes); + var frameLength = BinaryPrimitives.ReadInt32LittleEndian(lengthBytes); + + if (frameLength < 1) + throw new InvalidOperationException($"Invalid frame length: {frameLength}. Minimum is 1 (frame type byte)."); + if (frameLength > maxFrameLength) + throw new InvalidOperationException($"Frame length {frameLength} exceeds maximum allowed length of {maxFrameLength}."); + + input.AdvanceTo(buffer.GetPosition(4)); + + var frameBytes = new byte[frameLength]; + var bytesRead = 0; + while (bytesRead < frameLength) + { + readResult = await input.ReadAsync(cancellationToken); + buffer = readResult.Buffer; + + if (readResult.IsCanceled) + { + input.AdvanceTo(buffer.Start, buffer.End); + throw new InvalidOperationException("Connection terminated during frame exchange."); + } + + var bytesToCopy = (int)Math.Min(buffer.Length, frameLength - bytesRead); + buffer.Slice(0, bytesToCopy).CopyTo(frameBytes.AsSpan(bytesRead, bytesToCopy)); + bytesRead += bytesToCopy; + input.AdvanceTo(buffer.GetPosition(bytesToCopy)); + + if (readResult.IsCompleted && bytesRead < frameLength) + { + throw new InvalidOperationException("Connection terminated during frame exchange."); + } + } + + byte frameType = frameBytes[0]; + byte[] payload; + if (frameLength > 1) + { + payload = new byte[frameLength - 1]; + Array.Copy(frameBytes, 1, payload, 0, payload.Length); + } + else + { + payload = Array.Empty(); + } + + return (frameType, payload); + } + + /// + /// Writes a frame with the given type and raw payload bytes. + /// + public static async ValueTask WriteFrameAsync( + ConnectionContext connection, + byte frameType, + byte[] payload, + CancellationToken cancellationToken) + { + WriteFrameToOutput(connection.Transport.Output, frameType, payload); + await FlushFrameAsync(connection.Transport.Output, cancellationToken); + } + + /// + /// Writes a frame using zero-copy framing via . + /// The delegate writes payload directly into the transport pipe buffer. + /// + public static async ValueTask WriteFrameAsync( + ConnectionContext connection, + byte frameType, + Action> writePayload, + CancellationToken cancellationToken) + { + WriteFrameWithPrefixingWriter(connection.Transport.Output, frameType, writePayload, MemoryPool.Shared); + await FlushFrameAsync(connection.Transport.Output, cancellationToken); + } + + private static async ValueTask FlushFrameAsync(PipeWriter output, CancellationToken cancellationToken) + { + var flushResult = await output.FlushAsync(cancellationToken); + if (flushResult.IsCanceled) + throw new OperationCanceledException("Flush canceled while writing frame."); + if (flushResult.IsCompleted) + throw new InvalidOperationException("Connection terminated while writing frame."); + } + + /// + /// Writes a length-prefixed UTF-8 string (4-byte LE length + bytes) into a buffer. + /// + public static void WriteLengthPrefixedString(IBufferWriter writer, string value) + { + var bytes = Encoding.UTF8.GetBytes(value ?? string.Empty); + + var lengthSpan = writer.GetSpan(4); + BinaryPrimitives.WriteInt32LittleEndian(lengthSpan, bytes.Length); + writer.Advance(4); + + if (bytes.Length > 0) + { + var dataSpan = writer.GetSpan(bytes.Length); + bytes.CopyTo(dataSpan); + writer.Advance(bytes.Length); + } + } + + /// + /// Reads a length-prefixed UTF-8 string from a payload byte array. + /// + public static string ReadLengthPrefixedString(byte[] data, ref int offset) + { + if ((uint)offset > (uint)data.Length || data.Length - offset < sizeof(int)) + throw new InvalidOperationException("Not enough data to read string length."); + + var length = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(offset, sizeof(int))); + offset += sizeof(int); + + if (length < 0) + throw new InvalidOperationException($"Invalid string length: {length}."); + if (length == 0) + return string.Empty; + if (length > data.Length - offset) + throw new InvalidOperationException($"Not enough data to read string of length {length}. Available: {data.Length - offset}."); + + var result = Encoding.UTF8.GetString(data, offset, length); + offset += length; + return result; + } + + private static void WriteFrameToOutput(PipeWriter output, byte frameType, byte[] payload) + { + var payloadLength = payload?.Length ?? 0; + var frameLength = 1 + payloadLength; + + Span prefix = stackalloc byte[FramePrefixSize]; + BinaryPrimitives.WriteInt32LittleEndian(prefix, frameLength); + prefix[4] = frameType; + output.Write(prefix); + + if (payloadLength > 0) + { + output.Write(payload); + } + } + + private static void WriteFrameWithPrefixingWriter( + PipeWriter output, + byte frameType, + Action> writeBody, + MemoryPool memoryPool) + { + using var prefixWriter = new PrefixingBufferWriter(FramePrefixSize, 256, memoryPool); + prefixWriter.Init(output); + + try + { + writeBody?.Invoke(prefixWriter); + + var payloadLength = prefixWriter.CommittedBytes; + var frameLength = 1 + payloadLength; + Span prefix = stackalloc byte[FramePrefixSize]; + BinaryPrimitives.WriteInt32LittleEndian(prefix, frameLength); + prefix[4] = frameType; + + prefixWriter.Complete(prefix); + } + finally + { + prefixWriter.Reset(); + } + } + + private static void CheckCompletionWithData(ref ReadResult result, long required) + { + if (result.IsCanceled) + throw new InvalidOperationException("Connection terminated during frame exchange."); + if (result.IsCompleted && result.Buffer.Length < required) + throw new InvalidOperationException("Connection terminated during frame exchange."); + } + } +} diff --git a/src/Orleans.Core/Networking/ConnectionMiddlewareExtensions.cs b/src/Orleans.Core/Networking/ConnectionMiddlewareExtensions.cs new file mode 100644 index 00000000000..02e22599cba --- /dev/null +++ b/src/Orleans.Core/Networking/ConnectionMiddlewareExtensions.cs @@ -0,0 +1,51 @@ +using System; +using Microsoft.AspNetCore.Connections; +using Microsoft.Extensions.DependencyInjection; +using Orleans.Runtime.Messaging; + +namespace Orleans +{ + /// + /// Extension methods for registering in the connection pipeline. + /// + public static class ConnectionMiddlewareExtensions + { + /// + /// Adds an to the connection pipeline. + /// The middleware must be registered as a singleton service and must be safe for concurrent use. + /// + /// The middleware type implementing . + public static IConnectionBuilder UseMiddleware(this IConnectionBuilder builder) where T : IConnectionMiddleware + { + builder.Use(next => + { + var middleware = builder.ApplicationServices.GetRequiredService(); + return context => middleware.OnConnectionAsync(context, next); + }); + + return builder; + } + + /// + /// Adds an instance to the connection pipeline. + /// + /// + /// The instance is shared by all connections and must be safe for concurrent use. + /// The caller owns the instance and is responsible for disposing it. + /// + public static IConnectionBuilder UseMiddleware(this IConnectionBuilder builder, IConnectionMiddleware middleware) + { + if (middleware is null) + { + throw new ArgumentNullException(nameof(middleware)); + } + + builder.Use(next => + { + return context => middleware.OnConnectionAsync(context, next); + }); + + return builder; + } + } +} diff --git a/src/Orleans.Core/Networking/IConnectionMiddleware.cs b/src/Orleans.Core/Networking/IConnectionMiddleware.cs new file mode 100644 index 00000000000..ecfc82eadf0 --- /dev/null +++ b/src/Orleans.Core/Networking/IConnectionMiddleware.cs @@ -0,0 +1,32 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.Connections; + +namespace Orleans.Runtime.Messaging +{ + /// + /// Interface for connection middleware. + /// + /// Implementers provide and invoke the supplied + /// to continue the pipeline. + /// + /// + /// Middleware instances can be invoked concurrently for multiple connections. + /// Per-connection state should be stored in local variables or on the + /// . + /// + /// + /// Register via builder.UseMiddleware() or manually with + /// builder.Use(next => ctx => middleware.OnConnectionAsync(ctx, next)). + /// + /// + public interface IConnectionMiddleware + { + /// + /// Called when a connection is established. Implementations should call + /// to continue the pipeline after performing their work. + /// + /// The connection context. + /// The next delegate in the connection pipeline. + Task OnConnectionAsync(ConnectionContext context, ConnectionDelegate next); + } +} diff --git a/src/api/Orleans.Core/Orleans.Core.cs b/src/api/Orleans.Core/Orleans.Core.cs index 1e4e28ab274..998d47a1dfa 100644 --- a/src/api/Orleans.Core/Orleans.Core.cs +++ b/src/api/Orleans.Core/Orleans.Core.cs @@ -87,6 +87,14 @@ public CollectionAgeLimitAttribute(string inactivityPeriod) { } public void Populate(System.IServiceProvider services, System.Type grainClass, Runtime.GrainType grainType, System.Collections.Generic.Dictionary properties) { } } + public static partial class ConnectionMiddlewareExtensions + { + public static Microsoft.AspNetCore.Connections.IConnectionBuilder UseMiddleware(this Microsoft.AspNetCore.Connections.IConnectionBuilder builder, Runtime.Messaging.IConnectionMiddleware middleware) { throw null; } + + public static Microsoft.AspNetCore.Connections.IConnectionBuilder UseMiddleware(this Microsoft.AspNetCore.Connections.IConnectionBuilder builder) + where T : Runtime.Messaging.IConnectionMiddleware { throw null; } + } + public delegate void ConnectionToClusterLostHandler(object? sender, System.EventArgs e); public delegate TInstance Factory(); public delegate TInstance Factory(TParam1 param1); @@ -1622,6 +1630,26 @@ public ConnectionFailedException(string message, System.Exception innerException public ConnectionFailedException(string message) { } } + public static partial class ConnectionFrameHelper + { + public const int DefaultMaxFrameLength = 1048576; + public const int FramePrefixSize = 5; + public static System.Threading.Tasks.ValueTask<(byte FrameType, byte[] Payload)> ReadFrameAsync(Microsoft.AspNetCore.Connections.ConnectionContext connection, System.Threading.CancellationToken cancellationToken, int maxFrameLength = 1048576) { throw null; } + + public static string ReadLengthPrefixedString(byte[] data, ref int offset) { throw null; } + + public static System.Threading.Tasks.ValueTask WriteFrameAsync(Microsoft.AspNetCore.Connections.ConnectionContext connection, byte frameType, System.Action> writePayload, System.Threading.CancellationToken cancellationToken) { throw null; } + + public static System.Threading.Tasks.ValueTask WriteFrameAsync(Microsoft.AspNetCore.Connections.ConnectionContext connection, byte frameType, byte[] payload, System.Threading.CancellationToken cancellationToken) { throw null; } + + public static void WriteLengthPrefixedString(System.Buffers.IBufferWriter writer, string value) { } + } + + public partial interface IConnectionMiddleware + { + System.Threading.Tasks.Task OnConnectionAsync(Microsoft.AspNetCore.Connections.ConnectionContext context, Microsoft.AspNetCore.Connections.ConnectionDelegate next); + } + [GenerateSerializer] public sealed partial class InvalidMessageFrameException : OrleansException { diff --git a/test/Orleans.Core.Tests/Networking/ConnectionFrameHelperTests.cs b/test/Orleans.Core.Tests/Networking/ConnectionFrameHelperTests.cs new file mode 100644 index 00000000000..2ed2b307ff3 --- /dev/null +++ b/test/Orleans.Core.Tests/Networking/ConnectionFrameHelperTests.cs @@ -0,0 +1,306 @@ +using System; +using System.Buffers; +using System.Buffers.Binary; +using System.IO.Pipelines; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Connections; +using Microsoft.AspNetCore.Http.Features; +using Orleans.Runtime.Messaging; +using Xunit; + +namespace Orleans.Core.Tests.Networking +{ + [Trait("Category", "BVT")] + public class ConnectionFrameHelperTests + { + [Fact] + public async Task WriteAndReadFrame_RoundTrips() + { + var pipe = new Pipe(); + var context = new TestConnectionContext(pipe); + + byte expectedFrameType = 0x01; + byte[] expectedPayload = Encoding.UTF8.GetBytes("hello world"); + + await ConnectionFrameHelper.WriteFrameAsync(context, expectedFrameType, expectedPayload, CancellationToken.None); + await pipe.Writer.CompleteAsync(); + + var (frameType, payload) = await ConnectionFrameHelper.ReadFrameAsync(context, CancellationToken.None); + + Assert.Equal(expectedFrameType, frameType); + Assert.Equal(expectedPayload, payload); + } + + [Fact] + public async Task WriteAndReadFrame_EmptyPayload() + { + var pipe = new Pipe(); + var context = new TestConnectionContext(pipe); + + byte expectedFrameType = 0x05; + byte[] expectedPayload = Array.Empty(); + + await ConnectionFrameHelper.WriteFrameAsync(context, expectedFrameType, expectedPayload, CancellationToken.None); + await pipe.Writer.CompleteAsync(); + + var (frameType, payload) = await ConnectionFrameHelper.ReadFrameAsync(context, CancellationToken.None); + + Assert.Equal(expectedFrameType, frameType); + Assert.Empty(payload); + } + + [Fact] + public async Task WriteAndReadFrame_ZeroCopyPath_RoundTrips() + { + var pipe = new Pipe(); + var context = new TestConnectionContext(pipe); + + byte expectedFrameType = 0x02; + var expectedText = "zero-copy test"; + + await ConnectionFrameHelper.WriteFrameAsync( + context, + expectedFrameType, + writer => { writer.Write(Encoding.UTF8.GetBytes(expectedText)); }, + CancellationToken.None); + + await pipe.Writer.CompleteAsync(); + + var (frameType, payload) = await ConnectionFrameHelper.ReadFrameAsync(context, CancellationToken.None); + + Assert.Equal(expectedFrameType, frameType); + Assert.Equal(expectedText, Encoding.UTF8.GetString(payload)); + } + + [Fact] + public async Task WriteFrame_CompletedReader_Throws() + { + var pipe = new Pipe(); + var context = new TestConnectionContext(pipe); + await pipe.Reader.CompleteAsync(); + + await Assert.ThrowsAsync(async () => + await ConnectionFrameHelper.WriteFrameAsync(context, 0x01, Array.Empty(), CancellationToken.None)); + } + + [Fact] + public async Task WriteFrame_ZeroCopyPath_CompletedReader_Throws() + { + var pipe = new Pipe(); + var context = new TestConnectionContext(pipe); + await pipe.Reader.CompleteAsync(); + + await Assert.ThrowsAsync(async () => + await ConnectionFrameHelper.WriteFrameAsync(context, 0x01, _ => { }, CancellationToken.None)); + } + + [Fact] + public async Task ReadFrame_RejectsFrameExceedingMaxLength() + { + var pipe = new Pipe(); + var context = new TestConnectionContext(pipe); + + var output = pipe.Writer; + var lengthBytes = new byte[4]; + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(lengthBytes, 2_000_000); + output.Write(lengthBytes); + await output.FlushAsync(); + await output.CompleteAsync(); + + await Assert.ThrowsAsync(async () => + await ConnectionFrameHelper.ReadFrameAsync(context, CancellationToken.None, maxFrameLength: 1024)); + } + + [Fact] + public async Task ReadFrame_RejectsInvalidFrameLength() + { + var pipe = new Pipe(); + var context = new TestConnectionContext(pipe); + + var output = pipe.Writer; + var lengthBytes = new byte[4]; + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(lengthBytes, 0); + output.Write(lengthBytes); + await output.FlushAsync(); + await output.CompleteAsync(); + + await Assert.ThrowsAsync(async () => + await ConnectionFrameHelper.ReadFrameAsync(context, CancellationToken.None)); + } + + [Fact] + public async Task WriteAndReadMultipleFrames() + { + var pipe = new Pipe(); + var context = new TestConnectionContext(pipe); + + await ConnectionFrameHelper.WriteFrameAsync(context, 0x01, Encoding.UTF8.GetBytes("first"), CancellationToken.None); + await ConnectionFrameHelper.WriteFrameAsync(context, 0x02, Encoding.UTF8.GetBytes("second"), CancellationToken.None); + await ConnectionFrameHelper.WriteFrameAsync(context, 0x03, Encoding.UTF8.GetBytes("third"), CancellationToken.None); + await pipe.Writer.CompleteAsync(); + + var (type1, payload1) = await ConnectionFrameHelper.ReadFrameAsync(context, CancellationToken.None); + var (type2, payload2) = await ConnectionFrameHelper.ReadFrameAsync(context, CancellationToken.None); + var (type3, payload3) = await ConnectionFrameHelper.ReadFrameAsync(context, CancellationToken.None); + + Assert.Equal(0x01, type1); + Assert.Equal("first", Encoding.UTF8.GetString(payload1)); + Assert.Equal(0x02, type2); + Assert.Equal("second", Encoding.UTF8.GetString(payload2)); + Assert.Equal(0x03, type3); + Assert.Equal("third", Encoding.UTF8.GetString(payload3)); + } + + [Fact] + public async Task ReadFrame_ConsumesDataUnderBackpressure() + { + var pipe = new Pipe(new PipeOptions( + pauseWriterThreshold: 64, + resumeWriterThreshold: 32, + minimumSegmentSize: 16, + useSynchronizationContext: false)); + var context = new TestConnectionContext(pipe); + var expectedPayload = new byte[256]; + Array.Fill(expectedPayload, (byte)0x2A); + + var writeTask = WriteFrameInChunksAsync(pipe.Writer, 0x04, expectedPayload, 16); + var readTask = ConnectionFrameHelper.ReadFrameAsync(context, CancellationToken.None).AsTask(); + + await Task.WhenAll(writeTask, readTask).WaitAsync(TimeSpan.FromSeconds(10)); + + var (frameType, payload) = await readTask; + Assert.Equal(0x04, frameType); + Assert.Equal(expectedPayload, payload); + } + + [Fact] + public void WriteLengthPrefixedString_ReadLengthPrefixedString_RoundTrips() + { + var buffer = new ArrayBufferWriter(); + var expected = "hello, orleans!"; + + ConnectionFrameHelper.WriteLengthPrefixedString(buffer, expected); + + var data = buffer.WrittenSpan.ToArray(); + int offset = 0; + var result = ConnectionFrameHelper.ReadLengthPrefixedString(data, ref offset); + + Assert.Equal(expected, result); + Assert.Equal(data.Length, offset); + } + + [Fact] + public void WriteLengthPrefixedString_EmptyString() + { + var buffer = new ArrayBufferWriter(); + + ConnectionFrameHelper.WriteLengthPrefixedString(buffer, ""); + + var data = buffer.WrittenSpan.ToArray(); + int offset = 0; + var result = ConnectionFrameHelper.ReadLengthPrefixedString(data, ref offset); + + Assert.Equal("", result); + Assert.Equal(4, offset); + } + + [Fact] + public void WriteLengthPrefixedString_MultipleStrings() + { + var buffer = new ArrayBufferWriter(); + var strings = new[] { "alpha", "beta", "gamma" }; + + foreach (var s in strings) + ConnectionFrameHelper.WriteLengthPrefixedString(buffer, s); + + var data = buffer.WrittenSpan.ToArray(); + int offset = 0; + foreach (var expected in strings) + { + var result = ConnectionFrameHelper.ReadLengthPrefixedString(data, ref offset); + Assert.Equal(expected, result); + } + } + + [Fact] + public void ReadLengthPrefixedString_InsufficientData_Throws() + { + var data = new byte[] { 0x01, 0x02 }; + int offset = 0; + + Assert.Throws(() => + ConnectionFrameHelper.ReadLengthPrefixedString(data, ref offset)); + } + + [Fact] + public void ReadLengthPrefixedString_OversizedLength_Throws() + { + var data = new byte[sizeof(int)]; + BinaryPrimitives.WriteInt32LittleEndian(data, int.MaxValue); + int offset = 0; + + Assert.Throws(() => + ConnectionFrameHelper.ReadLengthPrefixedString(data, ref offset)); + } + + [Fact] + public void ReadLengthPrefixedString_NegativeOffset_Throws() + { + var data = Array.Empty(); + int offset = -1; + + Assert.Throws(() => + ConnectionFrameHelper.ReadLengthPrefixedString(data, ref offset)); + } + + private static async Task WriteFrameInChunksAsync(PipeWriter writer, byte frameType, byte[] payload, int chunkSize) + { + var frame = new byte[ConnectionFrameHelper.FramePrefixSize + payload.Length]; + BinaryPrimitives.WriteInt32LittleEndian(frame, payload.Length + 1); + frame[4] = frameType; + payload.CopyTo(frame, ConnectionFrameHelper.FramePrefixSize); + + for (var offset = 0; offset < frame.Length; offset += chunkSize) + { + var length = Math.Min(chunkSize, frame.Length - offset); + writer.Write(frame.AsSpan(offset, length)); + await writer.FlushAsync(); + } + + await writer.CompleteAsync(); + } + + /// + /// Minimal ConnectionContext backed by a Pipe for testing. + /// + private sealed class TestConnectionContext : ConnectionContext + { + private readonly IDuplexPipe _transport; + + public TestConnectionContext(Pipe pipe) + { + _transport = new DuplexPipe(pipe.Reader, pipe.Writer); + } + + public override string ConnectionId { get; set; } = Guid.NewGuid().ToString(); + public override IDuplexPipe Transport { get => _transport; set => throw new NotSupportedException(); } + public override IFeatureCollection Features { get; } = new FeatureCollection(); + public override IDictionary Items { get; set; } = new Dictionary(); + + private sealed class DuplexPipe : IDuplexPipe + { + public DuplexPipe(PipeReader input, PipeWriter output) + { + Input = input; + Output = output; + } + + public PipeReader Input { get; } + public PipeWriter Output { get; } + } + + } + } +} diff --git a/test/Orleans.Core.Tests/Networking/ConnectionMiddlewareTests.cs b/test/Orleans.Core.Tests/Networking/ConnectionMiddlewareTests.cs new file mode 100644 index 00000000000..1e3364065f1 --- /dev/null +++ b/test/Orleans.Core.Tests/Networking/ConnectionMiddlewareTests.cs @@ -0,0 +1,207 @@ +using System; +using System.Collections.Generic; +using System.IO.Pipelines; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Connections; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.Extensions.DependencyInjection; +using Orleans.Runtime.Messaging; +using Xunit; + +namespace Orleans.Core.Tests.Networking +{ + [Trait("Category", "BVT")] + public class ConnectionMiddlewareTests + { + [Fact] + public async Task UseMiddleware_InvokesMiddlewareAndNext() + { + var callOrder = new List(); + + var services = new ServiceCollection().BuildServiceProvider(); + var builder = new TestConnectionBuilder(services); + + builder.UseMiddleware(new TrackingMiddleware("first", callOrder)); + builder.UseMiddleware(new TrackingMiddleware("second", callOrder)); + + var pipeline = builder.Build(); + var context = CreateContext(); + + await pipeline(context); + + Assert.Equal(new[] { "first", "second" }, callOrder); + } + + [Fact] + public async Task UseMiddleware_MiddlewareThatDoesNotCallNext_TerminatesPipeline() + { + var callOrder = new List(); + + var services = new ServiceCollection().BuildServiceProvider(); + var builder = new TestConnectionBuilder(services); + + builder.UseMiddleware(new TerminatingMiddleware("blocker", callOrder)); + builder.UseMiddleware(new TrackingMiddleware("should-not-run", callOrder)); + + var pipeline = builder.Build(); + var context = CreateContext(); + + await pipeline(context); + + Assert.Equal(new[] { "blocker" }, callOrder); + } + + [Fact] + public async Task UseMiddleware_Generic_ResolvesFromDI() + { + var callOrder = new List(); + var middleware = new InjectedMiddleware(callOrder); + + var services = new ServiceCollection() + .AddSingleton(callOrder) + .AddSingleton(middleware) + .BuildServiceProvider(); + + var builder = new TestConnectionBuilder(services); + builder.UseMiddleware(); + + var pipeline = builder.Build(); + var context = CreateContext(); + + await pipeline(context); + + Assert.Equal(new[] { "injected-middleware" }, callOrder); + Assert.Equal(1, middleware.InvocationCount); + } + + [Fact] + public void UseMiddleware_Generic_RequiresRegistration() + { + var services = new ServiceCollection().BuildServiceProvider(); + var builder = new TestConnectionBuilder(services); + builder.UseMiddleware(); + + Assert.Throws(() => builder.Build()); + } + + private static ConnectionContext CreateContext() + { + var pipe = new Pipe(); + return new TestConnectionContext(pipe); + } + + private sealed class TrackingMiddleware : IConnectionMiddleware + { + private readonly string _name; + private readonly List _callOrder; + + public TrackingMiddleware(string name, List callOrder) + { + _name = name; + _callOrder = callOrder; + } + + public async Task OnConnectionAsync(ConnectionContext context, ConnectionDelegate next) + { + _callOrder.Add(_name); + await next(context); + } + } + + private sealed class TerminatingMiddleware : IConnectionMiddleware + { + private readonly string _name; + private readonly List _callOrder; + + public TerminatingMiddleware(string name, List callOrder) + { + _name = name; + _callOrder = callOrder; + } + + public Task OnConnectionAsync(ConnectionContext context, ConnectionDelegate next) + { + _callOrder.Add(_name); + // Intentionally NOT calling next + return Task.CompletedTask; + } + } + + private sealed class InjectedMiddleware : IConnectionMiddleware + { + private readonly List _callOrder; + + public InjectedMiddleware(List callOrder) + { + _callOrder = callOrder; + } + + public int InvocationCount { get; private set; } + + public async Task OnConnectionAsync(ConnectionContext context, ConnectionDelegate next) + { + InvocationCount++; + _callOrder.Add("injected-middleware"); + await next(context); + } + } + + private sealed class TestConnectionBuilder : IConnectionBuilder + { + private readonly List> _middlewares = new(); + + public TestConnectionBuilder(IServiceProvider services) + { + ApplicationServices = services; + } + + public IServiceProvider ApplicationServices { get; } + + public IConnectionBuilder Use(Func middleware) + { + _middlewares.Add(middleware); + return this; + } + + public ConnectionDelegate Build() + { + ConnectionDelegate app = _ => Task.CompletedTask; + + for (var i = _middlewares.Count - 1; i >= 0; i--) + { + app = _middlewares[i](app); + } + + return app; + } + } + + private sealed class TestConnectionContext : ConnectionContext + { + private readonly IDuplexPipe _transport; + + public TestConnectionContext(Pipe pipe) + { + _transport = new DuplexPipe(pipe.Reader, pipe.Writer); + } + + public override string ConnectionId { get; set; } = Guid.NewGuid().ToString(); + public override IDuplexPipe Transport { get => _transport; set => throw new NotSupportedException(); } + public override IFeatureCollection Features { get; } = new FeatureCollection(); + public override IDictionary Items { get; set; } = new Dictionary(); + + private sealed class DuplexPipe : IDuplexPipe + { + public DuplexPipe(PipeReader input, PipeWriter output) + { + Input = input; + Output = output; + } + + public PipeReader Input { get; } + public PipeWriter Output { get; } + } + + } + } +}