<commit_before># frozen_string_literal: true

require "action_dispatch/middleware/exception_wrapper"
require "action_dispatch/routing/inspector"

require "action_view"

module ActionDispatch
  # This middleware is responsible for logging exceptions and
  # showing a debugging page in case the request is local.
  class DebugExceptions
    cattr_reader :interceptors, instance_accessor: false, default: []

    def self.register_interceptor(object = nil, &block)
      interceptor = object || block
      interceptors << interceptor
    end

    def initialize(app, routes_app = nil, response_format = :default, interceptors = self.class.interceptors)
      @app             = app
      @routes_app      = routes_app
      @response_format = response_format
      @interceptors    = interceptors
    end

    def call(env)
      request = ActionDispatch::Request.new env
      _, headers, body = response = @app.call(env)

      if headers["X-Cascade"] == "pass"
        body.close if body.respond_to?(:close)
        raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
      end

      response
    rescue Exception => exception
      backtrace_cleaner = request.get_header("action_dispatch.backtrace_cleaner")
      wrapper = ExceptionWrapper.new(backtrace_cleaner, exception)

      invoke_interceptors(request, exception, wrapper)
      raise exception unless request.show_exceptions?
      render_exception(request, exception, wrapper)
    end

    private
      def invoke_interceptors(request, exception, wrapper)
        @interceptors.each do |interceptor|
          interceptor.call(request, exception)
        rescue Exception
          log_error(request, wrapper)
        end
      end

      def render_exception(request, exception, wrapper)
        log_error(request, wrapper)

        if request.get_header("action_dispatch.show_detailed_exceptions")
          begin
            content_type = request.formats.first
          rescue ActionDispatch::Http::MimeNegotiation::InvalidType
            content_type = Mime[:text]
          end

          if api_request?(content_type)
            render_for_api_request(content_type, wrapper)
          else
            render_for_browser_request(request, wrapper)
          end
        else
          raise exception
        end
      end

      def render_for_browser_request(request, wrapper)
        template = create_template(request, wrapper)
        file = "rescues/#{wrapper.rescue_template}"

        if request.xhr?
          body = template.render(template: file, layout: false, formats: [:text])
          format = "text/plain"
        else
          body = template.render(template: file, layout: "rescues/layout")
          format = "text/html"
        end
        render(wrapper.status_code, body, format)
      end

      def render_for_api_request(content_type, wrapper)
        body = {
          status: wrapper.status_code,
          error:  Rack::Utils::HTTP_STATUS_CODES.fetch(
            wrapper.status_code,
            Rack::Utils::HTTP_STATUS_CODES[500]
          ),
          exception: wrapper.exception_inspect,
          traces: wrapper.traces
        }

        to_format = "to_#{content_type.to_sym}"

        if content_type && body.respond_to?(to_format)
          formatted_body = body.public_send(to_format)
          format = content_type
        else
          formatted_body = body.to_json
          format = Mime[:json]
        end

        render(wrapper.status_code, formatted_body, format)
      end

      def create_template(request, wrapper)
        DebugView.new(
          request: request,
          exception_wrapper: wrapper,
          exception: BasicObject.new,
          traces: wrapper.traces,
          show_source_idx: wrapper.source_to_show_id,
          trace_to_show: wrapper.trace_to_show,
          routes_inspector: routes_inspector(wrapper),
          source_extracts: wrapper.source_extracts,
          error_highlight_available: wrapper.error_highlight_available?
        )<commit_msg>remove sentinel object<commit_after># frozen_string_literal: true

require "action_dispatch/middleware/exception_wrapper"
require "action_dispatch/routing/inspector"

require "action_view"

module ActionDispatch
  # This middleware is responsible for logging exceptions and
  # showing a debugging page in case the request is local.
  class DebugExceptions
    cattr_reader :interceptors, instance_accessor: false, default: []

    def self.register_interceptor(object = nil, &block)
      interceptor = object || block
      interceptors << interceptor
    end

    def initialize(app, routes_app = nil, response_format = :default, interceptors = self.class.interceptors)
      @app             = app
      @routes_app      = routes_app
      @response_format = response_format
      @interceptors    = interceptors
    end

    def call(env)
      request = ActionDispatch::Request.new env
      _, headers, body = response = @app.call(env)

      if headers["X-Cascade"] == "pass"
        body.close if body.respond_to?(:close)
        raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
      end

      response
    rescue Exception => exception
      backtrace_cleaner = request.get_header("action_dispatch.backtrace_cleaner")
      wrapper = ExceptionWrapper.new(backtrace_cleaner, exception)

      invoke_interceptors(request, exception, wrapper)
      raise exception unless request.show_exceptions?
      render_exception(request, exception, wrapper)
    end

    private
      def invoke_interceptors(request, exception, wrapper)
        @interceptors.each do |interceptor|
          interceptor.call(request, exception)
        rescue Exception
          log_error(request, wrapper)
        end
      end

      def render_exception(request, exception, wrapper)
        log_error(request, wrapper)

        if request.get_header("action_dispatch.show_detailed_exceptions")
          begin
            content_type = request.formats.first
          rescue ActionDispatch::Http::MimeNegotiation::InvalidType
            content_type = Mime[:text]
          end

          if api_request?(content_type)
            render_for_api_request(content_type, wrapper)
          else
            render_for_browser_request(request, wrapper)
          end
        else
          raise exception
        end
      end

      def render_for_browser_request(request, wrapper)
        template = create_template(request, wrapper)
        file = "rescues/#{wrapper.rescue_template}"

        if request.xhr?
          body = template.render(template: file, layout: false, formats: [:text])
          format = "text/plain"
        else
          body = template.render(template: file, layout: "rescues/layout")
          format = "text/html"
        end
        render(wrapper.status_code, body, format)
      end

      def render_for_api_request(content_type, wrapper)
        body = {
          status: wrapper.status_code,
          error:  Rack::Utils::HTTP_STATUS_CODES.fetch(
            wrapper.status_code,
            Rack::Utils::HTTP_STATUS_CODES[500]
          ),
          exception: wrapper.exception_inspect,
          traces: wrapper.traces
        }

        to_format = "to_#{content_type.to_sym}"

        if content_type && body.respond_to?(to_format)
          formatted_body = body.public_send(to_format)
          format = content_type
        else
          formatted_body = body.to_json
          format = Mime[:json]
        end

        render(wrapper.status_code, formatted_body, format)
      end

      def create_template(request, wrapper)
        DebugView.new(
          request: request,
          exception_wrapper: wrapper,
          # Everything should use the wrapper, but we need to pass
          # `exception` for legacy code.
          exception: wrapper.exception,
          traces: wrapper.traces,
          show_source_idx: wrapper.source_to_show_id,
          trace_to_show: wrapper.trace_to_show,
          routes_inspector: routes_inspector(wrapper),
          source_extracts: wrapper.source_extracts,
          error_highlight_available: wrapper.error_highlight_available?
        )
{'fraction_non_alphanumeric': 0.07920552258689596, 'fraction_numerical': 0.0007266561705219813, 'mean_word_length': 2.574891774891775, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, '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': '2651303', 'n_tokens_mistral': 2258, 'n_tokens_neox': 2217, 'n_words': 492}