Module: Tina4::Router

Defined in:
lib/tina4/router.rb

Defined Under Namespace

Classes: GroupContext

Constant Summary collapse

STRING_MIDDLEWARE =

Known string-addressable middleware, for a route declared as middleware: ["ResponseCache:300"]. Matches PHP (Router::resolveStringMiddleware) and Node (resolveStringMiddleware), which both know exactly one name today. Python's registry is larger; unifying the three registries is scheduled separately, so this deliberately does NOT guess at Python's extra names.

Each entry is a builder taking the parsed colon-args. See .resolve_string_middleware.

{
  "ResponseCache" => lambda { |args|
    ttl = args.first
    ttl.to_s.match?(/\A\d+\z/) ? Tina4::ResponseCache.new(ttl: ttl.to_i) : Tina4::ResponseCache.new
  }
}.freeze

Class Method Summary collapse

Class Method Details

.add(method, path, handler, auth_handler: nil, swagger_meta: {}, middleware: [], template: nil) ⇒ Object



472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
# File 'lib/tina4/router.rb', line 472

def add(method, path, handler, auth_handler: nil, swagger_meta: {}, middleware: [], template: nil)
  route = Route.new(method, path, handler,
                    auth_handler: auth_handler,
                    swagger_meta: swagger_meta,
                    middleware: middleware,
                    template: template)
  # Replace semantics: re-registering the same (method, path) overwrites
  # the existing entry in place rather than appending a second one.
  # This is what makes dev hot-reload work — when a changed route file is
  # re-loaded, its Router.get("/x") call runs again with a fresh handler,
  # and #find_route returns the FIRST match, so a stale leftover would
  # otherwise shadow the new handler forever. Overwriting keeps the
  # registry free of duplicates and ensures the latest handler wins.
  # Distinct (method, path) pairs are untouched — only an exact dup
  # collapses onto the prior slot, preserving its position/order.
  bucket = method_index[route.method]
  existing_index = routes.index { |r| r.method == route.method && r.path == route.path }
  if existing_index
    routes[existing_index] = route
    bucket_index = bucket.index { |r| r.path == route.path }
    if bucket_index
      bucket[bucket_index] = route
    else
      bucket << route
    end
    Tina4::Log.debug("Route replaced: #{route.method} #{route.path}")
  else
    routes << route
    bucket << route
    Tina4::Log.debug("Route registered: #{route.method} #{route.path}")
  end
  route
end

.any(path, middleware: [], swagger_meta: {}, template: nil, &block) ⇒ Object



526
527
528
# File 'lib/tina4/router.rb', line 526

def any(path, middleware: [], swagger_meta: {}, template: nil, &block)
  add("ANY", path, block, middleware: middleware, swagger_meta: swagger_meta, template: template)
end

.clear!Object Also known as: clear



696
697
698
699
700
# File 'lib/tina4/router.rb', line 696

def clear!
  @routes = []
  @method_index = Hash.new { |h, k| h[k] = [] }
  @ws_routes = []
end

.delete(path, middleware: [], swagger_meta: {}, template: nil, &block) ⇒ Object



522
523
524
# File 'lib/tina4/router.rb', line 522

def delete(path, middleware: [], swagger_meta: {}, template: nil, &block)
  add("DELETE", path, block, middleware: middleware, swagger_meta: swagger_meta, template: template)
end

.find_route(method, path) ⇒ Object



549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
# File 'lib/tina4/router.rb', line 549

