@@ -20,24 +20,38 @@ private SentryContextWrapper(final @NotNull Context delegate) {
2020 this .delegate = delegate ;
2121 }
2222
23- @ SuppressWarnings ("unchecked" )
2423 @ Override
2524 public <V > @ Nullable V get (final @ NotNull ContextKey <V > contextKey ) {
26- V result = delegate .get (contextKey );
27- if (Sentry .isGlobalHubMode ()) {
28- if (result == null
29- || (result instanceof Span && !((Span ) result ).getSpanContext ().isValid ())) {
30- if (isOpentelemetrySpan (contextKey )) {
31- IOtelSpanWrapper sentrySpan =
32- SentryWeakSpanStorage .getInstance ().getLastKnownUnfinishedRootSpan ();
33- if (sentrySpan != null ) {
34- try {
35- return (V ) sentrySpan .getOpenTelemetrySpan ();
36- } catch (Throwable t ) {
37- return result ;
38- }
39- }
40- }
25+ final @ Nullable V result = delegate .get (contextKey );
26+ if (shouldReturnRootSpanInstead (contextKey , result )) {
27+ return returnUnfinishedRootSpanIfAvailable (result );
28+ }
29+ return result ;
30+ }
31+
32+ private <V > boolean shouldReturnRootSpanInstead (
33+ final @ NotNull ContextKey <V > contextKey , final @ Nullable V result ) {
34+ if (!Sentry .isGlobalHubMode ()) {
35+ return false ;
36+ }
37+ if (!isOpentelemetrySpan (contextKey )) {
38+ return false ;
39+ }
40+ if (result == null ) {
41+ return true ;
42+ }
43+ return result instanceof Span && !((Span ) result ).getSpanContext ().isValid ();
44+ }
45+
46+ @ SuppressWarnings ("unchecked" )
47+ private <V > @ Nullable V returnUnfinishedRootSpanIfAvailable (final @ Nullable V result ) {
48+ final @ Nullable IOtelSpanWrapper sentrySpan =
49+ SentryWeakSpanStorage .getInstance ().getLastKnownUnfinishedRootSpan ();
50+ if (sentrySpan != null ) {
51+ try {
52+ return (V ) sentrySpan .getOpenTelemetrySpan ();
53+ } catch (Throwable t ) {
54+ return result ;
4155 }
4256 }
4357 return result ;
0 commit comments