Skip to content
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

Remove some Linq usages from Kestrel.Core #47012

Merged
merged 2 commits into from
Mar 8, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 3 additions & 2 deletions src/Servers/Kestrel/Core/src/Internal/AddressBinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal;

internal sealed class AddressBinder
{
public static async Task BindAsync(IEnumerable<ListenOptions> listenOptions, AddressBindContext context, CancellationToken cancellationToken)
// note this doesn't copy the ListenOptions[], only call this with an array that isn't mutated elsewhere
public static async Task BindAsync(ListenOptions[] listenOptions, AddressBindContext context, CancellationToken cancellationToken)
{
var strategy = CreateStrategy(
listenOptions.ToArray(),
listenOptions,
context.Addresses.ToArray(),
context.ServerAddressesFeature.PreferHostingUrls);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
#nullable enable

using System.IO.Pipelines;
using System.Linq;
using System.Net;
using System.Net.Security;
using Microsoft.AspNetCore.Connections;
Expand Down Expand Up @@ -179,7 +178,14 @@ private void StartAcceptLoop<T>(IConnectionListener<T> connectionListener, Func<

public Task StopEndpointsAsync(List<EndpointConfig> endpointsToStop, CancellationToken cancellationToken)
{
var transportsToStop = _transports.Where(t => t.EndpointConfig != null && endpointsToStop.Contains(t.EndpointConfig)).ToList();
var transportsToStop = new List<ActiveTransport>();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How many do we expect? Almost none? Almost all? I'm thinking "list initial size" reasons

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At most it is _transports.Count. At minimum, it is 0. I'm not sure what the typical case would be.

This is only called on RebindAsync, which happens when the configuration changes and there are endpoints to stop.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd leave it. There are much bigger optimizations we could make to endpoint rebinding if we cared more about this scenario. For example, we could start bringing new endpoints online before completely stopping all the removed ones if they don't conflict.

foreach (var t in _transports)
{
if (t.EndpointConfig is not null && endpointsToStop.Contains(t.EndpointConfig))
{
transportsToStop.Add(t);
}
}
return StopTransportsAsync(transportsToStop, cancellationToken);
}

Expand Down
8 changes: 6 additions & 2 deletions src/Servers/Kestrel/Core/src/Internal/KestrelServerImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ private async Task BindAsync(CancellationToken cancellationToken)

Options.ConfigurationLoader?.Load();

await AddressBinder.BindAsync(Options.ListenOptions, AddressBindContext!, cancellationToken).ConfigureAwait(false);
await AddressBinder.BindAsync(Options.GetListenOptions(), AddressBindContext!, cancellationToken).ConfigureAwait(false);
_configChangedRegistration = reloadToken?.RegisterChangeCallback(TriggerRebind, this);
}
finally
Expand Down Expand Up @@ -364,7 +364,11 @@ private async Task RebindAsync()

// TODO: It would be nice to start binding to new endpoints immediately and reconfigured endpoints as soon
// as the unbinding finished for the given endpoint rather than wait for all transports to unbind first.
var configsToStop = endpointsToStop.Select(lo => lo.EndpointConfig!).ToList();
var configsToStop = new List<EndpointConfig>(endpointsToStop.Count);
foreach (var lo in endpointsToStop)
{
configsToStop.Add(lo.EndpointConfig!);
}
await _transportManager.StopEndpointsAsync(configsToStop, combinedCts.Token).ConfigureAwait(false);

foreach (var listenOption in endpointsToStop)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,14 @@ public void Load()

// Now that defaults have been loaded, we can compare to the currently bound endpoints to see if the config changed.
// There's no reason to rerun an EndpointConfigurations callback if nothing changed.
var matchingBoundEndpoints = endpointsToStop.Where(o => o.EndpointConfig == endpoint).ToList();
var matchingBoundEndpoints = new List<ListenOptions>();
foreach (var o in endpointsToStop)
{
if (o.EndpointConfig == endpoint)
{
matchingBoundEndpoints.Add(o);
}
}

if (matchingBoundEndpoints.Count > 0)
{
Expand Down
15 changes: 14 additions & 1 deletion src/Servers/Kestrel/Core/src/KestrelServerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,20 @@ public class KestrelServerOptions
// The following two lists configure the endpoints that Kestrel should listen to. If both lists are empty, the "urls" config setting (e.g. UseUrls) is used.
internal List<ListenOptions> CodeBackedListenOptions { get; } = new List<ListenOptions>();
internal List<ListenOptions> ConfigurationBackedListenOptions { get; } = new List<ListenOptions>();
internal IEnumerable<ListenOptions> ListenOptions => CodeBackedListenOptions.Concat(ConfigurationBackedListenOptions);

internal ListenOptions[] GetListenOptions()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it really be that bad to leave it as a property? It's not that expensive, and might be easier than tracking down all the tests.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can leave it as a property, but I really dislike allocating in a property getter.

Copy link
Member

@mgravell mgravell Mar 3, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: are the two lists mutated much at the moment? Thery could be stored in a single list or array, with an int that marks the split between the two chunks. Then the combined list is "ignore the split", and the other two lists are just separate pieces of the single chunk - ideally returning either RwadOnlyMemory-ListenOptions, ReadOnlySpan-ListenOptions, or ArraySegment-ListenOptions. If it is easiest to use a list when building, theres a CollectionsMarshal API to sneak inside when needed

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From a quick investigation, for a dotnet new api template app, neither list is mutated.

The way CodeBackedListenOptions gets mutated is if someone adds endpoints in code, ex: builder.WebHost.ConfigureKestrel(o => o.ListenLocalhost(5556));.

The way ConfigurationBackedListenOptions get mutated is if someone adds endpoints through configuration, ex: builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>() { { "Kestrel:EndPoints:Http:Url", "http://localhost:5555" } });.

They are kept separate in order to correctly "reload" on configuration changes. Kestrel knows which ones were added by the previous configuration, and can remove any endpoints that are now removed.

I think your idea might be a good idea, but I think it is out of scope for this PR. Feel free to open a separate PR for it.

{
int resultCount = CodeBackedListenOptions.Count + ConfigurationBackedListenOptions.Count;
if (resultCount == 0)
{
return Array.Empty<ListenOptions>();
}

var result = new ListenOptions[resultCount];
CodeBackedListenOptions.CopyTo(result);
ConfigurationBackedListenOptions.CopyTo(result, CodeBackedListenOptions.Count);
return result;
}

// For testing and debugging.
internal List<ListenOptions> OptionsInUse { get; } = new List<ListenOptions>();
Expand Down
12 changes: 6 additions & 6 deletions src/Servers/Kestrel/Core/test/AddressBinderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ public async Task WrapsAddressInUseExceptionAsIOException()
endpoint => throw new AddressInUseException("already in use"));

await Assert.ThrowsAsync<IOException>(() =>
AddressBinder.BindAsync(options.ListenOptions, addressBindContext, CancellationToken.None));
AddressBinder.BindAsync(options.GetListenOptions(), addressBindContext, CancellationToken.None));
}

