hello_world.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. # frozen_string_literal: true
  2. # Our Rack application to be executed by rackup
  3. class HelloWorld
  4. DEFAULT_HEADERS = {}.tap do |h|
  5. h[SERVER_HEADER] = SERVER_STRING if SERVER_STRING
  6. h.freeze
  7. end
  8. def bounded_queries(env)
  9. params = Rack::Utils.parse_query(env['QUERY_STRING'])
  10. queries = params['queries'].to_i
  11. queries.clamp(QUERIES_MIN, QUERIES_MAX)
  12. end
  13. # Return a random number between 1 and MAX_PK
  14. def rand1
  15. rand(MAX_PK).succ
  16. end
  17. def db
  18. World::BY_ID.(id: rand1)
  19. end
  20. def queries(env)
  21. DB.synchronize do
  22. ALL_IDS.sample(bounded_queries(env)).map do |id|
  23. World::BY_ID.(id: id)
  24. end
  25. end
  26. end
  27. def fortunes
  28. fortunes = Fortune.all
  29. fortunes << Fortune.new(
  30. id: 0,
  31. message: 'Additional fortune added at request time.'
  32. )
  33. fortunes.sort_by!(&:message)
  34. html = String.new(<<~'HTML')
  35. <!DOCTYPE html>
  36. <html>
  37. <head>
  38. <title>Fortunes</title>
  39. </head>
  40. <body>
  41. <table>
  42. <tr>
  43. <th>id</th>
  44. <th>message</th>
  45. </tr>
  46. HTML
  47. fortunes.each do |fortune|
  48. html << <<~"HTML"
  49. <tr>
  50. <td>#{fortune.id}</td>
  51. <td>#{Rack::Utils.escape_html(fortune.message)}</td>
  52. </tr>
  53. HTML
  54. end
  55. html << <<~'HTML'
  56. </table>
  57. </body>
  58. </html>
  59. HTML
  60. end
  61. def updates(env)
  62. DB.synchronize do
  63. worlds =
  64. ALL_IDS.sample(bounded_queries(env)).map do |id|
  65. world = World::BY_ID.(id: id)
  66. world[:randomnumber] = rand1
  67. world
  68. end
  69. World.batch_update(worlds)
  70. worlds
  71. end
  72. end
  73. def call(env)
  74. content_type, *body =
  75. case env['PATH_INFO']
  76. when '/json'
  77. # Test type 1: JSON serialization
  78. [JSON_TYPE, { message: 'Hello, World!' }.to_json]
  79. when '/db'
  80. # Test type 2: Single database query
  81. [JSON_TYPE, db.to_json]
  82. when '/queries'
  83. # Test type 3: Multiple database queries
  84. [JSON_TYPE, queries(env).to_json]
  85. when '/fortunes'
  86. # Test type 4: Fortunes
  87. [HTML_TYPE, fortunes]
  88. when '/updates'
  89. # Test type 5: Database updates
  90. [JSON_TYPE, updates(env).to_json]
  91. when '/plaintext'
  92. # Test type 6: Plaintext
  93. [PLAINTEXT_TYPE, 'Hello, World!']
  94. end
  95. [
  96. 200,
  97. DEFAULT_HEADERS.merge(
  98. CONTENT_TYPE => content_type,
  99. DATE_HEADER => Time.now.httpdate
  100. ),
  101. body
  102. ]
  103. end
  104. end