connectrpc-async 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -66,6 +66,18 @@ module ConnectRPC
66
66
  !Streaming.codec(Protocol.single(headers, "content-type")).nil?)
67
67
  end
68
68
 
69
+ # Other native Connect POSTs and GETs, such as unary calls, whose whole
70
+ # response is ready once processing finishes.
71
+ def http1_unary_route?(request)
72
+ return false if request.respond_to?(:stream) || !%w[GET POST].include?(request.method)
73
+
74
+ path = request.path&.split("?", 2)&.first
75
+ return false unless path && @server.handles?(path)
76
+
77
+ @server.send(:request_protocol, Internal.headers(request), request.method) == :connect &&
78
+ !http1_streaming_route?(request)
79
+ end
80
+
69
81
  # Client-streaming and bidi routes, whose request bodies may idle.
70
82
  def input_stream_route?(request)
71
83
  path = request.path&.split("?", 2)&.first
@@ -84,7 +96,8 @@ module ConnectRPC
84
96
  declaration.is_a?(ServerStreamMethod) || declaration.is_a?(BidiStreamMethod)
85
97
  end
86
98
 
87
- private :call_headers, :publication?, :http1_streaming_route?, :input_stream_route?, :output_stream_route?
99
+ private :call_headers, :publication?, :http1_streaming_route?, :http1_unary_route?, :input_stream_route?,
100
+ :output_stream_route?
88
101
 
89
102
  def admission_response(request)
90
103
  path = request.path&.split("?", 2)&.first
@@ -3,178 +3,54 @@
3
3
  module ConnectRPC
4
4
  module Async
5
5
  module Internal
6
- # A result is distinct from task finalization and retained child ownership.
6
+ # Joins a task and its non-transient descendants until every one has
7
+ # settled: its promise resolved, so its block, ensure included, has
8
+ # returned. Async resolves a cancelled task's promise before it stops
9
+ # that task's children and clears its fiber, and Task#finished? turns
10
+ # true with no signal to wait on. Past the settled boundary only that
11
+ # bookkeeping remains (stop_children raising into children the walk
12
+ # still joins, then finish!), which runs no application code and
13
+ # touches no descriptor. So a descriptor closed after a join is no
14
+ # longer in use by any fiber the join saw.
15
+ #
16
+ # The boundary assumes a task's block never starts after its promise
17
+ # resolved. Async 2.46.0 allows that only when an initialized task that
18
+ # already has children is cancelled, the cancel cascade into those
19
+ # children yields, and something then runs the task. No task here gains
20
+ # children before it runs, and a task that may be cancelled before it
21
+ # runs is started only behind a finished? or status guard.
7
22
  class CompletionJoin
