Skip to main content

cratestack_axum/compact_layer/
layer.rs

1//! [`CompactLayer`]: the tower layer and its configuration.
2
3use std::sync::Arc;
4
5use cratestack_core::CratestackError;
6use cratestack_core::compact::KeyTables;
7use tower::Layer;
8
9use super::service::CompactService;
10
11/// The compact-keys layer; see the [module docs](super).
12#[derive(Clone)]
13pub struct CompactLayer {
14    pub(super) tables: Arc<KeyTables>,
15    pub(super) body_limit: usize,
16}
17
18impl CompactLayer {
19    /// A layer over `tables`. `body_limit_bytes` bounds a compact request
20    /// body and the named body it expands to (pass the router's own limit).
21    pub fn new(tables: KeyTables, body_limit_bytes: usize) -> Self {
22        Self {
23            tables: Arc::new(tables),
24            body_limit: body_limit_bytes,
25        }
26    }
27
28    /// [`new`](Self::new) over a [`KeyTables::to_bytes`] artifact, such as
29    /// the generated `KEY_TABLES` constant.
30    pub fn from_artifact(
31        artifact: &[u8],
32        body_limit_bytes: usize,
33    ) -> Result<Self, CratestackError> {
34        let tables = KeyTables::from_bytes(artifact)
35            .map_err(|error| CratestackError::Internal(format!("key tables: {error}")))?;
36        Ok(Self::new(tables, body_limit_bytes))
37    }
38}
39
40impl<S> Layer<S> for CompactLayer {
41    type Service = CompactService<S>;
42
43    fn layer(&self, inner: S) -> Self::Service {
44        CompactService {
45            inner,
46            layer: self.clone(),
47        }
48    }
49}