Skip to content

Commit a064940

Browse files
authored
Lock request context changes during read/write spawned tasks (#1046)
1 parent 9c1d42a commit a064940

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

src/clientlayers/StreamRequest.jl

+14-5
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,15 @@ function streamlayer(stream::Stream; iofunction=nothing, decompress::Union{Nothi
3333
try
3434
@sync begin
3535
if iofunction === nothing
36+
# use a lock here for request.context changes (this is currently the only places
37+
# where multiple threads may modify/change context at the same time)
38+
lock = ReentrantLock()
3639
Threads.@spawn try
37-
writebody(stream, req)
40+
writebody(stream, req, lock)
3841
finally
39-
req.context[:write_duration_ms] = get(req.context, :write_duration_ms, 0.0) + ((time() - write_start) * 1000)
42+
Base.@lock lock begin
43+
req.context[:write_duration_ms] = get(req.context, :write_duration_ms, 0.0) + ((time() - write_start) * 1000)
44+
end
4045
@debugv 2 "client closewrite"
4146
closewrite(stream)
4247
end
@@ -48,7 +53,9 @@ function streamlayer(stream::Stream; iofunction=nothing, decompress::Union{Nothi
4853
readbody(stream, response, decompress)
4954
end
5055
finally
51-
req.context[:read_duration_ms] = get(req.context, :read_duration_ms, 0.0) + ((time() - read_start) * 1000)
56+
Base.@lock lock begin
57+
req.context[:read_duration_ms] = get(req.context, :read_duration_ms, 0.0) + ((time() - read_start) * 1000)
58+
end
5259
@debugv 2 "client closeread"
5360
closeread(stream)
5461
end
@@ -77,14 +84,16 @@ function streamlayer(stream::Stream; iofunction=nothing, decompress::Union{Nothi
7784
return response
7885
end
7986

80-
function writebody(stream::Stream, req::Request)
87+
function writebody(stream::Stream, req::Request, lock)
8188
if !isbytes(req.body)
8289
n = writebodystream(stream, req.body)
8390
closebody(stream)
8491
else
8592
n = write(stream, req.body)
8693
end
87-
stream.message.request.context[:nbytes_written] = n
94+
Base.@lock lock begin
95+
req.context[:nbytes_written] = n
96+
end
8897
return n
8998
end
9099

0 commit comments

Comments
 (0)