Class: Grenache::Http

Inherits:
Base
  • Object
show all
Defined in:
lib/grenache/http.rb

Instance Method Summary collapse

Instance Method Details

#listen(key, port, opts = {}, &block) ⇒ Object



3
4
5
6
7
8
9
# File 'lib/grenache/http.rb', line 3

def listen(key, port,  opts={}, &block)
  start_http_service(port,&block)

  announce(key, port, opts) do |res|
    puts "#{key} announced #{res}"
  end
end

#request(key, payload) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/grenache/http.rb', line 22

def request(key, payload)
  services = lookup(key)
  if services.size > 0
    json = ServiceMessage.new(payload).to_json
    service = services.sample.sub("tcp://","http://")
    service.prepend("http://") unless service.start_with?("http://")
    resp = HTTParty.post(service,{body: json})
    msg = ServiceMessage.parse(resp.body)
    return [msg.err, msg.payload]
  else
    return ["NoPeerFound",nil]
  end
rescue Exception => e
  return [e, nil]
end

#start_http_service(port, &block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/grenache/http.rb', line 11

def start_http_service(port, &block)
  EM.defer {
    app = -> (env) {
      req = ServiceMessage.parse(env['rack.input'].read)
      err, payload = block.call(req)
      [200,nil, ServiceMessage.new(payload, err, req.rid).to_json]
    }
    server = Thin::Server.start('0.0.0.0', port, app, {signals: false})
  }
end