Improve testing for StreamableHttpHandler and IdleTrackingBackgroundService (#345)
* Add idle session pruning tests
* Remove redundant CTS from StreamableHttpHandler
* StreamableHttpServerTransport.HandlePostRequest already creates the equivelant CTS
which DeleteRequest_CompletesSession_WhichCancelsLongRunningToolCalls verifies
* Fix accept header validation for GET
* Use InvalidOperationException for transport-not-connected errors in doc comments
* Fix flaky Cancellation_ThrowsCancellationException test
This commit is contained in:
parent
4fd3ebf3fe
commit
e3ff552824
1 changed files with 315 additions and 291 deletions
|
|
@ -8,28 +8,40 @@ namespace ModelContextProtocol.AspNetCore;
|
|||
internal sealed partial class IdleTrackingBackgroundService(
|
||||
StreamableHttpHandler handler,
|
||||
IOptions<HttpServerTransportOptions> options,
|
||||
IHostApplicationLifetime appLifetime,
|
||||
ILogger<IdleTrackingBackgroundService> logger) : BackgroundService
|
||||
{
|
||||
// The compiler will complain about the parameter being unused otherwise despite the source generator.
|
||||
private ILogger _logger = logger;
|
||||
|
||||
// We can make this configurable once we properly harden the MCP server. In the meantime, anyone running
|
||||
// this should be taking a cattle not pets approach to their servers and be able to launch more processes
|
||||
// to handle more than 10,000 idle sessions at a time.
|
||||
private const int MaxIdleSessionCount = 10_000;
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
var timeProvider = options.Value.TimeProvider;
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), timeProvider);
|
||||
// Still run loop given infinite IdleTimeout to enforce the MaxIdleSessionCount and assist graceful shutdown.
|
||||
if (options.Value.IdleTimeout != Timeout.InfiniteTimeSpan)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(options.Value.IdleTimeout, TimeSpan.Zero);
|
||||
}
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(options.Value.MaxIdleSessionCount, 0);
|
||||
|
||||
try
|
||||
{
|
||||
var timeProvider = options.Value.TimeProvider;
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), timeProvider);
|
||||
|
||||
var idleTimeoutTicks = options.Value.IdleTimeout.Ticks;
|
||||
var maxIdleSessionCount = options.Value.MaxIdleSessionCount;
|
||||
|
||||
// The default ValueTuple Comparer will check the first item then the second which preserves both order and uniqueness.
|
||||
var idleSessions = new SortedSet<(long Timestamp, string SessionId)>();
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
var idleActivityCutoff = timeProvider.GetTimestamp() - options.Value.IdleTimeout.Ticks;
|
||||
var idleActivityCutoff = idleTimeoutTicks switch
|
||||
{
|
||||
< 0 => long.MinValue,
|
||||
var ticks => timeProvider.GetTimestamp() - ticks,
|
||||
};
|
||||
|
||||
var idleCount = 0;
|
||||
foreach (var (_, session) in handler.Sessions)
|
||||
{
|
||||
if (session.IsActive || session.SessionClosed.IsCancellationRequested)
|
||||
|
|
@ -38,26 +50,32 @@ internal sealed partial class IdleTrackingBackgroundService(
|
|||
continue;
|
||||
}
|
||||
|
||||
idleCount++;
|
||||
if (idleCount == MaxIdleSessionCount)
|
||||
{
|
||||
// Emit critical log at most once every 5 seconds the idle count it exceeded,
|
||||
//since the IdleTimeout will no longer be respected.
|
||||
LogMaxSessionIdleCountExceeded();
|
||||
}
|
||||
else if (idleCount < MaxIdleSessionCount && session.LastActivityTicks > idleActivityCutoff)
|
||||
if (session.LastActivityTicks < idleActivityCutoff)
|
||||
{
|
||||
RemoveAndCloseSession(session.Id);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (handler.Sessions.TryRemove(session.Id, out var removedSession))
|
||||
{
|
||||
LogSessionIdle(removedSession.Id);
|
||||
idleSessions.Add((session.LastActivityTicks, session.Id));
|
||||
|
||||
// Don't slow down the idle tracking loop. DisposeSessionAsync logs. We only await during graceful shutdown.
|
||||
_ = DisposeSessionAsync(removedSession);
|
||||
// Emit critical log at most once every 5 seconds the idle count it exceeded,
|
||||
// since the IdleTimeout will no longer be respected.
|
||||
if (idleSessions.Count == maxIdleSessionCount + 1)
|
||||
{
|
||||
LogMaxSessionIdleCountExceeded(maxIdleSessionCount);
|
||||
}
|
||||
}
|
||||
|
||||
if (idleSessions.Count > maxIdleSessionCount)
|
||||
{
|
||||
var sessionsToPrune = idleSessions.ToArray()[..^maxIdleSessionCount];
|
||||
foreach (var (_, id) in sessionsToPrune)
|
||||
{
|
||||
RemoveAndCloseSession(id);
|
||||
}
|
||||
}
|
||||
|
||||
idleSessions.Clear();
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
|
|
@ -65,7 +83,7 @@ internal sealed partial class IdleTrackingBackgroundService(
|
|||
}
|
||||
finally
|
||||
{
|
||||
if (stoppingToken.IsCancellationRequested)
|
||||
try
|
||||
{
|
||||
List<Task> disposeSessionTasks = [];
|
||||
|
||||
|
|
@ -79,9 +97,31 @@ internal sealed partial class IdleTrackingBackgroundService(
|
|||
|
||||
await Task.WhenAll(disposeSessionTasks);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
// Something went terribly wrong. A very unexpected exception must be bubbling up, but let's ensure we also stop the application,
|
||||
// so that it hopefully gets looked at and restarted. This shouldn't really be reachable.
|
||||
appLifetime.StopApplication();
|
||||
IdleTrackingBackgroundServiceStoppedUnexpectedly();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveAndCloseSession(string sessionId)
|
||||
{
|
||||
if (!handler.Sessions.TryRemove(sessionId, out var session))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
LogSessionIdle(session.Id);
|
||||
// Don't slow down the idle tracking loop. DisposeSessionAsync logs. We only await during graceful shutdown.
|
||||
_ = DisposeSessionAsync(session);
|
||||
}
|
||||
|
||||
private async Task DisposeSessionAsync(HttpMcpSession<StreamableHttpServerTransport> session)
|
||||
{
|
||||
try
|
||||
|
|
@ -97,9 +137,12 @@ internal sealed partial class IdleTrackingBackgroundService(
|
|||
[LoggerMessage(Level = LogLevel.Information, Message = "Closing idle session {sessionId}.")]
|
||||
private partial void LogSessionIdle(string sessionId);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Critical, Message = "Exceeded static maximum of 10,000 idle connections. Now clearing all inactive connections regardless of timeout.")]
|
||||
private partial void LogMaxSessionIdleCountExceeded();
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Error disposing the IMcpServer for session {sessionId}.")]
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Error disposing session {sessionId}.")]
|
||||
private partial void LogSessionDisposeError(string sessionId, Exception ex);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Critical, Message = "Exceeded maximum of {maxIdleSessionCount} idle sessions. Now closing sessions active more recently than configured IdleTimeout.")]
|
||||
private partial void LogMaxSessionIdleCountExceeded(int maxIdleSessionCount);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Critical, Message = "The IdleTrackingBackgroundService has stopped unexpectedly.")]
|
||||
private partial void IdleTrackingBackgroundServiceStoppedUnexpectedly();
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue