hello_world.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # frozen_string_literal: true
  2. # Our Rack application to be executed by rackup
  3. class HelloWorld < Sinatra::Base
  4. configure do
  5. # Static file serving is ostensibly disabled in modular mode but Sinatra
  6. # still calls an expensive Proc on every request...
  7. disable :static
  8. # XSS, CSRF, IP spoofing, etc. protection are not explicitly required
  9. disable :protection
  10. # disable it for all environments
  11. set :host_authorization, { permitted_hosts: [] }
  12. # Only add the charset parameter to specific content types per the requirements
  13. set :add_charset, [mime_type(:html)]
  14. end
  15. helpers do
  16. def bounded_queries
  17. queries = params[:queries].to_i
  18. queries.clamp(QUERIES_MIN, QUERIES_MAX)
  19. end
  20. def json(data)
  21. content_type :json
  22. data.to_json
  23. end
  24. # Return a random number between 1 and MAX_PK
  25. def rand1
  26. rand(MAX_PK).succ
  27. end
  28. end
  29. after do
  30. response['Date'] = Time.now.httpdate
  31. end if defined?(Falcon) || defined?(Puma) || defined?(Agoo)
  32. after do
  33. response['Server'] = SERVER_STRING
  34. end if SERVER_STRING
  35. # Test type 1: JSON serialization
  36. get '/json' do
  37. json message: 'Hello, World!'
  38. end
  39. # Test type 2: Single database query
  40. get '/db' do
  41. world =
  42. ActiveRecord::Base.with_connection do
  43. World.find(rand1).attributes
  44. end
  45. json world
  46. end
  47. # Test type 3: Multiple database queries
  48. get '/queries' do
  49. ids = ALL_IDS.sample(bounded_queries)
  50. worlds =
  51. ActiveRecord::Base.with_connection do
  52. ids.map do |id|
  53. World.find(id).attributes
  54. end
  55. end
  56. json worlds
  57. end
  58. # Test type 4: Fortunes
  59. get '/fortunes' do
  60. @fortunes = ActiveRecord::Base.with_connection do
  61. Fortune.all
  62. end.to_a
  63. @fortunes << Fortune.new(
  64. id: 0,
  65. message: 'Additional fortune added at request time.'
  66. )
  67. @fortunes.sort_by!(&:message)
  68. erb :fortunes, layout: true
  69. end
  70. # Test type 5: Database updates
  71. get '/updates' do
  72. worlds = nil
  73. ids = ALL_IDS.sample(bounded_queries)
  74. ActiveRecord::Base.with_connection do
  75. worlds = ids.map do |id|
  76. world = World.find(id)
  77. new_value = rand1
  78. new_value = rand1 until new_value != world.randomNumber
  79. { id: id, randomNumber: new_value }
  80. end
  81. end
  82. worlds.sort_by!{_1[:id]}
  83. ActiveRecord::Base.with_connection do
  84. World.upsert_all(worlds)
  85. end
  86. json worlds
  87. end
  88. # Test type 6: Plaintext
  89. get '/plaintext' do
  90. content_type :text
  91. 'Hello, World!'
  92. end
  93. end