def find_route(method, path)
  normalized_method = method.upcase
  # Normalize path once (not per-route)
  normalized_path = path.gsub("\\", "/")
  normalized_path = "/#{normalized_path}" unless normalized_path.start_with?("/")
  normalized_path = normalized_path.chomp("/") unless normalized_path == "/"

  # Candidates in REGISTRATION order, which is what Python, PHP and Node
  # all do. This used to be `ANY + method`, which made an ANY route beat
  # every same-path specific route no matter when either was registered -
  # so an app with an ordinary CMS catch-all (`any("/{slug}")`) silently
  # swallowed the framework's own GET routes, `/__health` among them. The
  # route was registered correctly; the router simply never reached it.
  #
  # `routes` is the registration-order array and `method_index` is the
  # per-method fast path. With no ANY routes registered - the common case -
  # the fast path is exactly what it was. Only an app that actually uses
  # ANY pays for the ordered scan, and only that app needed it.
  any_routes = method_index["ANY"]
  candidates = if any_routes.nil? || any_routes.empty?
                 method_index[normalized_method] || []
               else
                 routes.select { |r| r.method == "ANY" || r.method == normalized_method }
               end
  candidates.each do |route|
    params = route.match_path(normalized_path)
    return [route, params] if params
  end

  # RFC 9110 §9.3.2: HEAD is identical to GET except for the absence
  # of a response body. If no explicit HEAD route matched, fall back
  # to the GET route — the dispatcher strips the body on the way out
  # so the handler doesn't need to know HEAD even happened.
  if normalized_method == "HEAD"
    (method_index["GET"] || []).each do |route|
      params = route.match_path(normalized_path)
      return [route, params] if params
    end
  end

  nil
end

.find_ws_route(path) ⇒ Object

Find a matching WebSocket route for a given path. Returns [ws_route, params] or nil.



455
456
457
458
459
460
461
462
463
464
465
# File 'lib/tina4/router.rb', line 455

def find_ws_route(path)
  normalized = path.gsub("\\", "/")
  normalized = "/#{normalized}" unless normalized.start_with?("/")
  normalized = normalized.chomp("/") unless normalized == "/"

  ws_routes.each do |ws_route|
    params = ws_route.match?(normalized)
    return [ws_route, params] if params
  end
  nil
end

.get(path, middleware: [], swagger_meta: {}, template: nil, &block) ⇒ Object

Convenience registration methods



506
507
508
# File 'lib/tina4/router.rb', line 506

def get(path, middleware: [], swagger_meta: {}, template: nil, &block)
  add("GET", path, block, middleware: middleware, swagger_meta: swagger_meta, template: template)
end

.get_routesObject



411
412
413
# File 'lib/tina4/router.rb', line 411

def get_routes
  routes
end

.get_web_socket_routesObject

Parity alias — returns all registered WebSocket routes.



425
426
427
# File 'lib/tina4/router.rb', line 425

def get_web_socket_routes
  ws_routes
end

.group(prefix, auth_handler: nil, middleware: [], &block) ⇒ Object



703
704
705
# File 'lib/tina4/router.rb', line 703

def group(prefix, auth_handler: nil, middleware: [], &block)
  GroupContext.new(prefix, auth_handler, middleware).instance_eval(&block)
end

.head(path, middleware: [], swagger_meta: {}, template: nil, &block) ⇒ Object

Register an explicit HEAD route. By default the framework auto-handles HEAD by falling back to the GET route and stripping the body (RFC 9110 §9.3.2). Use this only when you need a HEAD handler that does something different from GET — e.g. cheaper existence-check logic, custom validator headers without the cost of building the body. The framework still strips the response body for you on the way out.



536
537
538
# File 'lib/tina4/router.rb', line 536

def head(path, middleware: [], swagger_meta: {}, template: nil, &block)
  add("HEAD", path, block, middleware: middleware, swagger_meta: swagger_meta, template: template)
end

.join_group_path(prefix, path) ⇒ Object

Join a route-group prefix with a route's own path.

Feature 32 (RG-DEC-01): ports PHP's normalization grammar verbatim (Tina4/Router.php addRoute - the reference) so Ruby converges with PHP/Python/Node instead of GroupContext's old bare concatenation. One separator between prefix and path, a single leading slash, no trailing slash, and any run of slashes collapsed to one - so group("/api") + get("users"), get("/users"), and group("/api/") + get("/users") all resolve to the SAME "/api/users". Before this fix, "#@prefix#path" bare-concatenated, so group("/api") + get("users") silently mis-registered at "/apiusers" (and a doubled trailing slash on a prefix could leave "/api//users").



719
720
721
722
723
# File 'lib/tina4/router.rb', line 719

def join_group_path(prefix, path)
  full = "#{prefix}/#{path.sub(%r{\A/+}, '')}"
  full = "/#{full.gsub(%r{\A/+|/+\z}, '')}"
  full.gsub(%r{/+}, "/")
