/
Program.cs
191 lines (163 loc) · 5.95 KB
/
Program.cs
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
using Microsoft.Extensions.Caching.Memory;
using System.Collections.Concurrent;
const string cookieName = "qq";
TimeSpan idleTimeout = TimeSpan.FromSeconds(20);
int cookieSequenceGen = 0;
var entryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(idleTimeout);
PostEvictionCallbackRegistration postEvictionCallbackRegistration = new PostEvictionCallbackRegistration();
postEvictionCallbackRegistration.State = typeof(Program);
postEvictionCallbackRegistration.EvictionCallback = (k, v, r, s) =>
{
if (r is EvictionReason.Expired && s is Type sType && sType == typeof(Program) && v is IDisposable disposable)
{
disposable.Dispose();
}
};
entryOptions.PostEvictionCallbacks.Add(postEvictionCallbackRegistration);
System.Timers.Timer checkSessions = null!;
TimeSpan checkSessionsInterval = TimeSpan.FromSeconds(1);
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMemoryCache(op =>
{
op.ExpirationScanFrequency = TimeSpan.FromSeconds(1);
});
builder.Services.AddScoped<SessionHolder>();
builder.Services.AddScoped<InfoProvider>();
builder.Services.AddScoped<Another>();
builder.Logging.ClearProviders();
builder.Logging.AddConsole(op =>
{
op.TimestampFormat = "[HH:mm:ss:fff] ";
});
var app = builder.Build();
app.Use(async (context, next) =>
{
IMemoryCache sessions = context.RequestServices.GetRequiredService<IMemoryCache>();
if (checkSessions is null)
{
lock (app)
{
if (checkSessions is null)
{
checkSessions = new(checkSessionsInterval.TotalMilliseconds);
checkSessions.Elapsed += (s, e) =>
{
sessions.TryGetValue(string.Empty, out object dumb);
};
checkSessions.Enabled = true;
checkSessions.AutoReset = true;
}
}
}
Session session = null;
int caseMatch = 0;
string key = context.Request.Cookies[cookieName];
bool isNewSession = false;
if (
key is null
|| !sessions.TryGetValue(key, out object sessionObj)
|| (session = sessionObj as Session) is null
)
{
key = $"{Guid.NewGuid()}:{Interlocked.Increment(ref cookieSequenceGen)}";
session = new(context.RequestServices.CreateScope().ServiceProvider);
session.SessionServiceProvider.GetRequiredService<SessionHolder>().Session = session;
context.Response.Cookies.Append(cookieName, key);
isNewSession = true;
}
session.RequestServiceProvider = context.RequestServices;
context.RequestServices.GetRequiredService<SessionHolder>().Session = session;
ILogger<Program> logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogInformation($"{context.Connection.Id}: {context.Request.Path}: {session}({session.GetHashCode()})");
try
{
await next?.Invoke();
if (isNewSession)
{
sessions.Set(key, session, entryOptions);
}
}
catch (Exception ex)
{
throw;
}
});
app.MapGet("/", async context =>
{
Session session = context.RequestServices.GetRequiredService<SessionHolder>().Session;
Another another = context.RequestServices.GetRequiredService<Another>();
await context.Response.WriteAsync($"[{DateTime.Now.ToString("HH:mm:ss.fff")}] Hello, World! {session}({session.GetHashCode()})"
+ $", controller {another}({another.GetHashCode()}), "
+ session.SessionServiceProvider.GetRequiredService<InfoProvider>().Get());
});
app.Run();
public class Session : IDisposable
{
private readonly ILogger<Session> _logger;
public IServiceProvider SessionServiceProvider { get; init; }
public IServiceProvider RequestServiceProvider { get; set; }
public Session(IServiceProvider serviceProvider) =>
(SessionServiceProvider, _logger) = (serviceProvider, serviceProvider.GetRequiredService<ILogger<Session>>());
public void Dispose()
{
if(SessionServiceProvider is IDisposable disposable)
{
disposable.Dispose();
}
_logger.LogInformation($"{this}({GetHashCode()}) disposed");
}
}
public class SessionHolder
{
public Session Session { get; set; }
}
public class InfoProvider : IDisposable
{
private ConcurrentQueue<int> _queue = new();
private readonly CancellationTokenSource _cancellationTokenSource = new();
private Task _fill = null;
private readonly ILogger<InfoProvider> _logger;
private readonly IServiceProvider _serviceProvider;
public InfoProvider(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
_logger = _serviceProvider.GetRequiredService<ILogger<InfoProvider>>();
int value = 0;
CancellationToken cancellationToken = _cancellationTokenSource.Token;
_fill = Task.Run(async () =>
{
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(1000);
_queue.Enqueue(++value);
}
});
}
public string Get()
{
Session session = _serviceProvider.GetRequiredService<SessionHolder>().Session;
Another another = session.RequestServiceProvider.GetRequiredService<Another>();
_logger.LogInformation($"{this}({GetHashCode()}) {another}({another.GetHashCode()})");
List<int> result = new();
while (_queue.TryDequeue(out int k))
{
result.Add(k);
}
return $"{this}({GetHashCode()}) {another}({another.GetHashCode()}), {string.Join(", ", result)}";
}
public void Dispose()
{
_cancellationTokenSource.Cancel();
_fill.Wait();
_logger.LogInformation($"{this}({GetHashCode()}) disposed");
}
}
public class Another : IDisposable
{
private readonly ILogger<Another> _logger;
public Another(ILogger<Another> logger) => _logger = logger;
public void Dispose()
{
_logger.LogInformation($"{this}({GetHashCode()}) disposed");
}
}