forked from modelcontextprotocol/csharp-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIdleTrackingBackgroundService.cs
More file actions
49 lines (43 loc) · 1.58 KB
/
Copy pathIdleTrackingBackgroundService.cs
File metadata and controls
49 lines (43 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
namespace ModelContextProtocol.AspNetCore;
internal sealed class IdleTrackingBackgroundService(StreamableHttpHandler handler, IOptions<HttpServerTransportOptions> options) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var timeProvider = options.Value.TimeProvider;
var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), timeProvider);
while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))
{
var idleActivityCutoff = timeProvider.GetUtcNow().Ticks - options.Value.IdleTimeout.Ticks;
foreach (var (_, session) in handler.Sessions)
{
if (session.IsActive || session.LastActivityTicks > idleActivityCutoff)
{
continue;
}
if (handler.Sessions.TryRemove(session.Id, out var removedSession))
{
await removedSession.DisposeAsync();
}
}
}
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
try
{
foreach (var (sessionKey, _) in handler.Sessions)
{
if (handler.Sessions.TryRemove(sessionKey, out var session))
{
await session.DisposeAsync();
}
}
}
finally
{
await base.StopAsync(cancellationToken);
}
}
}