hyperlane-plugin-etag 23.3.0

An opt-in automatic ETag and HTTP conditional request plugin for the Hyperlane framework providing strong/weak XxHash3_64 entity tags, zero-allocation If-None-Match 304 Not Modified, and If-Match 412 Precondition Failed optimistic concurrency.
Documentation
use super::*;

/// Default construction for [`EtagConfig`].
impl Default for EtagConfig {
    /// Constructs an [`EtagConfig`] generating strong ETags with `If-Match` validation enabled.
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    fn default() -> Self {
        Self {
            strength: EtagStrength::Strong,
            min_body_bytes: DEFAULT_MIN_ETAG_BYTES,
            exempt_prefixes: Vec::new(),
            enforce_if_match: true,
        }
    }
}

/// Fluent builder helpers for [`EtagConfig`].
impl EtagConfig {
    /// Selects strong or weak entity-tag generation.
    ///
    /// # Arguments
    ///
    /// - `EtagStrength` - Desired tag strength.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_strength(mut self, strength: EtagStrength) -> Self {
        self.set_strength(strength);
        self
    }

    /// Sets the minimum response body length eligible for automatic ETag computation.
    ///
    /// # Arguments
    ///
    /// - `usize` - Minimum body size in bytes.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_min_body_bytes(mut self, min_bytes: usize) -> Self {
        self.set_min_body_bytes(min_bytes);
        self
    }

    /// Configures path prefixes excluded from ETag processing.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of exempt path prefixes.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_exempt_prefixes<I, S>(mut self, prefixes: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.set_exempt_prefixes(prefixes.into_iter().map(Into::into).collect());
        self
    }
}

/// Request precondition and response conditional evaluation methods for [`EtagPlugin`].
impl EtagPlugin {
    /// Compiles a standalone [`EtagPlugin`] with an optional [`EtagValidator`].
    ///
    /// # Arguments
    ///
    /// - `EtagConfig` - ETag configuration.
    /// - `Option<Arc<dyn EtagValidator>>` - Optional validator for `If-Match` checks.
    ///
    /// # Returns
    ///
    /// - `Self` - Compiled plugin.
    pub fn new(config: EtagConfig, validator: Option<Arc<dyn EtagValidator>>) -> Self {
        let exempt_prefixes: Box<[String]> = config
            .get_exempt_prefixes()
            .iter()
            .filter(|p: &&String| !p.trim().is_empty())
            .map(|p: &String| normalize_prefix(p))
            .collect::<Vec<String>>()
            .into_boxed_slice();
        let mut r412: Response = Response::default();
        r412.set_status_code(HttpStatus::PreconditionFailed.code())
            .set_header(CONTENT_TYPE, DEFAULT_PRECONDITION_CONTENT_TYPE)
            .set_body(DEFAULT_PRECONDITION_BODY);
        let precondition_failed_wire: Vec<u8> = r412.build();
        Self {
            config,
            exempt_prefixes,
            validator,
            precondition_failed_wire,
        }
    }