8
- # Installed only on a selected instance. connectrpc-falcon aliases this
9
- # class, so every join on a task shares one observation.
10
- module Consume
11
- def consume
12
- result = super
13
- @connectrpc_async_completion&.consumed
14
- result
15
- end
16
- end
17
- private_constant :Consume
18
-
19
- class Observation
20
- attr_reader :required, :generation, :promise, :violation
21
-
22
- def initialize(target)
23
- @target = target
24
- @fiber = target.fiber
25
- @scheduler = Fiber.scheduler
26
- @required = {}.compare_by_identity
27
- @generation = 0
28
- @promise = ::Async::Promise.new
29
- @active = true
30
- @terminal = false
31
- @queued = nil
32
- end
33
-
34
- def terminal? = @terminal
35
- def fiber_alive? = @fiber&.alive?
36
-
37
- def retain(children)
38
- added = false
39
- children.each do |child|
40
- next if @required.key?(child)
41
-
42
- @required[child] = true
43
- added = true
44
- end
45
- advance if added
46
- end
47
-
48
- # Node#consume can expose work before Task#finished? becomes true.
49
- # Capture identities here, before any deferred check or tree mutation.
50
- def consumed
51
- return unless @active
52
-
53
- retain(CompletionJoin.children(@target))
54
- return if @terminal || @queued
55
-
56
- no_work = @required.each_key.none? { |child| CompletionJoin.pending?(child) }
57
- return unless @target.finished? || (@target.fiber.nil? && no_work)
58
-
59
- raise "Completion scheduler closed before finalization" if @scheduler.closed?
60
-
61
- @queued = Check.new(self)
62
- @scheduler.push(@queued)
63
- rescue StandardError => e
64
- violate(e)
65
- end
66
-
67
- def check
68
- @queued = nil
69
- retain(CompletionJoin.children(@target))
70
- unless @target.finished?
71
- if !fiber_alive? && @required.each_key.none? { |child| CompletionJoin.pending?(child) }
72
- raise CompletionJoin.residual_violation(@target)
73
- end
74
-
75
- return
23
+ def self.settled?(task) = task.completed? || task.failed? || task.cancelled?
24
+
25
+ # One non-yielding pass over the target and every identity already
26
+ # retained, returning each unsettled task. Every non-transient child
27
+ # seen is retained, so it stays joined after it is reparented away or
28
+ # flagged transient. A transient child's subtree is skipped.
29
+ def self.unsettled(target, retained)
30
+ pending = []
31
+ seen = {}.compare_by_identity
32
+ stack = [target, *retained.keys]
33
+ while (node = stack.pop)
34
+ next if seen.key?(node)
35
+
36
+ seen[node] = true
37
+ pending << node unless settled?(node)
38
+ node.children&.each do |child|
39
+ next if child.transient?
40
+
41
+ retained[child] = true
42
+ stack << child
76
43
  end
77
-
78
- raise "Finished task still has its captured live fiber" if fiber_alive?
79
-
80
- @terminal = true
81
- # The original fiber is gone, but retained joins can still expose
82
- # new membership at consume. Keep that hook active until joined.
83
- @fiber = @scheduler = nil
84
- advance
85
- end
86
-
87
- def violate(error)
88
- return if @violation
89
-
90
- @violation = error
91
- release
92
- advance
93
- rescue StandardError
94
- # Keep the violation inspectable even if shutdown prevents waking.
95
- nil
96
- end
97
-
98
- def release
99
- @active = false
100
- @fiber = @scheduler = nil
101
- end
102
-
103
- private
104
-
105
- def advance
106
- previous = @promise
107
- @generation += 1
108
- @promise = ::Async::Promise.new
109
- previous.resolve(nil)
110
- end
111
- end
112
- private_constant :Observation
113
-
114
- # Scheduler callbacks run after finish!'s non-yielding tail. They are
115
- # neither Tasks nor children, and never execute application work.
116
- class Check
117
- def initialize(observation)
118
- @observation = observation
119
- end
120
-
121
- def alive? = !@observation.nil?
122
-
123
- def transfer
124
- observation = @observation
125
- return unless observation
126
-
127
- @observation = nil
128
- observation.check
129
- rescue StandardError => e
130
- observation.violate(e)
131
- end
132
- end
133
- private_constant :Check
134
-
135
- def self.observation(target)
136
- target.instance_variable_get(:@connectrpc_async_completion)
137
- end
138
-
139
- def self.children(target)
140
- target.children&.to_a&.reject { |child| child.transient? || child.finished? } || []
141
- end
142
-
143
- def self.pending?(target, seen = {}.compare_by_identity)
144
- return false if seen.key?(target)
145
- return true unless target.finished?
146
-
147
- seen[target] = true
148
- state = observation(target)
149
- return false unless state
150
-
151
- !state.terminal? || state.violation || state.required.each_key.any? { |child| pending?(child, seen) }
152
- end
153
-
154
- def self.scan(target, retained)
155
- actual = children(target)
156
- state = observation(target)
157
- state&.retain(actual)
158
- actual.each { |child| retained[child] = true }
159
- state&.required&.each_key { |child| retained[child] = true }
160
- retained.keys.select { |child| pending?(child) }
161
- end
162
-
163
- def self.residual_violation(target)
164
- attached = target.children&.to_a&.map do |child|
165
- { status: child.status, finished: child.finished?, transient: child.transient? }
166
44
  end
