-
-
Notifications
You must be signed in to change notification settings - Fork 210
/
Scope.cs
471 lines (397 loc) · 14 KB
/
Scope.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
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Sentry.Extensibility;
namespace Sentry
{
/// <summary>
/// Scope data to be sent with the event.
/// </summary>
/// <remarks>
/// Scope data is sent together with any event captured
/// during the lifetime of the scope.
/// </remarks>
public class Scope : IEventLike
{
internal SentryOptions Options { get; }
internal bool Locked { get; set; }
private readonly object _lastEventIdSync = new();
private SentryId _lastEventId;
internal SentryId LastEventId
{
get
{
lock (_lastEventIdSync)
{
return _lastEventId;
}
}
set
{
lock (_lastEventIdSync)
{
_lastEventId = value;
}
}
}
private readonly object _evaluationSync = new();
private volatile bool _hasEvaluated;
/// <summary>
/// Whether the <see cref="OnEvaluating"/> event has already fired.
/// </summary>
internal bool HasEvaluated => _hasEvaluated;
private readonly Lazy<ConcurrentBag<ISentryEventExceptionProcessor>> _lazyExceptionProcessors =
new(LazyThreadSafetyMode.PublicationOnly);
/// <summary>
/// A list of exception processors.
/// </summary>
internal ConcurrentBag<ISentryEventExceptionProcessor> ExceptionProcessors => _lazyExceptionProcessors.Value;
private readonly Lazy<ConcurrentBag<ISentryEventProcessor>> _lazyEventProcessors =
new(LazyThreadSafetyMode.PublicationOnly);
/// <summary>
/// A list of event processors.
/// </summary>
internal ConcurrentBag<ISentryEventProcessor> EventProcessors => _lazyEventProcessors.Value;
/// <summary>
/// An event that fires when the scope evaluates.
/// </summary>
/// <remarks>
/// This allows registering an event handler that is invoked in case
/// an event is about to be sent to Sentry. If an event is never sent,
/// this event is never fired and the resources spared.
/// It also allows registration at an early stage of the processing
/// but execution at a later time, when more data is available.
/// </remarks>
/// <see cref="Evaluate"/>
internal event EventHandler? OnEvaluating;
/// <inheritdoc />
public SentryLevel? Level { get; set; }
private Request? _request;
/// <inheritdoc />
public Request Request
{
get => _request ??= new Request();
set => _request = value;
}
private readonly Contexts _contexts = new();
/// <inheritdoc />
public Contexts Contexts
{
get => _contexts;
set => _contexts.ReplaceWith(value);
}
// Internal for testing.
internal Action<User?> UserChanged => user =>
{
if (Options.EnableScopeSync &&
Options.ScopeObserver is { } observer)
{
observer.SetUser(user);
}
};
private User? _user;
/// <inheritdoc />
public User User
{
get => _user ??= new User { PropertyChanged = UserChanged };
set
{
_user = value;
if (_user is not null)
{
_user.PropertyChanged = UserChanged;
}
UserChanged.Invoke(_user);
}
}
/// <inheritdoc />
public string? Platform { get; set; }
/// <inheritdoc />
public string? Release { get; set; }
/// <inheritdoc />
public string? Environment { get; set; }
// TransactionName is kept for legacy purposes because
// SentryEvent still makes use of it.
// It should be possible to set the transaction name
// without starting a fully fledged transaction.
// Consequently, Transaction.Name and TransactionName must
// be kept in sync as much as possible.
private string? _fallbackTransactionName;
/// <inheritdoc />
public string? TransactionName
{
get => Transaction?.Name ?? _fallbackTransactionName;
set
{
// Set the fallback regardless, so that the variable is always kept up to date
_fallbackTransactionName = value;
// If a transaction has been started, overwrite its name
if (Transaction is { } transaction)
{
// Null name is not allowed in a transaction, but
// allowed on `scope.TransactionName` because it's optional.
// As a workaround, we coerce null into empty string.
// Context: https://github.com/getsentry/develop/issues/246#issuecomment-762274438
transaction.Name = !string.IsNullOrWhiteSpace(value)
? value
: string.Empty;
}
}
}
private ITransaction? _transaction;
/// <summary>
/// Transaction.
/// </summary>
public ITransaction? Transaction
{
get => _transaction;
set => _transaction = value;
}
internal SessionUpdate? SessionUpdate { get; set; }
/// <inheritdoc />
public SdkVersion Sdk { get; } = new();
/// <inheritdoc />
public IReadOnlyList<string> Fingerprint { get; set; } = Array.Empty<string>();
private readonly ConcurrentQueue<Breadcrumb> _breadcrumbs = new();
/// <inheritdoc />
public IReadOnlyCollection<Breadcrumb> Breadcrumbs => _breadcrumbs;
private readonly ConcurrentDictionary<string, object?> _extra = new();
/// <inheritdoc />
public IReadOnlyDictionary<string, object?> Extra => _extra;
private readonly ConcurrentDictionary<string, string> _tags = new();
/// <inheritdoc />
public IReadOnlyDictionary<string, string> Tags => _tags;
#if NETSTANDARD2_0 || NET461
private ConcurrentBag<Attachment> _attachments = new();
#else
private readonly ConcurrentBag<Attachment> _attachments = new();
#endif
/// <summary>
/// Attachments.
/// </summary>
public IReadOnlyCollection<Attachment> Attachments => _attachments;
/// <summary>
/// Creates a scope with the specified options.
/// </summary>
public Scope(SentryOptions? options)
{
Options = options ?? new SentryOptions();
}
// For testing. Should explicitly require SentryOptions.
internal Scope()
: this(new SentryOptions())
{
}
/// <inheritdoc />
public void AddBreadcrumb(Breadcrumb breadcrumb)
{
if (Options.BeforeBreadcrumb is { } beforeBreadcrumb)
{
if (beforeBreadcrumb(breadcrumb) is { } processedBreadcrumb)
{
breadcrumb = processedBreadcrumb;
}
else
{
// Callback returned null, which means the breadcrumb should be dropped
return;
}
}
if (Options.MaxBreadcrumbs <= 0)
{
//Always drop the breadcrumb.
return;
}
else if (Breadcrumbs.Count - Options.MaxBreadcrumbs + 1 > 0)
{
_breadcrumbs.TryDequeue(out _);
}
_breadcrumbs.Enqueue(breadcrumb);
if (Options.EnableScopeSync)
{
Options.ScopeObserver?.AddBreadcrumb(breadcrumb);
}
}
/// <inheritdoc />
public void SetExtra(string key, object? value)
{
_extra[key] = value;
if (Options.EnableScopeSync)
{
Options.ScopeObserver?.SetExtra(key, value);
}
}
/// <inheritdoc />
public void SetTag(string key, string value)
{
_tags[key] = value;
if (Options.EnableScopeSync)
{
Options.ScopeObserver?.SetTag(key, value);
}
}
/// <inheritdoc />
public void UnsetTag(string key)
{
_tags.TryRemove(key, out _);
if (Options.EnableScopeSync)
{
Options.ScopeObserver?.UnsetTag(key);
}
}
/// <summary>
/// Adds an attachment.
/// </summary>
public void AddAttachment(Attachment attachment) => _attachments.Add(attachment);
/// <summary>
/// Clear all Attachments.
/// </summary>
public void ClearAttachments()
{
#if NETSTANDARD2_0 || NET461
Interlocked.Exchange(ref _attachments, new());
#else
_attachments.Clear();
#endif
}
/// <summary>
/// Applies the data from this scope to another event-like object.
/// </summary>
/// <param name="other">The scope to copy data to.</param>
/// <remarks>
/// Applies the data of 'from' into 'to'.
/// If data in 'from' is null, 'to' is unmodified.
/// Conflicting keys are not overriden.
/// This is a shallow copy.
/// </remarks>
public void Apply(IEventLike other)
{
// Not to throw on code that ignores nullability warnings.
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (other is null)
{
return;
}
// Fingerprint isn't combined. It's absolute.
// One set explicitly on target (i.e: event)
// takes precedence and is not overwritten
if (!other.Fingerprint.Any() && Fingerprint.Any())
{
other.Fingerprint = Fingerprint;
}
foreach (var breadcrumb in Breadcrumbs)
{
other.AddBreadcrumb(breadcrumb);
}
foreach (var (key, value) in Extra)
{
if (!other.Extra.ContainsKey(key))
{
other.SetExtra(key, value);
}
}
foreach (var (key, value) in Tags)
{
if (!other.Tags.ContainsKey(key))
{
other.SetTag(key, value);
}
}
Contexts.CopyTo(other.Contexts);
Request.CopyTo(other.Request);
User.CopyTo(other.User);
other.Platform ??= Platform;
other.Release ??= Release;
other.Environment ??= Environment;
other.TransactionName ??= TransactionName;
other.Level ??= Level;
if (Sdk.Name is not null && Sdk.Version is not null)
{
other.Sdk.Name = Sdk.Name;
other.Sdk.Version = Sdk.Version;
}
foreach (var package in Sdk.InternalPackages)
{
other.Sdk.AddPackage(package);
}
}
/// <summary>
/// Applies data from one scope to another.
/// </summary>
public void Apply(Scope other)
{
// Not to throw on code that ignores nullability warnings.
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if (other is null)
{
return;
}
Apply((IEventLike)other);
other.Transaction ??= Transaction;
other.SessionUpdate ??= SessionUpdate;
foreach (var attachment in Attachments)
{
other.AddAttachment(attachment);
}
}
/// <summary>
/// Applies the state object into the scope.
/// </summary>
/// <param name="state">The state object to apply.</param>
public void Apply(object state) => Options.SentryScopeStateProcessor.Apply(this, state);
/// <summary>
/// Clones the current <see cref="Scope"/>.
/// </summary>
public Scope Clone()
{
var clone = new Scope(Options);
Apply(clone);
foreach (var processor in EventProcessors)
{
clone.EventProcessors.Add(processor);
}
foreach (var processor in ExceptionProcessors)
{
clone.ExceptionProcessors.Add(processor);
}
return clone;
}
internal void Evaluate()
{
if (_hasEvaluated)
{
return;
}
lock (_evaluationSync)
{
if (_hasEvaluated)
{
return;
}
try
{
OnEvaluating?.Invoke(this, EventArgs.Empty);
}
catch (Exception ex)
{
Options.DiagnosticLogger?.LogError(
"Failed invoking event handler.",
ex);
}
finally
{
_hasEvaluated = true;
}
}
}
/// <summary>
/// Gets the currently ongoing (not finished) span or <c>null</c> if none available.
/// This relies on the transactions being manually set on the scope via <see cref="Transaction"/>.
/// </summary>
public ISpan? GetSpan() => Transaction?.GetLastActiveSpan() ?? Transaction;
internal void ResetTransaction(ITransaction? expectedCurrentTransaction) =>
Interlocked.CompareExchange(ref _transaction, null, expectedCurrentTransaction);
}
}