Class: Hyperion::Kim

Inherits:
Object
  • Object
show all
Defined in:
lib/hyperion_test/kim.rb,
lib/hyperion_test/kim/matcher.rb,
lib/hyperion_test/kim/matchers.rb

Defined Under Namespace

Modules: Matchers Classes: Handler, Matcher, Request

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(port:) ⇒ Kim

Returns a new instance of Kim.



47
48
49
50
51
# File 'lib/hyperion_test/kim.rb', line 47

def initialize(port:)
  @port = port
  @handlers = []
  @lock = Mutex.new # controls access to this instance of Kim (via public methods and callbacks)
end

Class Method Details

.webrick_mutexObject



53
54
55
# File 'lib/hyperion_test/kim.rb', line 53

def self.webrick_mutex
  @webrick_mutex ||= Mutex.new # controls access to the Rack::Handler::WEBrick singleton
end

Instance Method Details

#add_handler(matcher_or_pred, &handler_proc) ⇒ Object

Add a handler. Returns a proc that removes the handler.



99
100
101
102
103
104
105
106
# File 'lib/hyperion_test/kim.rb', line 99

def add_handler(matcher_or_pred, &handler_proc)
  @lock.synchronize do
    handler = Handler.new(Matcher.wrap(matcher_or_pred), handler_proc)
    @handlers.unshift(handler)
    remover = proc { @lock.synchronize { @handlers.delete(handler) } }
    remover
  end
end

#clear_handlersObject



108
109
110
111
112
# File 'lib/hyperion_test/kim.rb', line 108

def clear_handlers
  @lock.synchronize do
    @handlers = []
  end
end

#startObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/hyperion_test/kim.rb', line 57

def start
  # Notes on synchronization:
  #
  # The only way to start a handler is with static method ::run
  # which touches singleton instance variables. webrick_mutex
  # ensures only one thread is in the singleton at a time.
  #
  # A threadsafe queue is used to notify the calling thread
  # that the server thread has started. The caller needs to
  # wait so it can obtain the webrick instance.

  @lock.synchronize do
    raise 'Cannot restart' if @stopped
    Kim.webrick_mutex.synchronize do
      q = Queue.new
      @thread = Thread.start do
        begin
          opts = {Port: @port, Logger: ::Logger.new('/dev/null'), AccessLog: []} # hide output
          Rack::Handler::WEBrick.run(method(:handle_request), opts) do |webrick|
            q.push(webrick)
          end
        ensure
          $stderr.puts "Hyperion fake server on port #{@port} exited unexpectedly!" unless @stopped
        end
      end
      @webrick = q.pop
    end
  end
end

#stopObject



87
88
89
90
91
92
93
94
95
96
# File 'lib/hyperion_test/kim.rb', line 87

def stop
  @lock.synchronize do
    return if @stopped
    @stopped = true
    @webrick.shutdown
    @thread.join
    @webrick = nil
    @thread = nil
  end
end