|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# Application wrapper for testing |
| 4 | +# This extracts the core application logic without loading config.ru |
| 5 | + |
| 6 | +require "fileutils" |
| 7 | +require "rack" |
| 8 | +require "logger" |
| 9 | +require_relative "lockfile_checker" |
| 10 | + |
| 11 | +class RailsMasterHookApp |
| 12 | + def initialize(run_file: nil, lock_file: nil, logger:) |
| 13 | + @run_file = run_file || ENV["RUN_FILE"] || File.expand_path("../run-rails-master-hook", __dir__) |
| 14 | + @lock_file = lock_file || ENV["LOCK_FILE"] |
| 15 | + @logger = logger |
| 16 | + end |
| 17 | + |
| 18 | + def call(env) |
| 19 | + request = Rack::Request.new(env) |
| 20 | + |
| 21 | + # Handle rails-master-hook routes (with or without trailing slash) |
| 22 | + if request.path_info == "/rails-master-hook" || request.path_info == "/rails-master-hook/" |
| 23 | + handle_rails_master_hook(request) |
| 24 | + else |
| 25 | + handle_root(request) |
| 26 | + end |
| 27 | + end |
| 28 | + |
| 29 | + private |
| 30 | + |
| 31 | + def handle_rails_master_hook(request) |
| 32 | + if request.request_method == "POST" |
| 33 | + @logger.info "Triggering Rails master hook by touching #{@run_file}" |
| 34 | + FileUtils.touch(@run_file) |
| 35 | + @logger.info "Rails master hook scheduled successfully" |
| 36 | + |
| 37 | + scheduled = <<~EOS |
| 38 | + Rails master hook tasks scheduled: |
| 39 | +
|
| 40 | + * updates the local checkout |
| 41 | + * updates Rails Contributors |
| 42 | + * generates and publishes edge docs |
| 43 | +
|
| 44 | + If a new stable tag is detected it also |
| 45 | +
|
| 46 | + * generates and publishes stable docs |
| 47 | +
|
| 48 | + This needs typically a few minutes. |
| 49 | + EOS |
| 50 | + |
| 51 | + [200, {"Content-Type" => "text/plain", "Content-Length" => scheduled.length.to_s}, [scheduled]] |
| 52 | + else |
| 53 | + @logger.warn "Rejected non-POST request (#{request.request_method}) to /rails-master-hook" |
| 54 | + [404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, []] |
| 55 | + end |
| 56 | + end |
| 57 | + |
| 58 | + def handle_root(request) |
| 59 | + lockfile_checker = LockfileChecker.new(@lock_file) |
| 60 | + |
| 61 | + if lockfile_checker.stale? |
| 62 | + age_minutes = lockfile_checker.age_in_minutes |
| 63 | + error_msg = "System down: Lock file has been present for more than 2 hours" |
| 64 | + @logger.error "#{error_msg} (actual age: #{age_minutes} minutes)" |
| 65 | + [503, {"Content-Type" => "text/plain", "Content-Length" => error_msg.length.to_s}, [error_msg]] |
| 66 | + else |
| 67 | + [200, {"Content-Type" => "text/plain", "Content-Length" => "4"}, ["PONG"]] |
| 68 | + end |
| 69 | + end |
| 70 | +end |
0 commit comments