    /// Initializes the global [`EtagPlugin`] singleton once.
    ///
    /// # Arguments
    ///
    /// - `EtagConfig` - ETag configuration.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the global plugin.
    pub fn init(config: EtagConfig) -> &'static Self {
        ETAG_PLUGIN.get_or_init(|| Self::new(config, None))
    }

    /// Initializes the global [`EtagPlugin`] singleton with a custom [`EtagValidator`].
    ///
    /// # Arguments
    ///
    /// - `EtagConfig` - ETag configuration.
    /// - `Arc<dyn EtagValidator>` - Optimistic concurrency validator.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the global plugin.
    pub fn init_with_validator(
        config: EtagConfig,
        validator: Arc<dyn EtagValidator>,
    ) -> &'static Self {
        ETAG_PLUGIN.get_or_init(|| Self::new(config, Some(validator)))
    }

    /// Returns the initialized global [`EtagPlugin`], if configured.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline(always)]
    pub fn get() -> Option<&'static Self> {
        ETAG_PLUGIN.get()
    }

    /// Evaluates `If-Match` precondition on a mutating request; returns `false` when `412` must be sent.
    ///
    /// # Arguments
    ///
    /// - `&Request` - Incoming HTTP request.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when precondition passes or does not apply; `false` when violated.
    #[inline]
    pub fn check_if_match(&self, request: &Request) -> bool {
        let Self {
            config,
            exempt_prefixes,
            validator,
            ..
        } = self;
        if !config.get_enforce_if_match() {
            return true;
        }
        let Some(val_impl) = validator else {
            return true;
        };
        let method: &Method = request.get_method();
        if method.is_get() || method.is_head() || method.is_options() {
            return true;
        }
        if exempt_prefixes
            .iter()
            .any(|p: &String| path_matches_prefix(request.get_path(), p))
        {
            return true;
        }
        let Some(if_match_val) = request
            .get_headers()
            .get(IF_MATCH)
            .and_then(|vals: &VecDeque<String>| vals.back())
        else {
            return true;
        };
        let current: Option<String> = val_impl.current_etag(request);
        matches_if_match_strong(if_match_val, current.as_deref())
    }

    /// Generates an ETag if absent and converts matching `If-None-Match` GET/HEAD responses to `304`.
    ///
    /// # Arguments
    ///
    /// - `&mut Context` - Active request/response context.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the response was converted to `304 Not Modified`.
    #[inline]
    pub fn apply_response(&self, ctx: &mut Context) -> bool {
        let Self {
            config,
            exempt_prefixes,
            ..
        } = self;
        let request: &Request = ctx.get_request();
        let method: &Method = request.get_method();
        if !method.is_get() && !method.is_head() {
            return false;
        }
        if exempt_prefixes
            .iter()
            .any(|p: &String| path_matches_prefix(request.get_path(), p))
        {
            return false;
        }
        let response: &Response = ctx.get_response();
        let status: usize = response.get_status_code();
        if !(200..300).contains(&status) || status_has_no_body(status) {
            return false;
        }
        let existing_tag: Option<&str> = response
            .get_headers()
            .get(ETAG)
            .and_then(|vals: &VecDeque<String>| vals.back().map(String::as_str));
        let matched: bool = if let Some(tag) = existing_tag {
            request.matches_if_none_match(tag)
        } else {
            let body: &[u8] = response.get_body();
            if body.len() < config.get_min_body_bytes() {
                return false;
            }
            let digest: u64 = hash_entity_bytes(body);
            match config.get_strength() {
                EtagStrength::Strong => {
                    let buf: [u8; 18] = format_strong_etag_stack(digest);
                    let tag: &str = from_utf8(&buf).unwrap_or_default();
                    let is_match: bool = request.matches_if_none_match(tag);
                    ctx.get_mut_response().set_header(ETAG, tag);
                    is_match
                }
                EtagStrength::Weak => {
                    let buf: [u8; 20] = format_weak_etag_stack(digest);
                    let tag: &str = from_utf8(&buf).unwrap_or_default();
                    let is_match: bool = request.matches_if_none_match(tag);
                    ctx.get_mut_response().set_header(ETAG, tag);
                    is_match
                }
            }
        };
        if matched {
            let resp: &mut Response = ctx.get_mut_response();
            resp.set_status_code(HttpStatus::NotModified.code());
            resp.get_mut_body().clear();
            return true;
        }
        false
    }
}

/// Implements [`ServerHook`] for [`EtagRequestHook`].
impl ServerHook for EtagRequestHook {
    /// Constructs a per-request [`EtagRequestHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Enforces `If-Match` preconditions on mutating requests when an [`EtagValidator`] is configured.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Continue` when satisfied; `Status::Reject` after sending `412`.
    #[inline(always)]
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = EtagPlugin::get() else {
            return Status::Continue;
        };
        if !plugin.check_if_match(ctx.get_request()) {
            let EtagPlugin {
                precondition_failed_wire,
                ..
            } = plugin;
            let _: Result<(), ResponseError> = stream.try_send(precondition_failed_wire).await;
            return Status::Reject;
        }
        Status::Continue
    }
}

/// Implements [`ServerHook`] for [`EtagResponseHook`].
impl ServerHook for EtagResponseHook {
    /// Constructs a per-response [`EtagResponseHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Generates `ETag` headers and converts matching `If-None-Match` responses to `304 Not Modified`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - Always `Status::Continue`.
    #[inline(always)]
    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = EtagPlugin::get() else {
            return Status::Continue;
        };
        let _: bool = plugin.apply_response(ctx);
        Status::Continue
    }
}