Class: Mayu::Server::App

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/mayu/server/app.rb

Constant Summary collapse

DEV_ASSETS_TIMEOUT_SECONDS =
4
DEV_ASSETS_RETRY_AFTER_SECONDS =
2
PING_INTERVAL =

seconds

2
NANOID_RE =
/[\w-]{21}/
MIME_TYPES =
T.let(
  {
    eventstream: "application/vnd.mayu.eventstream",
    session: "application/vnd.mayu.session"
  },
  T::Hash[Symbol, String]
)

Instance Method Summary collapse

Constructor Details

#initialize(environment:) ⇒ App



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/mayu/server/app.rb', line 29

def initialize(environment:)
  @environment = environment
  @metrics = T.let(environment.metrics, AppMetrics)
  @barrier = T.let(Async::Barrier.new, Async::Barrier)
  @stop = T.let(Async::Variable.new, Async::Variable)
  @sessions = T.let({}, T::Hash[String, Session])

  @runtime_assets =
    T.let(FileServer.new(@environment.js_runtime_path), FileServer)
  @static_assets =
    T.let(FileServer.new(@environment.path(:assets)), FileServer)
end

Instance Method Details

#call(request) ⇒ Object



85
86
87
88
89
90
91
# File 'lib/mayu/server/app.rb', line 85

def call(request)
  # The following line generates very noisy logs,
  # but can be useful when debugging.
  # Console.logger.info(self, "#{request.method} #{request.path}")

  Errors.handle_exceptions { handle_request(request) }
end

#clear_expired_sessions!Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/mayu/server/app.rb', line 43

def clear_expired_sessions!
  old_size = @sessions.size

  @sessions.delete_if do |id, session|
    next unless session.expired?(20)

    Console.logger.warn(self, "Session #{session.id} timed out")
    session.stop!
    @metrics.session_timeout_count.increment
    true
  end

  unless @sessions.size == old_size
    Console.logger.warn(self, "Session count: #{@sessions.size}")
  end

  @metrics.session_count.set(@sessions.size)
end

#closeObject



70
71
72
# File 'lib/mayu/server/app.rb', line 70

def close
  @barrier.wait
end

#get_session(id, request, resume: false) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
# File 'lib/mayu/server/app.rb', line 105

def get_session(id, request, resume: false)
  session = load_session(id, resume ? request.read.to_s : "")
  cookie_value = get_token_cookie_value(request)

  if session.authorized?(cookie_value)
    session
  else
    raise Errors::UnauthorizedSessionCookie,
          "session with id #{id} had wrong value #{cookie_value.inspect}"
  end
end

#handle_request(request) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/mayu/server/app.rb', line 122

def handle_request(request)
  # FIXME: raise_if_shutting_down! should only prevent the following:
  # * starting new sessions
  # * updating sessions that have been transferred
  # * updating sessions that have been paused for transferring
  raise_if_shutting_down!

  case request.path.delete_prefix("/").split("/")
  in ["__mayu", "session", NANOID_RE => session_id, *rest]
    handle_session_post(request, session_id, rest)
  in ["index.js"]
    body = File.read(File.join(__dir__, "client", "dist", "live.js"))
    Protocol::HTTP::Response[
      200,
      { "content-type": "application/javascript" },
      [body]
    ]
  in ["robots.txt"]
    Protocol::HTTP::Response[
      200,
      { "content-type" => "text/plain; charset=utf-8" },
      File.read(File.join(@environment.root, "app", "robots.txt"))
    ]
  in ["favicon.ico"]
    # Idea: Maybe it would be possible to create
    # an asset from the favicon and redirect to the asset?
    Protocol::HTTP::Response[
      200,
      { "content-type" => "image/png" },
      Protocol::HTTP::Body::File.open(
        File.join(@environment.root, "app", "favicon.png")
      )
    ]
  in ["__mayu", "status"]
    Protocol::HTTP::Response[200, {}, "ok"]
  in ["__mayu", "runtime", *path]
    accept_encodings = request.headers["accept-encoding"].to_s.split(", ")

    filename = File.join(*path)

    if filename == "entries.json"
      return Protocol::HTTP::Response[403, {}, ["forbidden"]]
    end

    @runtime_assets.serve(filename, accept_encodings:)
  in ["__mayu", "static", filename]
    if @environment.config.server.generate_assets
      begin
        @environment.resources.wait_for_asset(
          filename,
          timeout: DEV_ASSETS_TIMEOUT_SECONDS
        )
      rescue Async::TimeoutError => e
        Console.logger.warn(
          self,
          "Asset #{filename} could not be generated in time"
        )
        return(
          Protocol::HTTP::Response[
            503,
            { "retry-after" => DEV_ASSETS_RETRY_AFTER_SECONDS },
            ["asset could not be generated in time"]
          ]
        )
      end
    end

    accept_encodings = request.headers["accept-encoding"].to_s.split(", ")

    @static_assets.serve(filename, accept_encodings:)
  in ["__mayu", *]
    raise Errors::FileNotFound,
          "Resource not found at: #{request.method} #{request.path}"
  in [*] if request.method == "GET"
    raise_if_shutting_down!

    handle_session_init(request)
  else
    Protocol::HTTP::Response[404, {}, ["not found"]]
  end
end

#handle_session_init(request) ⇒ Object



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/mayu/server/app.rb', line 292

