lib/grenache/http.rb in grenache-ruby-http-0.2.3 vs lib/grenache/http.rb in grenache-ruby-http-0.2.4

- old
+ new

@@ -1,49 +1,39 @@ -require "puma/events" - module Grenache - class Http < Grenache::Base def listen(key, port, opts={}, &block) start_http_service(port,&block) announce(key, port, opts) do |res| puts "#{key} announced #{res}" end end - def start_http_service(port, &block) - app = -> (env) { - req = ServiceMessage.parse(env['rack.input'].read) - fingerprint = extract_fingerprint(env['puma.peercert']) - e, payload = block.call(req, fingerprint) - err = e.kind_of?(Exception) ? e.message : e - [200,[], [ServiceMessage.new(payload, err, req.rid).to_json]] + def start_http_service(port, &block) + EM.defer { + app = -> (env) { + req = ServiceMessage.parse(env['rack.input'].read) + fingerprint = extract_fingerprint(env['rack.peer_cert']) + e, payload = block.call(req, fingerprint) + err = e.kind_of?(Exception) ? e.message : e + [200,nil, ServiceMessage.new(payload, err, req.rid).to_json] + } + server = Thin::Server.new config.service_host, port, {signals: false}, app + if tls? + server.ssl = true + server.ssl_options = { + private_key_file: config.key, + cert_chain_file: config.cert_pem, + verify_peer: true + } + end + server.start } - - event = Puma::Events.new $stdout, $stderr - server = Puma::Server.new app, event - host = config.service_host - - if tls? - ctx = Puma::MiniSSL::Context.new - ctx.key = config.key - ctx.cert = config.cert_pem - ctx.ca = config.ca - ctx.verify_mode = config.verify_mode - - server.add_ssl_listener host, port, ctx - else - server.add_tcp_listener host, port - end - - puts "starting server on port #{port}" - server.run end - def request(key, payload, params = {}) + def request(key, payload, params={}) services = lookup(key) if services.size > 0 json = ServiceMessage.new(payload,key).to_json service = get_random_service services resp = http_client.request service, json, params @@ -56,18 +46,22 @@ return [e, nil] end private + def tls? + !! config.cert_pem + end + def extract_fingerprint cert return "" unless cert cert = OpenSSL::X509::Certificate.new cert OpenSSL::Digest::SHA1.new(cert.to_der).to_s end - def tls? - !! config.cert_pem + def http_client + @http_client ||= HttpClient.new(config) end def get_random_service services service = services.sample service.sub!("tcp://","https://") @@ -75,12 +69,8 @@ service.prepend("https://") unless service.start_with?("https://") else service.prepend("http://") unless service.start_with?("http://") end service - end - - def http_client - @http_client ||= HttpClient.new(config) end end end