167
- RuntimeError.new("Completion observation violation: unfinished task without a live fiber or required work; " \
168
- "status=#{target.status}; attached_children=#{attached.inspect}")
45
+ pending
169
46
  end
170
47
 
171
- # A join retains its caller's first interruption until the target has
172
- # actually finished, then raises it. An interruptible join raises it at
173
- # once and leaves the target running on its own. A target's or child's
174
- # own failure is never raised: the task that failed reports it.
48
+ # A join retains its caller's first interruption until every task it
49
+ # joins has settled, then raises it. An interruptible join raises it
50
+ # at once and leaves the tasks running on their own. A task's own
51
+ # failure is never raised: the task that failed reports it.
175
52
  def self.call(task, interruptible: false)
176
53
  interruption = nil
177
- pending = [[task, false, {}.compare_by_identity]]
178
54
  begin
179
55
  yield if block_given?
180
56
  rescue Exception => e # rubocop:disable Lint/RescueException -- finish the join before propagating caller interruption
@@ -182,61 +58,17 @@ module ConnectRPC
182
58
 
183
59
  interruption = e
184
60
  end
185
- while (entry = pending.last)
186
- target, known, retained = entry
187
- raise ArgumentError, "Cannot join the current task" if target.current?
61
+ retained = {}.compare_by_identity
62
+ until (pending = unsettled(task, retained)).empty?
63
+ raise ArgumentError, "Cannot join the current task" if pending.any?(&:current?)
188
64
 
65
+ # A task that has not run yet is waited on: another fiber may
66
+ # start it.
67
+ waiting = pending.first
189
68
  begin
190
- target.wait unless known
191
- entry[1] = true
69
+ waiting.wait
192
70
  rescue Exception => e # rubocop:disable Lint/RescueException -- repeated interruption cannot abandon retirement
193
- if target.failed? && target.result.equal?(e)
194
- entry[1] = true
195
- else
196
- raise if interruptible
197
-
198
- interruption ||= e
199
- end
200
- next
201
- end
202
-
203
- work = scan(target, retained)
204
- state = observation(target)
205
- state.consumed if state && target.finished? && !state.terminal?
206
- raise state.violation if state&.violation
207
-
208
- unless work.empty?
209
- pending.concat(work.map { |child| [child, false, {}.compare_by_identity] })
210
- next
211
- end
212
- if target.finished? && (!state || state.terminal?)
213
- state&.release
214
- pending.pop
215
- next
216
- end
217
-
218
- unless state
219
- raise residual_violation(target) unless target.fiber&.alive?
220
-
221
- state = Observation.new(target)
222
- target.instance_variable_set(:@connectrpc_async_completion, state)
223
- target.extend(Consume)
224
- # Installation, capture and the first rescan have no yielding gap.
225
- state.consumed
226
- next
227
- end
228
-
229
- generation = state.generation
230
- signal = state.promise
231
- next unless scan(target, retained).empty?
232
- raise state.violation if state.violation
233
- next if target.finished? && state.terminal?
234
- raise residual_violation(target) if !target.finished? && !state.fiber_alive?
235
- next unless generation == state.generation && signal.equal?(state.promise)
236
-
237
- begin
238
- signal.wait
239
- rescue Exception => e # rubocop:disable Lint/RescueException -- latch interruption owns no completion credit
71
+ next if waiting.failed? && waiting.result.equal?(e)
240
72
  raise if interruptible
241
73
 
242
74
  interruption ||= e
@@ -546,6 +546,60 @@ module ConnectRPC
546
546
  end
547
547
  end
548
548
 
