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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# 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","stderr"
    process_yield = Pytty::Daemon.yields[params["id"]]
    return [404, {'content-type' => 'text/html; charset=utf-8'}, ["does not exist"]] unless process_yield

    stream_path = if params["component"] == "stdout"
      process_yield.stdout_path
    else
      process_yield.stderr_path
    end

    stream = Async::IO::Stream.new(
      File.open stream_path, "r"
    )

    body = Async::HTTP::Body::Writable.new
    begin
      while c = stream.read
        body.write c
      end
    rescue Exception => ex
      p "read", ex
    ensure
      stream.close if stream
      body.close
    end

    [200, {'content-type' => 'text/html; charset=utf-8'}, body]
  when "attach"
    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

    stderr_done = Async::Task.current.async do |task|
      notification = process_yield.add_stderr body
      notification.wait
    end

    stdout_done = Async::Task.current.async do |task|
      notification = process_yield.add_stdout body
      notification.wait
    end

    Async::Task.current.async do |task|
      stderr_done.wait
      p ["stderr done"]
      stdout_done.wait
      p ["stderr done"]
    ensure
      p ["closing attach:", req.object_id]
      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","port"
    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