-
-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathScope.cs
More file actions
829 lines (718 loc) · 24.1 KB
/
Scope.cs
File metadata and controls
829 lines (718 loc) · 24.1 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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Sentry.Extensibility;
using Sentry.Internal;
using Sentry.Internal.Extensions;
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 Lock _lastEventIdSync = new();
private SentryId _lastEventId;
internal SentryId LastEventId
{
get
{
lock (_lastEventIdSync)
{
return _lastEventId;
}
}
set
{
lock (_lastEventIdSync)
{
_lastEventId = value;
}
}
}
private readonly Lock _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);
private readonly Lazy<ConcurrentBag<ISentryTransactionProcessor>> _lazyTransactionProcessors =
new(LazyThreadSafetyMode.PublicationOnly);
/// <summary>
/// A list of event processors.
/// </summary>
internal ConcurrentBag<ISentryEventProcessor> EventProcessors => _lazyEventProcessors.Value;
/// <summary>
/// A list of event processors.
/// </summary>
internal ConcurrentBag<ISentryTransactionProcessor> TransactionProcessors => _lazyTransactionProcessors.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<Scope>? OnEvaluating;
/// <inheritdoc />
public SentryLevel? Level { get; set; }
private SentryRequest? _request;
/// <inheritdoc />
public SentryRequest Request
{
get => _request ??= new SentryRequest();
set => _request = value;
}
private readonly SentryContexts _contexts = new();
/// <inheritdoc />
public SentryContexts Contexts
{
get => _contexts;
set => _contexts.ReplaceWith(value);
}
// Internal for testing.
internal Action<SentryUser?> UserChanged => user =>
{
if (Options.EnableScopeSync &&
Options.ScopeObserver is { } observer)
{
observer.SetUser(user);
}
};
private SentryUser? _user;
/// <inheritdoc />
public SentryUser User
{
get => _user ??= new SentryUser
{
PropertyChanged = UserChanged
};
set
{
if (_user != value)
{
_user = value;
if (_user is not null)
{
_user.PropertyChanged = UserChanged;
}
UserChanged.Invoke(_user);
}
}
}
/// <inheritdoc />
public string? Release { get; set; }
/// <inheritdoc />
public string? Distribution { 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;
}
}
}
/// <summary>
/// <para>
/// Most of the properties on the Scope should have the same affinity as the Scope... For example, when using a
/// GlobalScopeStackContainer, anything you store on the scope will be applied to all events that get sent to Sentry
/// (no matter which thread they are sent from).
/// </para>
/// <para>
/// Transactions are an exception, however. We don't want spans from threads created on the UI thread to be added as
/// children of Transactions/Spans that get created on the background thread, or vice versa. As such,
/// Scope.Transaction is always stored as an AsyncLocal, regardless of the ScopeStackContainer implementation.
/// </para>
/// <para>
/// See https://github.com/getsentry/sentry-dotnet/issues/3590 for more information.
/// </para>
/// </summary>
private readonly AsyncLocal<ITransactionTracer?> _transaction = new();
/// <summary>
/// The current Transaction
/// </summary>
public ITransactionTracer? Transaction
{
get
{
_transactionLock.EnterReadLock();
try
{
// Workaround for https://github.com/getsentry/sentry-dotnet/pull/4125#discussion_r2087994417
// TODO: We should really find the root cause of this issue and address in a seprate PR
return _transaction.Value is { IsFinished: false } transaction ? transaction : null;
}
finally
{
_transactionLock.ExitReadLock();
}
}
set
{
_transactionLock.EnterWriteLock();
try
{
_transaction.Value = value;
if (Options.EnableScopeSync)
{
if (_transaction.Value != null)
{
// If there is a transaction set we propagate the trace to the native layer
Options.ScopeObserver?.SetTrace(_transaction.Value.TraceId, _transaction.Value.SpanId);
}
else
{
// If the transaction is being removed from the scope, reset and sync the trace as well
Options.ScopeObserver?.SetTrace(PropagationContext.TraceId, PropagationContext.SpanId);
}
}
}
finally
{
_transactionLock.ExitWriteLock();
}
}
}
internal SentryPropagationContext PropagationContext { get; private set; }
internal SessionUpdate? SessionUpdate { get; set; }
/// <inheritdoc />
public SdkVersion Sdk { get; } = new();
/// <inheritdoc />
public IReadOnlyList<string> Fingerprint { get; set; } = Array.Empty<string>();
#if NETSTANDARD2_0 || NETFRAMEWORK
private ConcurrentQueue<Breadcrumb> _breadcrumbs = new();
#else
private readonly ConcurrentQueue<Breadcrumb> _breadcrumbs = new();
#endif
/// <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 || NETFRAMEWORK
private ConcurrentBag<SentryAttachment> _attachments = new();
#else
private readonly ConcurrentBag<SentryAttachment> _attachments = new();
#endif
/// <summary>
/// Attachments.
/// </summary>
public IReadOnlyCollection<SentryAttachment> Attachments => _attachments;
/// <summary>
/// Creates a scope with the specified options.
/// </summary>
public Scope(SentryOptions? options)
: this(options, null)
{
}
internal Scope(SentryOptions? options, SentryPropagationContext? propagationContext)
{
Options = options ?? new SentryOptions();
PropagationContext = new SentryPropagationContext(propagationContext);
}
// For testing. Should explicitly require SentryOptions.
internal Scope()
: this(new SentryOptions())
{
}
/// <inheritdoc />
public void AddBreadcrumb(Breadcrumb breadcrumb) => AddBreadcrumb(breadcrumb, new SentryHint());
/// <summary>
/// Adds a breadcrumb with a hint.
/// </summary>
/// <param name="breadcrumb">The breadcrumb</param>
/// <param name="hint">A hint for use in the BeforeBreadcrumb callback</param>
public void AddBreadcrumb(Breadcrumb breadcrumb, SentryHint hint)
{
if (Options.BeforeBreadcrumbInternal is { } beforeBreadcrumb)
{
hint.AddAttachmentsFromScope(this);
if (beforeBreadcrumb(breadcrumb, hint) 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;
}
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)
{
if (Options.TagFilters.MatchesSubstringOrRegex(key))
{
return;
}
_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(SentryAttachment attachment) => _attachments.Add(attachment);
internal void SetPropagationContext(SentryPropagationContext propagationContext)
{
PropagationContext = propagationContext;
if (Options.EnableScopeSync)
{
Options.ScopeObserver?.SetTrace(propagationContext.TraceId, propagationContext.SpanId);
}
}
/// <summary>
/// Resets all the properties and collections within the scope to their default values.
/// </summary>
public void Clear()
{
Level = default;
Request = new();
Contexts.Clear();
User = new();
Release = default;
Distribution = default;
Environment = default;
TransactionName = default;
Transaction = default;
Fingerprint = Array.Empty<string>();
ClearBreadcrumbs();
_extra.Clear();
_tags.Clear();
ClearAttachments();
PropagationContext = new();
}
/// <summary>
/// Clear all Attachments.
/// </summary>
public void ClearAttachments()
{
#if NETSTANDARD2_0 || NETFRAMEWORK
Interlocked.Exchange(ref _attachments, new());
#else
_attachments.Clear();
#endif
}
/// <summary>
/// Removes all Breadcrumbs from the scope.
/// </summary>
public void ClearBreadcrumbs()
{
#if NETSTANDARD2_0 || NETFRAMEWORK
// No Clear method on ConcurrentQueue for these target frameworks
Interlocked.Exchange(ref _breadcrumbs, new());
#else
_breadcrumbs.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.
if (other.IsNull())
{
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.Release ??= Release;
other.Distribution ??= Distribution;
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.
if (other.IsNull())
{
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, PropagationContext)
{
OnEvaluating = OnEvaluating
};
Apply(clone);
foreach (var processor in EventProcessors)
{
clone.EventProcessors.Add(processor);
}
foreach (var processor in TransactionProcessors)
{
clone.TransactionProcessors.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, this);
}
catch (Exception ex)
{
Options.DiagnosticLogger?.LogError(ex, "Failed invoking event handler.");
}
finally
{
_hasEvaluated = true;
}
}
}
private ISpan? _span;
/// <summary>
/// Gets or sets the active span, or <c>null</c> if none available.
/// </summary>
/// <remarks>
/// If a span has been set on this property, it will become the active span until it is finished.
/// Otherwise, the active span is the latest unfinished span on the transaction, presuming a transaction
/// was set on the scope via the <see cref="Transaction"/> property.
/// </remarks>
public ISpan? Span
{
get
{
if (_span?.IsFinished is false)
{
return _span;
}
return Transaction?.GetLastActiveSpan() ?? Transaction;
}
set => _span = value;
}
/// <summary>
/// Invokes all event processor providers available.
/// </summary>
public IEnumerable<ISentryEventProcessor> GetAllEventProcessors()
{
foreach (var processor in Options.GetAllEventProcessors())
{
yield return processor;
}
foreach (var processor in EventProcessors)
{
yield return processor;
}
}
/// <summary>
/// Invokes all transaction processor providers available.
/// </summary>
public IEnumerable<ISentryTransactionProcessor> GetAllTransactionProcessors()
{
foreach (var processor in Options.GetAllTransactionProcessors())
{
yield return processor;
}
foreach (var processor in TransactionProcessors)
{
yield return processor;
}
}
/// <summary>
/// Invokes all exception processor providers available.
/// </summary>
public IEnumerable<ISentryEventExceptionProcessor> GetAllExceptionProcessors()
{
foreach (var processor in Options.GetAllExceptionProcessors())
{
yield return processor;
}
foreach (var processor in ExceptionProcessors)
{
yield return processor;
}
}
/// <summary>
/// Add an exception processor.
/// </summary>
/// <param name="processor">The exception processor.</param>
public void AddExceptionProcessor(ISentryEventExceptionProcessor processor)
=> ExceptionProcessors.Add(processor);
/// <summary>
/// Add the exception processors.
/// </summary>
/// <param name="processors">The exception processors.</param>
public void AddExceptionProcessors(IEnumerable<ISentryEventExceptionProcessor> processors)
{
foreach (var processor in processors)
{
ExceptionProcessors.Add(processor);
}
}
/// <summary>
/// Adds an event processor which is invoked when creating a <see cref="SentryEvent"/>.
/// </summary>
/// <param name="processor">The event processor.</param>
public void AddEventProcessor(ISentryEventProcessor processor)
=> EventProcessors.Add(processor);
/// <summary>
/// Adds an event processor which is invoked when creating a <see cref="SentryEvent"/>.
/// </summary>
/// <param name="processor">The event processor.</param>
public void AddEventProcessor(Func<SentryEvent, SentryEvent> processor)
=> AddEventProcessor(new DelegateEventProcessor(processor));
/// <summary>
/// Adds event processors which are invoked when creating a <see cref="SentryEvent"/>.
/// </summary>
/// <param name="processors">The event processors.</param>
public void AddEventProcessors(IEnumerable<ISentryEventProcessor> processors)
{
foreach (var processor in processors)
{
EventProcessors.Add(processor);
}
}
/// <summary>
/// Adds an transaction processor which is invoked when creating a <see cref="SentryTransaction"/>.
/// </summary>
/// <param name="processor">The transaction processor.</param>
public void AddTransactionProcessor(ISentryTransactionProcessor processor)
=> TransactionProcessors.Add(processor);
/// <summary>
/// Adds an transaction processor which is invoked when creating a <see cref="SentryTransaction"/>.
/// </summary>
/// <param name="processor">The transaction processor.</param>
public void AddTransactionProcessor(Func<SentryTransaction, SentryTransaction?> processor)
=> AddTransactionProcessor(new DelegateTransactionProcessor(processor));
/// <summary>
/// Adds transaction processors which are invoked when creating a <see cref="SentryTransaction"/>.
/// </summary>
/// <param name="processors">The transaction processors.</param>
public void AddTransactionProcessors(IEnumerable<ISentryTransactionProcessor> processors)
{
foreach (var processor in processors)
{
TransactionProcessors.Add(processor);
}
}
/// <summary>
/// Adds an attachment.
/// </summary>
/// <remarks>
/// Note: the stream must be seekable.
/// </remarks>
public void AddAttachment(
Stream stream,
string fileName,
AttachmentType type = AttachmentType.Default,
string? contentType = null)
{
var length = stream.TryGetLength();
if (length is null)
{
Options.LogWarning(
"Cannot evaluate the size of attachment '{0}' because the stream is not seekable.",
fileName);
return;
}
// TODO: Envelope spec allows the last item to not have a length.
// So if we make sure there's only 1 item without length, we can support it.
AddAttachment(
new SentryAttachment(
type,
new StreamAttachmentContent(stream),
fileName,
contentType));
}
/// <summary>
/// Adds an attachment.
/// </summary>
public void AddAttachment(
byte[] data,
string fileName,
AttachmentType type = AttachmentType.Default,
string? contentType = null) =>
AddAttachment(
new SentryAttachment(
type,
new ByteAttachmentContent(data),
fileName,
contentType));
/// <summary>
/// Adds an attachment.
/// </summary>
public void AddAttachment(string filePath, AttachmentType type = AttachmentType.Default, string? contentType = null)
=> AddAttachment(
new SentryAttachment(
type,
new FileAttachmentContent(filePath, Options.UseAsyncFileIO),
Path.GetFileName(filePath),
contentType));
/// <summary>
/// We need this lock to prevent a potential race condition in <see cref="ResetTransaction"/>.
/// </summary>
private readonly ReaderWriterLockSlim _transactionLock = new();
internal void ResetTransaction(ITransactionTracer? expectedCurrentTransaction)
{
_transactionLock.EnterWriteLock();
try
{
if (ReferenceEquals(_transaction.Value, expectedCurrentTransaction))
{
_transaction.Value = null;
SetPropagationContext(new SentryPropagationContext());
}
}
finally
{
_transactionLock.ExitWriteLock();
}
}
}