Module: Thrift::EventMachineConnection

Includes:
EM::Deferrable
Defined in:
lib/thrift_client/event_machine.rb

Constant Summary collapse

GARBAGE_BUFFER_SIZE =

4kB

4096

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.connect(host = 'localhost', port = 9090, timeout = 5, &block) ⇒ Object



52
53
54
55
56
# File 'lib/thrift_client/event_machine.rb', line 52

def self.connect(host='localhost', port=9090, timeout=5, &block)
  EM.connect(host, port, self, host, port) do |conn|
    conn.pending_connect_timeout = timeout
  end
end

Instance Method Details

#blocking_read(size) ⇒ Object

Raises:

  • (IOError)


81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/thrift_client/event_machine.rb', line 81

def blocking_read(size)
  raise IOError, "lost connection to #{@host}:#{@port}: #{@disconnected}" if @disconnected
  if can_read?(size)
    yank(size)
  else
    raise ArgumentError, "Unexpected state" if @size or @callback

    fiber = Fiber.current
    @size = size
    @callback = proc { |data|
      fiber.resume(data)
    }
    Fiber.yield
  end
end

#can_read?(size) ⇒ Boolean

Returns:

  • (Boolean)


127
128
129
# File 'lib/thrift_client/event_machine.rb', line 127

def can_read?(size)
  @buf.size >= @index + size
end

#closeObject



74
75
76
77
78
79
# File 'lib/thrift_client/event_machine.rb', line 74

def close
  trap do
    @disconnected = 'closed'
    close_connection(true)
  end
end

#connected?Boolean

Returns:

  • (Boolean)


110
111
112
# File 'lib/thrift_client/event_machine.rb', line 110

def connected?
  !@disconnected
end

#connection_completedObject



114
115
116
117
# File 'lib/thrift_client/event_machine.rb', line 114

def connection_completed
  @disconnected = nil
  succeed
end

#initialize(host, port = 9090) ⇒ Object



67
68
69
70
71
72
# File 'lib/thrift_client/event_machine.rb', line 67

def initialize(host, port=9090)
  @host, @port = host, port
  @index = 0
  @disconnected = 'not connected'
  @buf = ''
end

#receive_data(data) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/thrift_client/event_machine.rb', line 97

def receive_data(data)
  trap do
    (@buf) << data

    if @callback and can_read?(@size)
      callback = @callback
      data = yank(@size)
      @callback = @size = nil
      callback.call(data)
    end
  end
end

#trapObject



58
59
60
61
62
63
64
65
# File 'lib/thrift_client/event_machine.rb', line 58

def trap
  begin
    yield
  rescue Exception => ex
    puts ex.message
    puts ex.backtrace.join("\n")
  end
end

#unbindObject



119
120
121
122
123
124
125
# File 'lib/thrift_client/event_machine.rb', line 119

def unbind
  if !@disconnected
    @disconnected = 'unbound'
  else
    fail
  end
end