-
Notifications
You must be signed in to change notification settings - Fork 607
/
Copy pathMiniProfiler.cs
384 lines (337 loc) · 13.5 KB
/
MiniProfiler.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
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
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using StackExchange.Profiling.Helpers;
using StackExchange.Profiling.Internal;
using StackExchange.Profiling.Storage;
namespace StackExchange.Profiling
{
/// <summary>
/// A single MiniProfiler can be used to represent any number of steps/levels in a call-graph, via Step()
/// </summary>
/// <remarks>Totally baller.</remarks>
[DataContract]
public partial class MiniProfiler
{
/// <summary>
/// The options this profiler uses, assigned at creation time.
/// It defaults for the global options, if present, as a fall back for all operations.
/// The vast majority of use cases will be a single options instance, so this works pretty well.
/// </summary>
[IgnoreDataMember]
[JsonIgnore]
public MiniProfilerBaseOptions Options { get; } = DefaultOptions;
/// <summary>
/// Initializes a new instance of the <see cref="MiniProfiler"/> class.
/// Obsolete - used for serialization.
/// </summary>
[Obsolete("Used for serialization")]
#pragma warning disable CS8618
public MiniProfiler() { /* serialization only */ }
#pragma warning restore CS8618
/// <summary>
/// Initializes a new instance of the <see cref="MiniProfiler"/> class. Creates and starts a new MiniProfiler
/// for the root <paramref name="name"/>.
/// </summary>
/// <param name="name">The name of this <see cref="MiniProfiler"/>, typically a URL.</param>
/// <param name="options">The options to use for this MiniProfiler.</param>
public MiniProfiler(string? name, MiniProfilerBaseOptions options)
{
Name = name;
Id = Guid.NewGuid();
MachineName = Environment.MachineName;
Started = DateTime.UtcNow;
Options = options ?? throw new ArgumentNullException(nameof(options));
Storage = options.Storage;
// stopwatch must start before any child Timings are instantiated
Stopwatch = options.StopwatchProvider();
_root = Root = new Timing(this, null, name);
IsActive = true;
}
/// <summary>
/// Whether the profiler is currently profiling
/// </summary>
internal bool IsActive { get; set; }
/// <summary>
/// Gets or sets the profiler id.
/// Identifies this Profiler so it may be stored/cached.
/// </summary>
[DataMember(Order = 1)]
public Guid Id { get; set; }
/// <summary>
/// Gets or sets a display name for this profiling session.
/// </summary>
[DataMember(Order = 2)]
public string? Name { get; set; }
/// <summary>
/// Gets or sets when this profiler was instantiated, in UTC time.
/// </summary>
[DataMember(Order = 3)]
public DateTime Started { get; set; }
/// <summary>
/// Gets the milliseconds, to one decimal place, that this MiniProfiler ran.
/// </summary>
[DataMember(Order = 4)]
public decimal DurationMilliseconds { get; set; }
/// <summary>
/// Gets or sets where this profiler was run.
/// </summary>
[DataMember(Order = 5)]
public string? MachineName { get; set; }
#if !MINIMAL
/// <summary>
/// Keys are names, values are URLs, allowing additional links to be added to a profiler result, e.g. perhaps a deeper
/// diagnostic page for the current request.
/// </summary>
/// <remarks>
/// Use <see cref="MiniProfilerExtensions.AddCustomLink"/> to easily add a name/URL pair to this dictionary.
/// </remarks>
[DataMember(Order = 6)]
public Dictionary<string, string>? CustomLinks { get; set; }
/// <summary>
/// JSON used to store Custom Links. Do not touch.
/// </summary>
[JsonIgnore]
public string? CustomLinksJson
{
get => CustomLinks?.ToJson();
set
{
if (value.HasValue())
{
CustomLinks = value.FromJson<Dictionary<string, string>>();
}
}
}
#endif
private Timing _root;
/// <summary>
/// Gets or sets the root timing.
/// The first <see cref="Timing"/> that is created and started when this profiler is instantiated.
/// All other <see cref="Timing"/>s will be children of this one.
/// </summary>
[DataMember(Order = 7)]
public Timing Root
{
get => _root;
set
{
_root = value;
RootTimingId = value.Id;
}
}
/// <summary>
/// Id of Root Timing. Used for Sql Storage purposes.
/// </summary>
public Guid? RootTimingId { get; set; }
#if !MINIMAL
/// <summary>
/// Gets or sets timings collected from the client
/// </summary>
[DataMember(Order = 8)]
public ClientTimings? ClientTimings { get; set; }
/// <summary>
/// RedirectCount in ClientTimings. Used for sql storage.
/// </summary>
[JsonIgnore]
public int? ClientTimingsRedirectCount { get; set; }
#endif
/// <summary>
/// Gets or sets a string identifying the user/client that is profiling this request.
/// </summary>
/// <remarks>
/// If this is not set manually at some point, the UserIdProvider implementation will be used;
/// by default, this will be the current request's IP address.
/// </remarks>
[DataMember(Order = 9)]
public string? User { get; set; }
/// <summary>
/// Returns true when this MiniProfiler has been viewed by the <see cref="User"/> that recorded it.
/// </summary>
/// <remarks>
/// Allows POSTs that result in a redirect to be profiled. <see cref="MiniProfilerBaseOptions.Storage"/> implementation
/// will keep a list of all profilers that haven't been fetched down.
/// </remarks>
[DataMember(Order = 10)]
public bool HasUserViewed { get; set; }
// Allows async to properly track the attachment point
private readonly AsyncLocal<Timing?> _head = new();
// When async context flows aren't preserved, fallback to enable correct profiling in most cases
private Timing? _lastSetHead;
/// <summary>
/// Gets or sets points to the currently executing Timing.
/// </summary>
[JsonIgnore]
public Timing? Head
{
get => _head.Value ?? _lastSetHead;
set => _head.Value = _lastSetHead = value;
}
/// <summary>
/// Gets the ticks since this MiniProfiler was started.
/// </summary>
internal long ElapsedTicks => Stopwatch.ElapsedTicks;
/// <summary>
/// Gets the timer, for unit testing, returns the timer.
/// </summary>
internal IStopwatch Stopwatch { get; set; }
/// <summary>
/// Gets the internal timer for this MiniProfile, primarily for unit testing.
/// </summary>
public IStopwatch GetStopwatch() => Stopwatch;
/// <summary>
/// Gets the currently running MiniProfiler for the current context; null if no MiniProfiler was started.
/// </summary>
public static MiniProfiler? Current => DefaultOptions.ProfilerProvider?.CurrentProfiler;
/// <summary>
/// A <see cref="IAsyncStorage"/> strategy to use for the current profiler.
/// </summary>
/// <remarks>Used to set custom storage for an individual request</remarks>
[IgnoreDataMember]
[JsonIgnore]
public IAsyncStorage? Storage { get; set; }
/// <summary>
/// Ends the current profiling session, if one exists.
/// </summary>
/// <param name="discardResults">
/// When true, clears the <see cref="Current"/>, allowing profiling to
/// be prematurely stopped and discarded. Useful for when a specific route does not need to be profiled.
/// </param>
public bool Stop(bool discardResults = false)
{
if (!InnerStop())
{
return false;
}
try
{
Options.ProfilerProvider.Stopped(this, discardResults);
}
catch (Exception ex)
{
Options.OnInternalError?.Invoke(ex);
}
return true;
}
/// <summary>
/// Asynchronously ends the current profiling session, if one exists.
/// This invokes async saving all the way down if the providers support it.
/// </summary>
/// <param name="discardResults">
/// When true, clears the <see cref="Current"/>, allowing profiling to
/// be prematurely stopped and discarded. Useful for when a specific route does not need to be profiled.
/// </param>
public async Task<bool> StopAsync(bool discardResults = false)
{
if (!InnerStop())
{
return false;
}
try
{
await Options.ProfilerProvider.StoppedAsync(this, discardResults).ConfigureAwait(false);
}
catch (Exception ex)
{
Options.OnInternalError?.Invoke(ex);
}
return true;
}
/// <summary>
/// Shared stop bits for <see cref="Stop(bool)"/> and <see cref="StopAsync(bool)"/>
/// </summary>
private bool InnerStop()
{
if (!Stopwatch.IsRunning)
{
return false;
}
Stopwatch.Stop();
DurationMilliseconds = GetMilliseconds(ElapsedTicks);
foreach (var timing in GetTimingHierarchy())
{
timing.Stop();
}
IsActive = false;
return true;
}
#if !MINIMAL
/// <summary>
/// Deserializes the JSON string parameter to a <see cref="MiniProfiler"/>.
/// </summary>
/// <param name="json">The string to deserialize into a <see cref="MiniProfiler"/>.</param>
public static MiniProfiler? FromJson(string json) => json.FromJson<MiniProfiler>();
#endif
/// <summary>
/// Returns the <see cref="Root"/>'s <see cref="Timing.Name"/> and <see cref="DurationMilliseconds"/> this profiler recorded.
/// </summary>
/// <returns>A string containing the recording information</returns>
public override string ToString() => Root != null ? Root.Name + " (" + DurationMilliseconds + " ms)" : string.Empty;
/// <summary>
/// Returns true if Ids match.
/// </summary>
/// <param name="obj">The <see cref="object"/> to compare to.</param>
public override bool Equals(object? obj) => obj is MiniProfiler miniProfiler && Id.Equals(miniProfiler.Id);
/// <summary>
/// Returns hash code of Id.
/// </summary>
public override int GetHashCode() => Id.GetHashCode();
/// <summary>
/// Walks the <see cref="Timing"/> hierarchy contained in this profiler, starting with <see cref="Root"/>, and returns each Timing found.
/// </summary>
public IEnumerable<Timing> GetTimingHierarchy()
{
var timings = new Stack<Timing>();
timings.Push(_root);
while (timings.Count > 0)
{
var timing = timings.Pop();
yield return timing;
if (timing.HasChildren)
{
var children = timing.Children;
for (int i = children.Count - 1; i >= 0; i--) timings.Push(children[i]);
}
}
}
/// <summary>
/// Create a DEEP clone of this MiniProfiler.
/// </summary>
public MiniProfiler Clone()
{
var serializer = new DataContractSerializer(typeof(MiniProfiler), new DataContractSerializerSettings
{
MaxItemsInObjectGraph = int.MaxValue,
IgnoreExtensionDataObject = false,
PreserveObjectReferences = true
});
using (var ms = new System.IO.MemoryStream())
{
serializer.WriteObject(ms, this);
ms.Position = 0;
return (MiniProfiler)serializer.ReadObject(ms)!;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Timing StepImpl(string? name, decimal? minSaveMs = null, bool? includeChildrenWithMinSave = false) =>
new Timing(this, Head, name, minSaveMs, includeChildrenWithMinSave);
/// <summary>
/// Returns milliseconds based on Stopwatch's Frequency.
/// </summary>
/// <param name="ticks">The tick count.</param>
internal decimal GetMilliseconds(long ticks)
{
return ticks * 1000M / Stopwatch.Frequency;
}
/// <summary>
/// Returns how many milliseconds have elapsed since <paramref name="startTicks"/> was recorded.
/// </summary>
/// <param name="startTicks">The start tick count.</param>
internal decimal GetDurationMilliseconds(long startTicks) =>
GetMilliseconds(ElapsedTicks - startTicks);
}
}