<commit_before>require 'pacto/server/settings'

module Pacto
  module Server
    class API < Goliath::API
      include Pacto::Server::Settings
      use ::Rack::ContentLength

      def initialize(_opts = {})
        @original_pwd = Dir.pwd
      end

      def on_headers(env, headers)
        env.logger.debug 'receiving headers: ' + headers.inspect
        env['client-headers'] = headers
      end

      def on_body(env, data)
        env.logger.debug 'received data: ' + data
        (env['async-body'] ||= '') << data
      end

      def response(env)
        log_request(env)
        req = prepare_pacto_request(env)
        resp = Pacto::Consumer::FaradayDriver.new.execute(req)
        process_pacto_response resp, env
      rescue => e
        backtrace = e.backtrace.join("\n")
        env.logger.warn "responding with error: #{e.message}, backtrace: #{backtrace}"
        [500, {}, e.message]
      end

      private

      def log_request(env)
        method = env['REQUEST_METHOD'].upcase
        env.logger.info "received: #{method} #{env['REQUEST_URI']} with headers #{env['client-headers']}"
      end

      def prepare_pacto_request(env)
        PactoRequest.new(
          body: env['async-body'],
          headers: filter_request_headers(env),
          method: :get,
          uri: determine_proxy_uri(env)
        )
      end

      def process_pacto_response(resp, _env)
        code = resp.status
        safe_response_headers = normalize_headers(resp.headers).reject { |k, _v| %w(connection content-encoding content-length transfer-encoding).include? k.downcase }
        body = proxy_rewrite(resp.body)
        [code, safe_response_headers, body]
      end

      def determine_proxy_uri(env)
        path = env[Goliath::Request::REQUEST_PATH]
        if env.config[:backend_host]
          uri = Addressable::URI.parse("#{env.config[:backend_host]}#{path}")
        else
          host = env['HTTP_HOST']
          # FIXME: These options are hacky, but cover the way I use in Pacto specs vs Polytrix
          host.gsub!(".dev:#{port}", '.com') if env.config[:strip_dev]<commit_msg>Fix server - was only using HTTP GET<commit_after>require 'pacto/server/settings'

module Pacto
  module Server
    class API < Goliath::API
      include Pacto::Server::Settings
      use ::Rack::ContentLength

      def initialize(_opts = {})
        @original_pwd = Dir.pwd
      end

      def on_headers(env, headers)
        env.logger.debug 'receiving headers: ' + headers.inspect
        env['client-headers'] = headers
      end

      def on_body(env, data)
        env.logger.debug 'received data: ' + data
        (env['async-body'] ||= '') << data
      end

      def response(env)
        log_request(env)
        req = prepare_pacto_request(env)
        resp = Pacto::Consumer::FaradayDriver.new.execute(req)
        process_pacto_response resp, env
      rescue => e
        backtrace = e.backtrace.join("\n")
        env.logger.warn "responding with error: #{e.message}, backtrace: #{backtrace}"
        [500, {}, e.message]
      end

      private

      def log_request(env)
        method = env['REQUEST_METHOD'].upcase
        env.logger.info "received: #{method} #{env['REQUEST_URI']} with headers #{env['client-headers']}"
      end

      def prepare_pacto_request(env)
        PactoRequest.new(
          body: env['async-body'],
          headers: filter_request_headers(env),
          method: env['REQUEST_METHOD'].downcase.to_sym,
          uri: determine_proxy_uri(env)
        )
      end

      def process_pacto_response(resp, _env)
        code = resp.status
        safe_response_headers = normalize_headers(resp.headers).reject { |k, _v| %w(connection content-encoding content-length transfer-encoding).include? k.downcase }
        body = proxy_rewrite(resp.body)
        [code, safe_response_headers, body]
      end

      def determine_proxy_uri(env)
        path = env[Goliath::Request::REQUEST_PATH]
        if env.config[:backend_host]
          uri = Addressable::URI.parse("#{env.config[:backend_host]}#{path}")
        else
          host = env['HTTP_HOST']
          # FIXME: These options are hacky, but cover the way I use in Pacto specs vs Polytrix
          host.gsub!(".dev:#{port}", '.com') if env.config[:strip_dev]
{'fraction_non_alphanumeric': 0.12085860942603827, 'fraction_numerical': 0.0013999066728884741, 'mean_word_length': 2.5400495458298926, 'pattern_counts': {'":': 0, '<': 9, '<?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': '2063604', 'n_tokens_mistral': 1315, 'n_tokens_neox': 1286, 'n_words': 281}