1 # -*- encoding: binary -*-
2 # internal implementation details here, do not rely on this in your code
5 module MogileFS::SocketCommon
6 attr_reader :mogilefs_addr
8 def post_init(host, port)
9 @mogilefs_addr = "#{host}:#{port}"
10 Socket.const_defined?(:TCP_NODELAY) and
11 setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
15 def unreadable_socket!
16 raise MogileFS::UnreadableSocketError,
17 "#@mogilefs_addr never became readable"
20 def request_truncated!(written, expect, timeout)
21 raise MogileFS::RequestTruncatedError,
22 "request truncated (sent #{written} expected #{expect}) after #{timeout}s"
25 SEP_RE = /\A(.*?#{Regexp.escape("\n")})/
26 def timed_gets(timeout = 5)
27 unless defined?(@rbuf) && @rbuf
28 @rbuf = timed_read(1024, "", timeout) or return # EOF
31 @rbuf.sub!(SEP_RE, "") and return $1
33 if timed_read(1024, tmp, timeout)
36 # EOF, return the last buffered bit even without SEP_RE matching
37 # (not ideal for MogileFS, this is an error)
38 return @rbuf.empty? ? nil : @rbuf.slice!(0, @rbuf.size)
43 def read(size, buf = "", timeout = 5)
44 timed_read(size, buf, timeout) or return # nil/EOF
46 while size > buf.bytesize
48 timed_read(size - buf.bytesize, tmp, timeout) or return buf # truncated
55 def readpartial(size, buf = "", timeout = 5)
56 timed_read(size, buf, timeout) or raise EOFError, "end of file reached"