-
-
Notifications
You must be signed in to change notification settings - Fork 206
/
Hub.cs
644 lines (556 loc) · 21.1 KB
/
Hub.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
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
using Sentry.Extensibility;
using Sentry.Infrastructure;
using Sentry.Protocol.Envelopes;
using Sentry.Protocol.Metrics;
namespace Sentry.Internal;
internal class Hub : IHub, IMetricHub, IDisposable
{
private readonly object _sessionPauseLock = new();
private readonly ISentryClient _ownedClient;
private readonly ISystemClock _clock;
private readonly ISessionManager _sessionManager;
private readonly SentryOptions _options;
private readonly RandomValuesFactory _randomValuesFactory;
private int _isPersistedSessionRecovered;
// Internal for testability
internal ConditionalWeakTable<Exception, ISpan> ExceptionToSpanMap { get; } = new();
internal IInternalScopeManager ScopeManager { get; }
/// <inheritdoc cref="IMetricAggregator"/>
public IMetricAggregator Metrics { get; }
private int _isEnabled = 1;
public bool IsEnabled => _isEnabled == 1;
internal SentryOptions Options => _options;
internal Hub(
SentryOptions options,
ISentryClient? client = null,
ISessionManager? sessionManager = null,
ISystemClock? clock = null,
IInternalScopeManager? scopeManager = null,
RandomValuesFactory? randomValuesFactory = null)
{
if (string.IsNullOrWhiteSpace(options.Dsn))
{
const string msg = "Attempt to instantiate a Hub without a DSN.";
options.LogFatal(msg);
throw new InvalidOperationException(msg);
}
options.LogDebug("Initializing Hub for Dsn: '{0}'.", options.Dsn);
_options = options;
_randomValuesFactory = randomValuesFactory ?? new SynchronizedRandomValuesFactory();
_sessionManager = sessionManager ?? new GlobalSessionManager(options);
_ownedClient = client ?? new SentryClient(options, randomValuesFactory: _randomValuesFactory, sessionManager: _sessionManager);
_clock = clock ?? SystemClock.Clock;
ScopeManager = scopeManager ?? new SentryScopeManager(options, _ownedClient);
if (!options.IsGlobalModeEnabled)
{
// Push the first scope so the async local starts from here
PushScope();
}
if (options.ExperimentalMetrics is not null)
{
Metrics = new MetricAggregator(options, this);
}
else
{
Metrics = new DisabledMetricAggregator();
}
foreach (var integration in options.Integrations)
{
options.LogDebug("Registering integration: '{0}'.", integration.GetType().Name);
integration.Register(this, options);
}
}
public void ConfigureScope(Action<Scope> configureScope)
{
try
{
ScopeManager.ConfigureScope(configureScope);
}
catch (Exception e)
{
_options.LogError(e, "Failure to ConfigureScope");
}
}
public async Task ConfigureScopeAsync(Func<Scope, Task> configureScope)
{
try
{
await ScopeManager.ConfigureScopeAsync(configureScope).ConfigureAwait(false);
}
catch (Exception e)
{
_options.LogError(e, "Failure to ConfigureScopeAsync");
}
}
public IDisposable PushScope() => ScopeManager.PushScope();
public IDisposable PushScope<TState>(TState state) => ScopeManager.PushScope(state);
public void RestoreScope(Scope savedScope) => ScopeManager.RestoreScope(savedScope);
public void BindClient(ISentryClient client) => ScopeManager.BindClient(client);
public ITransactionTracer StartTransaction(
ITransactionContext context,
IReadOnlyDictionary<string, object?> customSamplingContext)
=> StartTransaction(context, customSamplingContext, null);
internal ITransactionTracer StartTransaction(
ITransactionContext context,
IReadOnlyDictionary<string, object?> customSamplingContext,
DynamicSamplingContext? dynamicSamplingContext)
{
var instrumenter = (context as SpanContext)?.Instrumenter;
if (instrumenter != _options.Instrumenter)
{
_options.LogWarning(
$"Attempted to start a transaction via {instrumenter} instrumentation when the SDK is" +
$" configured for {_options.Instrumenter} instrumentation. The transaction will not be created.");
return NoOpTransaction.Instance;
}
var transaction = new TransactionTracer(this, context);
// If the hub is disabled, we will always sample out. In other words, starting a transaction
// after disposing the hub will result in that transaction not being sent to Sentry.
// Additionally, we will always sample out if tracing is explicitly disabled.
// Do not invoke the TracesSampler, evaluate the TracesSampleRate, and override any sampling decision
// that may have been already set (i.e.: from a sentry-trace header).
if (!IsEnabled || _options.EnableTracing is false)
{
transaction.IsSampled = false;
transaction.SampleRate = 0.0;
}
else
{
// Except when tracing is disabled, TracesSampler runs regardless of whether a decision
// has already been made, as it can be used to override it.
if (_options.TracesSampler is { } tracesSampler)
{
var samplingContext = new TransactionSamplingContext(
context,
customSamplingContext);
if (tracesSampler(samplingContext) is { } sampleRate)
{
transaction.IsSampled = _randomValuesFactory.NextBool(sampleRate);
transaction.SampleRate = sampleRate;
}
}
// Random sampling runs only if the sampling decision hasn't been made already.
if (transaction.IsSampled == null)
{
var sampleRate = _options.TracesSampleRate ?? (_options.EnableTracing is true ? 1.0 : 0.0);
transaction.IsSampled = _randomValuesFactory.NextBool(sampleRate);
transaction.SampleRate = sampleRate;
}
if (transaction.IsSampled is true &&
_options.TransactionProfilerFactory is { } profilerFactory &&
_randomValuesFactory.NextBool(_options.ProfilesSampleRate ?? 0.0))
{
// TODO cancellation token based on Hub being closed?
transaction.TransactionProfiler = profilerFactory.Start(transaction, CancellationToken.None);
}
}
// Use the provided DSC, or create one based on this transaction.
// DSC creation must be done AFTER the sampling decision has been made.
transaction.DynamicSamplingContext =
dynamicSamplingContext ?? transaction.CreateDynamicSamplingContext(_options);
// A sampled out transaction still appears fully functional to the user
// but will be dropped by the client and won't reach Sentry's servers.
return transaction;
}
public void BindException(Exception exception, ISpan span)
{
// Don't bind on sampled out spans
if (span.IsSampled == false)
{
return;
}
// Don't overwrite existing pair in the unlikely event that it already exists
_ = ExceptionToSpanMap.GetValue(exception, _ => span);
}
public ISpan? GetSpan() => ScopeManager.GetCurrent().Key.Span;
public SentryTraceHeader GetTraceHeader()
{
if (GetSpan()?.GetTraceHeader() is { } traceHeader)
{
return traceHeader;
}
// With either tracing disabled or no active span on the current scope we fall back to the propagation context
var propagationContext = ScopeManager.GetCurrent().Key.PropagationContext;
// In either case, we must not append a sampling decision.
return new SentryTraceHeader(propagationContext.TraceId, propagationContext.SpanId, null);
}
public BaggageHeader GetBaggage()
{
var span = GetSpan();
if (span?.GetTransaction() is TransactionTracer { DynamicSamplingContext: { IsEmpty: false } dsc })
{
return dsc.ToBaggageHeader();
}
var propagationContext = ScopeManager.GetCurrent().Key.PropagationContext;
return propagationContext.GetOrCreateDynamicSamplingContext(_options).ToBaggageHeader();
}
public TransactionContext ContinueTrace(
string? traceHeader,
string? baggageHeader,
string? name = null,
string? operation = null)
{
SentryTraceHeader? sentryTraceHeader = null;
if (traceHeader is not null)
{
sentryTraceHeader = SentryTraceHeader.Parse(traceHeader);
}
BaggageHeader? sentryBaggageHeader = null;
if (baggageHeader is not null)
{
sentryBaggageHeader = BaggageHeader.TryParse(baggageHeader, onlySentry: true);
}
return ContinueTrace(sentryTraceHeader, sentryBaggageHeader, name, operation);
}
public TransactionContext ContinueTrace(
SentryTraceHeader? traceHeader,
BaggageHeader? baggageHeader,
string? name = null,
string? operation = null)
{
var propagationContext = SentryPropagationContext.CreateFromHeaders(_options.DiagnosticLogger, traceHeader, baggageHeader);
ConfigureScope(scope => scope.PropagationContext = propagationContext);
// If we have to create a new SentryTraceHeader we don't make a sampling decision
traceHeader ??= new SentryTraceHeader(propagationContext.TraceId, propagationContext.SpanId, null);
return new TransactionContext(
name ?? string.Empty,
operation ?? string.Empty,
traceHeader);
}
public void StartSession()
{
// Attempt to recover persisted session left over from previous run
if (Interlocked.Exchange(ref _isPersistedSessionRecovered, 1) != 1)
{
try
{
var recoveredSessionUpdate = _sessionManager.TryRecoverPersistedSession();
if (recoveredSessionUpdate is not null)
{
CaptureSession(recoveredSessionUpdate);
}
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to recover persisted session.");
}
}
// Start a new session
try
{
var sessionUpdate = _sessionManager.StartSession();
if (sessionUpdate is not null)
{
CaptureSession(sessionUpdate);
}
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to start a session.");
}
}
public void PauseSession()
{
lock (_sessionPauseLock)
{
try
{
_sessionManager.PauseSession();
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to pause a session.");
}
}
}
public void ResumeSession()
{
lock (_sessionPauseLock)
{
try
{
foreach (var update in _sessionManager.ResumeSession())
{
CaptureSession(update);
}
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to resume a session.");
}
}
}
private void EndSession(DateTimeOffset timestamp, SessionEndStatus status)
{
try
{
var sessionUpdate = _sessionManager.EndSession(timestamp, status);
if (sessionUpdate is not null)
{
CaptureSession(sessionUpdate);
}
}
catch (Exception ex)
{
_options.LogError(ex, "Failed to end a session.");
}
}
public void EndSession(SessionEndStatus status = SessionEndStatus.Exited) =>
EndSession(_clock.GetUtcNow(), status);
private ISpan? GetLinkedSpan(SentryEvent evt)
{
// Find the span which is bound to the same exception
if (evt.Exception is { } exception &&
ExceptionToSpanMap.TryGetValue(exception, out var spanBoundToException))
{
return spanBoundToException;
}
return null;
}
private void ApplyTraceContextToEvent(SentryEvent evt, ISpan span)
{
evt.Contexts.Trace.SpanId = span.SpanId;
evt.Contexts.Trace.TraceId = span.TraceId;
evt.Contexts.Trace.ParentSpanId = span.ParentSpanId;
if (span.GetTransaction() is TransactionTracer transactionTracer)
{
evt.DynamicSamplingContext = transactionTracer.DynamicSamplingContext;
}
}
private void ApplyTraceContextToEvent(SentryEvent evt, SentryPropagationContext propagationContext)
{
evt.Contexts.Trace.TraceId = propagationContext.TraceId;
evt.Contexts.Trace.SpanId = propagationContext.SpanId;
evt.Contexts.Trace.ParentSpanId = propagationContext.ParentSpanId;
evt.DynamicSamplingContext = propagationContext.GetOrCreateDynamicSamplingContext(_options);
}
public SentryId CaptureEvent(SentryEvent evt, Action<Scope> configureScope)
=> CaptureEvent(evt, null, configureScope);
public SentryId CaptureEvent(SentryEvent evt, SentryHint? hint, Action<Scope> configureScope)
{
if (!IsEnabled)
{
return SentryId.Empty;
}
try
{
var clonedScope = ScopeManager.GetCurrent().Key.Clone();
configureScope(clonedScope);
return CaptureEvent(evt, clonedScope, hint);
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture event: {0}", evt.EventId);
return SentryId.Empty;
}
}
public bool CaptureEnvelope(Envelope envelope) => _ownedClient.CaptureEnvelope(envelope);
public SentryId CaptureEvent(SentryEvent evt, Scope? scope = null, SentryHint? hint = null)
{
if (!IsEnabled)
{
return SentryId.Empty;
}
try
{
ScopeManager.GetCurrent().Deconstruct(out var currentScope, out var sentryClient);
var actualScope = scope ?? currentScope;
// We get the span linked to the event or fall back to the current span
var span = GetLinkedSpan(evt) ?? actualScope.Span;
if (span is not null)
{
if (span.IsSampled is not false)
{
ApplyTraceContextToEvent(evt, span);
}
}
else
{
// If there is no span on the scope (and not just no sampled one), fall back to the propagation context
ApplyTraceContextToEvent(evt, actualScope.PropagationContext);
}
// Now capture the event with the Sentry client on the current scope.
var id = sentryClient.CaptureEvent(evt, actualScope, hint);
actualScope.LastEventId = id;
actualScope.SessionUpdate = null;
if (evt.HasTerminalException() && actualScope.Transaction is { } transaction)
{
// Event contains a terminal exception -> finish any current transaction as aborted
// Do this *after* the event was captured, so that the event is still linked to the transaction.
_options.LogDebug("Ending transaction as Aborted, due to unhandled exception.");
transaction.Finish(SpanStatus.Aborted);
}
return id;
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture event: {0}", evt.EventId);
return SentryId.Empty;
}
}
public void CaptureUserFeedback(UserFeedback userFeedback)
{
if (!IsEnabled)
{
return;
}
try
{
_ownedClient.CaptureUserFeedback(userFeedback);
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture user feedback: {0}", userFeedback.EventId);
}
}
public void CaptureTransaction(SentryTransaction transaction) => CaptureTransaction(transaction, null, null);
public void CaptureTransaction(SentryTransaction transaction, Scope? scope, SentryHint? hint)
{
// Note: The hub should capture transactions even if it is disabled.
// This allows transactions to be reported as failed when they encountered an unhandled exception,
// in the case where the hub was disabled before the transaction was captured.
// For example, that can happen with a top-level async main because IDisposables are processed before
// the unhandled exception event fires.
//
// Any transactions started after the hub was disabled will already be sampled out and thus will
// not be passed along to sentry when captured here.
try
{
var (currentScope, client) = ScopeManager.GetCurrent();
scope ??= currentScope;
client.CaptureTransaction(transaction, scope, hint);
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture transaction: {0}", transaction.SpanId);
}
}
/// <inheritdoc cref="IMetricHub.CaptureMetrics"/>
public void CaptureMetrics(IEnumerable<Metric> metrics)
{
if (!IsEnabled)
{
return;
}
Metric[]? enumerable = null;
try
{
enumerable = metrics as Metric[] ?? metrics.ToArray();
_options.LogDebug("Capturing metrics.");
_ownedClient.CaptureEnvelope(Envelope.FromMetrics(metrics));
}
catch (Exception e)
{
var metricEventIds = enumerable?.Select(m => m.EventId).ToArray() ?? [];
_options.LogError(e, "Failure to capture metrics: {0}", string.Join(",", metricEventIds));
}
}
/// <inheritdoc cref="IMetricHub.CaptureCodeLocations"/>
public void CaptureCodeLocations(CodeLocations codeLocations)
{
if (!IsEnabled)
{
return;
}
try
{
_options.LogDebug("Capturing code locations for period: {0}", codeLocations.Timestamp);
_ownedClient.CaptureEnvelope(Envelope.FromCodeLocations(codeLocations));
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture code locations");
}
}
/// <inheritdoc cref="IMetricHub.StartSpan"/>
public ISpan StartSpan(string operation, string description)
{
ITransactionTracer? currentTransaction = null;
ConfigureScope(s => currentTransaction = s.Transaction);
return currentTransaction is { } transaction
? transaction.StartChild(operation, description)
: this.StartTransaction(operation, description);
}
public void CaptureSession(SessionUpdate sessionUpdate)
{
if (!IsEnabled)
{
return;
}
try
{
_ownedClient.CaptureSession(sessionUpdate);
}
catch (Exception e)
{
_options.LogError(e, "Failure to capture session update: {0}", sessionUpdate.Id);
}
}
public SentryId CaptureCheckIn(string monitorSlug, CheckInStatus status, SentryId? sentryId = null)
{
if (!IsEnabled)
{
return SentryId.Empty;
}
try
{
_options.LogDebug("Capturing '{0}' check-in for '{1}'", status, monitorSlug);
return _ownedClient.CaptureCheckIn(monitorSlug, status, sentryId);
}
catch (Exception e)
{
_options.LogError(e, "Failed to capture check in for: {0}", monitorSlug);
}
return SentryId.Empty;
}
public async Task FlushAsync(TimeSpan timeout)
{
try
{
var (_, client) = ScopeManager.GetCurrent();
await client.FlushAsync(timeout).ConfigureAwait(false);
}
catch (Exception e)
{
_options.LogError(e, "Failure to Flush events");
}
}
public void Dispose()
{
_options.LogInfo("Disposing the Hub.");
if (Interlocked.Exchange(ref _isEnabled, 0) != 1)
{
return;
}
try
{
Metrics.FlushAsync().ContinueWith(_ =>
_ownedClient.FlushAsync(_options.ShutdownTimeout).Wait()
).ConfigureAwait(false).GetAwaiter().GetResult();
}
catch (Exception e)
{
_options.LogError(e, "Failed to wait on disposing tasks to flush.");
}
//Dont dispose of ScopeManager since we want dangling transactions to still be able to access tags.
#if __IOS__
// TODO
#elif ANDROID
// TODO
#elif NET8_0_OR_GREATER
if (AotHelper.IsNativeAot)
{
_options?.LogDebug("Closing native SDK");
SentrySdk.CloseNativeSdk();
}
#endif
}
public SentryId LastEventId
{
get
{
var currentScope = ScopeManager.GetCurrent();
return currentScope.Key.LastEventId;
}
}
}