549
+ # A client request body. A response that ends while the body is open
550
+ # stops it at the next frame boundary: DATA admission holds the frame
551
+ # guard while it rechecks the response's end, the stream and its credit,
552
+ # then debits and writes the frame, so no DATA follows the end and an
553
+ # abandoned frame debits no credit. Credit waits happen outside the guard
554
+ # and end with the response too. The output then reads the producer's end
555
+ # and its stream resets the stream (ResponseStream#finish_output).
556
+ class ClientOutput < Output
557
+ def write(chunk)
558
+ until chunk.empty?
559
+ stream = @stream or raise IOError, "HTTP/2 stream is closed!"
560
+ return if stream.response_ended?
561
+ next await_credit(stream) unless stream.available_frame_size.positive?
562
+
563
+ chunk = admit(stream, chunk) or break
564
+ end
565
+ end
566
+
567
+ # Whether the producer closed its side before the response ended.
568
+ def committed? = !@body || (@body.respond_to?(:write_closed?) && @body.write_closed?)
569
+
570
+ # Called by the stream's reader once the response ended, without
571
+ # yielding: retires the producer and wakes a credit wait.
572
+ def response_ended
573
+ @body.retire if @body.respond_to?(:retire)
574
+ @guard.synchronize { @window_updated.broadcast }
575
+ end
576
+
577
+ private
578
+
579
+ # Returns the unsent remainder, or nil once the chunk was sent or the
580
+ # response ended.
581
+ def admit(stream, chunk)
582
+ stream.connection.synchronize do
583
+ next if stream.response_ended?
584
+ raise IOError, "HTTP/2 stream is closed!" if stream.closed?
585
+
586
+ size = stream.available_frame_size
587
+ next chunk unless size.positive?
588
+
589
+ send_data(stream, chunk, size)
590
+ end
591
+ end
592
+
593
+ def await_credit(stream)
594
+ @guard.synchronize do
595
+ until stream.available_frame_size.positive? || stream.response_ended?
596
+ @window_updated.wait(@guard)
597
+ stream = @stream or raise IOError, "HTTP/2 stream is closed!"
598
+ end
599
+ end
600
+ end
601
+ end
602
+
549
603
  module Stream # rubocop:disable Metrics/ModuleLength
550
604
  attr_reader :grpc_initial_headers, :grpc_initial_end_stream, :grpc_trailers, :grpc_error, :grpc_reset,
551
605
  :declared_length
@@ -733,7 +787,7 @@ module ConnectRPC
733
787
  # Upstream otherwise starts an output task on the closed stream.
734
788
  return body.close if closed?
735
789
 
736
- @output = Output.new(self, body, trailer)
790
+ @output = output_class.new(self, body, trailer)
737
791
  @output.bound_progress(*@output_bound) if @output_bound
738
792
  @output.start do |task|
739
793
  connection.output_started(task)
@@ -743,6 +797,8 @@ module ConnectRPC
743
797
 
744
798
  private
745
799
 
800
+ def output_class = Output
801
+
746
802
  # Stream credit returns once the application has consumed or
747
803
  # discarded a quarter of the window, as grpc-go does (`inFlow.onRead`),
748
804
  # so a stream whose reader keeps up has at least three quarters of its
@@ -836,18 +892,32 @@ module ConnectRPC
836
892
  end
837
893
  end
838
894
 
895
+ # A response that ends with END_STREAM while the request body is open
896
+ # ends the request too, as in grpc-go's client: the reader latches the
897
+ # end, retires the producer and wakes the output, which stops at a frame
898
+ # boundary and writes RST_STREAM(NO_ERROR). A producer that closed its
899
+ # side first commits a clean END_STREAM instead.
839
900
  class ResponseStream < ::Async::HTTP::Protocol::HTTP2::Response::Stream
840
901
  include Stream
841
902
 
842
903
  attr_reader :output_task
843
904
 
905
+ def response_ended? = !!@response_ended
906
+
844
907
  # Output unwinding on a retiring connection must not attempt another
845
908
  # write or reset on its closed socket. A cancelled upload means the