end

.list_routesObject



415
416
417
# File 'lib/tina4/router.rb', line 415

def list_routes
  routes
end

.load_routes(directory) ⇒ Object

Load route files from a directory (file-based route discovery).

mtime-tracked & re-runnable so re-discovery on /__dev/api/reload is cheap and picks up edits without a server restart:

* NEW file (not seen before)            → load it, record its mtime.
* CHANGED file (mtime newer than seen)  → load it again. Ruby's `load`
RE-EXECUTES the file, so its Router.get(...) calls run afresh and
#add replaces the (method, path) in place — the new handler wins
instead of being shadowed by the stale one.
* UNCHANGED file (present, same mtime)  → skip (keeps reload cheap).

Scope guard: the glob is rooted at the user's routes/src directory, so only application route files are ever (re)loaded — framework files are never touched. Records the directory so #rescan_routes! can re-run without re-passing it.



741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
# File 'lib/tina4/router.rb', line 741

def load_routes(directory)
  return unless Dir.exist?(directory)

  @loaded_route_files ||= {}
  @last_routes_dir = directory

  files = Dir.glob(File.join(directory, "**/*.rb")).sort
  total = files.length
  files.each do |file|
    current_mtime = File.mtime(file).to_i
    # Skip only when we've seen this file AND it hasn't changed since.
    next if @loaded_route_files.key?(file) && current_mtime <= @loaded_route_files[file]
    begin
      load file
      @loaded_route_files[file] = current_mtime
      Tina4::Log.debug("Route loaded: #{file}")
    rescue ScriptError, StandardError => e
      # ScriptError catches SyntaxError, which is NOT a StandardError —
      # a bare `rescue => e` would let a syntax-broken route file crash
      # the whole discovery pass.
      Tina4::Log.error("Failed to load route #{file}: #{e.message}")
      record_broken_route_import(file, e)
    end
  end

  # Zero-routes warning — src/routes/ has .rb files but the router
  # is still empty. Almost certainly the user forgot Tina4::Router.get.
  if total > 0 && routes.empty?
    Tina4::Log.warning(
      "Auto-discover found #{total} .rb file(s) in #{directory} but no routes registered. " \
      "Each route file must call Tina4::Router.get / .post / etc."
    )
  end
end

.match(method, path) ⇒ Object

Find a route matching method + path. Returns [route, params] or nil. match(method, path) — consistent with Python, PHP, and Node.



640
641
642
# File 'lib/tina4/router.rb', line 640

def match(method, path)
  find_route(method, path)
end

.method_indexObject

Routes indexed by HTTP method for O(1) method lookup



468
469
470
# File 'lib/tina4/router.rb', line 468

def method_index
  @method_index ||= Hash.new { |h, k| h[k] = [] }
end

.methods_allowed_for_path(path) ⇒ Object

Return the list of HTTP methods registered for path, in the order GET / POST / PUT / PATCH / DELETE / HEAD / OPTIONS. Used by the dispatcher to build the Allow: header on 405 / OPTIONS responses (RFC 9110 §10.2.1, §9.3.7).

If GET is registered for the path, HEAD is appended implicitly (HEAD auto-fallback). OPTIONS is appended whenever the path has any registered method (the framework auto-handles OPTIONS).



600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# File 'lib/tina4/router.rb', line 600

def methods_allowed_for_path(path)
  normalized_path = path.gsub("\\", "/")
  normalized_path = "/#{normalized_path}" unless normalized_path.start_with?("/")
  normalized_path = normalized_path.chomp("/") unless normalized_path == "/"

  method_order = %w[GET POST PUT PATCH DELETE HEAD OPTIONS]
  seen = []
  any_matched = false

  method_index.each do |m, routes_for_method|
    next if routes_for_method.empty?
    matched = routes_for_method.any? { |r| r.match_path(normalized_path) }
    next unless matched
    if m == "ANY"
      any_matched = true
    elsif method_order.include?(m)
      seen << m unless seen.include?(m)
    end
  end

  seen = method_order.dup if any_matched

  if !seen.empty?
    seen << "HEAD" if seen.include?("GET") && !seen.include?("HEAD")
    seen << "OPTIONS" unless seen.include?("OPTIONS")
  end

  method_order.select { |m| seen.include?(m) }
