Class: Pf2::Serve

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

Constant Summary collapse

CONFIG =
{
  Host: ENV.fetch('PF2_SERVE_HOST', 'localhost'),
  Port: ENV.fetch('PF2_SERVE_PORT', '51502').to_i, # 1502 = 0xF2 (as in "Pf2")
  Logger: Logger.new(nil),
  AccessLog: [],
}

Class Method Summary collapse

Class Method Details

.at_exitObject



49
50
51
52
53
54
55
# File 'lib/pf2/serve.rb', line 49

def self.at_exit
  STDERR.puts ""
  STDERR.puts "[Pf2] Script execution complete (Pf2 server is still listening). Hit Ctrl-C to quit."

  # Allow the user to download the profile after the target program exits
  sleep
end

.startObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/pf2/serve.rb', line 20

def self.start

  # Ignore Bundler as in `bundle exec`.
  if File.basename($PROGRAM_NAME) == 'bundle' && ARGV.first == 'exec'
    return
  end

  server = WEBrick::HTTPServer.new(CONFIG)
  server.mount_proc('/profile') do |req, res|
    profile = Pf2.stop
    profile = JSON.parse(profile, symbolize_names: true, max_nesting: false)
    res.header['Content-Type'] = 'application/json'
    res.header['Access-Control-Allow-Origin'] = '*'
    res.body = JSON.generate(Pf2::Reporter::FirefoxProfiler.new((profile)).emit)
    Pf2.start
  end

  Pf2.start

  Thread.new do
    hostport = "#{server.config[:Host]}:#{server.config[:Port]}"
    # Print host:port to trigger VS Code's auto port-forwarding feature
    STDERR.puts "[Pf2] Listening on #{hostport}."
    STDERR.puts "[Pf2] Open https://profiler.firefox.com/from-url/#{URI.encode_www_form_component("http://#{hostport}/profile")} for visualization."
    STDERR.puts ""
    server.start
  end
end