846
909
  # call no longer needs the stream, which RFC 9113 section 8.7 signals
847
910
  # with CANCEL; upstream resets every output error with INTERNAL_ERROR.
911
+ # Once the response ended, the reset is NO_ERROR however the output
912
+ # ended, cancellation by cleanup included.
848
913
  def finish_output(error = nil)
849
914
  return if connection.retiring?
850
915
 
916
+ if @response_ended
917
+ @output = nil
918
+ reset_ended
919
+ return
920
+ end
851
921
  if error.is_a?(::Async::Cancel) && !closed?
852
922
  @output = nil
853
923
  send_reset_stream(::Protocol::HTTP2::Error::CANCEL)
@@ -856,10 +926,99 @@ module ConnectRPC
856
926
  super
857
927
  end
858
928
 
859
- def send_body(...)
929
+ # A body attached after the response ended starts retired, so its
930
+ # output ends at once with the reset.
931
+ def send_body(body, trailer = nil, &)
932
+ body.retire if @response_ended && body.respond_to?(:retire)
860
933
  super { |task| @output_task = task }
861
934
  end
862
935
 
936
+ # The one RST_STREAM(NO_ERROR) after the response ended, written by
937
+ # the output or by cleanup, whichever holds the frame guard first. It
938
+ # is skipped once the stream closed, as by a peer reset. Cancellation
939
+ # is deferred across the frame, its flush and the close. A failed
940
+ # write closes the stream locally, keeping the received response, and
941
+ # fails the connection.
942
+ def reset_ended
943
+ connection.synchronize do
944
+ ::Async::Task.current.defer_cancel do
945
+ next if closed? || connection.retiring?
946
+
947
+ frame = ::Protocol::HTTP2::ResetStreamFrame.new(id)
948
+ frame.pack(::Protocol::HTTP2::Error::NO_ERROR)
949
+ write_frame(frame)
950
+ close! unless closed?
951
+ end
952
+ end
953
+ rescue UnusableConnection
954
+ nil
955
+ rescue StandardError => e
956
+ close! unless closed?
957
+ resource = connection.resource
958
+ resource&.abort(e) unless resource&.peer_departed? || resource&.outlives_peer?(e)
959
+ end
960
+
961
+ # Ends an abandoned call's stream. After the response ended this is
962
+ # the NO_ERROR reset, unless the output already wrote it; both recheck
963
+ # inside the frame guard, so only one is written, and the close stops
964
+ # an output still attached. Otherwise CANCEL, also decided inside the
965
+ # guard: while cleanup waits for it the stream may close, as by a peer
966
+ # reset, or the response may end. A response that ended takes the
967
+ # NO_ERROR path after the guard is released, so a failed reset retires
968
+ # the connection from outside the guard, as every other abort does.
969
+ def reset_in_cleanup
970
+ return reset_ended if @response_ended
971
+ return close! if state == :idle
972
+ return if closed?
973
+
974
+ ended = connection.synchronize do
975
+ next false if closed?
976
+ next true if @response_ended
977
+
978
+ send_reset_stream(::Protocol::HTTP2::Error::CANCEL)
979
+ false
980
+ end
981
+ reset_ended if ended
982
+ end
983
+
984
+ # async-http resets a stream whose HEADERS fail validation, and
985
+ # protocol-http2 then records the frame's END_STREAM on the closed
986
+ # stream anyway. Restoring the closed state keeps the end unlatched
987
+ # and stops cleanup from resetting the stream a second time.
988
+ def receive_headers(frame)
989
+ request_open = state == :open
990
+ super
991
+ return @state = :closed unless connection.streams[id].equal?(self)
992
+
993
+ response_ended if request_open && state == :half_closed_remote
994
+ end
995
+
996
+ def receive_data(frame)
997
+ request_open = state == :open
998
+ super
999
+ response_ended if request_open && state == :half_closed_remote
1000
+ end
1001
+
1002
+ # protocol-http2 opens a stream once its request HEADERS are flushed.
1003
+ # A response that ended during that flush already moved the stream to
1004
+ # half_closed_remote, and the body attached next starts retired.
1005
+ def open!
1006
+ return super unless state == :half_closed_remote
1007
+
1008
+ @response_ended = true
1009
+ self
1010
+ end
1011
+
1012
+ # A response that ended was fully received, so a close with an error,
1013
+ # as by connection retirement, keeps its unread bytes for the caller.
1014
+ def closed(error)
1015
+ if @response_ended && (input = @input)
1016
+ @input = nil
1017
+ input.retire
1018
+ end
1019
+ super
1020
+ end
1021
+
863
1022
  # Any response HEADERS, including 1xx, show the server saw the request,
