Repository navigation
Expand file tree
/
Copy pathSentryOtelThreadLocalStorage.java
More file actions
87 lines (73 loc) · 2.63 KB
/
Copy pathSentryOtelThreadLocalStorage.java
File metadata and controls
87 lines (73 loc) · 2.63 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
/*
* Adapted from https://github.com/open-telemetry/opentelemetry-java/blob/0aacc55d1e3f5cc6dbb4f8fa26bcb657b01a7bc9/context/src/main/java/io/opentelemetry/context/ThreadLocalContextStorage.java
*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.sentry.opentelemetry;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.ContextStorage;
import io.opentelemetry.context.Scope;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
/**
* Workaround to make OpenTelemetry context storage work for Sentry since Sentry sometimes forks
* Context without cleaning up. We are not yet sure if this is something we can easliy fix, since
* Sentry static API makes heavy use of getCurrentScopes and there is no easy way of knowing when to
* restore previous Context.
*/
@ApiStatus.Experimental
@ApiStatus.Internal
public final class SentryOtelThreadLocalStorage implements ContextStorage {
private static final Logger logger =
Logger.getLogger(SentryOtelThreadLocalStorage.class.getName());
private static final ThreadLocal<Context> THREAD_LOCAL_STORAGE = new ThreadLocal<>();
// temp fix for JDK 21: Same identity check as OpenTelemetry's ThreadLocalContextStorage.
@SuppressWarnings("ReferenceEquality")
@Override
public Scope attach(Context toAttach) {
if (toAttach == null) {
// Null context not allowed so ignore it.
return NoopScope.INSTANCE;
}
Context beforeAttach = current();
if (toAttach == beforeAttach) {
return NoopScope.INSTANCE;
}
THREAD_LOCAL_STORAGE.set(toAttach);
return new SentryScopeImpl(beforeAttach);
}
private static class SentryScopeImpl implements Scope {
@Nullable private final Context beforeAttach;
private boolean closed;
private SentryScopeImpl(@Nullable Context beforeAttach) {
this.beforeAttach = beforeAttach;
}
@Override
public void close() {
// if (!closed && current() == toAttach) {
// Used to make OTel thread local storage compatible with Sentry where cleanup isn't always
// performed correctly
if (!closed) {
closed = true;
THREAD_LOCAL_STORAGE.set(beforeAttach);
} else {
logger.log(
Level.FINE,
" Trying to close scope which does not represent current context. Ignoring the call.");
}
}
}
@Override
@Nullable
public Context current() {
return THREAD_LOCAL_STORAGE.get();
}
enum NoopScope implements Scope {
INSTANCE;
@Override
public void close() {}
}
}