1 # -*- encoding: binary -*-
2 # internal implementation details here, do not rely on them in your code
4 # This class is needed because Net::HTTP streaming is still inefficient
5 # for reading huge response bodies over fast LANs.
6 class MogileFS::HTTPReader < MogileFS::Socket
7 attr_accessor :content_length, :uri
9 # backwards compat, if anybody cares
10 alias mogilefs_size content_length # :nodoc:
12 # this may OOM your system on large files
15 read(@content_length, buf)
16 return buf if buf.size == @content_length
18 raise MogileFS::SizeMismatchError,
19 "read=#{buf.size} bytes, expected=#@content_length from #@uri", []
22 def self.first(paths, timeout, count = nil, offset = nil)
26 range_end = count ? offset + count - 1 : ""
27 range = "Range: bytes=#{offset}-#{range_end}\r\n"
32 sock = try(path, timeout, range) and return sock
35 errors << "#{path} - #{e.message} (#{e.class})"
38 raise MogileFS::Error,
39 "all paths failed with GET: #{errors.join(', ')}", []
42 # given a path, this returns a readable socket with ready data from the
43 # body of the response.
44 def self.try(path, timeout, range) # :nodoc:
46 sock = tcp(uri.host, uri.port, timeout)
47 buf = "GET #{uri.request_uri} HTTP/1.0\r\n#{range}\r\n" # no chunking
48 sock.timed_write(buf, timeout)
50 sock.timed_peek(2048, buf, timeout) or
51 raise MogileFS::InvalidResponseError, "EOF while reading header", []
53 head, _ = buf.split(/\r\n\r\n/, 2)
55 # we're dealing with a seriously slow/stupid HTTP server if we can't
56 # get the header in a single recv(2) syscall.
57 if ((range && head =~ %r{\AHTTP/\d+\.\d+\s+206\s*}) ||
58 (!range && head =~ %r{\AHTTP/\d+\.\d+\s+200\s*})) &&
59 head =~ %r{^Content-Length:\s*(\d+)}i
60 sock.content_length = $1.to_i
62 sock.timed_read(head.bytesize + 4, buf, 0)
65 msg = range ? "Expected 206 w/#{range.strip}: " : "header="
67 raise MogileFS::InvalidResponseError, msg, []