864
1023
  # so a later refusal no longer proves it was never processed.
865
1024
  def receive_initial_headers(headers, end_stream)
@@ -868,6 +1027,19 @@ module ConnectRPC
868
1027
  end
869
1028
 
870
1029
  def response_headers? = !!@response_headers
1030
+
1031
+ private
1032
+
1033
+ def output_class = ClientOutput
1034
+
1035
+ # Runs in the reader without yielding.
1036
+ def response_ended
1037
+ output = @output
1038
+ return if !output || output.committed?
1039
+
1040
+ @response_ended = true
1041
+ output.response_ended
1042
+ end
871
1043
  end
872
1044
 
873
1045
  class ClientConnection < ::Async::HTTP::Protocol::HTTP2::Client
@@ -1665,18 +1837,20 @@ module ConnectRPC
1665
1837
  # An ancestor's cascade can leave the registered frame writer with
1666
1838
  # only a deferred request. Logical coverage is not forced delivery.
1667
1839
  writers.each { |writer| escapes << Internal::Teardown.capture { force_deferred(writer) } }
1668
- # A join retains an interruption until its member has finished. A
1669
- # join's own failure, such as a completion violation, still
1840
+ # A join retains an interruption until its member has settled. A
1841
+ # join's own failure, such as joining the current task, still
1670
1842
  # escapes: retrying that member would never end.
1671
1843
  @retirement_members.keys.reverse_each do |task|
1672
1844
  Internal.join_complete(task)
1673
1845
  rescue StandardError
1674
1846
  raise
1675
- rescue Exception => e # rubocop:disable Lint/RescueException -- the member has finished; retirement continues
1847
+ rescue Exception => e # rubocop:disable Lint/RescueException -- the member has settled; retirement continues
1676
1848
  escapes << e
1677
1849
  end
1678
1850
  capture_retirement
1679
- break if @retirement_members.keys.all?(&:finished?)
1851
+ # A settled member can stay unfinished, with no signal, until
1852
+ # Async clears its fiber; finished? here would spin without yielding.
1853
+ break if @retirement_members.keys.all? { |task| CompletionJoin.settled?(task) }
1680
1854
  end
1681
1855
  # A drain's discard read is not a member, but the shutdown ends it
1682
1856
  # with EOF. The protocol stream and TLS socket below close raw too,
@@ -5,7 +5,7 @@ require_relative "teardown"
5
5
 
6
6
  module ConnectRPC
7
7
  module Async
8
- module Internal
8
+ module Internal # rubocop:disable Metrics/ModuleLength
9
9
  CLEANUP_SECONDS = 1.0 # Spans several 100 ms GVL time slices; see the README (#187).
10
10
  MAX_WAIT = 86_400
11
11
 
@@ -410,11 +410,17 @@ module ConnectRPC
410
410
  def self.close_consumed_http1(request)
411
411
  return if request.respond_to?(:stream) || !request.body.respond_to?(:body)
412
412
 
413
+ request.body.close if http1_input_complete?(request)
414
+ end
415
+
416
+ # Framing completion never relies on empty?, which also becomes true
417
+ # when an upload ends early.
418
+ def self.http1_input_complete?(request)
419
+ return !request.body || request.body.empty? unless request.body.respond_to?(:body)
420
+
413
421
  framed = request.body.body
