Module: Fraggle::Connection

Defined in:
lib/fraggle/connection.rb

Defined Under Namespace

Classes: DisconnectedError, ResponseError, SendError

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#addrObject (readonly)

Returns the value of attribute addr.



39
40
41
# File 'lib/fraggle/connection.rb', line 39

def addr
  @addr
end

Instance Method Details

#err?Boolean

Returns:

  • (Boolean)


110
111
112
# File 'lib/fraggle/connection.rb', line 110

def err?
  !!@err
end

#initialize(addr) ⇒ Object



41
42
43
# File 'lib/fraggle/connection.rb', line 41

def initialize(addr)
  @addr, @cb = addr, {}
end

#next_tick(&blk) ⇒ Object



118
119
120
# File 'lib/fraggle/connection.rb', line 118

def next_tick(&blk)
  EM.next_tick(&blk)
end

#receive_data(data) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/fraggle/connection.rb', line 45

def receive_data(data)
  (@buf ||= "") << data

  while @buf.length > 0
    if @len && @buf.length >= @len
      bytes = @buf.slice!(0, @len)
      @len = nil
      res = Response.decode(bytes)
      receive_response(res)
    elsif @buf.length >= 4
      bytes = @buf.slice!(0, 4)
      @len = bytes.unpack("N")[0]
    else
      break
    end
  end
end

#receive_response(res) ⇒ Object

The default receive_response



64
65
66
67
68
69
70
71
72
73
# File 'lib/fraggle/connection.rb', line 64

def receive_response(res)
  return if err?
  req, blk = @cb.delete(res.tag)
  return if ! blk
  if res.err_code
    blk.call(nil, ResponseError.new(res))
  else
    blk.call(res, nil)
  end
end

#send_request(req, blk) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/fraggle/connection.rb', line 75

def send_request(req, blk)
  if req.tag
    raise SendError, "Already sent #{req.inspect}"
  end

  if err?
    next_tick { blk.call(nil, DisconnectedError.new(self.addr)) }
    return req
  end

  req.tag = 0
  while @cb.has_key?(req.tag)
    req.tag += 1

    req.tag %= 2**31
  end

  # TODO: remove this!
  @cb[req.tag] = [req, blk]

  data = req.encode
  head = [data.length].pack("N")

  send_data("#{head}#{data}")

  req
end

#timer(n, &blk) ⇒ Object



114
115
116
# File 'lib/fraggle/connection.rb', line 114

def timer(n, &blk)
  EM.add_timer(n, &blk)
end

#unbindObject



103
104
105
106
107
108
# File 'lib/fraggle/connection.rb', line 103

def unbind
  @err = true
  @cb.values.each do |_, blk|
    blk.call(nil, DisconnectedError.new(self.addr))
  end
end