Module: Redis::Connection::SocketMixin

Included in:
SSLSocket, TCPSocket, UNIXSocket
Defined in:
lib/redis/connection/ruby.rb

Constant Summary collapse

CRLF =
"\r\n"

Instance Method Summary collapse

Instance Method Details

#_read_from_socket(nbytes) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/redis/connection/ruby.rb', line 51

def _read_from_socket(nbytes)
  loop do
    case chunk = read_nonblock(nbytes, exception: false)
    when :wait_readable
      unless wait_readable(@timeout)
        raise Redis::TimeoutError
      end
    when :wait_writable
      unless wait_writable(@timeout)
        raise Redis::TimeoutError
      end
    when nil
      raise Errno::ECONNRESET
    when String
      return chunk
    end
  end
end

#_write_to_socket(data) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/redis/connection/ruby.rb', line 70

def _write_to_socket(data)
  total_bytes_written = 0
  loop do
    case bytes_written = write_nonblock(data, exception: false)
    when :wait_readable
      unless wait_readable(@write_timeout)
        raise Redis::TimeoutError
      end
    when :wait_writable
      unless wait_writable(@write_timeout)
        raise Redis::TimeoutError
      end
    when nil
      raise Errno::ECONNRESET
    when Integer
      total_bytes_written += bytes_written
      if bytes_written < data.bytesize
        data.slice!(0, bytes_written)
      else
        return total_bytes_written
      end
    end
  end
end

#getsObject



43
44
45
46
47
48
49
# File 'lib/redis/connection/ruby.rb', line 43

def gets
  while (crlf = @buffer.index(CRLF)).nil?
    @buffer << _read_from_socket(16_384)
  end

  @buffer.slice!(0, crlf + CRLF.bytesize)
end

#initialize(*args) ⇒ Object



20
21
22
23
24
25
# File 'lib/redis/connection/ruby.rb', line 20

def initialize(*args)
  super(*args)

  @timeout = @write_timeout = nil
  @buffer = "".dup
end

#read(nbytes) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/redis/connection/ruby.rb', line 35

def read(nbytes)
  result = @buffer.slice!(0, nbytes)

  result << _read_from_socket(nbytes - result.bytesize) while result.bytesize < nbytes

  result
end

#timeout=(timeout) ⇒ Object



27
28
29
# File 'lib/redis/connection/ruby.rb', line 27

def timeout=(timeout)
  @timeout = (timeout if timeout && timeout > 0)
end

#write(data) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/redis/connection/ruby.rb', line 95

def write(data)
  return super(data) unless @write_timeout

  length = data.bytesize
  total_count = 0
  loop do
    count = _write_to_socket(data)

    total_count += count
    return total_count if total_count >= length

    data = data.byteslice(count..-1)
  end
end

#write_timeout=(timeout) ⇒ Object



31
32
33
# File 'lib/redis/connection/ruby.rb', line 31

def write_timeout=(timeout)
  @write_timeout = (timeout if timeout && timeout > 0)
end