[Fact]
Expand All @@ -193,7 +193,7 @@ public void LogsWarningWhenHostingAddressesAreOverridden()
logger,
endpoint => Task.CompletedTask);

var bindTask = AddressBinder.BindAsync(options.ListenOptions, addressBindContext, CancellationToken.None);
var bindTask = AddressBinder.BindAsync(options.GetListenOptions(), addressBindContext, CancellationToken.None);
Assert.True(bindTask.IsCompletedSuccessfully);

var log = Assert.Single(logger.Messages);
Expand Down Expand Up @@ -221,7 +221,7 @@ public void LogsInformationWhenKestrelAddressesAreOverridden()

addressBindContext.ServerAddressesFeature.PreferHostingUrls = true;

var bindTask = AddressBinder.BindAsync(options.ListenOptions, addressBindContext, CancellationToken.None);
var bindTask = AddressBinder.BindAsync(options.GetListenOptions(), addressBindContext, CancellationToken.None);
Assert.True(bindTask.IsCompletedSuccessfully);

var log = Assert.Single(logger.Messages);
Expand All @@ -247,7 +247,7 @@ public async Task FlowsCancellationTokenToCreateBinddingCallback()
});

await Assert.ThrowsAsync<OperationCanceledException>(() =>
AddressBinder.BindAsync(options.ListenOptions, addressBindContext, new CancellationToken(true)));
AddressBinder.BindAsync(options.GetListenOptions(), addressBindContext, new CancellationToken(true)));
}

[Theory]
Expand Down Expand Up @@ -284,7 +284,7 @@ public async Task FallbackToIPv4WhenIPv6AnyBindFails(string address)
return Task.CompletedTask;
});

await AddressBinder.BindAsync(options.ListenOptions, addressBindContext, CancellationToken.None);
await AddressBinder.BindAsync(options.GetListenOptions(), addressBindContext, CancellationToken.None);

Assert.True(ipV4Attempt, "Should have attempted to bind to IPAddress.Any");
Assert.True(ipV6Attempt, "Should have attempted to bind to IPAddress.IPv6Any");
Expand Down Expand Up @@ -315,7 +315,7 @@ public async Task DefaultAddressBinderBindsToHttpPort5000()
return Task.CompletedTask;
});

await AddressBinder.BindAsync(options.ListenOptions, addressBindContext, CancellationToken.None);
await AddressBinder.BindAsync(options.GetListenOptions(), addressBindContext, CancellationToken.None);

Assert.Contains(endpoints, e => e.IPEndPoint.Port == 5000 && !e.IsTls);
}
Expand Down