-
Notifications
You must be signed in to change notification settings - Fork 45
/
fiber_request.rb
50 lines (39 loc) · 1.2 KB
/
fiber_request.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
# Wraps Typhoeus request in a fiber, resumes the fiber in callbacks.
class RMT::FiberRequest < RMT::HttpRequest
attr_accessor :base_url, :download_path, :remote_file
def initialize(base_url, download_path:, request_fiber:, remote_file:, **options)
@base_url = base_url
@download_path = download_path
@request_fiber = request_fiber
@remote_file = remote_file
super(base_url, options)
on_headers { |response| @request_fiber.resume(response) }
on_body do |chunk|
next :abort if @download_path.closed?
@download_path.write(chunk)
end
on_complete do |response|
@request_fiber.resume(response) unless (response.return_code == :ok)
@request_fiber.resume(response) if @request_fiber.alive?
end
end
def receive_headers
Fiber.yield(self)
end
def receive_body
response = read_body
if (response.return_code && response.return_code != :ok)
raise RMT::Downloader::Exception.new("#{@remote_file} - return code #{response.return_code}")
end
@download_path.close
response
rescue StandardError => e
@download_path.unlink
raise e
end
protected
# helper method for specs
def read_body
Fiber.yield
end
end