Skip to content

Multiple accept loops in named pipes transport #46259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ internal sealed class NamedPipeConnectionListener : IConnectionListener
private readonly PipeOptions _inputOptions;
private readonly PipeOptions _outputOptions;
private readonly Mutex _mutex;
private Task? _listeningTask;
private Task[]? _listeningTasks;
private int _disposed;

public NamedPipeConnectionListener(
Expand All @@ -45,7 +45,7 @@ public NamedPipeConnectionListener(
// The OS maintains a backlog of clients that are waiting to connect, so the app queue only stores a single connection.
// We want to have a queue plus a background task that populates the queue, rather than creating NamedPipeServerStream
// when AcceptAsync is called, so that the server is always the owner of the pipe name.
_acceptedQueue = Channel.CreateBounded<ConnectionContext>(new BoundedChannelOptions(capacity: 1) { SingleWriter = true });
_acceptedQueue = Channel.CreateBounded<ConnectionContext>(new BoundedChannelOptions(capacity: 1));

var maxReadBufferSize = _options.MaxReadBufferSize ?? 0;
var maxWriteBufferSize = _options.MaxWriteBufferSize ?? 0;
Expand All @@ -56,12 +56,17 @@ public NamedPipeConnectionListener(

public void Start()
{
Debug.Assert(_listeningTask == null, "Already started");
Debug.Assert(_listeningTasks == null, "Already started");

// Start first stream inline to catch creation errors.
var initialStream = CreateServerStream();
_listeningTasks = new Task[_options.ListenerQueueCount];

_listeningTask = StartAsync(initialStream);
for (var i = 0; i < _listeningTasks.Length; i++)
{
// Start first stream inline to catch creation errors.
var initialStream = CreateServerStream();

_listeningTasks[i] = Task.Run(() => StartAsync(initialStream));
}
}

public EndPoint EndPoint => _endpoint;
Expand Down Expand Up @@ -182,9 +187,9 @@ public async ValueTask DisposeAsync()

_listeningTokenSource.Dispose();
_mutex.Dispose();
if (_listeningTask != null)
if (_listeningTasks != null)
{
await _listeningTask;
await Task.WhenAll(_listeningTasks);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes;
/// </summary>
public sealed class NamedPipeTransportOptions
{
/// <summary>
/// The number of listener queues used to accept name pipe connections.
/// </summary>
/// <remarks>
/// Defaults to <see cref="Environment.ProcessorCount" /> rounded down and clamped between 1 and 16.
/// </remarks>
public int ListenerQueueCount { get; set; } = Math.Min(Environment.ProcessorCount, 16);

/// <summary>
/// Gets or sets the maximum unconsumed incoming bytes the transport will buffer.
/// <para>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ Microsoft.AspNetCore.Hosting.WebHostBuilderNamedPipeExtensions
Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes.NamedPipeTransportOptions
Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes.NamedPipeTransportOptions.CurrentUserOnly.get -> bool
Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes.NamedPipeTransportOptions.CurrentUserOnly.set -> void
Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes.NamedPipeTransportOptions.ListenerQueueCount.get -> int
Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes.NamedPipeTransportOptions.ListenerQueueCount.set -> void
Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes.NamedPipeTransportOptions.MaxReadBufferSize.get -> long?
Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes.NamedPipeTransportOptions.MaxReadBufferSize.set -> void
Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes.NamedPipeTransportOptions.MaxWriteBufferSize.get -> long?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,73 @@ public async Task AcceptAsync_UnbindAfterCall_CleanExitAndLog()
Assert.Contains(LogMessages, m => m.EventId.Name == "ConnectionListenerAborted");
}

[Theory]
[InlineData(1)]
[InlineData(4)]
[InlineData(16)]
public async Task AcceptAsync_ParallelConnections_ClientConnectionsSuccessfullyAccepted(int listenerQueueCount)
{
// Arrange
const int ParallelCount = 10;
const int ParallelCallCount = 250;
const int TotalCallCount = ParallelCount * ParallelCallCount;

var currentCallCount = 0;
var options = new NamedPipeTransportOptions();
options.ListenerQueueCount = listenerQueueCount;
await using var connectionListener = await NamedPipeTestHelpers.CreateConnectionListenerFactory(LoggerFactory, options: options);

// Act
var serverTask = Task.Run(async () =>
{
while (currentCallCount < TotalCallCount)
{
_ = await connectionListener.AcceptAsync();

currentCallCount++;

Logger.LogInformation($"Server accepted {currentCallCount} calls.");
}

Logger.LogInformation($"Server task complete.");
});

var cts = new CancellationTokenSource();
var parallelTasks = new List<Task>();
for (var i = 0; i < ParallelCount; i++)
{
parallelTasks.Add(Task.Run(async () =>
{
var clientStreamCount = 0;
while (clientStreamCount < ParallelCallCount)
{
try
{
var clientStream = NamedPipeTestHelpers.CreateClientStream(connectionListener.EndPoint);
await clientStream.ConnectAsync(cts.Token);

await clientStream.WriteAsync(new byte[1], cts.Token);
await clientStream.DisposeAsync();
clientStreamCount++;
}
catch (IOException ex)
{
Logger.LogInformation(ex, "Client exception.");
}
catch (OperationCanceledException)
{
break;
}
}
}));
}

await serverTask.DefaultTimeout();

cts.Cancel();
await Task.WhenAll(parallelTasks).DefaultTimeout();
}

[ConditionalFact]
[OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX, SkipReason = "Non-OS implementations use UDS with an unlimited accept limit.")]
public async Task AcceptAsync_HitBacklogLimit_ClientConnectionsSuccessfullyAccepted()
Expand Down