Jelajahi Sumber

Fixed the broken rack benchmarks. Upgraded ruby version to 3.2 and upgraded the gems used. The benchmarks only use postgres now and use the Sequel gem for database access only (no ORM, everything is done with raw SQL). Made some minor changes to improve query speed including preparing statements (#8240)

Tim Uckun 2 tahun lalu
induk
melakukan
472a935fce

+ 3 - 1
.gitignore

@@ -33,6 +33,7 @@ build/
 *.patch
 */bin/
 
+
 # intellij
 *.iml
 *.ipr
@@ -57,7 +58,8 @@ benchmark.cfg
 
 # Visual Studio Code
 .vscode
-.history
+.history/
+.devcontainer
 
 # vim
 .*.sw[a-p]

+ 1 - 0
frameworks/Ruby/rack/.dockerignore

@@ -0,0 +1 @@
+Gemfile.lock

+ 1 - 0
frameworks/Ruby/rack/.gitignore

@@ -0,0 +1 @@
+tmp

+ 20 - 7
frameworks/Ruby/rack/Gemfile

@@ -1,8 +1,21 @@
-source 'http://rubygems.org'
+# frozen_string_literal: true
 
-gem 'mysql2', '0.4.5'
-gem 'unicorn', '5.3.0'
-gem 'puma', '3.12.6'
-gem 'rack', '2.0.8'
-gem 'json', '2.1.0'
-gem 'falcon'
+source 'https://rubygems.org'
+
+gem 'rack', '~>3.0'
+gem 'connection_pool', '~>2.4'
+gem 'falcon', '~>0.42', platforms: %i[ruby mswin]
+gem 'jdbc-postgres', '~> 42.2', platforms: :jruby, require: 'jdbc/postgres'
+gem 'json', '~> 2.6', platforms: :jruby
+gem 'oj', '~> 3.14', platforms: %i[ruby mswin]
+gem 'pg', '~>1.5', platforms: %i[ruby mswin]
+gem 'puma', '~> 6.2'
+gem 'sequel'
+gem 'sequel_pg', platforms: %i[ruby mswin]
+gem 'tzinfo-data', '1.2023.3'
+gem 'unicorn', '~> 6.1', platforms: %i[ruby mswin], require: false
+
+group :development do
+  gem 'rack-test'
+  gem 'rubocop', platforms: %i[ruby mswin]
+end

+ 130 - 0
frameworks/Ruby/rack/Gemfile.lock

@@ -0,0 +1,130 @@
+GEM
+  remote: https://rubygems.org/
+  specs:
+    ast (2.4.2)
+    async (2.5.0)
+      console (~> 1.10)
+      io-event (~> 1.1)
+      timers (~> 4.1)
+    async-container (0.16.12)
+      async
+      async-io
+    async-http (0.60.1)
+      async (>= 1.25)
+      async-io (>= 1.28)
+      async-pool (>= 0.2)
+      protocol-http (~> 0.24.0)
+      protocol-http1 (~> 0.15.0)
+      protocol-http2 (~> 0.15.0)
+      traces (>= 0.8.0)
+    async-http-cache (0.4.3)
+      async-http (~> 0.56)
+    async-io (1.34.3)
+      async
+    async-pool (0.4.0)
+      async (>= 1.25)
+    build-environment (1.13.0)
+    concurrent-ruby (1.2.2)
+    connection_pool (2.4.0)
+    console (1.16.2)
+      fiber-local
+    falcon (0.42.3)
+      async
+      async-container (~> 0.16.0)
+      async-http (~> 0.57)
+      async-http-cache (~> 0.4.0)
+      async-io (~> 1.22)
+      build-environment (~> 1.13)
+      bundler
+      localhost (~> 1.1)
+      openssl (~> 3.0)
+      process-metrics (~> 0.2.0)
+      protocol-rack (~> 0.1)
+      samovar (~> 2.1)
+    fiber-local (1.0.0)
+    io-event (1.1.7)
+    json (2.6.3)
+    kgio (2.11.4)
+    localhost (1.1.10)
+    mapping (1.1.1)
+    nio4r (2.5.9)
+    oj (3.14.2)
+    openssl (3.1.0)
+    parallel (1.23.0)
+    parser (3.2.2.1)
+      ast (~> 2.4.1)
+    pg (1.5.3)
+    process-metrics (0.2.1)
+      console (~> 1.8)
+      samovar (~> 2.1)
+    protocol-hpack (1.4.2)
+    protocol-http (0.24.1)
+    protocol-http1 (0.15.0)
+      protocol-http (~> 0.22)
+    protocol-http2 (0.15.1)
+      protocol-hpack (~> 1.4)
+      protocol-http (~> 0.18)
+    protocol-rack (0.2.4)
+      protocol-http (~> 0.23)
+      rack (>= 1.0)
+    puma (6.2.1)
+      nio4r (~> 2.0)
+    rack (3.0.7)
+    rack-test (2.1.0)
+      rack (>= 1.3)
+    rainbow (3.1.1)
+    raindrops (0.20.1)
+    regexp_parser (2.8.0)
+    rexml (3.2.5)
+    rubocop (1.51.0)
+      json (~> 2.3)
+      parallel (~> 1.10)
+      parser (>= 3.2.0.0)
+      rainbow (>= 2.2.2, < 4.0)
+      regexp_parser (>= 1.8, < 3.0)
+      rexml (>= 3.2.5, < 4.0)
+      rubocop-ast (>= 1.28.0, < 2.0)
+      ruby-progressbar (~> 1.7)
+      unicode-display_width (>= 2.4.0, < 3.0)
+    rubocop-ast (1.28.1)
+      parser (>= 3.2.1.0)
+    ruby-progressbar (1.13.0)
+    samovar (2.1.4)
+      console (~> 1.0)
+      mapping (~> 1.0)
+    sequel (5.68.0)
+    sequel_pg (1.17.1)
+      pg (>= 0.18.0, != 1.2.0)
+      sequel (>= 4.38.0)
+    timers (4.3.5)
+    traces (0.9.1)
+    tzinfo (2.0.6)
+      concurrent-ruby (~> 1.0)
+    tzinfo-data (1.2023.3)
+      tzinfo (>= 1.0.0)
+    unicode-display_width (2.4.2)
+    unicorn (6.1.0)
+      kgio (~> 2.6)
+      raindrops (~> 0.7)
+
+PLATFORMS
+  x86_64-darwin-20
+  x86_64-linux
+
+DEPENDENCIES
+  connection_pool (~> 2.4)
+  falcon (~> 0.42)
+  jdbc-postgres (~> 42.2)
+  json (~> 2.6)
+  oj (~> 3.14)
+  pg (~> 1.5)
+  puma (~> 6.2)
+  rack-test
+  rubocop
+  sequel
+  sequel_pg
+  tzinfo-data (= 1.2023.3)
+  unicorn (~> 6.1)
+
+BUNDLED WITH
+   2.4.10

+ 14 - 20
frameworks/Ruby/rack/README.md

@@ -11,37 +11,31 @@ comparing a variety of web servers.
 ## Infrastructure Software Versions
 The tests were run with:
 
-* [Ruby 2.0.0-p0](http://www.ruby-lang.org/)
-* [JRuby 1.7.8](http://jruby.org/)
-* [Rubinius 2.2.10](http://rubini.us/)
-* [Rack 1.5.2](http://rack.github.com/)
-* [Unicorn 4.8.3](http://unicorn.bogomips.org/)
-* [TorqBox 0.1.7](http://torquebox.org/torqbox/)
-* [Puma 3.9](http://puma.io/)
-* [Falcon](https://github.com/socketry/falcon)
-* [Thin 1.6.2](http://code.macournoyer.com/thin/)
+* [Ruby 3.2](http://www.ruby-lang.org/)
+* [JRuby 9.4](http://jruby.org/)
+* [Rack 3.0.7](http://rack.github.com/)
+* [Unicorn 6.1.0](http://unicorn.bogomips.org/)
+* [Puma 6.2.1](http://puma.io/)
+* [Falcon 0.42.3](https://github.com/socketry/falcon)
+* [Sequel 5.68.0](https://sequel.jeremyevans.net/)
+
+
 
 ## Paths & Source for Tests
 
-* [JSON Serialization](app/ruby_impl.rb) [[jruby version](app/jruby_impl.rb)]: "/json"
-* [Single Database Query](app/ruby_impl.rb) [[jruby version](app/jruby_impl.rb)]: "/db", [World Model](models/world.rb)
-* [Multiple Database Queries](app/ruby_impl.rb) [[jruby version](app/jruby_impl.rb)]: "/query?queries={#}", [World Model](models/world.rb)
-* _Fortunes: N/A_
-* [Database Updates](app/ruby_impl.rb) [[jruby version](app/jruby_impl.rb)]: "/updates?queries={#}", [World Model](models/world.rb)
-* [Plaintext](app/ruby_impl.rb) [[jruby version](app/jruby_impl.rb)]: "/plaintext"
+* Routing and controller logic is in hello_world.rb
+* Database access is done with pg_db.rb (only postgres is supported and we are using sequel to connect and run queries)
+* No ORM is used.
 
 ## Get Help
 
 ### Experts
 
 * Samuel Williams (@ioquatix) -- Async & Falcon developer.
+* Tim Uckun (@timuckun)
 
-### Community
-
-* `#rack` IRC Channel ([irc.freenode.net](http://freenode.net/))
-* [Rack Google Group](https://groups.google.com/forum/#!forum/rack-devel)
 
 ### Resources
 
 * [Rack Source Code](https://github.com/rack/rack)
-* [PR: passenger-install-apache2-module doesn't work on ruby 2.0](https://github.com/FooBarWidget/passenger/pull/71)
+

+ 0 - 91
frameworks/Ruby/rack/app/jruby_impl.rb

@@ -1,91 +0,0 @@
-require 'java'
-Jdbc::MySQL.load_driver
-Java::com.mysql.jdbc.Driver
-
-host, database     = DB_CONFIG[:host], DB_CONFIG[:database]
-username, password = DB_CONFIG[:username], DB_CONFIG[:password]
-JDBC_CONFIG = "jdbc:mysql://#{host}/#{database}?user=#{username}&password=#{password}"
-
-module App
-  JRuby = lambda do |env|
-    content_type, body = case env['PATH_INFO']
-      when '/plaintext'
-        ['text/plain', "Hello, World!"]
-      when '/json'
-        ['application/json', {:message => "Hello, World!"}.to_json]
-      when '/db'
-        id = Random.rand(10000) + 1
-        query = "SELECT * FROM World WHERE id = " + id.to_s
-
-        connection = java.sql.DriverManager.get_connection(JDBC_CONFIG)
-        results = begin
-          statement = connection.create_statement
-          begin
-            rs = statement.execute_query(query)
-            rs.next
-            {id: rs.getObject('id'), randomNumber: rs.getObject('randomNumber')}
-          ensure
-            statement.close
-          end
-        ensure
-          connection.close
-        end
-        ['application/json', results.to_json]
-      when '/queries'
-        query_string = Rack::Utils.parse_query(env['QUERY_STRING'])
-        queries = query_string['queries'].to_i
-        queries = 1 if queries < 1
-        queries = 500 if queries > 500
-
-        connection = java.sql.DriverManager.get_connection(JDBC_CONFIG)
-        results = begin
-          statement = connection.create_statement
-          begin
-            (1..queries).map do
-              id = Random.rand(10000) + 1
-              rs = statement.execute_query("SELECT * FROM World WHERE id = " + id.to_s)
-              rs.next
-              {id: rs.getObject('id'), randomNumber: rs.getObject('randomNumber')}
-            end
-          ensure
-            statement.close
-          end
-        ensure
-          connection.close
-        end
-        ['application/json', results.to_json]
-      when '/updates'
-        query_string = Rack::Utils.parse_query(env['QUERY_STRING'])
-        queries = query_string['queries'].to_i
-        queries = 1 if queries < 1
-        queries = 500 if queries > 500
-
-        connection = java.sql.DriverManager.get_connection(JDBC_CONFIG)
-        results = begin
-          statement = connection.create_statement
-          begin
-            results = (1..queries).map do
-              id = Random.rand(10000) + 1
-              rs = statement.execute_query("SELECT * FROM World WHERE id = " + id.to_s)
-              rs.next
-              {id: rs.getObject('id'), randomNumber: rs.getObject('randomNumber')}
-            end
-
-            #mass update
-            values = results.map { |h| ['(', h[:id], ',' ,Random.rand(10000) + 1, ')', ','] }.flatten[0..-2].join
-            sql = "INSERT INTO `World` (`id`,`randomNumber`) VALUES #{values} ON DUPLICATE KEY UPDATE `World`.`randomNumber` = VALUES(`randomNumber`)"
-            rs = statement.execute_update(sql)
-
-            results
-          ensure
-            statement.close
-          end
-        ensure
-          connection.close
-        end
-
-        ['application/json', results.to_json]
-      end
-    [200, { 'Content-Type' => content_type }, [body]]
-  end
-end

+ 0 - 58
frameworks/Ruby/rack/app/ruby_impl.rb

@@ -1,58 +0,0 @@
-module App
-  Ruby = lambda do |env|
-    content_type, body = case env['PATH_INFO']
-      when '/plaintext'
-        ['text/plain', "Hello, World!"]
-      when '/json'
-        ['application/json', {:message => "Hello, World!"}.to_json]
-      when '/db'
-        id = Random.rand(10000) + 1
-        query = "SELECT * FROM World WHERE id = " + id.to_s
-
-        client = Mysql2::Client.new(DB_CONFIG)
-        results = begin
-          client.query(query)
-        ensure
-          client.close
-        end
-        ['application/json', results.first.to_json]
-      when '/queries'
-        query_string = Rack::Utils.parse_query(env['QUERY_STRING'])
-        queries = query_string['queries'].to_i
-        queries = 1 if queries < 1
-        queries = 500 if queries > 500
-
-        client = Mysql2::Client.new(DB_CONFIG)
-        results = begin
-          (1..queries).map do
-            id = Random.rand(10000) + 1
-            client.query("SELECT * FROM World WHERE id = " + id.to_s).first
-          end
-        ensure
-          client.close
-        end
-        ['application/json', results.to_json]
-      when '/updates'
-        query_string = Rack::Utils.parse_query(env['QUERY_STRING'])
-        queries = query_string['queries'].to_i
-        queries = 1 if queries < 1
-        queries = 500 if queries > 500
-
-        client = Mysql2::Client.new(DB_CONFIG)
-        results = begin
-          results = (1..queries).map do
-            id = Random.rand(10000) + 1
-            num = Random.rand(10000) + 1
-            client.query("UPDATE World SET randomNumber = " + num.to_s + " WHERE id = " + id.to_s)
-            client.query("SELECT * FROM World WHERE id = " + id.to_s).first
-          end
-
-          results
-        ensure
-          client.close
-        end
-        ['application/json', results.to_json]
-      end
-    [200, { 'Content-Type' => content_type, 'Date' => Time.now.httpdate, 'Server' => 'WebServer' }, [body]]
-  end
-end

+ 83 - 64
frameworks/Ruby/rack/benchmark_config.json

@@ -1,68 +1,87 @@
 {
   "framework": "rack",
-  "tests": [{
-    "default": {
-      "json_url": "/json",
-      "db_url": "/db",
-      "query_url": "/queries?queries=",
-      "update_url": "/updates?queries=",
-      "plaintext_url": "/plaintext",
-      "port": 8080,
-      "approach": "Stripped",
-      "classification": "Platform",
-      "database": "MySQL",
-      "framework": "rack",
-      "language": "Ruby",
-      "orm": "Raw",
-      "platform": "Rack",
-      "webserver": "Puma",
-      "os": "Linux",
-      "database_os": "Linux",
-      "display_name": "rack-puma-mri",
-      "notes": "",
-      "tags": ["broken"]
-    },
-    "unicorn": {
-      "json_url": "/json",
-      "db_url": "/db",
-      "query_url": "/queries?queries=",
-      "update_url": "/updates?queries=",
-      "plaintext_url": "/plaintext",
-      "port": 8080,
-      "approach": "Stripped",
-      "classification": "Platform",
-      "database": "MySQL",
-      "framework": "rack",
-      "language": "Ruby",
-      "orm": "Raw",
-      "platform": "Rack",
-      "webserver": "Unicorn",
-      "os": "Linux",
-      "database_os": "Linux",
-      "display_name": "rack-unicorn-mri",
-      "notes": "",
-      "tags": ["broken"]
-    },
-    "falcon": {
-      "json_url": "/json",
-      "db_url": "/db",
-      "query_url": "/queries?queries=",
-      "update_url": "/updates?queries=",
-      "plaintext_url": "/plaintext",
-      "port": 8080,
-      "approach": "Stripped",
-      "classification": "Platform",
-      "database": "MySQL",
-      "framework": "rack",
-      "language": "Ruby",
-      "orm": "Raw",
-      "platform": "Rack",
-      "webserver": "Falcon",
-      "os": "Linux",
-      "database_os": "Linux",
-      "display_name": "rack-falcon-mri",
-      "notes": "",
-      "tags": ["broken"]
+  "tests": [
+    {
+      "default": {
+        "json_url": "/json",
+        "plaintext_url": "/plaintext",
+        "db_url": "/db",
+        "query_url": "/queries?queries=",
+        "update_url": "/updates?queries=",
+        "port": 8080,
+        "approach": "Stripped",
+        "classification": "Micro",
+        "orm": "raw",
+        "database": "Postgres",
+        "framework": "rack",
+        "language": "Ruby",
+        "platform": "Mri",
+        "webserver": "Puma",
+        "os": "Linux",
+        "database_os": "Linux",
+        "display_name": "rack-puma-mri-sequel-raw",
+        "notes": ""
+      },
+      "unicorn": {
+        "json_url": "/json",
+        "plaintext_url": "/plaintext",
+        "db_url": "/db",
+        "query_url": "/queries?queries=",
+        "update_url": "/updates?queries=",
+        "port": 8080,
+        "approach": "Stripped",
+        "classification": "Micro",
+        "orm": "raw",
+        "database": "Postgres",
+        "framework": "rack",
+        "language": "Ruby",
+        "platform": "Mri",
+        "webserver": "Unicorn",
+        "os": "Linux",
+        "database_os": "Linux",
+        "display_name": "rack-unicorn-mri-sequel-raw",
+        "notes": ""
+      },
+      "falcon": {
+        "json_url": "/json",
+        "plaintext_url": "/plaintext",
+        "db_url": "/db",
+        "query_url": "/queries?queries=",
+        "update_url": "/updates?queries=",
+        "port": 8080,
+        "approach": "Stripped",
+        "classification": "Micro",
+        "orm": "raw",
+        "database": "Postgres",
+        "framework": "rack",
+        "language": "Ruby",
+        "platform": "Mri",
+        "webserver": "Falcon",
+        "os": "Linux",
+        "database_os": "Linux",
+        "display_name": "rack-falcon-mri-sequel-raw",
+        "notes": ""
+      },
+      "jruby": {
+        "json_url": "/json",
+        "plaintext_url": "/plaintext",
+        "db_url": "/db",
+        "query_url": "/queries?queries=",
+        "update_url": "/updates?queries=",
+        "port": 8080,
+        "approach": "Stripped",
+        "classification": "Micro",
+        "orm": "raw",
+        "database": "Postgres",
+        "framework": "rack",
+        "language": "Ruby",
+        "platform": "Jruby",
+        "webserver": "Puma",
+        "os": "Linux",
+        "database_os": "Linux",
+        "display_name": "rack-puma-jruby-sequel-raw",
+        "notes": ""
+      }
     }
-  }]
+  ]
 }

+ 3 - 13
frameworks/Ruby/rack/config.ru

@@ -1,15 +1,5 @@
-Bundler.require :default
-require 'erb'
-require 'yaml'
+# frozen_string_literal: true
 
-$: << "."
+require_relative 'hello_world'
 
-DB_CONFIG = YAML.load(ERB.new(File.read("config/database.yml")).result)
-
-if RUBY_PLATFORM == 'java'
- require 'app/jruby_impl'
- run App::JRuby
-else
- require 'app/ruby_impl'
- run App::Ruby
-end
+run HelloWorld.new

+ 0 - 50
frameworks/Ruby/rack/config.toml

@@ -1,50 +0,0 @@
-[framework]
-name = "rack"
-
-[main]
-urls.plaintext = "/plaintext"
-urls.json = "/json"
-urls.db = "/db"
-urls.query = "/queries?queries="
-urls.update = "/updates?queries="
-approach = "Stripped"
-classification = "Platform"
-database = "MySQL"
-database_os = "Linux"
-os = "Linux"
-orm = "Raw"
-platform = "Rack"
-webserver = "Puma"
-versus = "None"
-
-[falcon]
-urls.plaintext = "/plaintext"
-urls.json = "/json"
-urls.db = "/db"
-urls.query = "/queries?queries="
-urls.update = "/updates?queries="
-approach = "Stripped"
-classification = "Platform"
-database = "MySQL"
-database_os = "Linux"
-os = "Linux"
-orm = "Raw"
-platform = "Rack"
-webserver = "Falcon"
-versus = "None"
-
-[unicorn]
-urls.plaintext = "/plaintext"
-urls.json = "/json"
-urls.db = "/db"
-urls.query = "/queries?queries="
-urls.update = "/updates?queries="
-approach = "Stripped"
-classification = "Platform"
-database = "MySQL"
-database_os = "Linux"
-os = "Linux"
-orm = "Raw"
-platform = "Rack"
-webserver = "Unicorn"
-versus = "None"

+ 43 - 0
frameworks/Ruby/rack/config/auto_tune.rb

@@ -0,0 +1,43 @@
+#!/usr/bin/env ruby
+# frozen_string_literal: true
+
+# Instantiate about one process per X MiB of available memory, scaling up to as
+# close to MAX_THREADS as possible while observing an upper bound based on the
+# number of virtual/logical CPUs. If there are fewer processes than
+# MAX_THREADS, add threads per process to reach MAX_THREADS.
+require 'etc'
+
+KB_PER_WORKER = 128 * 1_024 # average of peak PSS of single-threaded processes (watch smem -k)
+MIN_WORKERS = 15
+MAX_WORKERS_PER_VCPU = 1.25 # virtual/logical
+MIN_THREADS_PER_WORKER = 1
+MAX_THREADS = Integer(ENV['MAX_CONCURRENCY'] || 256)
+
+def meminfo(arg)
+  File.open('/proc/meminfo') do |f|
+    f.each_line do |line|
+      key, value = line.split(/:\s+/)
+      return value.split(/\s+/).first.to_i if key == arg
+    end
+  end
+
+  raise "Unable to find `#{arg}' in /proc/meminfo!"
+end
+
+def auto_tune
+  avail_mem = meminfo('MemAvailable') * 0.8 - MAX_THREADS * 1_024
+
+  workers = [
+    [(1.0 * avail_mem / KB_PER_WORKER).floor, MIN_WORKERS].max,
+    [(Etc.nprocessors * MAX_WORKERS_PER_VCPU).ceil, MIN_WORKERS].max
+  ].min
+
+  threads_per_worker = [
+    workers < MAX_THREADS ? (1.0 * MAX_THREADS / workers).ceil : -Float::INFINITY,
+    MIN_THREADS_PER_WORKER
+  ].max
+
+  [workers, threads_per_worker]
+end
+
+p auto_tune if $PROGRAM_NAME == __FILE__

+ 0 - 8
frameworks/Ruby/rack/config/database.yml

@@ -1,8 +0,0 @@
----
-  :encoding: utf8
-  :host: tfb-database
-  :database: hello_world
-  :username: benchmarkdbuser
-  :password: benchmarkdbpass
-  :pool: 256
-  :timeout: 5000

+ 0 - 158
frameworks/Ruby/rack/config/nginx.conf

@@ -1,158 +0,0 @@
-# This is example contains the bare mininum to get nginx going with
-# Unicorn or Rainbows! servers.  Generally these configuration settings
-# are applicable to other HTTP application servers (and not just Ruby
-# ones), so if you have one working well for proxying another app
-# server, feel free to continue using it.
-#
-# The only setting we feel strongly about is the fail_timeout=0
-# directive in the "upstream" block.  max_fails=0 also has the same
-# effect as fail_timeout=0 for current versions of nginx and may be
-# used in its place.
-#
-# Users are strongly encouraged to refer to nginx documentation for more
-# details and search for other example configs.
-
-# you generally only need one nginx worker unless you're serving
-# large amounts of static files which require blocking disk reads
-worker_processes 8;
-
-# # drop privileges, root is needed on most systems for binding to port 80
-# # (or anything < 1024).  Capability-based security may be available for
-# # your system and worth checking out so you won't need to be root to
-# # start nginx to bind on 80
-# user nobody nogroup; # for systems with a "nogroup"
-#user nobody nobody; # for systems with "nobody" as a group instead
-
-# Feel free to change all paths to suite your needs here, of course
-pid /tmp/nginx.pid;
-#error_log /tmp/nginx.error.log;
-error_log stderr error;
-
-events {
-  worker_connections 4096; # increase if you have lots of clients
-  accept_mutex off; # "on" if nginx worker_processes > 1
-  use epoll; # enable for Linux 2.6+
-  # use kqueue; # enable for FreeBSD, OSX
-}
-
-http {
-  # nginx will find this file in the config directory set at nginx build time
-  include /etc/nginx/mime.types;
-
-  # fallback in case we can't determine a type
-  default_type application/octet-stream;
-
-  # click tracking!
-  #access_log /tmp/nginx.access.log combined;
-  access_log off;
-
-  # you generally want to serve static files with nginx since neither
-  # Unicorn nor Rainbows! is optimized for it at the moment
-  sendfile on;
-
-  tcp_nopush on; # off may be better for *some* Comet/long-poll stuff
-  tcp_nodelay off; # on may be better for some Comet/long-poll stuff
-
-  # we haven't checked to see if Rack::Deflate on the app server is
-  # faster or not than doing compression via nginx.  It's easier
-  # to configure it all in one place here for static files and also
-  # to disable gzip for clients who don't get gzip/deflate right.
-  # There are other gzip settings that may be needed used to deal with
-  # bad clients out there, see http://wiki.nginx.org/NginxHttpGzipModule
-  #gzip on;
-  #gzip_http_version 1.0;
-  #gzip_proxied any;
-  #gzip_min_length 500;
-  #gzip_disable "MSIE [1-6]\.";
-  #gzip_types text/plain text/html text/xml text/css
-  #           text/comma-separated-values
-  #           text/javascript application/x-javascript
-  #           application/atom+xml;
-
-  # this can be any application server, not just Unicorn/Rainbows!
-  upstream app_server {
-    # fail_timeout=0 means we always retry an upstream even if it failed
-    # to return a good HTTP response (in case the Unicorn master nukes a
-    # single worker for timing out).
-
-    # for UNIX domain socket setups:
-    server unix:/tmp/.sock fail_timeout=0;
-
-    # for TCP setups, point these to your backend servers
-    # server 192.168.0.7:8080 fail_timeout=0;
-    # server 192.168.0.8:8080 fail_timeout=0;
-    # server 192.168.0.9:8080 fail_timeout=0;
-  }
-
-  server {
-    # enable one of the following if you're on Linux or FreeBSD
-    listen 8080 default deferred; # for Linux
-    # listen 80 default accept_filter=httpready; # for FreeBSD
-
-    # If you have IPv6, you'll likely want to have two separate listeners.
-    # One on IPv4 only (the default), and another on IPv6 only instead
-    # of a single dual-stack listener.  A dual-stack listener will make
-    # for ugly IPv4 addresses in $remote_addr (e.g ":ffff:10.0.0.1"
-    # instead of just "10.0.0.1") and potentially trigger bugs in
-    # some software.
-    # listen [::]:80 ipv6only=on; # deferred or accept_filter recommended
-
-    client_max_body_size 4G;
-    server_name _;
-
-    # ~2 seconds is often enough for most folks to parse HTML/CSS and
-    # retrieve needed images/icons/frames, connections are cheap in
-    # nginx so increasing this is generally safe...
-    keepalive_timeout 10;
-
-    # path for static files
-    root /path/to/app/current/public;
-
-    # Prefer to serve static files directly from nginx to avoid unnecessary
-    # data copies from the application server.
-    #
-    # try_files directive appeared in in nginx 0.7.27 and has stabilized
-    # over time.  Older versions of nginx (e.g. 0.6.x) requires
-    # "if (!-f $request_filename)" which was less efficient:
-    # http://bogomips.org/unicorn.git/tree/examples/nginx.conf?id=v3.3.1#n127
-    try_files $uri/index.html $uri.html $uri @app;
-
-    location @app {
-      # an HTTP header important enough to have its own Wikipedia entry:
-      #   http://en.wikipedia.org/wiki/X-Forwarded-For
-      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
-
-      # enable this if you forward HTTPS traffic to unicorn,
-      # this helps Rack set the proper URL scheme for doing redirects:
-      # proxy_set_header X-Forwarded-Proto $scheme;
-
-      # pass the Host: header from the client right along so redirects
-      # can be set properly within the Rack application
-      proxy_set_header Host $http_host;
-
-      # we don't want nginx trying to do something clever with
-      # redirects, we set the Host: header above already.
-      proxy_redirect off;
-
-      # set "proxy_buffering off" *only* for Rainbows! when doing
-      # Comet/long-poll/streaming.  It's also safe to set if you're using
-      # only serving fast clients with Unicorn + nginx, but not slow
-      # clients.  You normally want nginx to buffer responses to slow
-      # clients, even with Rails 3.1 streaming because otherwise a slow
-      # client can become a bottleneck of Unicorn.
-      #
-      # The Rack application may also set "X-Accel-Buffering (yes|no)"
-      # in the response headers do disable/enable buffering on a
-      # per-response basis.
-      # proxy_buffering off;
-
-      proxy_pass http://app_server;
-    }
-
-    # Rails error pages
-    error_page 500 502 503 504 /500.html;
-    location = /500.html {
-      root /path/to/app/current/public;
-    }
-  }
-}

+ 32 - 0
frameworks/Ruby/rack/config/puma.rb

@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+require_relative 'auto_tune'
+require 'etc'
+require 'sequel'
+
+# FWBM only... use the puma_auto_tune gem in production!
+num_workers, num_threads = auto_tune
+
+
+before_fork do
+  Sequel::DATABASES.each(&:disconnect)
+end
+
+if RUBY_PLATFORM == 'java'
+  num_threads = 512
+  num_workers = 0
+end
+
+workers num_workers
+threads num_threads, num_threads
+  # Use the `preload_app!` method when specifying a `workers` number.
+  # This directive tells Puma to first boot the application and load code
+  # before forking the application. This takes advantage of Copy On Write
+  # process behavior so workers use less memory.
+  #
+  preload_app!
+
+
+
+
+

+ 8 - 50
frameworks/Ruby/rack/config/unicorn.rb

@@ -1,53 +1,11 @@
-worker_processes 8
-listen "/tmp/.sock", :backlog => 4096
+# frozen_string_literal: true
 
-preload_app true
-GC.respond_to?(:copy_on_write_friendly=) and
-  GC.copy_on_write_friendly = true
+require_relative 'auto_tune'
+require 'sequel'
+num_workers, = auto_tune
 
-  before_fork do |server, worker|
-    # the following is highly recomended for Rails + "preload_app true"
-    # as there's no need for the master process to hold a connection
-    #defined?(ActiveRecord::Base) and
-    #  ActiveRecord::Base.connection.disconnect!
+worker_processes num_workers
 
-    # The following is only recommended for memory/DB-constrained
-    # installations.  It is not needed if your system can house
-    # twice as many worker_processes as you have configured.
-    #
-    # # This allows a new master process to incrementally
-    # # phase out the old master process with SIGTTOU to avoid a
-    # # thundering herd (especially in the "preload_app false" case)
-    # # when doing a transparent upgrade.  The last worker spawned
-    # # will then kill off the old master process with a SIGQUIT.
-    # old_pid = "#{server.config[:pid]}.oldbin"
-    # if old_pid != server.pid
-    #   begin
-    #     sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
-    #     Process.kill(sig, File.read(old_pid).to_i)
-    #   rescue Errno::ENOENT, Errno::ESRCH
-    #   end
-    # end
-    #
-    # Throttle the master from forking too quickly by sleeping.  Due
-    # to the implementation of standard Unix signal handlers, this
-    # helps (but does not completely) prevent identical, repeated signals
-    # from being lost when the receiving process is busy.
-    # sleep 1
-  end
-
-  after_fork do |server, worker|
-    # per-process listener ports for debugging/admin/migrations
-    # addr = "127.0.0.1:#{9293 + worker.nr}"
-    # server.listen(addr, :tries => -1, :delay => 5, :tcp_nopush => true)
-
-    # the following is *required* for Rails + "preload_app true",
-    #defined?(ActiveRecord::Base) and
-    #  ActiveRecord::Base.establish_connection
-
-    # if preload_app is true, then you may also want to check and
-    # restart any other shared sockets/descriptors such as Memcached,
-    # and Redis.  TokyoCabinet file handles are safe to reuse
-    # between any number of forked children (assuming your kernel
-    # correctly implements pread()/pwrite() system calls)
-  end
+before_fork do |_server, _worker|
+  Sequel::DATABASES.each(&:disconnect)
+end

+ 14 - 0
frameworks/Ruby/rack/falcon.rb

@@ -0,0 +1,14 @@
+#!/usr/bin/env -S falcon host
+# frozen_string_literal: true
+
+load :rack, :supervisor
+
+hostname = File.basename(__dir__)
+rack hostname do
+  endpoint Async::HTTP::Endpoint.parse('http://0.0.0.0:8080').with(
+    protocol: Async::HTTP::Protocol::HTTP11
+  )
+end
+
+supervisor
+

+ 116 - 0
frameworks/Ruby/rack/hello_world.rb

@@ -0,0 +1,116 @@
+# frozen_string_literal: true
+
+# Our Rack application to be executed by rackup
+
+require_relative 'pg_db'
+require_relative 'config/auto_tune'
+require 'rack'
+
+if RUBY_PLATFORM == 'java'
+  require 'json'
+  DEFAULT_DATABASE_URL = 'jdbc:postgresql://tfb-database/hello_world?user=benchmarkdbuser&password=benchmarkdbpass'
+else
+  require 'oj'
+  Oj.mimic_JSON
+  DEFAULT_DATABASE_URL = 'postgresql://tfb-database/hello_world?user=benchmarkdbuser&password=benchmarkdbpass'
+end
+
+class HelloWorld
+  QUERY_RANGE = (1..10_000).freeze # range of IDs in the Fortune DB
+  ALL_IDS = QUERY_RANGE.to_a # enumeration of all the IDs in fortune DB
+  MIN_QUERIES = 1 # min number of records that can be retrieved
+  MAX_QUERIES = 500 # max number of records that can be retrieved
+  CONTENT_TYPE = 'Content-Type'
+  CONTENT_LENGTH = 'Content-Length'
+  JSON_TYPE = 'application/json'
+  HTML_TYPE = 'text/html; charset=utf-8'
+  PLAINTEXT_TYPE = 'text/plain'
+  DATE = 'Date'
+  SERVER = 'Server'
+  SERVER_STRING = if defined?(PhusionPassenger)
+                    'Passenger'
+                  elsif defined?(Puma)
+                    Puma::Const::PUMA_SERVER_STRING
+                  elsif defined?(Unicorn)
+                    'Unicorn'
+                  elsif defined?(Falcon)
+                    'Falcon'
+                  else
+                    ' Ruby Rack'
+                  end
+  TEMPLATE_PREFIX = '<!DOCTYPE html>
+<html>
+<head>
+  <title>Fortune</title>
+</head>
+<body>
+  <table>
+    <tr>
+      <th>id</th>
+      <th>message</th>
+    </tr>'
+  TEMPLATE_POSTFIX = '</table>
+    </body
+  </html>'
+
+  def initialize
+    # auto_tune
+    max_connections = 512
+    @db = PgDb.new(DEFAULT_DATABASE_URL, max_connections)
+  end
+
+  def respond(content_type, body = '')
+    [
+      200,
+      {
+        CONTENT_TYPE => content_type,
+        DATE => Time.now.utc.httpdate,
+        SERVER => SERVER_STRING,
+        CONTENT_LENGTH => body.length.to_s
+
+      },
+      [body]
+    ]
+  end
+
+  def fortunes
+    fortunes = @db.select_fortunes
+    fortunes << { id: 0, message: 'Additional fortune added at request time.' }
+    fortunes.sort_by! { |item| item[:message] }
+    buffer = String.new
+    buffer << TEMPLATE_PREFIX
+
+    fortunes.each do |item|
+      buffer << "<tr><td> #{item[:id]} </td> <td>#{Rack::Utils.escape_html(item[:message])}</td></tr>"
+    end
+    buffer << TEMPLATE_POSTFIX
+  end
+
+  def call(env)
+    case env['PATH_INFO']
+    when '/json'
+      # Test type 1: JSON serialization
+      respond JSON_TYPE,
+              { message: 'Hello, World!' }.to_json
+    when '/db'
+      # Test type 2: Single database query
+      respond JSON_TYPE, @db.select_random_world.to_json
+    when '/queries'
+      # Test type 3: Multiple database queries
+      params = Rack::Utils.parse_query(env['QUERY_STRING'])
+      queries = params['queries']
+      respond JSON_TYPE, @db.select_worlds(queries).to_json
+    when '/fortunes'
+      # Test type 4: Fortunes
+      respond HTML_TYPE, fortunes
+    when '/updates'
+      # Test type 5: Database updates
+      params = Rack::Utils.parse_query(env['QUERY_STRING'])
+      queries = params['queries']
+      respond JSON_TYPE, @db.update_worlds(queries).to_json
+    when '/plaintext'
+      # Test type 6: Plaintext
+      respond PLAINTEXT_TYPE, 'Hello, World!'
+    end
+  end
+end

+ 121 - 0
frameworks/Ruby/rack/pg_db.rb

@@ -0,0 +1,121 @@
+# frozen_string_literal: true
+
+require 'sequel'
+
+if RUBY_PLATFORM == 'java'
+  require 'jdbc/postgres'
+  Jdbc::Postgres.load_driver
+end
+
+
+
+class PgDb
+  QUERY_RANGE = (1..10_000).freeze # range of IDs in the Fortune DB
+  ALL_IDS = QUERY_RANGE.to_a # enumeration of all the IDs in fortune DB
+  MIN_QUERIES = 1 # min number of records that can be retrieved
+  MAX_QUERIES = 500 # max number of records that can be retrieved
+
+  attr_reader :connection
+
+  def initialize(connection_string = nil, max_connections = 512)
+    @connection = Sequel.connect(connection_string, max_connections: max_connections, sql_log_level: :warning)
+    if defined?(Falcon)
+      Sequel.extension :fiber_concurrency if defined?(Falcon)
+    else
+      @connection.extension :async_thread_pool
+    end
+
+    prepare_statements
+  end
+
+  def prepare_statements
+    @world_select = @connection['SELECT id, randomNumber FROM World WHERE id = ?', :$id].prepare(:select, :select_by_id)
+    @world_update = @connection['UPDATE World SET randomNumber = ? WHERE id = ?', :$random_number, :$id].prepare(:update,
+                                                                                                                 :update_by_id)
+
+    @fortune_select = @connection['SELECT id, message FROM Fortune'].prepare(:select, :select_all)
+  end
+
+  def select_random_world
+    @world_select.call(id: random_id)[0]
+  end
+
+  def select_world(id)
+    @world_select.call(id: id)[0]
+  end
+
+  def validate_count(count)
+    count = count.to_i
+    if count < MIN_QUERIES
+      MIN_QUERIES
+    elsif count > MAX_QUERIES
+      MAX_QUERIES
+    else
+      count
+    end
+  end
+
+  def select_promises(count)
+    count = validate_count(count)
+    promises = []
+    count.times do
+      @connection.synchronize do
+        promises << @connection['SELECT id, randomNumber FROM World WHERE id = ?', random_id].async.first
+      end
+    end
+    promises
+  end
+
+  def select_random_numbers(count)
+    count = validate_count(count)
+    results = []
+    count.times do
+      results << @world_random_select.call(randomvalue: random_id, id: random_id)[0]
+    end
+    results
+  end
+
+  def select_worlds(count)
+    count = validate_count(count)
+    results = []
+    count.times do
+      results << @world_select.call(id: random_id)[0]
+    end
+    results
+  end
+
+  def select_worlds_async(count)
+    promises = select_promises(count)
+    results = []
+    promises.each do |p|
+      results << p.to_hash
+    end
+    results
+  end
+
+  def update_worlds(count, async = false)
+    results = if async
+      select_worlds_async(count)
+    else
+      select_worlds(count)
+    end
+    #values = []
+    ids=[]
+    sql = String.new("UPDATE world SET randomnumber = CASE id ")
+    results.each do |r|
+      r[:randomnumber] = random_id
+      ids << r[:id]
+      sql << "when #{r[:id]} then #{r[:randomnumber]} "
+    end
+    sql << "ELSE randomnumber END WHERE id IN ( #{ids.join(',')})"
+    @connection[sql].update
+    results
+  end
+  def select_fortunes
+    @fortune_select.call
+  end
+
+  def random_id
+    Random.rand(QUERY_RANGE)
+  end
+end

+ 10 - 6
frameworks/Ruby/rack/rack-falcon.dockerfile

@@ -1,13 +1,17 @@
-FROM ruby:2.4
+FROM ruby:3.2
 
-RUN apt-get update -yqq && apt-get install -yqq nginx
-
-ADD ./ /rack
+ENV BUNDLE_FORCE_RUBY_PLATFORM=true
+ENV RUBY_YJIT_ENABLE=1
 
 WORKDIR /rack
 
-RUN bundle install --jobs=4 --gemfile=/rack/Gemfile --path=/rack/rack/bundle
+COPY Gemfile  ./
+
+RUN bundle config set without 'development test'
+RUN bundle install --jobs=8
+
+COPY . .
 
 EXPOSE 8080
 
-CMD bundle exec falcon serve --forked --bind tcp://0.0.0.0:8080
+CMD bundle exec falcon host

+ 16 - 0
frameworks/Ruby/rack/rack-jruby.dockerfile

@@ -0,0 +1,16 @@
+FROM jruby:9.4-jdk17
+
+RUN apt-get update -y && apt-get install netbase -y
+
+WORKDIR /rack
+
+COPY Gemfile  ./
+
+RUN bundle config set without 'development test'
+RUN bundle install --jobs=8
+
+COPY . .
+
+EXPOSE 8080
+
+CMD bundle exec puma -C config/puma.rb -b tcp://0.0.0.0:8080 -e production

+ 13 - 5
frameworks/Ruby/rack/rack-unicorn.dockerfile

@@ -1,13 +1,21 @@
-FROM ruby:2.4
+FROM ruby:3.2
 
-RUN apt-get update -yqq && apt-get install -yqq nginx
+#RUN apt-get update -yqq && apt-get install -yqq nginx
 
-ADD ./ /rack
+ENV BUNDLE_FORCE_RUBY_PLATFORM=true
+ENV RUBY_YJIT_ENABLE=1
 
 WORKDIR /rack
 
-RUN bundle install --jobs=4 --gemfile=/rack/Gemfile --path=/rack/rack/bundle
+COPY Gemfile ./
+
+RUN bundle config set without 'development test'
+RUN bundle install --jobs=8
+
+COPY . .
 
 EXPOSE 8080
 
-CMD nginx -c /rack/config/nginx.conf && bundle exec unicorn -E production -c config/unicorn.rb
+#CMD nginx -c /rack/config/nginx.conf && bundle exec unicorn -E production -c config/unicorn.rb
+
+CMD bundle exec unicorn -c config/unicorn.rb -o 0.0.0.0 -p 8080 -E production

+ 12 - 4
frameworks/Ruby/rack/rack.dockerfile

@@ -1,11 +1,19 @@
-FROM ruby:2.4
 
-ADD ./ /rack
+FROM ruby:3.2
+
+ENV BUNDLE_FORCE_RUBY_PLATFORM=true
+ENV RUBY_YJIT_ENABLE=1
 
 WORKDIR /rack
 
-RUN bundle install --jobs=4 --gemfile=/rack/Gemfile --path=/rack/rack/bundle
+COPY Gemfile  ./
+
+RUN bundle config set without 'development test'
+RUN bundle install --jobs=8
+
+COPY . .
 
 EXPOSE 8080
 
-CMD bundle exec puma -t 8:32 -w 8 --preload -b tcp://0.0.0.0:8080 -e production
+CMD bundle exec puma -C config/puma.rb -b tcp://0.0.0.0:8080 -e production
+