mogilefs-client.git  about / heads / tags
MogileFS client library for Ruby
blob 404acd0f7a885d7cf3b15a1e0ad3b94f32c37200 1617 bytes (raw)
$ git show checksums:lib/mogilefs/socket_common.rb	# shows this blob on the CLI

 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
 
# -*- encoding: binary -*-
# internal implementation details here, do not rely on this in your code
require "socket"

module MogileFS::SocketCommon
  attr_reader :mogilefs_addr

  def post_init(host, port)
    @mogilefs_addr = "#{host}:#{port}"
    Socket.const_defined?(:TCP_NODELAY) and
      setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
    self
  end

  def unreadable_socket!
    raise MogileFS::UnreadableSocketError,
          "#@mogilefs_addr never became readable"
  end

  def request_truncated!(written, expect, timeout)
    raise MogileFS::RequestTruncatedError,
     "request truncated (sent #{written} expected #{expect}) after #{timeout}s"
  end

  SEP_RE = /\A(.*?#{Regexp.escape("\n")})/
  def timed_gets(timeout = 5)
    unless defined?(@rbuf) && @rbuf
      @rbuf = timed_read(1024, "", timeout) or return # EOF
    end
    begin
      @rbuf.sub!(SEP_RE, "") and return $1
      tmp ||= ""
      if timed_read(1024, tmp, timeout)
        @rbuf << tmp
      else
        # EOF, return the last buffered bit even without SEP_RE matching
        # (not ideal for MogileFS, this is an error)
        return @rbuf.empty? ? nil : @rbuf.slice!(0, @rbuf.size)
      end
    end while true
  end

  def read(size, buf = "", timeout = 5)
    timed_read(size, buf, timeout) or return # nil/EOF

    while (size -= buf.bytesize) > 0
      tmp ||= ""
      timed_read(size, tmp, timeout) or return buf # truncated
      buf << tmp
    end

    buf # full read
  end

  def readpartial(size, buf = "", timeout = 5)
    timed_read(size, buf, timeout) or raise EOFError, "end of file reached"
  end
end

git clone https://yhbt.net/mogilefs-client.git