Class: Tina4::WebServer

Inherits:
Object
  • Object
show all
Defined in:
lib/tina4/webserver.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, host: "0.0.0.0", port: 7147) ⇒ WebServer

Returns a new instance of WebServer.



5
6
7
8
9
# File 'lib/tina4/webserver.rb', line 5

def initialize(app, host: "0.0.0.0", port: 7147)
  @app = app
  @host = host
  @port = port
end

Instance Method Details

#free_port(port) ⇒ Object

Kill whatever process is listening on port. Uses lsof on macOS/Linux and netstat + taskkill on Windows. Raises RuntimeError if the port cannot be freed.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/tina4/webserver.rb', line 14

def free_port(port)
  puts "  Port #{port} in use — killing existing process..."

  if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
    output = `netstat -ano 2>&1`
    pid = nil
    output.each_line do |line|
      if line.include?(":#{port}") && (line.include?("LISTENING") || line.include?("ESTABLISHED"))
        parts = line.strip.split(/\s+/)
        candidate = parts.last
        if candidate =~ /^\d+$/
          pid = candidate
          break
        end
      end
    end
    if pid
      system("taskkill /PID #{pid} /F")
    else
      raise "Could not free port #{port}: no PID found"
    end
  else
    pids = `lsof -ti :#{port} 2>/dev/null`.strip.split("\n")
    if pids.empty?
      return # Nothing found — port may have freed itself
    end
    pids.each do |pid|
      pid = pid.strip
      next unless pid =~ /^\d+$/
      begin
        Process.kill("TERM", pid.to_i)
      rescue Errno::ESRCH
        # Process already gone
      end
    end
  end

  # Give the OS a moment to reclaim the port
  sleep(0.5)
  puts "  Port #{port} freed"
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.

Parameters:

  • env (Hash)

    A Rack environment hash

Returns:

  • (Array)

    Rack-style response triple [status, headers, body]



308
309
310
# File 'lib/tina4/webserver.rb', line 308

def handle(env)
  @app.call(env)
end

#startObject



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
# File 'lib/tina4/webserver.rb', line 56

def start
  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.print_banner(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: []
  )

  # 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|
      # Reject new requests during shutdown
      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.cookies << WEBrick::Cookie.parse_set_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|
          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.cookies << WEBrick::Cookie.parse_set_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
end

#stopObject



295
296
297
298
299
# File 'lib/tina4/webserver.rb', line 295

def stop
  @ai_server&.shutdown
  @ai_thread&.join(5)
  @server&.shutdown
end