class Pincerna::Server

Main HTTP server to handle requests.

Constants

DELAY

Delay before responding to a request.

Public Class Methods

enqueue_request() click to toggle source

Enqueues a request.

# File lib/pincerna/server.rb, line 19
def self.enqueue_request
  @requests ||= Queue.new
  @requests << Time.now.to_f
  EM::Synchrony.sleep(DELAY)
end
perform_request?() click to toggle source

Enqueues a request.

@return [Boolean] `true` if the request was the last arrived and therefore must be performed, `false` otherwise.

# File lib/pincerna/server.rb, line 28
def self.perform_request?
  @requests.pop
  @requests.empty?
end

Public Instance Methods

handle_request(type, args) click to toggle source

Handles a valid request.

@param type [String] The type of request. @param args [Hash] The parameters of the request. @return [Array] A response complaint to Rack interface.

# File lib/pincerna/server.rb, line 38
def handle_request(type, args)
  # Enqueue the request. This will wait to avoid too many requests.
  Server.enqueue_request

  # Execute the request, if none were added.
  response = Server.perform_request? ? Pincerna::Base.execute!(type, (args["q"] || "").strip, args["format"], args["debug"]) : false

  if response then
    [200, {"Content-Type" => response.format_content_type}, response.output]
  else
    [response.nil? ? 404 : 429, {"Content-Type" => "text/plain"}, ""]
  end
end
handle_stop() click to toggle source

Schedule the server's stop. @return [Array] A response complaint to Rack interface.

# File lib/pincerna/server.rb, line 54
def handle_stop
  EM.add_timer(0.1) { stop_server }
  [200, {}, ""]
end
response(env) click to toggle source

Send a response to a request.

@param env [Goliath::Env] The environment of the request. @return [Array] A response complaint to Rack interface.

# File lib/pincerna/server.rb, line 63
def response(env)
  begin
    type = env["REQUEST_PATH"].gsub(/\//, "")

    case type
      when "quit" then handle_stop
      when "install" then handle_install
      when "uninstall" then handle_uninstall
      else handle_request(type, params)
    end
  rescue => e
    [500, {"X-Error" => e.class.to_s, "X-Error-Message" => e.message, "Content-Type" => "text/plain"}, e.backtrace.join("\n")]
  end
end

Private Instance Methods

stop_server() click to toggle source

Stops the server.

# File lib/pincerna/server.rb, line 80
def stop_server
  Pincerna::Cache.instance.destroy
  EM.stop
end