end

.options(path, middleware: [], swagger_meta: {}, template: nil, &block) ⇒ Object

Register an explicit OPTIONS route. By default the framework auto- handles OPTIONS by building an Allow header from every method registered for the path and returning 204 (RFC 9110 §9.3.7). Use this to take over that behaviour — e.g. to return a richer OPTIONS payload describing the resource.



545
546
547
# File 'lib/tina4/router.rb', line 545

def options(path, middleware: [], swagger_meta: {}, template: nil, &block)
  add("OPTIONS", path, block, middleware: middleware, swagger_meta: swagger_meta, template: template)
end

.patch(path, middleware: [], swagger_meta: {}, template: nil, &block) ⇒ Object



518
519
520
# File 'lib/tina4/router.rb', line 518

def patch(path, middleware: [], swagger_meta: {}, template: nil, &block)
  add("PATCH", path, block, middleware: middleware, swagger_meta: swagger_meta, template: template)
end

.post(path, middleware: [], swagger_meta: {}, template: nil, &block) ⇒ Object



510
511
512
# File 'lib/tina4/router.rb', line 510

def post(path, middleware: [], swagger_meta: {}, template: nil, &block)
  add("POST", path, block, middleware: middleware, swagger_meta: swagger_meta, template: template)
end

.put(path, middleware: [], swagger_meta: {}, template: nil, &block) ⇒ Object



514
515
516
# File 'lib/tina4/router.rb', line 514

def put(path, middleware: [], swagger_meta: {}, template: nil, &block)
  add("PUT", path, block, middleware: middleware, swagger_meta: swagger_meta, template: template)
end

.record_broken_route_import(file, error) ⇒ Object

Write a .broken sentinel to data/.broken/ so an auto-discover failure leaves a durable on-disk artifact instead of being swallowed into a log line.

Ruby only WRITES these files today — nothing under lib/ reads them back. lib/tina4/health.rb contains no broken reference, and GET /__dev/api/broken serves the in-memory Tina4::DevAdmin::ErrorTracker (its own JSON store under Dir.tmpdir, dev_admin.rb:127-132), not this directory. Python's /health DOES glob data/.broken and answer 503 with errors + latest_error (tina4-python/tina4_python/core/server.py:296-320); mirroring that read side in Ruby is an OPEN parity gap. This comment used to claim "/health and the dev dashboard surface" it, which was false in both halves. (feature-recount D12)



808
809
810
811
812
813
814
815
816
817
818
819
820
821
# File 'lib/tina4/router.rb', line 808

def record_broken_route_import(file, error)
  broken_dir = File.join(Dir.pwd, "data", ".broken")
  FileUtils.mkdir_p(broken_dir) unless Dir.exist?(broken_dir)
  slug = file.gsub(%r{[/\\]}, "_")
  payload = JSON.generate(
    type: "auto_discover_failure",
    file: file,
    error: "#{error.class}: #{error.message}"
  )
  File.write(File.join(broken_dir, "discover_#{slug}.broken"), payload)
rescue StandardError
  # If the .broken write itself fails, the original error is already
  # in the log — nothing more to do.
end

.rescan_routes!Object

Re-run the most recent load_routes — called by /__dev/api/reload so files dropped into src/routes/ after server boot get picked up without a restart. No-op if load_routes has never been called.



779
780
781
782
783
784
785
786
# File 'lib/tina4/router.rb', line 779

def rescan_routes!
  return [] if @last_routes_dir.nil? || @last_routes_dir.empty?
  before = routes.length
  load_routes(@last_routes_dir)
  added = routes.length - before
  Tina4::Log.info("Re-discovered #{added} new route(s) on reload") if added.positive?
  added
end

.reset_route_discovery!Object

Test-only helper — reset the loaded-files state so tests can scan the same directory multiple times with different file contents.



790
791
792
793
# File 'lib/tina4/router.rb', line 790

def reset_route_discovery!
  @loaded_route_files = {}
  @last_routes_dir = nil
end

.resolve_string_middleware(spec) ⇒ Object

