Route matching overview
File list
| File | Topic |
|------|-------|
| 01-http-route.md | HTTP route engine — RadixPath, RegexSet, per-listener ConfHandler, proxy implementation |
| 02-grpc-route.md | gRPC route engine — Service/Method matching, gRPC-Web support, HTTP pipeline integration |
| 03-tcp-route.md | TCP route — per-listener route table, TCP proxy implementation, ConfHandler |
| 04-tls-route.md | TLS route — SNI matching, per-listener route table, terminate vs passthrough proxies |
| 05-udp-route.md | UDP route — per-listener route table, per-client session pinning, ConfHandler |
Multi-stage matching pipeline
After a request reaches the Gateway, route matching proceeds through these layers in order:
flowchart LR
A["Listener"] --> B["Domain (exact / wildcard / catch-all)"]
B --> C["Path (radix Exact/Prefix, then regex)"]
C --> D["Deep match"]
- Listener isolation: based on the connection's listening address and protocol (
ListenerKey, formatted as"{addr}/{protocol}"), pick the corresponding per-listener route table. - Domain match: look up
RouteRulesby hostname inDomainRouteRules. - Path match: try radix Exact/PathPrefix candidates first; only if none deep-match, try RegularExpression candidates.
- Deep match: run Gateway/Listener constraints, HTTP method, headers, and query-param exact checks against candidate routes.
Per-listener isolation
Each listener owns an independent route table, managed by GlobalHttpRouteManagers:
GlobalHttpRouteManagers
├── route_cache: DashMap<String, Arc<HTTPRoute>> # global route cache
└── by_listener: DashMap<ListenerKey, Arc<HttpPortRouteManager>>
└── HttpPortRouteManager
└── route_table: ArcSwap<DomainRouteRules> # per-listener snapshot
route_cacheholds the canonical shared copy of every HTTPRoute
(resource_key -> Arc<HTTPRoute>).
by_listenerkeeps anHttpPortRouteManagerperListenerKey; theArcSwap<DomainRouteRules>inside enables lock-free reads.- When the route table is updated, only affected listeners are rebuilt; other listeners are not disturbed.
pg_request_filtercallsload_route_table()per request to obtain the current snapshot, and the reference stays stable for the entire request lifetime.
The global managers for other protocols (gRPC / TCP / TLS / UDP) follow the same Global*RouteManagers → per-listener manager → ArcSwap pattern.
Shared L4 per-listener management (TCP / TLS / UDP)
The TCP, TLS, and UDP route docs all share the same listener-bucketing, rebuild, and ConfHandler mechanics. Canonical description (the per-protocol docs only call out their deltas):
- Layout:
Global*RouteManagers { route_cache: DashMap<String, Arc<*RouteUnit>>, by_listener: DashMap<ListenerKey, Arc<*PortRouteManager>> }, with each per-listener manager holdingroute_table: ArcSwap<*RouteTable>for lock-free reads. The TCP, TLS, and UDP caches own compiled companion units rather than raw schema resources. - Listener bucketing:
bucket_routes_by_listenerdistributes routes to listeners viaresolved_listeners(Controller-precomputed). A route with noresolved_listenerslogs a warning and is skipped. - Rebuild strategy:
rebuild_all_listener_managersfully rebuilds every listener table and cleans up stale listeners with no routes;rebuild_affected_listener_managersrebuilds only affected listeners (incremental updates). - ConfHandler:
full_setclearsroute_cache, replaces it in full, and callsrebuild_all_listener_managers;partial_updatecomputes affected listeners, updatesroute_cache, and callsrebuild_affected_listener_managers. TCP/TLS connections already matched against an old snapshot continue with their selected unit. New UDP sessions load the latest snapshot, while established UDP sessions remain pinned to their selected upstream until removal or expiry.
Per-protocol deltas: TCP = first-match over a flat Vec (no hostname dimension); TLS = SNI-indexed RadixHostnameMatcher candidates + two proxies (terminate-to-TCP vs passthrough); UDP = first-packet route match and weighted backend selection when creating a client session, followed by a pinned-session fast path.
Domain match
HTTPRoute, GRPCRoute and TLSRoute share edgion_algo::matcher::radix_hostname::RadixHostnameMatcher<T>:
one frozen reverse-byte hostname radix plus a persistent ID-to-content map,
published with protocol data through the existing outer snapshot. The matcher
returns borrowed candidates, exact first then longest-to-shortest wildcard
suffixes. It knows no Route, Listener, attachment or policy semantics.
HTTP/gRPC keep hostless fallback outside the matcher; TLSRoute has none.
Groups use authored Route names, never Listener-narrowed intersections as
precedence keys. Rule no-match may continue to broader groups, but Listener
eligibility remains mandatory and post-selection failure never restarts routing.
EdgionTls and Gateway TLS/certificate matchers are not migrated.
See the algorithm contract.
Path match
Each RouteRules holds two engines internally:
RadixRouteMatchEngine (Exact / Prefix)
- Based on the Gateway-owned path radix (
PathRadixBuilder+PathRadixTree); all routes are inserted at initialization and frozen into an immutable tree. - A single
for_each_match_exttraversal fills the candidate buffer directly with each match and itsPathMatchKind(FullyConsumed/SegmentBoundary/PartialSegment). - Exact routes accept only
FullyConsumed; Prefix routes acceptFullyConsumedorSegmentBoundary(rejecting partial-segment matches like/v2matching/v2example). - Candidate ordering is resolved at build time, not per request: the whole snapshot is ranked once
into a per-RadixPath precedence_rank, so the request path only sorts (rank, path_idx)
integers before deep-matching candidates in turn.
RegexRoutesEngine (RegularExpression)
- Uses
regex::RegexSetto batch-match all regex patterns at once, with O(P * M) complexity, where P is the combined pattern-set size and M is the input path length. - Routes are sorted by regex pattern length in descending order (longer patterns are preferred).
- Match order: the radix engine runs first; the regex engine is the fallback, preserving
Gateway API precedence Exact > PathPrefix > RegularExpression.
RadixPath specificity
RadixPath::specificity is a fixed-size PathSpecificity key, computed once from
the normalized path. Its fields compare in this order, higher first:
| Field | Meaning |
|-------|---------|
| is_exact | Every Exact outranks every PathPrefix |
| static_segment_count | Number of nonempty literal segments |
| static_char_count | Unicode characters in literal content, including slashes, after /:: escapes |
| segment_count | Number of nonempty segments, including one for each parameter |
A parameter's marker and complete identifier contribute no static characters.
Only a : immediately after / starts a parameter; /:: removes one escaped
colon and remains literal. Repeated slashes are collapsed before counting.
A trailing slash is ignored for PathPrefix matching and specificity. Exact
retains it as one static character, without adding a segment.
This is Edgion's aggregate-specificity extension for named parameters. Static
constraints across the entire path matter, not their left-to-right position.
For /a/b/c, /:x/b/c outranks /a/:x/:y; /a/:x/c and /:x/b/c
have equal path keys. For prefixes, /a outranks /:x/:y when both match:
static constraints take precedence over parameter depth. Among simultaneously
matching standard literal prefixes, the key preserves longest-character
precedence because additional segments necessarily extend the same path.
Equal path keys continue through MatchSpecificity::cmp_precedence(): method
match, header count, query count, older creation timestamp, ascending
namespace/name, then ascending rule/match index. Ascending path_idx is final.
Parameter spelling never bypasses these tie-breaks.
assign_precedence_ranks remains the sole place combining these immutable
inputs into precedence_rank. A request sorts only (rank, path_idx) integer
pairs; no pattern parsing, key comparison, or route-key string comparison is
added to that path. Restricting a strict total order to any candidate subset
preserves its order. See the specificity regression guard.
Deep match
After path matching, candidate routes go through deep_match_common for exact validation:
- Gateway/Listener constraints (
check_gateway_listener_match):
- Verify that the parentRef's namespace + name match the Gateway.
- Verify that sectionName matches the Listener (if specified).
- Verify that the request hostname matches the Listener hostname (HTTP Listener Isolation).
- Reject if a more specific Listener in the same physical ListenerKey serving index also matches the hostname, across Gateways and including empty Listeners.
- Verify AllowedRoutes (namespace and kind restrictions).
- HTTP method:
match_item.methodis compared with the request method. - Headers: all effective header match conditions must be satisfied (AND logic); supports
ExactandRegularExpression(precompiled regex). Typed decoding retains only the first ASCII-case-equivalent name within each match; the canonical vector also determines regex indexes and header specificity. - Query params: all query-param match conditions must be satisfied (AND logic); supports
ExactandRegularExpression.
Route registration flow
This diagram shows full-list and Gateway-triggered rebuilds. Partial updates
use patch_domain_route_rules to replace only touched hostname path groups.
flowchart TD
A["Full-list or Gateway refresh"] --> B["ConfHandler<HTTPRoute>::full_set / Gateway rebuild"]
B --> C["route_cache update (DashMap insert/remove)"]
C --> E["rebuild_all_listener_managers"]
E --> F["bucket_routes_by_listener (bucket by resolved_listeners)"]
F -->|"resolved_listeners empty"| F1["skip + warn"]
E --> G["For each affected listener"]
G --> G1["parse_http_routes_to_domain_rules"]
G1 --> G1a["filter_accepted_parent_refs"]
G1 --> G1b["get_declared_hostnames"]
G1 --> G1c["declared hostname groups: shared normal/regex units"]
G --> G2["build_domain_route_rules_from_routes"]
G2 --> G2a["RadixRouteMatchEngine::build (radix tree freeze)"]
G2 --> G2b["RegexRoutesEngine::build (RegexSet compile)"]
G2 --> G2c["RadixHostnameMatcher: reuse hosts when final keys agree"]
G --> G3["HttpPortRouteManager::store_route_table (ArcSwap atomic swap)"]
E --> H["Clean up stale listeners with no routes and no active Listener"]
Throughout the update, in-flight requests hold the old snapshot reference and are not interrupted. New requests automatically pick up the latest snapshot.
Multi-Gateway Listener sharing
When listeners from multiple Gateways bind to the same address/protocol combination (the same ListenerKey), all Gateways' routes are merged into the same per-listener DomainRouteRules. During deep match, check_gateway_listener_match walks gateway_infos (from ListenerGatewayInfoStore) to verify that each route belongs to the Gateway/Listener matched by the current request, achieving logical Listener isolation.
Key source files
| File | Responsibility |
|------|----------------|
| edgion-gateway/src/routes/http/routes_mgr.rs | GlobalHttpRouteManagers, DomainRouteRules, RouteRules |
| edgion-gateway/src/routes/http/conf_handler_impl.rs | ConfHandler<HTTPRoute> implementation, route parsing and construction |
| edgion-gateway/src/routes/http/match_engine/radix_route_match.rs | RadixRouteMatchEngine |
| edgion-gateway/src/routes/http/match_engine/regex_routes_engine.rs | RegexRoutesEngine |
| edgion-gateway/src/routes/http/match_engine/radix_path.rs | RadixPath priority calculation |
| edgion-gateway/src/routes/http/match_unit.rs | HttpRouteRuleUnit, deep_match_common |
| edgion-gateway/src/runtime/matching/route.rs | check_gateway_listener_match, hostname_matches_listener |