Module: LogStruct::Integrations::Puma::RackHandlerPatch

Extended by:
T::Sig
Defined in:
lib/log_struct/integrations/puma.rb

Overview

Hook Rack::Handler::Puma.run to emit structured started/shutdown

Instance Method Summary collapse

Instance Method Details

#run(app, *args, &block) ⇒ T.untyped

Parameters:

  • app (T.untyped)
  • args (T.untyped)
  • block (T.proc.returns(T.untyped), nil)

Returns:

  • (T.untyped)


418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/log_struct/integrations/puma.rb', line 418

def run(app, *args, &block)
  rest = args
  options = T.let({}, T::Hash[T.untyped, T.untyped])
  rest.each do |value|
    next unless value.is_a?(Hash)
    options.merge!(value)
  end

  begin
    si = T.cast(::LogStruct::Integrations::Puma::STATE[:start_info], T::Hash[Symbol, T.untyped])
    si[:mode] ||= "single"
    si[:environment] ||= ((defined?(::Rails) && ::Rails.respond_to?(:env)) ? ::Rails.env : nil)
    si[:pid] ||= Process.pid
    si[:listening] ||= []
    port = T.let(nil, T.untyped)
    host = T.let(nil, T.untyped)
    if options.respond_to?(:[])
      port = options[:Port] || options["Port"] || options[:port] || options["port"]
      host = options[:Host] || options["Host"] || options[:host] || options["host"]
    end
    if port
      list = T.cast(si[:listening], T::Array[T.untyped])
      list.clear
      h = (host && host != "0.0.0.0") ? host : "127.0.0.1"
      list << "tcp://#{h}:#{port}"
    end
    state = ::LogStruct::Integrations::Puma::STATE
    state[:handler_pending_started] = true unless state[:started_emitted]
  rescue => e
    ::LogStruct::Integrations::Puma.handle_integration_error(e)
  end

  begin
    Kernel.at_exit do
      unless ::LogStruct::Integrations::Puma::STATE[:shutdown_emitted]
        ::LogStruct::Integrations::Puma.emit_shutdown!("Exiting")
        ::LogStruct::Integrations::Puma::STATE[:shutdown_emitted] = true
      end
    rescue => e
      ::LogStruct::Integrations::Puma.handle_integration_error(e)
    end
  rescue => e
    ::LogStruct::Integrations::Puma.handle_integration_error(e)
  end

  begin
    result = super(app, **options, &block)
  ensure
    state = ::LogStruct::Integrations::Puma::STATE
    if state[:handler_pending_started] && !state[:started_emitted]
      begin
        ::LogStruct::Integrations::Puma.emit_started!
        state[:started_emitted] = true
      rescue => e
        ::LogStruct::Integrations::Puma.handle_integration_error(e)
      ensure
        state[:handler_pending_started] = false
      end
    end
  end

  result
end