def handle_session_init(request)
  Console.logger.info(self) { "Init session: #{request.path}" }

  validate_header!(
    request.headers,
    "sec-fetch-mode",
    "navigate"
  ) do |value|
    raise Errors::InvalidSecFetchHeader,
          "Expected sec-fetch-mode to equal navigate but got #{value.inspect}"
  end

  validate_header!(
    request.headers,
    "sec-fetch-dest",
    "document"
  ) do |value|
    raise Errors::InvalidSecFetchHeader,
          "Expected sec-fetch-dest to equal document but got #{value.inspect}"
  end

  session =
    Session.new(
      environment: @environment,
      path: request.path,
      headers: request.headers.to_h.freeze
    )
  body = Async::HTTP::Body::Writable.new

  headers = {
    "content-type" => "text/html; charset=utf-8",
    "cache" => "no-cache"
  }

  accept_encodings = request.headers["accept-encoding"].to_s.split(", ")

  writer =
    if accept_encodings.include?("br")
      headers["content-encoding"] = "br"
      Brotli::Writer.new(body)
    else
      body
    end

  session.initial_render(writer) => { stylesheets: }

  headers["link"] = [
    "</__mayu/runtime/#{@environment.init_js}##{session.id}>; rel=preload; as=script; crossorigin=same-origin; fetchpriority=high",
    *stylesheets.map { "<#{_1}>; rel=preload; as=style" }
  ].join(", ")

  headers["set-cookie"] = set_token_cookie_value(session)

  @sessions.store(session.id, session)

  @environment.metrics.session_init_count.increment()

  Protocol::HTTP::Response[200, headers, body]
end

#handle_session_post(request, session_id, path) ⇒ Object



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/mayu/server/app.rb', line 216

def handle_session_post(request, session_id, path)
  raise Errors::InvalidMethod unless request.method == "POST"

  if ["resume"] === path
    body = Async::HTTP::Body::Writable.new
    session = get_session(session_id, request, resume: true)
    run_event_stream(session, body:)

    return(
      Protocol::HTTP::Response[
        200,
        { "content-type": MIME_TYPES[:eventstream] },
        body
      ]
    )
  end

  session = get_session(session_id, request, resume: false)
  session.activity!

  case path
  in ["init"]
    body = Async::HTTP::Body::Writable.new
    run_event_stream(session, body:)
    Protocol::HTTP::Response[
      200,
      { "content-type": MIME_TYPES[:eventstream] },
      body
    ]
  in ["ping"]
    body = JSON.parse(request.read.to_s)
    pong = body["pong"].to_f
    ping = body["ping"]
    time = time_ping_value
    server_pong = time_ping_value - body["pong"].to_f
    headers = {
      "content-type": "application/json",
      "set-cookie": set_token_cookie_value(session)
    }
    session.log.push(
      :pong,
      pong: ping,
      server: server_pong,
      region: @environment.config.instance.region,
      instance: @environment.config.instance.alloc_id.split("-", 2).first
    )
    Protocol::HTTP::Response[200, headers, [JSON.generate(ping)]]
  in ["navigate"]
    @environment.metrics.session_navigate_count.increment()
    path = request.read.force_encoding("utf-8")
    session.handle_callback("navigate", { path: })
    headers = {
      "content-type": "text/plain",
      "set-cookie": set_token_cookie_value(session),
      "x-request-time": request.headers["x-request-time"]
    }
    Protocol::HTTP::Response[200, headers, ["ok"]]
  in ["callback", String => callback_id]
    session.handle_callback(
      callback_id,
      JSON.parse(request.read, symbolize_names: true)
    )
    headers = {
      "content-type": "text/plain",
      "set-cookie": set_token_cookie_value(session),
      "x-request-time": request.headers["x-request-time"]
    }
    Protocol::HTTP::Response[200, headers, ["ok"]]
  end
end

#raise_if_shutting_down!Object



205
206
207
# File 'lib/mayu/server/app.rb', line 205

def raise_if_shutting_down!
  raise Errors::ServerIsShuttingDown if @stop.resolved?
end

#rerenderObject



94
95
96
# File 'lib/mayu/server/app.rb', line 94

def rerender
  @sessions.values.each(&:rerender)
end

#run_event_stream(session, body:) ⇒ Object



357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/mayu/server/app.rb', line 357

def run_event_stream(session, body:)
  @barrier.async do |task|
    session.activity!

    stream = EventStream::Writable.new(body)

    Console.logger.info(self, "Streaming events to session #{session.id}")

    barrier = Async::Barrier.new
    stop_notification = Async::Notification.new

    task.async do
      @stop.wait
      stop_notification.signal
    end

    session_task =
      barrier.async do
        session
          .run do |message|
            case message
            in [event, payload]
              session.log.push(:"session.#{event}", payload)
            end
          end
          .wait
      ensure
        stop_notification.signal
      end

    ping_task =
      barrier.async do
        loop do
          sleep PING_INTERVAL
          session.log.push(:ping, time_ping_value)
        end
      end

    message_task =
      barrier.async do |subtask|
        loop { stream.write(session.log.pop.to_a) }
      ensure
        barrier.stop
      end

    stop_notification.wait

    barrier.stop
    perform_transfer(session, stream)
    task.stop
  end
end

#stopObject



63
64
65
66
67
# File 'lib/mayu/server/app.rb', line 63

def stop
  @stop.resolve(true)
  @barrier.wait
  Console.logger.info(self, "Stopped sessions")
end

#time_ping_valueObject



75
76
77
78
# File 'lib/mayu/server/app.rb', line 75

def time_ping_value
  Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond).to_i &
    0x0fffffff
end