Class: Startback::Event::Engine

Inherits:
Object
  • Object
show all
Defined in:
lib/startback/event/engine.rb

Overview

This class runs an infinite loop using ServerEngine. It is intended to be used to run jobs that listen to a Startback Bus instance without having the main process terminating immediately.

The Engine automatically runs a Webrick small webapp with a /healthcheck webservice. The class can be extended and method on_health_check overriden to run specific checks.

This class goes hand in hand with the startback:engine docker image.

Example:

# Dockerfile
FROM enspirit/startback:engine-0.11

# engine.rb
require 'startback/event/engine'
Startback::Event::Engine.run

Constant Summary collapse

DEFAULT_OPTIONS =
{
  daemonize: false,
  worker_type: 'process',
  workers: 1
}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeEngine

Returns a new instance of Engine.



37
38
39
# File 'lib/startback/event/engine.rb', line 37

def initialize
  require 'serverengine'
end

Class Method Details

.build_health_check(engine) ⇒ Object



59
60
61
62
63
64
65
66
67
68
# File 'lib/startback/event/engine.rb', line 59

def build_health_check(engine)
  Rack::Builder.new do
    map '/health-check' do
      health = Startback::Web::HealthCheck.new {
        engine.on_health_check
      }
      run(health)
    end
  end
end

.build_worker(health) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/startback/event/engine.rb', line 70

def build_worker(health)
  Module.new do
    include Support::Env

    def initialize
      @stop_flag = ServerEngine::BlockingFlag.new
    end

    define_method(:health) do
      health
    end

    def run
      until @stop_flag.set?
        Rack::Handler::WEBrick.run(health, {
          :Port => env('STARTBACK_ENGINE_PORT', '3000').to_i,
          :Host => env('STARTBACK_ENGINE_LISTEN', '0.0.0.0')
        })
      end
    end

    def stop
      @stop_flag.set!
      Rack::Handler::WEBrick.shutdown
    end
  end
end

.run(*args, &bl) ⇒ Object



55
56
57
# File 'lib/startback/event/engine.rb', line 55

def run(*args, &bl)
  new.run(*args, &bl)
end

Instance Method Details

#on_health_checkObject



41
42
43
# File 'lib/startback/event/engine.rb', line 41

def on_health_check
  "Ok"
end

#run(options = {}) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/startback/event/engine.rb', line 45

def run(options = {})
  options = DEFAULT_OPTIONS.merge(options)
  health = Engine.build_health_check(self)
  worker = Engine.build_worker(health)
  se = ServerEngine.create(nil, worker, options)
  se.run
  se
end