# encoding: utf-8 module HTTPkit class Server def self.start(config) Connection::EventMachine.start_server(config, self) end include Support::HandlerManager::Setup include Connection::Status attr_reader :config def initialize(config, connection) @sequence = 0 @config = config (@config[:handlers] ||= []).push(MandatoryHandler.new, BodyHandler.new) setup_connection(connection) setup_handlers end def serve(request) served = Promise.new served.then { |response| respond(request, response) } serve!(request, served).resume end def respond(request, response) fiber = Fiber.new do request, response = @handlers.invoke(:respond, request, response) @connection.serialize(response) finish(request) end fiber.resume end def finish(request) @handlers.invoke(:finish, request) end private def setup_connection(connection) @connection = connection @connection.on_message = method(:serve) end def serve!(request, served) Fiber.new do request.sequence(self, @sequence += 1) request, _ = @handlers.invoke(:serve, request, served) end end end end