<commit_before># frozen_string_literal: true

module Puma
  module App
    # Check out {#call}'s source code to see what actions this web application
    # can respond to.
    class Status
      OK_STATUS = '{ "status": "ok" }'.freeze

      def initialize(cli, token = nil)
        @cli = cli
        @auth_token = token
      end

      def call(env)
        unless authenticate(env)
          return rack_response(403, 'Invalid auth token', 'text/plain')
        end

        if env['PATH_INFO'] =~ /\/(gc-stats|stats|thread-backtraces)$/
          require 'json'
        end

        case env['PATH_INFO']
        when /\/stop$/
          @cli.stop
          rack_response(200, OK_STATUS)

        when /\/halt$/
          @cli.halt
          rack_response(200, OK_STATUS)

        when /\/restart$/
          @cli.restart
          rack_response(200, OK_STATUS)

        when /\/phased-restart$/
          if !@cli.phased_restart
            rack_response(404, '{ "error": "phased restart not available" }')
          else
            rack_response(200, OK_STATUS)
          end

        when /\/reload-worker-directory$/
          if !@cli.send(:reload_worker_directory)
            rack_response(404, '{ "error": "reload_worker_directory not available" }')
          else
            rack_response(200, OK_STATUS)
          end

        when /\/gc$/
          GC.start
          rack_response(200, OK_STATUS)

        when /\/gc-stats$/
          rack_response(200, GC.stat.to_json)

        when /\/stats$/
          rack_response(200, @cli.stats.to_json)

        when /\/thread-backtraces$/
          backtraces = []
          @cli.thread_status do |name, backtrace|
            backtraces << { name: name, backtrace: backtrace }
          end

          rack_response(200, backtraces.to_json)

        when /\/refork$/
          Process.kill "SIGURG", $$
          rack_response(200, OK_STATUS)

        else
          rack_response 404, "Unsupported action", 'text/plain'
        end
      end

      private

      def authenticate(env)
        return true unless @auth_token
        env['QUERY_STRING'].to_s.split(/&;/).include?("token=#{@auth_token}")
      end

      def rack_response(status, body, content_type='application/json')
        headers = {
          'Content-Type' => content_type,
          'Content-Length' => body.bytesize.to_s
        }

        [status, headers, [body]]
      end
    end
  end
end<commit_msg>Refactor status.rb - dry it up a bit (#2450)<commit_after># frozen_string_literal: true

module Puma
  module App
    # Check out {#call}'s source code to see what actions this web application
    # can respond to.
    class Status
      OK_STATUS = '{ "status": "ok" }'.freeze

      # @param launcher [::Puma::Launcher]
      # @param token [String, nil] the token used for authentication
      #
      def initialize(launcher, token = nil)
        @launcher = launcher
        @auth_token = token
      end

      # most commands call methods in `::Puma::Launcher` based on command in
      # `env['PATH_INFO']`
      def call(env)
        unless authenticate(env)
          return rack_response(403, 'Invalid auth token', 'text/plain')
        end

        if env['PATH_INFO'] =~ /\/(gc-stats|stats|thread-backtraces)$/
          require 'json'
        end

        # resp_type is processed by following case statement, return
        # is a number (status) or a string used as the body of a 200 response
        resp_type =
          case env['PATH_INFO'][/\/([^\/]+)$/, 1]
          when 'stop'
            @launcher.stop ; 200

          when 'halt'
            @launcher.halt ; 200

          when 'restart'
            @launcher.restart ; 200

          when 'phased-restart'
            @launcher.phased_restart ? 200 : 404

          when 'reload-worker-directory'
            @launcher.send(:reload_worker_directory) ? 200 : 404

          when 'gc'
            GC.start ; 200

          when 'gc-stats'
            GC.stat.to_json

          when 'stats'
            @launcher.stats.to_json

          when 'thread-backtraces'
            backtraces = []
            @launcher.thread_status do |name, backtrace|
              backtraces << { name: name, backtrace: backtrace }
            end
            backtraces.to_json

          else
            return rack_response(404, "Unsupported action", 'text/plain')
          end

        case resp_type
        when String
          rack_response 200, resp_type
        when 200
          rack_response 200, OK_STATUS
        when 404
          str = env['PATH_INFO'][/\/(\S+)/, 1].tr '-', '_'
          rack_response 404, "{ \"error\": \"#{str} not available\" }"
        end
      end

      private

      def authenticate(env)
        return true unless @auth_token
        env['QUERY_STRING'].to_s.split(/&;/).include?("token=#{@auth_token}")
      end

      def rack_response(status, body, content_type='application/json')
        headers = {
          'Content-Type' => content_type,
          'Content-Length' => body.bytesize.to_s
        }

        [status, headers, [body]]
      end
    end
  end
end
{'fraction_non_alphanumeric': 0.11271732760304747, 'fraction_numerical': 0.018753662824770465, 'mean_word_length': 1.7705627705627707, 'pattern_counts': {'":': 5, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '623297', 'n_tokens_mistral': 1621, 'n_tokens_neox': 1482, 'n_words': 378}