Skip to content

Commit 728129d

Browse files
committed
fix(okhttp): bind out-of-window cancels to the listener of their call
1 parent 552a731 commit 728129d

2 files changed

Lines changed: 63 additions & 25 deletions

File tree

‎sentry-okhttp/src/main/java/io/sentry/okhttp/SentryOkHttpEventListener.kt‎

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,12 @@ public open class SentryOkHttpEventListener(
4545
private val scopes: IScopes = ScopesAdapter.getInstance(),
4646
private val originalEventListenerCreator: ((call: Call) -> EventListener)? = null,
4747
) : EventListener() {
48-
private val originalEventListenerMap: MutableMap<Call, EventListener> = ConcurrentHashMap()
48+
private val originalEventListenerMap: ConcurrentHashMap<Call, EventListener> = ConcurrentHashMap()
49+
50+
// Set only by the constructors that wrap a single EventListener instance. Such a listener is
51+
// shared by every Call anyway, exactly like OkHttp's own EventListener.asFactory(), so it
52+
// exists independently of the callStart()..callEnd() window and can always be delegated to.
53+
private var fixedOriginalEventListener: EventListener? = null
4954

5055
public companion object {
5156
internal const val PROXY_SELECT_EVENT = "http.client.proxy_select_ms"
@@ -65,7 +70,9 @@ public open class SentryOkHttpEventListener(
6570

6671
public constructor(
6772
originalEventListener: EventListener
68-
) : this(ScopesAdapter.getInstance(), originalEventListenerCreator = { originalEventListener })
73+
) : this(ScopesAdapter.getInstance(), originalEventListenerCreator = { originalEventListener }) {
74+
fixedOriginalEventListener = originalEventListener
75+
}
6976

7077
public constructor(
7178
originalEventListenerFactory: Factory
@@ -77,7 +84,9 @@ public open class SentryOkHttpEventListener(
7784
public constructor(
7885
scopes: IScopes = ScopesAdapter.getInstance(),
7986
originalEventListener: EventListener,
80-
) : this(scopes, originalEventListenerCreator = { originalEventListener })
87+
) : this(scopes, originalEventListenerCreator = { originalEventListener }) {
88+
fixedOriginalEventListener = originalEventListener
89+
}
8190

8291
public constructor(
8392
scopes: IScopes = ScopesAdapter.getInstance(),
@@ -87,10 +96,7 @@ public open class SentryOkHttpEventListener(
8796
override fun callStart(call: Call) {
8897
// The EventListener.Factory contract binds a listener to a single call, so the wrapped
8998
// listener is kept per call instead of in a field shared by all concurrent calls
90-
val originalEventListener = originalEventListenerCreator?.invoke(call)
91-
if (originalEventListener != null) {
92-
originalEventListenerMap[call] = originalEventListener
93-
}
99+
val originalEventListener = getOrCreateEventListener(call)
94100
originalEventListener?.callStart(call)
95101
// If the wrapped EventListener is ours, we can just delegate the calls,
96102
// without creating other events that would create duplicates
@@ -397,13 +403,17 @@ public open class SentryOkHttpEventListener(
397403
}
398404

399405
override fun canceled(call: Call) {
400-
// Unlike the other callbacks, canceled() can occur before callStart() and after
401-
// callEnd()/callFailed(), so there is not always a listener bound to the call. Create one on
402-
// the fly in that case, but do not put it in the map: nothing would remove it again, because
403-
// a call that is canceled before it starts never gets a callEnd() or callFailed().
406+
// canceled() is not part of the call window: OkHttp may deliver it before callStart() and
407+
// after callEnd()/callFailed(), because it holds the listener for the whole Call lifetime
408+
// while we only keep it for the duration of the call.
404409
val originalEventListener =
405-
originalEventListenerMap[call] ?: originalEventListenerCreator?.invoke(call) ?: return
406-
originalEventListener.canceled(call)
410+
originalEventListenerMap[call]
411+
?: fixedOriginalEventListener
412+
// The call already reached its terminal event, so its listener is gone. Call.cancel() is
413+
// documented as a no-op for a completed request, thus there is nothing to report, and
414+
// creating a second listener here would break the Factory contract and leak the entry.
415+
?: if (call.isExecuted()) null else getOrCreateEventListener(call)
416+
originalEventListener?.canceled(call)
407417
}
408418

409419
override fun satisfactionFailure(call: Call, response: Response) {
@@ -422,6 +432,13 @@ public open class SentryOkHttpEventListener(
422432
originalEventListenerMap[call]?.cacheConditionalHit(call, cachedResponse)
423433
}
424434

435+
// computeIfAbsent, so that a cancel racing callStart() cannot make the Factory produce two
436+
// listeners for the same Call
437+
private fun getOrCreateEventListener(call: Call): EventListener? {
438+
val creator = originalEventListenerCreator ?: return null
439+
return originalEventListenerMap.computeIfAbsent(call) { creator.invoke(it) }
440+
}
441+
425442
private fun canCreateEventSpan(originalEventListener: EventListener?): Boolean {
426443
// If the wrapped EventListener is ours, we shouldn't create spans, as the originalEventListener
427444
// already did it

‎sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpEventListenerDelegationTest.kt‎

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,17 @@ class SentryOkHttpEventListenerDelegationTest {
5454

5555
fun newCall(path: String): Call =
5656
client.newCall(Request.Builder().url("http://localhost/$path").build())
57+
58+
// The tests drive the listener by hand, so no call is ever really executed. canceled() branches
59+
// on Call.isExecuted() to tell a cancel that precedes callStart() from one that follows the
60+
// terminal event, so those cases need a Call that reports the state under test.
61+
fun mockCall(path: String, isExecuted: Boolean): Call {
62+
val request = Request.Builder().url("http://localhost/$path").build()
63+
return mock<Call>().also {
64+
whenever(it.request()).thenReturn(request)
65+
whenever(it.isExecuted()).thenReturn(isExecuted)
66+
}
67+
}
5768
}
5869

5970
private val fixture = Fixture()
@@ -139,45 +150,55 @@ class SentryOkHttpEventListenerDelegationTest {
139150
}
140151

141152
@Test
142-
fun `cancel before callStart is delegated`() {
153+
fun `cancel before callStart binds the listener that callStart then reuses`() {
143154
val sut = fixture.getSut()
144-
val call = fixture.newCall("1")
155+
val call = fixture.mockCall("1", isExecuted = false)
145156

146157
sut.canceled(call)
158+
sut.callStart(call)
159+
sut.dnsStart(call, "sentry.io")
160+
sut.callEnd(call)
147161

148-
assertThat(fixture.listeners.single().received).containsExactly("canceled" to call)
162+
assertThat(fixture.listeners).hasSize(1)
163+
assertThat(fixture.listeners.single().received.map { it.first })
164+
.containsExactly("canceled", "callStart", "dnsStart", "callEnd")
165+
.inOrder()
149166
}
150167

151168
@Test
152-
fun `cancel after callEnd is delegated`() {
169+
fun `cancel after the terminal event is ignored`() {
153170
val sut = fixture.getSut()
154-
val call = fixture.newCall("1")
171+
val call = fixture.mockCall("1", isExecuted = true)
155172

156173
sut.callStart(call)
157174
sut.callEnd(call)
158175
sut.canceled(call)
159176

160-
assertThat(fixture.listeners.first().received.map { it.first })
177+
assertThat(fixture.listeners).hasSize(1)
178+
assertThat(fixture.listeners.single().received.map { it.first })
161179
.containsExactly("callStart", "callEnd")
162180
.inOrder()
163-
assertThat(fixture.listeners.last().received).containsExactly("canceled" to call)
164181
}
165182

166183
@Test
167-
fun `cancel outside of a call does not bind a listener to the call`() {
184+
fun `cancel after a failed call is ignored`() {
168185
val sut = fixture.getSut()
169-
val call = fixture.newCall("1")
186+
val call = fixture.mockCall("1", isExecuted = true)
170187

188+
sut.callStart(call)
189+
sut.callFailed(call, IOException())
171190
sut.canceled(call)
172-
sut.dnsStart(call, "sentry.io")
173191

174-
assertThat(fixture.listeners.single().received.map { it.first }).containsExactly("canceled")
192+
assertThat(fixture.listeners).hasSize(1)
193+
assertThat(fixture.listeners.single().received.map { it.first })
194+
.containsExactly("callStart", "callFailed")
195+
.inOrder()
175196
}
176197

177198
@Test
178199
fun `a single wrapped listener receives cancels outside of the call window`() {
179200
whenever(fixture.scopes.options).thenReturn(SentryOptions())
180-
val call = fixture.newCall("1")
201+
val call = fixture.mockCall("1", isExecuted = true)
181202
val listener = RecordingListener(call)
182203
val sut = SentryOkHttpEventListener(fixture.scopes, listener)
183204

0 commit comments

Comments
 (0)