Sha256: 2fa5185c82c402237b0b7bb89f35239187d7e99dee3e3efa9f4b7e9f7ecd7a96

Contents?: true

Size: 1.01 KB

Versions: 3

Compression:

Stored size: 1.01 KB

Contents

# frozen_string_literal: true

require "net/http"
require "time"
require "neetodeploy/autoscale/worker"

module Neetodeploy
  class Middleware
    attr_reader :worker

    def initialize(app)
      @app = app
      init_worker
    end

    def call(env)
      payload = URI.encode_www_form(
        app_name: ENV.to_h["NEETODEPLOY_APP_NAME"],
        process_type: "web",
        queue_time: queue_time(env)
      )
      worker.push(payload)
      @app.call(env)
    end

    private

    def started_at(env)
      return nil unless env["HTTP_X_REQUEST_START"].present?

      env["HTTP_X_REQUEST_START"].to_i
    end

    def network_time(env)
      env["puma.request_body_wait"].to_i
    end

    def queue_time(now = Time.now.to_f * 1000, env)
      return if started_at(env).nil?

      queue_time = (now - started_at(env)).round
      queue_time -= network_time(env)

      queue_time.positive? ? queue_time : 0
    end

    def init_worker
      return if @worker

      @worker = Neetodeploy::Worker.new
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
neetodeploy-autoscale-1.0.5 lib/neetodeploy/autoscale/middleware.rb
neetodeploy-autoscale-1.0.4 lib/neetodeploy/autoscale/middleware.rb
neetodeploy-autoscale-1.0.3 lib/neetodeploy/autoscale/middleware.rb