Class: Tina4::WebServer
- Inherits:
-
Object
- Object
- Tina4::WebServer
- Defined in:
- lib/tina4/webserver.rb
Constant Summary collapse
- DEFAULT_HOST =
"0.0.0.0"- DEFAULT_PORT =
7147
Instance Method Summary collapse
-
#free_port(port) ⇒ Object
Reclaim port from a stale Tina4 dev server via the shared, guarded path.
-
#handle(env) ⇒ Array
Dispatch a Rack-style env through the Tina4 app and return [status, headers, body].
-
#initialize(app, host: nil, port: nil) ⇒ WebServer
constructor
Bind address and port, when the caller does not pass host:/port:.
- #start ⇒ Object
- #stop ⇒ Object
Constructor Details
#initialize(app, host: nil, port: nil) ⇒ WebServer
Bind address and port, when the caller does not pass host:/port:.
Both go through Tina4.resolve_bind_* so this and Tina4.start! cannot drift apart - they already had: this file read TINA4_PORT first while tina4.rb read bare PORT first, so the same variable meant different things depending which entry point you came through.
16 17 18 19 20 |
# File 'lib/tina4/webserver.rb', line 16 def initialize(app, host: nil, port: nil) @app = app @host = host || Tina4.resolve_bind_host(DEFAULT_HOST) @port = port || Tina4.resolve_bind_port(DEFAULT_PORT) end |
Instance Method Details
#free_port(port) ⇒ Object
Reclaim port from a stale Tina4 dev server via the shared, guarded path.
This is the runtime bind-failure fallback. It used to SIGTERM whatever held the port with NONE of the CLI's guards -- no identity check, no container guard, no PID-safety filter -- so a foreign holder (another dev server, a database) was killed on any bind failure. It now routes through the SAME identity-checked helper the CLI uses (TAKEOVER-DEC-02), so only a PID-file-confirmed Tina4 dev server is ever signalled.
Raises RuntimeError when the port is held by a non-Tina4 process (or takeover is opted out / disabled outside dev), so the bind fails loudly with a clear message instead of killing an innocent process.
34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/tina4/webserver.rb', line 34 def free_port(port) result = Tina4::PortTakeover.take_over_port( port, dev: Tina4::PortTakeover.dev?, no_takeover: Tina4::PortTakeover.no_takeover_opted_out? ) if result.reclaimed? puts " #{result.}" return end raise result. if result.refused? # NOTHING / container: nothing to reclaim -- let the real bind decide. end |
#handle(env) ⇒ Array
Dispatch a Rack-style env through the Tina4 app and return [status, headers, body].
Useful for testing and embedding — does not require a running server. Cross-framework parity with Python and Node.js.
327 328 329 |
# File 'lib/tina4/webserver.rb', line 327 def handle(env) @app.call(env) end |
#start ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
# File 'lib/tina4/webserver.rb', line 47 def start # Refuse to boot with v3.11 / v2 era un-prefixed env vars set. Tina4.check_legacy_env_vars! is_managed = ARGV.include?('--managed') unless is_managed || ENV['TINA4_OVERRIDE_CLIENT'] == 'true' puts puts '=' * 60 puts puts ' Tina4 must be started with the tina4 CLI:' puts puts ' tina4 serve (development)' puts ' tina4 serve --production (production)' puts puts ' Install: cargo install tina4' puts ' Docs: https://tina4.com' puts puts ' To run directly, add to .env:' puts ' TINA4_OVERRIDE_CLIENT=true' puts puts '=' * 60 puts exit 1 end require "webrick" require "stringio" require "socket" # Ensure the main port is available — kill whatever is on it if needed begin test = TCPServer.new("0.0.0.0", @port) test.close rescue Errno::EADDRINUSE free_port(@port) # Verify the port is now free; raise if still occupied begin test = TCPServer.new("0.0.0.0", @port) test.close rescue Errno::EADDRINUSE raise "Could not free port #{@port}" end end Tina4.(host: @host, port: @port) Tina4::Log.info("Starting Tina4 WEBrick server on http://#{@host}:#{@port}") @server = WEBrick::HTTPServer.new( BindAddress: @host, Port: @port, Logger: WEBrick::Log.new(File::NULL), AccessLog: [] ) # Record THIS process as the Tina4 dev server on the main port, so a later # `tina4 serve` can identify it as reclaimable (TAKEOVER-DEC-01). Tina4::PortTakeover.write_pidfile(@port) # Setup graceful shutdown with WEBrick server reference Tina4::Shutdown.setup(server: @server) # Use a custom servlet that passes ALL methods (including OPTIONS) to Rack rack_app = @app servlet = Class.new(WEBrick::HTTPServlet::AbstractServlet) do define_method(:initialize) do |server, app| super(server) @app = app end %w[GET POST PUT DELETE PATCH HEAD OPTIONS].each do |http_method| define_method("do_#{http_method}") do |webrick_req, webrick_res| handle_request(webrick_req, webrick_res) end end define_method(:handle_request) do |webrick_req, webrick_res| # Belt-and-braces, NOT the primary mechanism. Shutdown closes the # listening socket FIRST, so a connection arriving after the signal is # refused by the kernel and never reaches here. What is left is a # genuine race: WEBrick accepts a connection and parses its request in # a worker thread, and the @shutting_down flag can flip in the gap # before that worker reaches this line. # # Measured (macOS 26.5.2, Ruby 4.0.2, webrick 1.9.2, 48 threads # hammering across a real SIGTERM): the window is the ~10-90ms between # the flag flip and the listener actually closing, and 0-2 requests per # run land in it out of ~2000. Every request after that is # ECONNREFUSED. Rare, but reachable - so the guard stays. if Tina4::Shutdown.shutting_down? webrick_res.status = 503 webrick_res.body = '{"error":"Service shutting down"}' webrick_res["content-type"] = "application/json" return end Tina4::Shutdown.track_request do env = build_rack_env(webrick_req) status, headers, body = @app.call(env) webrick_res.status = status headers.each do |key, value| if key.downcase == "set-cookie" Array(value.split("\n")).each { |c| webrick_res. << WEBrick::Cookie.(c) } else webrick_res[key] = value end end response_body = "" body.each { |chunk| response_body += chunk } webrick_res.body = response_body end end define_method(:build_rack_env) do |req| input = StringIO.new(req.body || "") env = { "REQUEST_METHOD" => req.request_method, "PATH_INFO" => req.path, "QUERY_STRING" => req.query_string || "", "SERVER_NAME" => webrick_req_host, "SERVER_PORT" => webrick_req_port, "CONTENT_TYPE" => req.content_type || "", "CONTENT_LENGTH" => (req.content_length rescue 0).to_s, "REMOTE_ADDR" => req.peeraddr&.last || "127.0.0.1", "rack.input" => input, "rack.errors" => $stderr, "rack.url_scheme" => "http", "rack.version" => [1, 3], "rack.multithread" => true, "rack.multiprocess" => false, "rack.run_once" => false } req.header.each do |key, values| env_key = "HTTP_#{key.upcase.gsub('-', '_')}" env[env_key] = values.join(", ") end env end end # Store host/port for the servlet's build_rack_env host = @host port = @port.to_s servlet.define_method(:webrick_req_host) { host } servlet.define_method(:webrick_req_port) { port } @server.mount("/", servlet, rack_app) # Test port (port + 1000) — stable, no-browser @ai_server = nil @ai_thread = nil no_ai_port = %w[true 1 yes].include?(ENV.fetch("TINA4_NO_AI_PORT", "").downcase) is_debug = %w[true 1 yes].include?(ENV.fetch("TINA4_DEBUG", "").downcase) if is_debug && !no_ai_port ai_port = @port + 1000 begin test = TCPServer.new("0.0.0.0", ai_port) test.close @ai_server = WEBrick::HTTPServer.new( BindAddress: @host, Port: ai_port, Logger: WEBrick::Log.new(File::NULL), AccessLog: [] ) # Wrap the rack app so AI-port requests are tagged ai_rack_app = Tina4::AiPortRackApp.new(@app) # Build a servlet identical to the main one but bound to the AI port host/port ai_host = @host ai_port_str = ai_port.to_s ai_servlet = Class.new(WEBrick::HTTPServlet::AbstractServlet) do define_method(:initialize) do |server, app| super(server) @app = app end %w[GET POST PUT DELETE PATCH HEAD OPTIONS].each do |http_method| define_method("do_#{http_method}") do |webrick_req, webrick_res| handle_request(webrick_req, webrick_res) end end define_method(:handle_request) do |webrick_req, webrick_res| # Same accepted-a-moment-before-the-listener-closed race as the # main servlet above - see the comment there. if Tina4::Shutdown.shutting_down? webrick_res.status = 503 webrick_res.body = '{"error":"Service shutting down"}' webrick_res["content-type"] = "application/json" return end Tina4::Shutdown.track_request do env = build_rack_env(webrick_req) status, headers, body = @app.call(env) webrick_res.status = status headers.each do |key, value| if key.downcase == "set-cookie" Array(value.split("\n")).each { |c| webrick_res. << WEBrick::Cookie.(c) } else webrick_res[key] = value end end response_body = "" body.each { |chunk| response_body += chunk } webrick_res.body = response_body end end define_method(:build_rack_env) do |req| input = StringIO.new(req.body || "") env = { "REQUEST_METHOD" => req.request_method, "PATH_INFO" => req.path, "QUERY_STRING" => req.query_string || "", "SERVER_NAME" => webrick_req_host, "SERVER_PORT" => webrick_req_port, "CONTENT_TYPE" => req.content_type || "", "CONTENT_LENGTH" => (req.content_length rescue 0).to_s, "REMOTE_ADDR" => req.peeraddr&.last || "127.0.0.1", "rack.input" => input, "rack.errors" => $stderr, "rack.url_scheme" => "http", "rack.version" => [1, 3], "rack.multithread" => true, "rack.multiprocess" => false, "rack.run_once" => false } req.header.each do |key, values| env_key = "HTTP_#{key.upcase.gsub('-', '_')}" env[env_key] = values.join(", ") end env end end ai_servlet.define_method(:webrick_req_host) { ai_host } ai_servlet.define_method(:webrick_req_port) { ai_port_str } @ai_server.mount("/", ai_servlet, ai_rack_app) @ai_thread = Thread.new { @ai_server.start } puts " Test Port: http://localhost:#{ai_port} (stable — no hot-reload)" rescue Errno::EADDRINUSE puts " Test Port: SKIPPED (port #{ai_port} in use)" end end @server.start # Shutdown closes the listener FIRST, so #start returns as soon as the # in-flight workers are joined - potentially while the signal handler's # thread is still stopping background tasks and closing the database. # Wait for that teardown instead of exiting out from under it. Tina4::Shutdown.wait_for_completion end |
#stop ⇒ Object
312 313 314 315 316 317 318 |
# File 'lib/tina4/webserver.rb', line 312 def stop @ai_server&.shutdown @ai_thread&.join(5) @server&.shutdown # Drop our identity marker so a later takeover does not match a dead PID. Tina4::PortTakeover.remove_pidfile(@port) end |