Skip to content

Commit d0b8507

Browse files
committed
work-around concurrency bug in okio.Pipe (square/okio#1412)
1 parent 081a61e commit d0b8507

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

okhttp/src/main/kotlin/com/connectrpc/okhttp/OkHttpStream.kt

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import okio.Buffer
3232
import okio.BufferedSink
3333
import okio.BufferedSource
3434
import okio.Pipe
35+
import okio.withLock
3536
import java.io.IOException
3637
import java.util.concurrent.CountDownLatch
3738

@@ -181,15 +182,25 @@ internal class PipeRequestBody(
181182
) : RequestBody() {
182183
private val pipe = Pipe(pipeMaxBufferSize)
183184

185+
/**
186+
* Lock used to provide extra synchronization so that fold, write, and
187+
* close can work correctly in the face of concurrency.
188+
*
189+
* See https://github.com/square/okio/issues/1412
190+
*/
191+
private val pipeLock = pipe.lock
192+
184193
/**
185194
* Latch that signals when the pipe's sink is closed.
186195
*/
187196
private val closed = CountDownLatch(1)
188197

189198
fun write(buffer: Buffer) {
190199
try {
191-
pipe.sink.write(buffer, buffer.size)
192-
pipe.sink.flush()
200+
pipeLock.withLock {
201+
pipe.sink.write(buffer, buffer.size)
202+
pipe.sink.flush()
203+
}
193204
} catch (e: Throwable) {
194205
close()
195206
throw e
@@ -199,7 +210,9 @@ internal class PipeRequestBody(
199210
override fun contentType() = contentType
200211

201212
override fun writeTo(sink: BufferedSink) {
202-
pipe.fold(sink)
213+
pipeLock.withLock {
214+
pipe.fold(sink)
215+
}
203216
if (!duplex) {
204217
// For non-duplex request bodies, okhttp3
205218
// expects this method to return only when
@@ -214,7 +227,9 @@ internal class PipeRequestBody(
214227

215228
fun close() {
216229
try {
217-
pipe.sink.close()
230+
pipeLock.withLock {
231+
pipe.sink.close()
232+
}
218233
} catch (_: Throwable) {
219234
// No-op
220235
} finally {

0 commit comments

Comments
 (0)