Module: Phlegethon::Exec

Extended by:
Exec
Included in:
Exec
Defined in:
lib/phlegethon/exec.rb

Constant Summary collapse

DEFAULTS =
{
  'rabbitmq' => {
    'exchange' => 'webhooks',
    'host' => 'localhost'
  },
  'server' => {
    'ip' => '0.0.0.0',
    'port' => 3002,
    'ssl' => false
  }
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#exchangeObject

Returns the value of attribute exchange.



26
27
28
# File 'lib/phlegethon/exec.rb', line 26

def exchange
  @exchange
end

Instance Method Details

#configObject



84
85
86
# File 'lib/phlegethon/exec.rb', line 84

def config
  @config ||= DEFAULTS.merge(YAML.load(File.read(config_path)))
end

#config_pathObject



88
89
90
91
92
93
94
95
96
97
# File 'lib/phlegethon/exec.rb', line 88

def config_path
  config_path_candidates.each do |f|
    if File.exist?(f)
      puts "Reading config from #{f}"
      return f
    end
  end
  warn 'config file not found'
  exit
end

#config_path_candidatesObject



99
100
101
102
# File 'lib/phlegethon/exec.rb', line 99

def config_path_candidates
  [ './phlegethon.yml',
    ENV['HOME'] + '/.phlegethon.yml' ]
end

#deep_encode(data, enc = 'UTF-8') ⇒ Object

TODO move to gem trickery



70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/phlegethon/exec.rb', line 70

def deep_encode(data, enc='UTF-8')
  case data
  when String
    data.encode(enc)
  when Array
    data.map { |e| deep_encode(e, enc) }
  when Hash
    data.inject({}) do |r, a|
      r.merge deep_encode(a[0], enc) => deep_encode(a[1], enc)
    end
  else data
  end
end

#handlerObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/phlegethon/exec.rb', line 36

def handler
  ->(env) {
    pp env
    req = Rack::Request.new(env)

    # perform some business logic on posted data
    message = deep_encode({
      'params'      => req.params,
      'method'      => req.request_method,
      'url'         => req.url,
      'user_agent'  => req.user_agent
    })
    case req.content_type
    when 'application/json'
      message['payload'] = JSON.parse(req.body.read)
    else
      message = deep_encode(env)
    end
    exchange.publish(JSON.unparse(message))
    # TODO make debug response configurable
    [200, {'Content-Type' => 'text/plain'}, message.to_yaml]
  }
end

#init_bunnyObject

TODO steal recoonect from simon or monitoring in vr_dev



61
62
63
64
65
66
67
# File 'lib/phlegethon/exec.rb', line 61

def init_bunny
  # TODO make bunny configurable
  bunny = Bunny.new read_timeout: 10, heartbeat: 10
  bunny.start
  bunny_channel = bunny.create_channel
  self.exchange = bunny_channel.fanout(config['rabbitmq']['exchange'])
end

#run(args) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/phlegethon/exec.rb', line 28

def run(args)
  init_bunny
  server = Thin::Server.new(config['server']['ip'],
                            config['server']['port'],
                            handler)
  server.start
end