Skip to main content

rs_zero/rest/
layer_stack.rs

1use axum::Router;
2
3use crate::rest::{RestConfig, middleware::apply_default_layers};
4
5/// Tower-first REST layer stack builder.
6///
7/// The current implementation preserves the existing rs-zero REST middleware
8/// order while exposing an explicit stack object. Future releases can move
9/// individual middleware pieces behind concrete Tower [`tower::Layer`] types
10/// without changing [`RestServer`](crate::rest::RestServer) callers.
11#[derive(Debug, Clone)]
12pub struct RestLayerStack {
13    config: RestConfig,
14}
15
16impl RestLayerStack {
17    /// Creates a REST layer stack from runtime configuration.
18    pub fn new(config: RestConfig) -> Self {
19        Self { config }
20    }
21
22    /// Creates a production-oriented REST layer stack.
23    pub fn production_defaults(name: impl Into<String>) -> Self {
24        Self::new(RestConfig::production_defaults(name))
25    }
26
27    /// Creates a production-oriented REST layer stack.
28    #[allow(deprecated)]
29    #[deprecated(note = "use production_defaults instead")]
30    pub fn go_zero_defaults(name: impl Into<String>) -> Self {
31        Self::production_defaults(name)
32    }
33
34    /// Applies the stack to an axum router.
35    pub fn layer(&self, router: Router) -> Router {
36        apply_default_layers(router, self.config.clone())
37    }
38
39    /// Returns an axum-compatible layer value.
40    pub fn into_layer(self) -> RestRouterLayer {
41        RestRouterLayer {
42            config: self.config,
43        }
44    }
45}
46
47/// Axum router layer produced by [`RestLayerStack`].
48#[derive(Debug, Clone)]
49pub struct RestRouterLayer {
50    config: RestConfig,
51}
52
53impl tower::Layer<Router> for RestRouterLayer {
54    type Service = Router;
55
56    fn layer(&self, inner: Router) -> Self::Service {
57        apply_default_layers(inner, self.config.clone())
58    }
59}