414
- complete = framed.nil? ||
415
- (framed.is_a?(::Protocol::HTTP1::Body::Fixed) && framed.remaining.zero?) ||
416
- (framed.is_a?(::Protocol::HTTP1::Body::Chunked) && !framed.length.nil?)
417
- request.body&.close if complete
422
+ framed.nil? || (framed.is_a?(::Protocol::HTTP1::Body::Fixed) && framed.remaining.zero?) ||
423
+ (framed.is_a?(::Protocol::HTTP1::Body::Chunked) && !framed.length.nil?)
418
424
  end
419
425
  end
420
426
  private_constant :Internal
@@ -508,7 +508,7 @@ module ConnectRPC
508
508
  # consumed unary input still permits incremental server streams.
509
509
  # Connect retirement owns input hygiene after response delivery.
510
510
  if publication && !retirement && GRPCWeb.intent?(Internal.headers(request)) &&
511
- request.body && !request.body.empty?
511
+ !Internal.http1_input_complete?(request)
512
512
  begin
513
513
  publication.wait
514
514
  rescue Exception => e # rubocop:disable Lint/RescueException -- cancellation must close deferred ownership too
@@ -13,14 +13,17 @@ module ConnectRPC
13
13
  @changed = ::Async::Condition.new
14
14
  @fragment = nil
15
15
  @queued_bytes = @maximum_queued_bytes = 0
16
- @ended = @closed = false
16
+ @ended = @closed = @retired = false
17
17
  end
18
18
 
19
+ # Whether the producer closed its side, committing END_STREAM.
20
+ def write_closed? = @ended
21
+
19
22
  def write(bytes, timeout: nil)
20
23
  raise ArgumentError, "Output fragments must fit one frame" if bytes.bytesize > 16_384
21
24
 
22
25
  expires = Internal.now + timeout if timeout
23
- while @fragment && !@closed
26
+ while @fragment && !@closed && !@retired
24
27
  if expires
25
28
  waiter = ::Async::Task.current.async(finished: false) { @changed.wait }
26
29
  begin
@@ -34,6 +37,7 @@ module ConnectRPC
34
37
  end
35
38
  end
36
39
  raise(@error || IOError.new("Output is closed")) if @closed || @ended
40
+ raise IOError, "HTTP/2 response ended before the request" if @retired
37
41
 
38
42
  @fragment = bytes.dup.freeze
39
43
  @queued_bytes = bytes.bytesize
@@ -43,7 +47,7 @@ module ConnectRPC
43
47
  end
44
48
 
45
49
  def read
46
- @changed.wait until @fragment || @ended || @closed
50
+ @changed.wait until @fragment || @ended || @closed || @retired
47
51
  raise @error if @error
48
52
 
49
53
  fragment = @fragment
@@ -59,6 +63,17 @@ module ConnectRPC
59
63
  nil
60
64
  end
61
65
 
66
+ # The response ended while the producer's side was open. The queued
67
+ # fragment is dropped, the output reads the end, and later writes
68
+ # raise. Never yields: the stream's reader calls it.
69
+ def retire
70
+ @retired = true
71
+ @fragment = nil
72
+ @queued_bytes = 0
73
+ @changed.signal
74
+ nil
75
+ end
76
+
62
77
  def close(error = nil)
63
78
  return if @closed
64
79
 
@@ -264,8 +279,12 @@ module ConnectRPC
264
279
  nil
265
280
  end
266
281
 
282
+ # A response that ended while the request was open does not wait for
283
+ # the output's reset, which completes or fails within cleanup's
284
+ # allowance.
267
285
  def finish(timeout: nil)
268
- perform(timeout: timeout) { @response.stream.output_task&.wait }
286
+ stream = @response.stream
287
+ perform(timeout: timeout) { stream.output_task&.wait unless stream.response_ended? }
269
288
  nil
270
289
  end
271
290