Class: LambdaRunner::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/lambda_runner.rb

Overview

abstract for running the program

Instance Method Summary collapse

Constructor Details

#initialize(module_path, name) ⇒ Runner

Returns a new instance of Runner.



15
16
17
18
19
# File 'lib/lambda_runner.rb', line 15

def initialize(module_path, name)
  @module_path = module_path
  @name = name
  @port = 8897
end

Instance Method Details

#add_aws_sdkObject



29
30
31
32
33
# File 'lib/lambda_runner.rb', line 29

def add_aws_sdk
  STDOUT.puts("Copying aws-sdk into the lambda function's node_modules.")
  # cp -r File.expand_path(../../js/node_modules/aws-sdk, __FILE__) $(dirname @module_path)/node_modules
  FileUtils.cp_r File.expand_path('../../js/node_modules/aws-sdk', __FILE__), "#{File.dirname(@module_path)}/node_modules"
end

#install_depsObject



21
22
23
24
25
26
27
# File 'lib/lambda_runner.rb', line 21

def install_deps
  @npm_cwd = File.expand_path('../../js/', __FILE__)
  STDOUT.puts("trying to use npm install in #{@npm_cwd}")
  npm_install_pid = spawn('npm', 'install', chdir: @npm_cwd)
  Process.wait(npm_install_pid)
  fail 'failed to install the lambda startup' if ($CHILD_STATUS.exitstatus != 0)
end

#send(message) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/lambda_runner.rb', line 63

def send(message)
  id = RestClient.post(url, message, content_type: :json).to_str
  loop do
    wait(RestClient.get(url, params: { id: id })) && break
    sleep(0.1)
  end
end

#start(opts = { cover: true }) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/lambda_runner.rb', line 35

def start(opts = { cover: true })
  if opts[:timeout] == nil
    opts[:timeout] = '30000'
  end
  install_deps
  add_aws_sdk
  # start node in a way that emulates how it's run in production
  cmd = ['node']
  cmd = [File.join(@npm_cwd, 'node_modules/.bin/istanbul'), 'cover', '--root', File.dirname(@module_path), '--'] if opts[:cover]
  cmd += [File.join(@npm_cwd, 'startup.js'), '-p', @port.to_s, '-m', @module_path, '-h', @name, '-t', opts[:timeout]]
  @proc = ProcessHelper::ProcessHelper.new(print_lines: true)
  @proc.start(cmd, 'Server running at http')
end

#stopObject



71
72
73
# File 'lib/lambda_runner.rb', line 71

def stop
  RestClient.delete(url)
end

#urlObject



49
50
51
# File 'lib/lambda_runner.rb', line 49

def url
  "http://localhost:#{@port}/"
end

#wait(response) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/lambda_runner.rb', line 53

def wait(response)
  case response.code
  when 201 then false
  when 200 then true
  when 504 then fail 'timeout'
  when 502 then fail response
  else fail "unknown response #{response.code}"
  end
end