-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathfinishable.rb
68 lines (54 loc) · 1.42 KB
/
finishable.rb
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
# frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2024, by Samuel Williams.
require "protocol/http/body/wrapper"
require "async/variable"
module Async
module HTTP
module Protocol
module HTTP1
# Keeps track of whether a body is being read, and if so, waits for it to be closed.
class Finishable < ::Protocol::HTTP::Body::Wrapper
def initialize(body)
super(body)
$stderr.puts "Finishable#initialize: #{body.inspect}"
@closed = Async::Variable.new
@error = nil
@reading = false
end
def reading?
@reading
end
def read
@reading = true
super.tap do |chunk|
$stderr.puts "Finishable#read: #{chunk.inspect}"
end
end
def close(error = nil)
super
$stderr.puts "Finishable#close: #{error.inspect}"
unless @closed.resolved?
@error = error
@closed.value = true
end
end
def wait(persistent = true)
if @reading
@closed.wait
elsif persistent
# If the connection can be reused, let's gracefully discard the body:
self.discard
else
# Else, we don't care about the body, so we can close it immediately:
self.close
end
end
def inspect
"#<#{self.class} closed=#{@closed} error=#{@error}> | #{super}"
end
end
end
end
end
end