pdk-classy 1.9.1-alpha.2

PDK Classy
Documentation
// Copyright (c) 2026, Salesforce, Inc.,
// All rights reserved.
// For full license text, see the LICENSE.txt file

//! Utils for Injecting code execution at specific events during the execution chain.

use crate::{
    event::{Event, EventData, RequestHeaders, ResponseHeaders},
    BoxError,
};

/// Result of the [`EventHandler`].
pub type EventHandlerResult = Result<(), BoxError>;

/// The trait that must be implemented to inject code execution at specific events.
pub trait EventHandler<S>
where
    S: Event,
{
    /// Execute the internal code.
    fn call(&mut self, event: &EventData<S>) -> EventHandlerResult;
}

/// Implement even handler for generic functions.
impl<F, S> EventHandler<S> for F
where
    F: for<'a> FnMut(&EventData<'a, S>) -> EventHandlerResult,
    S: Event,
{
    fn call(&mut self, event: &EventData<S>) -> EventHandlerResult {
        self(event)
    }
}

/// A collection of [`EventHandler`]s
pub trait EventHandlerPush<S>
where
    S: Event,
{
    /// Add a handle to the collection.
    fn push<H>(&mut self, handler: H)
    where
        H: EventHandler<S> + 'static;
}

/// An interface to Invoke internal logic for the specified event.
pub trait EventHandlerDispatch<S>
where
    S: Event + Sized,
{
    /// Invoke the internal logic for the specified event.
    fn dispatch(&mut self, event: &EventData<S>) -> Result<(), BoxError>;
}

#[derive(Default)]
/// Implementation that handles [`EventHandler`]s for [`RequestHeaders`] and [`ResponseHeaders`].
pub struct EventHandlerStack {
    request_headers_handlers: Vec<Box<dyn EventHandler<RequestHeaders>>>,
    response_headers_handlers: Vec<Box<dyn EventHandler<ResponseHeaders>>>,
}

impl EventHandlerPush<RequestHeaders> for EventHandlerStack {
    fn push<H>(&mut self, handler: H)
    where
        H: EventHandler<RequestHeaders> + 'static,
    {
        self.request_headers_handlers.push(Box::new(handler))
    }
}

impl EventHandlerPush<ResponseHeaders> for EventHandlerStack {
    fn push<H>(&mut self, handler: H)
    where
        H: EventHandler<ResponseHeaders> + 'static,
    {
        self.response_headers_handlers.push(Box::new(handler))
    }
}

impl EventHandlerDispatch<RequestHeaders> for EventHandlerStack {
    fn dispatch(&mut self, event: &EventData<RequestHeaders>) -> Result<(), BoxError> {
        for h in &mut self.request_headers_handlers {
            h.call(event)?;
        }
        Ok(())
    }
}

impl EventHandlerDispatch<ResponseHeaders> for EventHandlerStack {
    fn dispatch(&mut self, event: &EventData<ResponseHeaders>) -> Result<(), BoxError> {
        for h in &mut self.response_headers_handlers {
            h.call(event)?;
        }
        Ok(())
    }
}