Skip to main content

rust_web_server/proxy_config/
builder.rs

1//! Builder: converts a `ProxyConfig` into a live `ConfigDrivenApp` with
2//! health checkers and L4/WS proxy threads.
3
4use std::collections::HashMap;
5use std::sync::atomic::AtomicBool;
6use std::sync::{Arc, RwLock};
7
8use crate::middleware::WithMiddleware;
9use crate::proxy_config::{
10    ActionConfig, AuthConfig, CompiledRoute, ConfigDrivenApp, DynamicProxy, MiddlewareConfig,
11    ProxyConfig, RedirectAdapter, RespondAdapter, RouteMatcher, StaticAdapter, arc_app,
12    AuthMisconfigured, BearerAuthMiddleware, PerRouteMaxBodySize, PerRouteRateLimit,
13};
14
15/// Build a `ConfigDrivenApp` from `rws.config.toml` and spawn L4/WS proxy
16/// threads. Returns the app and a list of background thread handles.
17/// Problems `ProxyConfig::validate` finds are printed first (the same
18/// findings `rws --check` reports). The returned app reloads its routes when
19/// the configuration is reloaded (`SIGHUP`, `POST /admin/config/reload`) —
20/// see [`ConfigDrivenApp::reload_from_file`].
21pub fn build_from_file() -> (ConfigDrivenApp, Vec<std::thread::JoinHandle<()>>) {
22    let source = std::fs::read_to_string(crate::proxy_config::config_file_path()).unwrap_or_default();
23    let config = ProxyConfig::from_str(&source);
24    let mut report = crate::config_check::ConfigReport::default();
25    config.validate(&mut report);
26    for e in &report.errors {
27        eprintln!("[proxy_config] ERROR: {e}");
28    }
29    for w in &report.warnings {
30        eprintln!("[proxy_config] Warning: {w}");
31    }
32    let (app, handles) = build_with_source(config, Some(source));
33    let reloadable = app.clone();
34    crate::config_reload::on_reload(move || reloadable.reload_from_file());
35    (app, handles)
36}
37
38/// Build a `ConfigDrivenApp` from a `ProxyConfig` struct.
39pub fn build(config: ProxyConfig) -> (ConfigDrivenApp, Vec<std::thread::JoinHandle<()>>) {
40    build_with_source(config, None)
41}
42
43fn build_with_source(config: ProxyConfig, source: Option<String>) -> (ConfigDrivenApp, Vec<std::thread::JoinHandle<()>>) {
44    let health_stop = Arc::new(AtomicBool::new(false));
45    let compiled = compile_routes(&config, &health_stop);
46    let handles = spawn_listeners(&config);
47    (ConfigDrivenApp::new(compiled, config, health_stop, source), handles)
48}
49
50/// Compile `config`'s routes and start health checkers for its upstreams;
51/// the checkers stop when `health_stop` is set. Used at startup and on every
52/// hot reload.
53pub(crate) fn compile_routes(config: &ProxyConfig, health_stop: &Arc<AtomicBool>) -> Vec<CompiledRoute> {
54    // ── 1. Build upstream name → live backends map ─────────────────────────
55    let mut upstream_lives: HashMap<String, Arc<RwLock<Vec<String>>>> = HashMap::new();
56    // tls_ca_file trust settings per upstream, loaded once per compile (so a
57    // reload picks up a rotated CA). A CA file that can't be loaded fails
58    // closed: every handshake fails (502) instead of trusting public CAs.
59    let mut upstream_trust: HashMap<String, Arc<crate::proxy::UpstreamTls>> = HashMap::new();
60    // Weights, stickiness, circuit breaker, retries: one state per
61    // upstream, shared by its routes.
62    let mut upstream_policies: HashMap<String, Arc<crate::proxy_config::upstream::UpstreamPolicy>> = HashMap::new();
63
64    for upstream in &config.upstreams {
65        let live = Arc::new(RwLock::new(upstream.backends.clone()));
66        upstream_lives.insert(upstream.name.clone(), Arc::clone(&live));
67        upstream_policies.insert(
68            upstream.name.clone(),
69            Arc::new(crate::proxy_config::upstream::UpstreamPolicy::new(
70                &upstream.name,
71                Arc::clone(&live),
72                &upstream.backends,
73                &upstream.weights,
74                upstream.sticky.clone(),
75                upstream.circuit_breaker.as_ref(),
76                upstream.retry.clone(),
77            )),
78        );
79
80        let client = upstream.tls_client_cert_file.as_deref().zip(upstream.tls_client_key_file.as_deref());
81        let configured = upstream.tls_ca_file.is_some() || upstream.tls_client_cert_file.is_some() || upstream.tls_client_key_file.is_some();
82        let trust = configured.then(|| {
83            Arc::new(crate::proxy::UpstreamTls::new(upstream.tls_ca_file.as_deref(), client).unwrap_or_else(|e| {
84                eprintln!("[proxy_config] ERROR: upstream '{}': {e} — its TLS backends answer 502 until this is fixed", upstream.name);
85                crate::proxy::UpstreamTls::reject_all(&upstream.name)
86            }))
87        });
88        if let Some(trust) = &trust {
89            upstream_trust.insert(upstream.name.clone(), Arc::clone(trust));
90        }
91
92        if let Some(ref hc) = upstream.health_check {
93            crate::proxy_config::health::start_health_checker(
94                upstream.name.clone(),
95                upstream.backends.clone(),
96                Arc::clone(&live),
97                hc.clone(),
98                Arc::clone(health_stop),
99                trust,
100            );
101        }
102    }
103
104    crate::proxy_config::upstream::register(upstream_policies.values().cloned().collect());
105
106    // ── 2. Build compiled routes ───────────────────────────────────────────
107    let mut caches: Vec<(String, crate::cache::CacheLayer)> = Vec::new();
108    let mut compiled: Vec<CompiledRoute> = Vec::new();
109
110    for route in &config.routes {
111        let matcher = RouteMatcher::from_match_config(&route.match_);
112
113        let mut async_proxy: Option<Arc<DynamicProxy>> = None;
114        let cache_name = format!("route:{}", if route.name.is_empty() { format!("#{}", compiled.len() + 1) } else { route.name.clone() });
115        let mirror = route.middleware.mirror.as_ref().map(|m| build_mirror(&route.name, m, &upstream_lives));
116
117        // Build the action handler (base application)
118        let base_handler: Arc<dyn crate::application::Application + Send + Sync> =
119            match &route.action {
120                ActionConfig::Proxy {
121                    upstream,
122                    connect_timeout_ms,
123                    read_timeout_ms,
124                    strip_path_prefix,
125                    add_path_prefix,
126                } => {
127                    let live = upstream_lives
128                        .get(upstream.as_str())
129                        .cloned()
130                        .unwrap_or_else(|| {
131                            // Fallback: upstream not declared, use name as single backend
132                            Arc::new(RwLock::new(vec![upstream.clone()]))
133                        });
134                    let upstream_cfg = config.upstreams.iter().find(|u| u.name == *upstream);
135                    let upstream_tls = upstream_cfg.map_or_else(|| upstream.starts_with("https://"), |u| u.tls);
136                    let upstream_strategy = upstream_cfg
137                        .map(|u| u.strategy.clone())
138                        .unwrap_or_else(|| "round_robin".to_string());
139                    let proxy = Arc::new(DynamicProxy::new(
140                        live,
141                        *connect_timeout_ms,
142                        *read_timeout_ms,
143                        strip_path_prefix.clone(),
144                        add_path_prefix.clone(),
145                        upstream_tls,
146                        upstream_strategy,
147                    )
148                    .with_trust(upstream_trust.get(upstream.as_str()).cloned())
149                    .with_policy(upstream, upstream_policies.get(upstream.as_str()).cloned())
150                    .with_mirror(mirror.clone()));
151                    if proxy.supports_async() && route.middleware.is_empty() {
152                        async_proxy = Some(Arc::clone(&proxy));
153                    }
154                    proxy
155                }
156
157                ActionConfig::Redirect { location, status } => {
158                    arc_app(RedirectAdapter::new(location.clone(), *status))
159                }
160
161                ActionConfig::Respond { status, body, content_type } => {
162                    arc_app(RespondAdapter::new(*status, body.clone(), content_type.clone()))
163                }
164
165                ActionConfig::Static { root, index } => {
166                    arc_app(StaticAdapter::new(root.clone(), index.clone()))
167                }
168
169                // Grpc action: HTTP/2 to the upstream (HTTP/1.1 only in builds
170                // without the http2 feature, where gRPC can't work anyway).
171                ActionConfig::Grpc { upstream, connect_timeout_ms, read_timeout_ms } => {
172                    let live = upstream_lives
173                        .get(upstream.as_str())
174                        .cloned()
175                        .unwrap_or_else(|| Arc::new(RwLock::new(vec![upstream.clone()])));
176                    let upstream_cfg = config.upstreams.iter().find(|u| u.name == *upstream);
177                    let upstream_tls = upstream_cfg.map_or_else(|| upstream.starts_with("https://"), |u| u.tls);
178                    #[cfg(feature = "http2")]
179                    {
180                        let _ = upstream_cfg;
181                        arc_app(crate::proxy_config::H2Route::new(
182                            live,
183                            upstream_tls,
184                            upstream_trust.get(upstream.as_str()).cloned(),
185                            *connect_timeout_ms,
186                            *read_timeout_ms,
187                        ))
188                    }
189                    #[cfg(not(feature = "http2"))]
190                    {
191                        let upstream_strategy = upstream_cfg
192                            .map(|u| u.strategy.clone())
193                            .unwrap_or_else(|| "round_robin".to_string());
194                        arc_app(
195                            DynamicProxy::new(live, *connect_timeout_ms, *read_timeout_ms, None, None, upstream_tls, upstream_strategy)
196                                .with_trust(upstream_trust.get(upstream.as_str()).cloned())
197                                .with_policy(upstream, upstream_policies.get(upstream.as_str()).cloned()),
198                        )
199                    }
200                }
201
202                ActionConfig::Mcp(gateway) => arc_app(crate::proxy_config::mcp_gateway::GatewayAdapter::start(
203                    (**gateway).clone(),
204                    route.match_.path.clone().unwrap_or_else(|| "/mcp".to_string()),
205                )),
206                ActionConfig::Llm(llm) => arc_app(crate::proxy_config::llm::build(llm)),
207                ActionConfig::Unknown(_) => {
208                    // No-op: these fall through to fallback
209                    arc_app(crate::proxy_config::NullApp)
210                }
211            };
212
213        // Wrap the base handler with middleware layers. A proxy route sends
214        // its mirror copies itself (so it keeps the async forwarder); any
215        // other action gets a MirrorLayer.
216        let handler = if matches!(route.action, ActionConfig::Proxy { .. }) || mirror.is_none() {
217            apply_middleware_named(base_handler, &route.middleware, &cache_name, &mut caches)
218        } else {
219            let handler = apply_middleware_named(base_handler, &route.middleware, &cache_name, &mut caches);
220            arc_app(WithMiddleware::new(ArcApp(handler)).wrap(crate::proxy::mirror::MirrorLayer::new(mirror.clone().expect("checked"))))
221        };
222
223        compiled.push(CompiledRoute { matcher, handler, async_proxy });
224    }
225    crate::cache::registry::replace_group("route:", caches);
226    compiled
227}
228
229/// Start the `[[tcp_proxy]]` / `[[udp_proxy]]` / `[[ws_proxy]]` listeners.
230/// Startup only: a hot reload can't move bound sockets, so changes to these
231/// sections need a restart.
232fn spawn_listeners(config: &ProxyConfig) -> Vec<std::thread::JoinHandle<()>> {
233    let mut handles: Vec<std::thread::JoinHandle<()>> = Vec::new();
234
235    for tcp_cfg in &config.tcp_proxies {
236        let listen = tcp_cfg.listen.clone();
237        let backends = tcp_cfg.backends.clone();
238        let timeout_ms = tcp_cfg.connect_timeout_ms;
239        let name = tcp_cfg.name.clone();
240        let h = std::thread::Builder::new()
241            .name(format!("tcp-proxy-{}", name))
242            .spawn(move || {
243                let proxy = crate::tcp_proxy::TcpProxy::new(backends)
244                    .connect_timeout_ms(timeout_ms);
245                if let Err(e) = proxy.bind(&listen) {
246                    eprintln!("[tcp_proxy:{}] {}", name, e);
247                }
248            })
249            .expect("failed to spawn tcp proxy thread");
250        handles.push(h);
251    }
252
253    for udp_cfg in &config.udp_proxies {
254        let listen = udp_cfg.listen.clone();
255        let backends = udp_cfg.backends.clone();
256        let reply_timeout_ms = udp_cfg.reply_timeout_ms;
257        let buffer_size = udp_cfg.buffer_size;
258        let name = udp_cfg.name.clone();
259        let h = std::thread::Builder::new()
260            .name(format!("udp-proxy-{}", name))
261            .spawn(move || {
262                let proxy = crate::udp_proxy::UdpProxy::new(backends)
263                    .reply_timeout_ms(reply_timeout_ms)
264                    .buffer_size(buffer_size);
265                if let Err(e) = proxy.bind(&listen) {
266                    eprintln!("[udp_proxy:{}] {}", name, e);
267                }
268            })
269            .expect("failed to spawn udp proxy thread");
270        handles.push(h);
271    }
272
273    for ws_cfg in &config.ws_proxies {
274        let listen = ws_cfg.listen.clone();
275        let backends = ws_cfg.backends.clone();
276        let connect_timeout_ms = ws_cfg.connect_timeout_ms;
277        let read_timeout_ms = ws_cfg.read_timeout_ms;
278        let name = ws_cfg.name.clone();
279
280        // With a health check configured, share a live-backend list with a
281        // background checker thread (same mechanism `[[upstream]]` pools
282        // use) instead of treating every configured backend as always live.
283        let live = Arc::new(RwLock::new(backends.clone()));
284        if let Some(ref hc) = ws_cfg.health_check {
285            crate::proxy_config::health::start_health_checker(
286                name.clone(),
287                backends.clone(),
288                Arc::clone(&live),
289                hc.clone(),
290                Arc::new(AtomicBool::new(false)),
291                None,
292            );
293        }
294
295        let h = std::thread::Builder::new()
296            .name(format!("ws-proxy-{}", name))
297            .spawn(move || {
298                let proxy = crate::ws_proxy::WsProxy::with_live_backends(backends, live)
299                    .connect_timeout_ms(connect_timeout_ms)
300                    .read_timeout_ms(read_timeout_ms);
301                if let Err(e) = proxy.bind(&listen) {
302                    eprintln!("[ws_proxy:{}] {}", name, e);
303                }
304            })
305            .expect("failed to spawn ws proxy thread");
306        handles.push(h);
307    }
308
309    handles
310}
311
312/// Wrap `handler` with the middleware layers described by `mw`, innermost
313/// (closest to the handler) to outermost (runs first, on every request):
314///
315///   1. Cache (innermost)
316///   2. Rewrite (request + response rules combined)
317///   3. Auth
318///   4. Rate limit
319///   5. IP filter
320///   6. Timeout — bounds this route's total time, including every layer above
321///   7. Max body size (outermost) — a fast, non-blocking length check, so a
322///      request this route will reject outright doesn't pay for a timeout
323///      wrapper (which runs its target on a background thread) or engage
324///      any other layer at all
325/// A route's mirror: a declared upstream's live backends, or its own list.
326fn build_mirror(route: &str, config: &crate::proxy_config::MirrorConfig, lives: &HashMap<String, Arc<RwLock<Vec<String>>>>) -> crate::proxy::mirror::Mirror {
327    let name = if config.upstream.is_empty() { format!("{route}-mirror") } else { config.upstream.clone() };
328    let mirror = match lives.get(&config.upstream) {
329        Some(live) if !config.upstream.is_empty() => crate::proxy::mirror::Mirror::with_live_backends(name, Arc::clone(live)),
330        _ if !config.upstream.is_empty() => crate::proxy::mirror::Mirror::new(name, vec![config.upstream.clone()]),
331        _ => crate::proxy::mirror::Mirror::new(name, config.backends.clone()),
332    };
333    mirror.percent(if config.percent.is_finite() { config.percent } else { 0.0 })
334}
335
336pub(crate) fn apply_middleware(
337    handler: Arc<dyn crate::application::Application + Send + Sync>,
338    mw: &MiddlewareConfig,
339) -> Arc<dyn crate::application::Application + Send + Sync> {
340    apply_middleware_named(handler, mw, "middleware", &mut Vec::new())
341}
342
343/// [`apply_middleware`], recording the route's cache (if any) as `name`
344/// in `caches` for the admin API's registry.
345pub(crate) fn apply_middleware_named(
346    handler: Arc<dyn crate::application::Application + Send + Sync>,
347    mw: &MiddlewareConfig,
348    name: &str,
349    caches: &mut Vec<(String, crate::cache::CacheLayer)>,
350) -> Arc<dyn crate::application::Application + Send + Sync> {
351    // Wrap the Arc<dyn Application> in an ArcApp adapter so it implements
352    // Application itself (needed for WithMiddleware::new).
353    let mut app: Arc<dyn crate::application::Application + Send + Sync> = handler;
354
355    // ── Cache (applied first so it's the innermost middleware) ─────────────
356    if let Some(ref cache_cfg) = mw.cache {
357        let mut layer = if cache_cfg.dir.is_empty() {
358            crate::cache::CacheLayer::memory(1000)
359        } else {
360            let max = crate::proxy_config::cache_max_bytes(&cache_cfg.max_size).unwrap_or(256 * 1024 * 1024);
361            crate::cache::CacheLayer::disk(&cache_cfg.dir, max).unwrap_or_else(|e| {
362                eprintln!("[proxy_config] ERROR: cache dir {}: {e} — this route caches in memory instead", cache_cfg.dir);
363                crate::cache::CacheLayer::memory(1000)
364            })
365        }
366        .ttl(cache_cfg.ttl_secs);
367        if !cache_cfg.purge_token_env.is_empty() {
368            layer = layer.purge_token(std::env::var(&cache_cfg.purge_token_env).unwrap_or_default().trim());
369        }
370        caches.push((name.to_string(), layer.clone()));
371        for vh in &cache_cfg.vary_by {
372            layer = layer.vary_by_header(vh.as_str());
373        }
374        app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer));
375    }
376
377    // ── Rewrite ────────────────────────────────────────────────────────────
378    if !mw.rewrite_request.is_empty() || !mw.rewrite_response.is_empty() {
379        let mut layer = crate::rewrite::RewriteLayer::new();
380        for rule in &mw.rewrite_request {
381            layer = apply_request_rewrite_rule(layer, rule);
382        }
383        for rule in &mw.rewrite_response {
384            layer = apply_response_rewrite_rule(layer, rule);
385        }
386        app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer));
387    }
388
389    // ── WebAssembly plugin (inside auth: it sees authenticated requests) ──
390    if let Some(ref wasm) = mw.wasm {
391        #[cfg(feature = "wasm-plugins")]
392        let layer = crate::wasm_plugin::WasmLayer::from_file(&wasm.module)
393            .map(|l| l.fuel(wasm.fuel).memory_mb(wasm.memory_mb).config(wasm.config.clone()));
394        #[cfg(not(feature = "wasm-plugins"))]
395        let layer: Result<crate::proxy_config::PluginMisconfigured, String> =
396            Err(format!("plugin {}: this rws binary was built without the wasm-plugins feature", wasm.module));
397        app = match layer {
398            Ok(layer) => arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer)),
399            Err(e) => {
400                eprintln!("[proxy_config] ERROR: {e} — this route answers 503 until the plugin is fixed.");
401                arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(crate::proxy_config::PluginMisconfigured))
402            }
403        };
404    }
405
406    // ── Auth ───────────────────────────────────────────────────────────────
407    // Fails closed: an auth setting that can't be honoured (secret unset,
408    // htpasswd missing, feature not compiled in) puts AuthMisconfigured in
409    // front of the route instead of silently serving it unauthenticated.
410    if let Some(ref auth_cfg) = mw.auth {
411        let deny = |reason: String| -> Arc<dyn crate::application::Application + Send + Sync> {
412            eprintln!(
413                "[proxy_config] ERROR: {reason} — this route answers 503 until the auth configuration is fixed."
414            );
415            arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(AuthMisconfigured))
416        };
417        app = match auth_cfg {
418            AuthConfig::Bearer { token_env } => {
419                let token = std::env::var(token_env).unwrap_or_default();
420                if token.is_empty() {
421                    deny(format!("bearer auth: env var '{token_env}' is unset or empty"))
422                } else {
423                    arc_app(
424                        WithMiddleware::new(ArcApp(Arc::clone(&app)))
425                            .wrap(BearerAuthMiddleware { token: Arc::new(token) }),
426                    )
427                }
428            }
429            #[cfg(feature = "auth")]
430            AuthConfig::Jwt { secret_env } => {
431                let secret = std::env::var(secret_env).unwrap_or_default();
432                if secret.is_empty() {
433                    deny(format!("JWT auth: env var '{secret_env}' is unset or empty"))
434                } else {
435                    arc_app(
436                        WithMiddleware::new(ArcApp(Arc::clone(&app)))
437                            .wrap(crate::auth::JwtLayer::new(secret)),
438                    )
439                }
440            }
441            #[cfg(not(feature = "auth"))]
442            AuthConfig::Jwt { .. } => {
443                deny("JWT auth requires the 'auth' feature, which this build doesn't include".to_string())
444            }
445            #[cfg(feature = "auth")]
446            AuthConfig::Basic { htpasswd_file } => {
447                match crate::auth::BasicAuthLayer::from_htpasswd_file(htpasswd_file) {
448                    Ok(layer) => arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(layer)),
449                    Err(e) => deny(format!("basic auth: {e}")),
450                }
451            }
452            #[cfg(not(feature = "auth"))]
453            AuthConfig::Basic { .. } => {
454                deny("basic auth requires the 'auth' feature, which this build doesn't include".to_string())
455            }
456        };
457    }
458
459    // ── Rate limit ─────────────────────────────────────────────────────────
460    if let Some(ref rl_cfg) = mw.rate_limit {
461        let limiter = Arc::new(crate::rate_limit::RateLimiter::new(
462            rl_cfg.max_requests,
463            rl_cfg.window_secs,
464        ));
465        app = arc_app(
466            WithMiddleware::new(ArcApp(Arc::clone(&app)))
467                .wrap(PerRouteRateLimit(limiter)),
468        );
469    }
470
471    // ── IP filter ────────────────────────────────────────────────────────────
472    if !mw.ip_allow.is_empty() {
473        let filter = crate::ip_filter::IpFilter::allow(mw.ip_allow.iter().map(|s| s.as_str()));
474        app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(filter));
475    } else if !mw.ip_deny.is_empty() {
476        let filter = crate::ip_filter::IpFilter::deny(mw.ip_deny.iter().map(|s| s.as_str()));
477        app = arc_app(WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(filter));
478    }
479
480    // ── Timeout (bounds this route's total time, including every other
481    // middleware above) ─────────────────────────────────────────────────────
482    if let Some(timeout_ms) = mw.timeout_ms {
483        app = arc_app(crate::timeout::TimeoutLayer::from_arc(
484            app,
485            std::time::Duration::from_millis(timeout_ms),
486        ));
487    }
488
489    // ── Max body size (outermost — see PerRouteMaxBodySize's docs for why
490    // this is not a substitute for RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES) ──────
491    if let Some(max_body_size) = mw.max_body_size {
492        app = arc_app(
493            WithMiddleware::new(ArcApp(Arc::clone(&app))).wrap(PerRouteMaxBodySize(max_body_size)),
494        );
495    }
496
497    app
498}
499
500fn apply_request_rewrite_rule(
501    layer: crate::rewrite::RewriteLayer,
502    rule: &crate::proxy_config::RewriteRuleConfig,
503) -> crate::rewrite::RewriteLayer {
504    match rule.type_.as_str() {
505        "header_set" => {
506            if let (Some(name), Some(value)) = (&rule.name, &rule.value) {
507                return layer.request_header_set(name, value);
508            }
509        }
510        "header_remove" => {
511            if let Some(name) = &rule.name {
512                return layer.request_header_remove(name);
513            }
514        }
515        "uri_set" => {
516            if let Some(value) = &rule.value {
517                return layer.request_uri_set(value);
518            }
519        }
520        "uri_strip_prefix" | "strip_prefix" => {
521            if let Some(prefix) = rule.prefix.as_ref().or(rule.value.as_ref()) {
522                return layer.request_uri_strip_prefix(prefix);
523            }
524        }
525        "uri_add_prefix" | "add_prefix" => {
526            if let Some(prefix) = rule.prefix.as_ref().or(rule.value.as_ref()) {
527                return layer.request_uri_add_prefix(prefix);
528            }
529        }
530        _ => {}
531    }
532    layer
533}
534
535fn apply_response_rewrite_rule(
536    layer: crate::rewrite::RewriteLayer,
537    rule: &crate::proxy_config::RewriteRuleConfig,
538) -> crate::rewrite::RewriteLayer {
539    match rule.type_.as_str() {
540        "header_set" => {
541            if let (Some(name), Some(value)) = (&rule.name, &rule.value) {
542                return layer.response_header_set(name, value);
543            }
544        }
545        "header_remove" => {
546            if let Some(name) = &rule.name {
547                return layer.response_header_remove(name);
548            }
549        }
550        "status" => {
551            if let (Some(code), Some(reason)) = (&rule.code, &rule.reason) {
552                return layer.response_status(*code as i16, reason);
553            }
554        }
555        "body_replace" => {
556            if let (Some(from), Some(to)) = (&rule.from, &rule.to) {
557                return layer.response_body_replace(from, to);
558            }
559        }
560        _ => {}
561    }
562    layer
563}
564
565// ── ArcApp adapter ─────────────────────────────────────────────────────────────
566
567/// Wraps `Arc<dyn Application + Send + Sync>` to implement `Application`
568/// (needed because you can't implement a foreign trait on a foreign type).
569struct ArcApp(Arc<dyn crate::application::Application + Send + Sync>);
570
571impl crate::application::Application for ArcApp {
572    fn execute(
573        &self,
574        request: &crate::request::Request,
575        conn: &crate::server::ConnectionInfo,
576    ) -> Result<crate::response::Response, String> {
577        self.0.execute(request, conn)
578    }
579
580    fn streams_body(&self, request: &crate::request::Request, conn: &crate::server::ConnectionInfo) -> bool {
581        self.0.streams_body(request, conn)
582    }
583}
584
585impl Clone for ArcApp {
586    fn clone(&self) -> Self {
587        ArcApp(Arc::clone(&self.0))
588    }
589}