# frozen_string_literal: true require 'agoo' require 'connection_pool' require 'oj' require 'pg' require 'rack' $pool = ConnectionPool.new(size: 1, timeout: 5) do PG::Connection.new({ dbname: 'hello_world', host: 'tfb-database', user: 'benchmarkdbuser', password: 'benchmarkdbpass' }) end QUERY_RANGE = (1..10_000).freeze ALL_IDS = QUERY_RANGE.to_a QUERIES_MIN = 1 QUERIES_MAX = 500 CONTENT_TYPE = 'Content-Type' CONTENT_LENGTH = 'Content-Length' DATE = 'Date' SERVER = 'Server' SERVER_STRING = 'Agoo' JSON_TYPE = 'application/json' HTML_TYPE = 'text/html; charset=utf-8' PLAINTEXT_TYPE = 'text/plain' class BaseHandler def self.extract_queries_param(request = nil) queries = Rack::Utils.parse_query(request['QUERY_STRING'])['queries'].to_i rescue 1 queries.clamp(QUERIES_MIN, QUERIES_MAX) end def self.get_one_random_number Random.rand(QUERY_RANGE) end def self.get_one_record(id = get_one_random_number) $pool.with do |conn| conn.exec_params(<<-SQL, [id]).first SELECT * FROM world WHERE id = $1 SQL end end def self.html_response(str = '') [ 200, { CONTENT_TYPE => HTML_TYPE, DATE => Time.now.httpdate, SERVER => SERVER_STRING }, [str] ] end def self.json_response(obj = {}) [ 200, { CONTENT_TYPE => JSON_TYPE, DATE => Time.now.httpdate, SERVER => SERVER_STRING }, [Oj.dump(obj, { :mode => :strict })] ] end def self.plain_response(str = '') [ 200, { CONTENT_TYPE => PLAINTEXT_TYPE, DATE => Time.now.httpdate, SERVER => SERVER_STRING }, [str] ] end end class PlaintextHandler < BaseHandler def self.call(_req) plain_response('Hello, World!') end def static? true end end class JsonHandler < BaseHandler def self.call(_req) json_response({ :message => "Hello, World!" }) end def static? true end end class DbHandler < BaseHandler def self.call(_req) json_response(get_one_record) end end class FortunesHandler < BaseHandler def self.call(_req) f_1 = $pool.with do |conn| conn.exec(<<-SQL) SELECT id, message FROM fortune SQL end f_2 = f_1.map(&:to_h). append({ 'id' => '0', 'message' => 'Additional fortune added at request time.' }). sort_by { |item| item['message'] }. map { |f| "
| id | message |
|---|