Class: Pytty::Daemon::Api::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/pytty/daemon/api/router.rb

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/pytty/daemon/api/router.rb', line 8

def call(env)
  req = Rack::Request.new(env)

  params = Mustermann.new('/:component(/?:id)?').params(req.path_info)
  body = begin
    JSON.parse(req.body.read)
  rescue
  end

  resp = case params["component"]
  when "stdout"
    process_yield = Pytty::Daemon.yields[params["id"]]
    return [404, {'content-type' => 'text/html; charset=utf-8'}, ["does not exist"]] unless process_yield

    body = Async::HTTP::Body::Writable.new

    begin
      our_stdout = process_yield.stdout.dup
      while c = our_stdout.read
        body.write c
      end
    rescue Exception => ex
      p ex
    ensure
      puts "closing body"
      body.close
    end

    [200, {'content-type' => 'text/html; charset=utf-8'}, body]
  when "attach"
    process_yield = Pytty::Daemon.yields[params["id"]]
    body = Async::HTTP::Body::Writable.new

    Async::Task.current.async do |task|
      notification = process_yield.add_stdout body
      p ["blocking", notification]
      notification.wait
      p "got notification"
    rescue Exception => ex
      p ex
    ensure
      puts "closing body"
      body.close
    end

    [200, {'content-type' => 'text/html; charset=utf-8'}, body]
  when "ps","yield"
    status, output = Pytty::Daemon::Components::Handler.handle component: params["component"], params: body
    [status, {"Content-Type" => "application/json"}, [output.to_json]]
  when "spawn","rm","signal","stdin"
    status, output = Pytty::Daemon::Components::YieldHandler.handle component: params["component"], id: params["id"], params: body
    [status, {"Content-Type" => "application/json"}, [output.to_json]]
  when "ws"
    if env["HTTP_UPGRADE"] == "websocket"
      ws = WebSockets.new env
      ws.handle
    end

    [200, {"Content-Type" => "text/html"}, ["ws"]]
  else
    [404, {"Content-Type" => "text/html"}, ["unknown: #{req.path_info}"]]
  end

  resp
end