Resolve a string middleware spec to the middleware it names.

"ResponseCache"      -> ResponseCache with the default/env TTL
"ResponseCache:300"  -> ResponseCache with ttl = 300

The head before the first ":" is the name; the colon-separated tail is its arguments. Same parse as Python's _resolve_string_middleware, PHP's Router::resolveStringMiddleware and Node's resolveStringMiddleware.

ONE INSTANCE PER SPEC. Route middleware is resolved per dispatch in Ruby, so without memoising, every request would build a fresh ResponseCache with a fresh empty store and the cache could never hit. PHP memoises for exactly this reason; Python gets it for free by resolving once at registration.

An unknown name RAISES, naming the known set — never a silent skip. Python raises ValueError, Node throws; a typo must surface, not quietly drop the middleware (which for an auth middleware would mean serving the route unprotected).



679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
# File 'lib/tina4/router.rb', line 679

def resolve_string_middleware(spec)
  spec = spec.to_s
  @resolved_string_middleware ||= {}
  return @resolved_string_middleware[spec] if @resolved_string_middleware.key?(spec)

  name, _sep, tail = spec.partition(":")
  builder = STRING_MIDDLEWARE[name]
  unless builder
    raise ArgumentError,
          "Unknown middleware #{name.inspect}. Known string middleware: " \
          "#{STRING_MIDDLEWARE.keys.sort.join(', ')}. For custom middleware, " \
          "pass the class directly to .middleware(MyMiddleware)."
  end

  @resolved_string_middleware[spec] = builder.call(tail.empty? ? [] : tail.split(":"))
end

.routesObject



407
408
409
# File 'lib/tina4/router.rb', line 407

def routes
  @routes ||= []
end

.secure_websocket(path, &block) ⇒ Object

Register a SECURED WebSocket route (auth required on the upgrade). The declarative sibling of Tina4::Router.websocket(...).secure — mirrors the secure_get/secure_post pair for HTTP routes.



449
450
451
# File 'lib/tina4/router.rb', line 449

def secure_websocket(path, &block)
  websocket(path, secure: true, &block)
end

.trailing_slash_redirect?Boolean

When TINA4_TRAILING_SLASH_REDIRECT is truthy, the rack app uses this to detect whether the original (un-stripped) path differed from the canonical form so it can issue a 301 redirect. Default false — silent match keeps backward compatibility.

Returns:

  • (Boolean)


634
635
636
# File 'lib/tina4/router.rb', line 634

def trailing_slash_redirect?
  %w[true 1 yes on].include?(ENV.fetch("TINA4_TRAILING_SLASH_REDIRECT", "").to_s.strip.downcase)
end

.use(klass) ⇒ Object

Register a class-based middleware globally. The class should define static before_* and/or after_* methods. Example:

class AuthMiddleware
def self.before_auth(request, response)
  unless request.headers["authorization"]
    return [request, response.json({ error: "Unauthorized" }, 401)]
  end
  [request, response]
end
end
Tina4::Router.use(AuthMiddleware)


656
657
658
# File 'lib/tina4/router.rb', line 656

def use(klass)
  Tina4::Middleware.use(klass)
end

.websocket(path, secure: false, &block) ⇒ Object

Register a WebSocket route. The handler block receives (connection, event, data) where:

connection — WebSocketConnection with #send, #broadcast, #close, #params
event      — :open, :message, or :close
data       — String payload for :message, nil for :open/:close

PUBLIC by default (mirrors GET). Pass secure: true (the declarative way) OR chain .secure on the returned route (the imperative way) to require a valid JWT on the upgrade — both set the same auth_required flag, exactly like the HTTP routes support both a decorator/docblock and .secure.



439
440
441
442
443
444
# File 'lib/tina4/router.rb', line 439

def websocket(path, secure: false, &block)
  ws_route = WebSocketRoute.new(path, block, auth_required: secure)
  ws_routes << ws_route
  Tina4::Log.debug("WebSocket route registered: #{path}#{secure ? ' (secured)' : ''}")
  ws_route
end

.ws_routesObject

Registered WebSocket routes



420
421
422
# File 'lib/tina4/router.rb', line 420

def ws_routes
  @ws_routes ||= []
end