-
Notifications
You must be signed in to change notification settings - Fork 610
Expand file tree
/
Copy pathMiniProfilerMiddleware.cs
More file actions
447 lines (392 loc) · 17.5 KB
/
MiniProfilerMiddleware.cs
File metadata and controls
447 lines (392 loc) · 17.5 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
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Options;
using StackExchange.Profiling.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if NETCOREAPP3_0 // Only in netcoreapp3.0 while in preview
using System.Text.Json;
#endif
namespace StackExchange.Profiling
{
/// <summary>
/// Represents a middleware that starts and stops a MiniProfiler
/// </summary>
public class MiniProfilerMiddleware
{
private readonly RequestDelegate _next;
#if NETCOREAPP3_0
private readonly IWebHostEnvironment _env;
#else
private readonly IHostingEnvironment _env;
#endif
private readonly IOptions<MiniProfilerOptions> _options;
internal readonly EmbeddedProvider Embedded;
internal MiniProfilerOptions Options => _options.Value;
/// <summary>
/// Creates a new instance of <see cref="MiniProfilerMiddleware"/>
/// </summary>
/// <param name="next">The delegate representing the next middleware in the request pipeline.</param>
/// <param name="hostingEnvironment">The Hosting Environment.</param>
/// <param name="options">The middleware options, containing the rules to apply.</param>
/// <exception cref="ArgumentNullException">Throws when <paramref name="next"/>, <paramref name="hostingEnvironment"/>, or <paramref name="options"/> is <c>null</c>.</exception>
public MiniProfilerMiddleware(
RequestDelegate next,
#if NETCOREAPP3_0
IWebHostEnvironment hostingEnvironment,
#else
IHostingEnvironment hostingEnvironment,
#endif
IOptions<MiniProfilerOptions> options)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_env = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
_options = options ?? throw new ArgumentNullException(nameof(options));
if (string.IsNullOrEmpty(Options.RouteBasePath))
{
throw new ArgumentException("RouteBasePath cannot be empty", nameof(Options.RouteBasePath));
}
Embedded = new EmbeddedProvider(_options, _env);
}
/// <summary>
/// Executes the MiniProfiler-wrapped middleware.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
/// <returns>A task that represents the execution of the MiniProfiler-wrapped middleware.</returns>
/// <exception cref="ArgumentNullException">Throws when <paramref name="context"/> is <c>null</c>.</exception>
public async Task Invoke(HttpContext context)
{
_ = context ?? throw new ArgumentNullException(nameof(context));
if (context.Request.Path.StartsWithSegments(Options.RouteBasePath, out PathString subPath))
{
// This is a request in the MiniProfiler path (e.g. one of "our" routes), HANDLE THE SITUATION.
await HandleRequest(context, subPath).ConfigureAwait(false);
return;
}
// Otherwise this is an app request, profile it!
if (ShouldProfile(context.Request))
{
// Wrap the request in this profiler
var mp = Options.StartProfiler();
// Set the user
mp.User = Options.UserIdProvider?.Invoke(context.Request);
// Always add this profiler's header (and any async requests before it)
using (mp.StepIf("MiniProfiler Init", minSaveMs: 0.1m))
{
await SetHeadersAndState(context, mp).ConfigureAwait(false);
}
#if NETCOREAPP3_0
var appendServerTimingHeader = Options.EnableServerTimingHeader && context.Response.SupportsTrailers();
if (appendServerTimingHeader)
{
context.Response.DeclareTrailer("Server-Timing");
appendServerTimingHeader = true;
}
#endif
// Execute the pipe
await _next(context);
// Assign name
EnsureName(mp, context);
// Stop (and record)
await mp.StopAsync().ConfigureAwait(false);
#if NETCOREAPP3_0 // TODO: Evaluate if this works after http/2 local support in preview 7, maybe backport to netcoreapp2.2
if (appendServerTimingHeader && mp != null)
{
context.Response.AppendTrailer("Server-Timing", mp.GetServerTimingHeader());
}
#endif
}
else
{
// Don't profile, only relay
await _next(context);
}
}
private bool ShouldProfile(HttpRequest request)
{
foreach (var ignored in Options.IgnoredPaths)
{
if (ignored != null && request.Path.Value.Contains(ignored, StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
return Options.ShouldProfile?.Invoke(request) ?? true;
}
private void EnsureName(MiniProfiler profiler, HttpContext context)
{
if (profiler.Name == nameof(MiniProfiler))
{
var url = StringBuilderCache.Get()
.Append(context.Request.Scheme)
.Append("://")
.Append(context.Request.Host.Value)
.Append(context.Request.PathBase.Value)
.Append(context.Request.Path.Value)
.Append(context.Request.QueryString.Value)
.ToStringRecycle();
var routeData = context.GetRouteData();
if (routeData?.Values["controller"] != null)
{
profiler.Name = routeData.Values["controller"] + "/" + routeData.Values["action"];
}
else if (routeData?.Values["page"] != null)
{
profiler.Name = routeData.Values["page"].ToString();
}
else
{
profiler.Name = url;
if (profiler.Name.Length > 50)
profiler.Name = profiler.Name.Remove(50);
}
if (profiler.Root?.Name == nameof(MiniProfiler))
{
profiler.Root.Name = url;
}
}
}
private async Task SetHeadersAndState(HttpContext context, MiniProfiler current)
{
try
{
// Are we authorized???
bool isAuthorized;
using (current.StepIf("Authorize", 0.1m))
{
isAuthorized = await AuthorizeRequestAsync(context, isList: false, setResponse: false);
}
// Grab any past profilers (e.g. from a previous redirect)
List<Guid> profilerIds;
using (current.StepIf("Get Profiler IDs", 0.1m))
{
profilerIds = (isAuthorized ? await Options.ExpireAndGetUnviewedAsync(current.User).ConfigureAwait(false) : null)
?? new List<Guid>(1);
}
// Always add the current
profilerIds.Add(current.Id);
if (profilerIds.Count > 0)
{
using (current.StepIf("Set Headers", 0.1m))
{
context.Response.Headers.Add("X-MiniProfiler-Ids", profilerIds.ToJson());
}
}
// Expose X-MiniProfiler-Ids header if this is a CORS request
if (context.Request.Headers.ContainsKey("Origin"))
{
context.Response.Headers.Add("Access-Control-Expose-Headers", "X-MiniProfiler-Ids");
}
// Set the state to use in RenderIncludes() down the pipe later
new RequestState { IsAuthorized = isAuthorized, RequestIDs = profilerIds }.Store(context);
}
catch { /* oh no! headers blew up */ }
}
private async Task HandleRequest(HttpContext context, PathString subPath)
{
// Is this a CORS request
if (context.Request.Headers.TryGetValue("Origin", out var originValues)
&& originValues.Any())
{
SetCorsHeaders(context.Response, originValues);
if (context.Request.Method == "OPTIONS")
{
await HandleCorsOptionsRequest(context.Response);
return;
}
}
context.Response.StatusCode = StatusCodes.Status200OK;
string result = null;
// File embed
if (subPath.Value.StartsWith("/includes.min", StringComparison.Ordinal))
{
result = Embedded.GetFile(context, subPath);
}
switch (subPath.Value)
{
case "/results-index":
result = await ResultsIndexAsync(context);
break;
case "/results-list":
result = await ResultsListAsync(context).ConfigureAwait(false);
break;
case "/results":
result = await GetSingleProfilerResultAsync(context).ConfigureAwait(false);
break;
}
result ??= NotFound(context, "Not Found: " + subPath);
context.Response.ContentLength = result != null ? Encoding.UTF8.GetByteCount(result) : 0;
await context.Response.WriteAsync(result).ConfigureAwait(false);
}
private static string NotFound(HttpContext context, string message = null, string contentType = "text/plain")
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
context.Response.ContentType = contentType;
return message;
}
/// <summary>
/// Returns true if the current request is allowed to see the profiler response.
/// </summary>
/// <param name="context">The context to attempt to authorize a user for.</param>
/// <param name="isList">Whether this is a list route being accessed.</param>
/// <param name="setResponse">Whether to set response properties</param>
private async Task<bool> AuthorizeRequestAsync(HttpContext context, bool isList, bool setResponse = true)
{
var req = context.Request;
// Deny access if we a) have a configured delegate, and b) it says no
if (Options.ResultsAuthorize != null && !Options.ResultsAuthorize.Invoke(req)
|| (Options.ResultsAuthorizeAsync != null && !await Options.ResultsAuthorizeAsync(req))
|| (isList && Options.ResultsListAuthorize != null && !Options.ResultsListAuthorize(req))
|| (isList && Options.ResultsListAuthorizeAsync != null && !await Options.ResultsListAuthorizeAsync(req))
)
{
if (setResponse)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.ContentType = "text/plain";
}
return false;
}
return true;
}
/// <summary>
/// Returns the list of profiling sessions
/// </summary>
/// <param name="context">The results list HTML, if authorized.</param>
private async Task<string> ResultsIndexAsync(HttpContext context)
{
if (!await AuthorizeRequestAsync(context, isList: true))
{
return "Unauthorized";
}
context.Response.ContentType = "text/html; charset=utf-8";
var path = context.Request.PathBase + Options.RouteBasePath.Value.EnsureTrailingSlash();
return Render.ResultListHtml(Options, path);
}
/// <summary>
/// Returns the JSON needed for the results list in MiniProfiler
/// </summary>
/// <param name="context">The context to get the results list for.</param>
private async Task<string> ResultsListAsync(HttpContext context)
{
if (!await AuthorizeRequestAsync(context, isList: true))
{
return "Unauthorized";
}
var guids = await Options.Storage.ListAsync(100).ConfigureAwait(false);
if (context.Request.Query.TryGetValue("last-id", out var lastId) && Guid.TryParse(lastId, out var lastGuid))
{
guids = guids.TakeWhile(g => g != lastGuid);
}
return guids.Reverse()
.Select(g => Options.Storage.Load(g))
.Where(p => p != null)
.Select(p => new
{
p.Id,
p.Name,
p.ClientTimings,
p.Started,
p.HasUserViewed,
p.MachineName,
p.User,
p.DurationMilliseconds
}).ToJson();
}
/// <summary>
/// Returns either JSON or full page HTML of a previous <c>MiniProfiler</c> session,
/// identified by its <c>"?id=GUID"</c> on the query.
/// </summary>
/// <param name="context">The context to get a profiler response for.</param>
private async Task<string> GetSingleProfilerResultAsync(HttpContext context)
{
Guid id;
ResultRequest clientRequest = null;
// When we're rendering as a button/popup in the corner, it's an AJAX/JSON request.
// If that's absent, we're rendering results as a full page for sharing.
bool jsonRequest = context.Request.Headers["Accept"].FirstOrDefault()?.Contains("application/json") == true;
// Try to parse from the JSON payload first
if (jsonRequest
&& context.Request.ContentLength > 0
#if NETCOREAPP3_0
&& ((clientRequest = await JsonSerializer.DeserializeAsync<ResultRequest>(context.Request.Body)) != null)
#else
&& ResultRequest.TryParse(context.Request.Body, out clientRequest)
#endif
&& clientRequest.Id.HasValue)
{
id = clientRequest.Id.Value;
}
else if (Guid.TryParse(context.Request.Query["id"], out id))
{
// We got the guid from the querystring
}
else if (Options.StopwatchProvider != null)
{
// Fall back to the last result
id = (await Options.Storage.ListAsync(1).ConfigureAwait(false)).FirstOrDefault();
}
if (id == default)
{
return NotFound(context, jsonRequest ? null : "No GUID id specified on the query string");
}
var profiler = await Options.Storage.LoadAsync(id).ConfigureAwait(false);
string user = Options.UserIdProvider?.Invoke(context.Request);
await Options.Storage.SetViewedAsync(user, id).ConfigureAwait(false);
if (profiler == null)
{
return NotFound(context, jsonRequest ? null : "No MiniProfiler results found with Id=" + id.ToString());
}
bool needsSave = false;
if (profiler.ClientTimings == null && clientRequest?.TimingCount > 0)
{
profiler.ClientTimings = ClientTimings.FromRequest(clientRequest);
needsSave = true;
}
if (!profiler.HasUserViewed)
{
profiler.HasUserViewed = true;
needsSave = true;
}
if (needsSave)
{
await Options.Storage.SaveAsync(profiler).ConfigureAwait(false);
}
if (!await AuthorizeRequestAsync(context, isList: false))
{
context.Response.ContentType = "application/json";
return @"""hidden"""; // JSON
}
if (jsonRequest)
{
context.Response.ContentType = "application/json";
return profiler.ToJson();
}
else
{
context.Response.ContentType = "text/html; charset=utf-8";
return Render.SingleResultHtml(profiler, context.Request.PathBase + Options.RouteBasePath.Value.EnsureTrailingSlash());
}
}
private void SetCorsHeaders(HttpResponse response, string origin)
{
response.Headers.Add("Vary", "Origin");
if (_options.Value.CorsOrigins != null
&& _options.Value.CorsOrigins.Contains(origin, StringComparer.OrdinalIgnoreCase))
{
response.Headers.Add("Access-Control-Allow-Origin", origin);
}
}
private async Task HandleCorsOptionsRequest(HttpResponse response)
{
response.StatusCode = 200;
response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
response.Headers.Add("Access-Control-Allow-Methods", "OPTIONS, GET");
await response.WriteAsync("").ConfigureAwait(false);
}
}
}