Skip to main content

hyperlane_core/hook/
impl.rs

1use super::*;
2
3/// A blanket implementation for any function that takes a `Context` and returns a value.
4///
5/// This implementation makes it easy to use any compatible function as a `FnContext`,
6/// promoting a flexible and functional programming style.
7impl<F, R> FnContext<R> for F where F: Fn(&mut Context) -> R + Send + Sync {}
8
9/// A blanket implementation for functions that return a pinned, boxed, sendable future.
10///
11/// This trait is a common pattern for asynchronous handlers in Rust, enabling type
12/// erasure and dynamic dispatch for futures. It is essential for storing different
13/// async functions in a collection.
14impl<F, T> FnContextPinBox<T> for F where F: FnContext<FutureBox<T>> {}
15
16/// A blanket implementation for static, sendable, synchronous functions that return a future.
17///
18/// This trait is used for handlers that are known at compile time, ensuring they
19/// are safe to be sent across threads and have a static lifetime. This is crucial
20/// for handlers that are part of the application's long-lived state.
21impl<F, Fut, T> FnContextStatic<Fut, T> for F
22where
23    F: FnContext<Fut> + 'static,
24    Fut: Future<Output = T> + Send,
25{
26}
27
28/// A blanket implementation for any future that is sendable and has a static lifetime.
29///
30/// This is a convenient trait for working with futures in an asynchronous context,
31/// ensuring that they can be safely managed by the async runtime across different
32/// threads.
33impl<T, R> FutureSendStatic<R> for T where T: Future<Output = R> + Send + 'static {}
34
35/// Blanket implementation of `FutureSend` for any type that satisfies the bounds.
36impl<T, O> FutureSend<O> for T where T: Future<Output = O> + Send {}
37
38/// Blanket implementation of `FutureFn` for any type that satisfies the bounds.
39impl<T, O> FutureFn<O> for T where T: Fn() -> FutureBox<O> + Send + Sync {}
40
41/// Provides a default implementation for `ServerControlHook`.
42impl Default for ServerControlHook {
43    /// Creates a new `ServerControlHook` instance with default no-op hooks.
44    ///
45    /// The default `wait_hook` and `shutdown_hook` do nothing, allowing the server
46    /// to run without specific shutdown or wait logic unless configured otherwise.
47    ///
48    /// # Returns
49    ///
50    /// - `Self` - A new instance with default hooks.
51    #[inline(always)]
52    fn default() -> Self {
53        Self {
54            wait_hook: Hook::default_control_handler(),
55            shutdown_hook: Hook::default_control_handler(),
56        }
57    }
58}
59
60/// Manages server lifecycle hooks, including waiting and shutdown procedures.
61///
62/// This struct holds closures that are executed during specific server lifecycle events.
63impl ServerControlHook {
64    /// Waits for the server's shutdown signal or completion.
65    ///
66    /// This method asynchronously waits until the server's `wait_hook` is triggered,
67    /// typically indicating that the server has finished its operations or is ready to shut down.
68    pub async fn wait(&self) {
69        self.get_wait_hook()().await;
70    }
71
72    /// Initiates the server shutdown process.
73    ///
74    /// This method asynchronously calls the `shutdown_hook`, which is responsible for
75    /// performing any necessary cleanup or graceful shutdown procedures.
76    pub async fn shutdown(&self) {
77        self.get_shutdown_hook()().await;
78    }
79}
80
81/// Factory and utility functions for creating hook handlers.
82///
83/// This impl block groups semantically related factory methods that create
84/// various hook handler types used throughout the server lifecycle.
85impl Hook {
86    /// Creates a default `ServerControlHookHandler` instance with default no-op hooks.
87    ///
88    /// The default `wait_hook` and `shutdown_hook` do nothing, allowing the server
89    /// to run without specific shutdown or wait logic unless configured otherwise.
90    ///
91    /// # Returns
92    ///
93    /// - `ServerControlHookHandler<()>` - A default `ServerControlHookHandler<()>` instance.
94    #[inline(always)]
95    pub fn default_control_handler() -> ServerControlHookHandler<()> {
96        Arc::new(|| Box::pin(async {}))
97    }
98
99    /// Creates a default `ServerHookHandler` from a trait object.
100    ///
101    /// # Returns
102    ///
103    /// - `ServerHookHandler` - A default `ServerHookHandler` instance.
104    #[inline(always)]
105    pub fn default_handler() -> ServerHookHandler {
106        Arc::new(|_: &mut Stream, _: &mut Context| -> FutureBox<Status> {
107            Box::pin(async move { Status::default() })
108        })
109    }
110
111    /// Creates a new `ServerHookHandler` from a trait object.
112    ///
113    /// The hook implementation is chosen by the caller through the type
114    /// parameter `R`, so this function takes no runtime argument.
115    ///
116    /// # Returns
117    ///
118    /// - `ServerHookHandler` - A new `ServerHookHandler` instance.
119    #[inline(always)]
120    pub fn factory<R>() -> ServerHookHandler
121    where
122        R: ServerHook,
123    {
124        let key_slot: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
125        let guard: InlineHookGuard = InlineHookGuard {
126            key: Arc::clone(&key_slot),
127        };
128        let handler: ServerHookHandler = Arc::new(
129            move |stream: &mut Stream, ctx: &mut Context| -> FutureBox<Status> {
130                let _guard: &InlineHookGuard = &guard;
131                let ctx_address: usize = ctx.into();
132                let stream_address: usize = stream.into();
133                Box::pin(async move {
134                    let ctx: &mut Context = ctx_address.into();
135                    let stream: &mut Stream = stream_address.into();
136                    R::new(stream, ctx).await.handle(stream, ctx).await
137                })
138            },
139        );
140        let key: usize = Arc::as_ptr(&handler) as *const () as usize;
141        key_slot.store(key, AtomicOrdering::Relaxed);
142        register_inline_hook(key, inline_init_hook::<R>);
143        handler
144    }
145}
146
147/// Implements the `PartialEq` trait for `HookType`.
148///
149/// This allows for comparing two `HookType` instances for equality.
150/// Function pointers are compared using `std::ptr::fn_addr_eq` for reliable comparison.
151impl PartialEq for HookType {
152    /// Checks if two `HookType` instances are equal.
153    ///
154    /// # Arguments
155    ///
156    /// - `&Self` - The other `HookType` instance to compare against.
157    ///
158    /// # Returns
159    ///
160    /// - `bool` - `true` if the instances are equal, `false` otherwise.
161    #[inline(always)]
162    fn eq(&self, other: &Self) -> bool {
163        match (self, other) {
164            (HookType::TaskPanic(order1, factory1), HookType::TaskPanic(order2, factory2)) => {
165                order1 == order2 && ptr::fn_addr_eq(*factory1, *factory2)
166            }
167            (
168                HookType::RequestError(order1, factory1),
169                HookType::RequestError(order2, factory2),
170            ) => order1 == order2 && ptr::fn_addr_eq(*factory1, *factory2),
171            (
172                HookType::RequestMiddleware(order1, factory1),
173                HookType::RequestMiddleware(order2, factory2),
174            ) => order1 == order2 && ptr::fn_addr_eq(*factory1, *factory2),
175            (HookType::Route(path1, factory1), HookType::Route(path2, factory2)) => {
176                path1 == path2 && ptr::fn_addr_eq(*factory1, *factory2)
177            }
178            (
179                HookType::ResponseMiddleware(order1, factory1),
180                HookType::ResponseMiddleware(order2, factory2),
181            ) => order1 == order2 && ptr::fn_addr_eq(*factory1, *factory2),
182            _ => false,
183        }
184    }
185}
186
187/// Implements the `Eq` trait for `HookType`.
188///
189/// This indicates that `HookType` has a total equality relation.
190impl Eq for HookType {}
191
192/// Implements the `Hash` trait for `HookType`.
193///
194/// This allows `HookType` to be used as a key in hash-based collections.
195/// Function pointers are hashed using their addresses.
196impl Hash for HookType {
197    /// Hashes the `HookType` instance.
198    ///
199    /// # Arguments
200    ///
201    /// - `&mut H` - The hasher to use.
202    #[inline]
203    fn hash<H: Hasher>(&self, state: &mut H) {
204        match self {
205            HookType::TaskPanic(order, factory) => {
206                0u8.hash(state);
207                order.hash(state);
208                (factory as *const fn() -> ServerHookHandler).hash(state);
209            }
210            HookType::RequestError(order, factory) => {
211                1u8.hash(state);
212                order.hash(state);
213                (factory as *const fn() -> ServerHookHandler).hash(state);
214            }
215            HookType::RequestMiddleware(order, factory) => {
216                2u8.hash(state);
217                order.hash(state);
218                (factory as *const fn() -> ServerHookHandler).hash(state);
219            }
220            HookType::Route(path, factory) => {
221                3u8.hash(state);
222                path.hash(state);
223                (factory as *const fn() -> ServerHookHandler).hash(state);
224            }
225            HookType::ResponseMiddleware(order, factory) => {
226                4u8.hash(state);
227                order.hash(state);
228                (factory as *const fn() -> ServerHookHandler).hash(state);
229            }
230        }
231    }
232}
233
234/// Implementation block for `HookType`.
235///
236/// This block defines utility methods associated with the `HookType` enum.
237/// These methods provide additional functionality for working with hooks,
238/// such as extracting the execution order (priority) used in duplicate checks.
239impl HookType {
240    /// Returns the optional execution priority (`order`) of a hook.
241    ///
242    /// Hooks that carry an `order` indicate their execution priority.
243    /// Hooks without an `order` are considered unordered and are ignored in duplicate checks.
244    ///
245    /// # Returns
246    ///
247    /// - `Option<isize>` - `Some(order)` if the hook defines a priority, otherwise `None`.
248    #[inline(always)]
249    pub fn try_get_order(&self) -> Option<isize> {
250        match *self {
251            HookType::RequestMiddleware(order, _)
252            | HookType::ResponseMiddleware(order, _)
253            | HookType::TaskPanic(order, _)
254            | HookType::RequestError(order, _) => order,
255            _ => None,
256        }
257    }
258
259    /// Returns the hook factory carried by this `HookType`, when it has one.
260    ///
261    /// Route hooks store a pattern instead of a factory, so `None` is
262    /// returned for them.
263    ///
264    /// # Returns
265    ///
266    /// - `Option<ServerHookHandlerFactory>` - `Some(factory)` for the hook
267    ///   variants that carry one, otherwise `None`.
268    #[inline(always)]
269    pub fn try_get_hook(&self) -> Option<ServerHookHandlerFactory> {
270        match *self {
271            HookType::RequestMiddleware(_, hook)
272            | HookType::ResponseMiddleware(_, hook)
273            | HookType::TaskPanic(_, hook)
274            | HookType::RequestError(_, hook) => Some(hook),
275            _ => None,
276        }
277    }
278
279    /// Verifies that hooks with the same type and execution priority are unique.
280    ///
281    /// This function validates that no two hooks of the same type have identical
282    /// execution priorities (orders). Only hooks that define an explicit priority
283    /// (non-None order) are checked for uniqueness. Hooks without a priority are
284    /// ignored in duplicate detection.
285    ///
286    /// # Arguments
287    ///
288    /// - `Vec<HookType>` - A vector of `HookType` instances to validate for uniqueness.
289    ///
290    /// # Panics
291    ///
292    /// - Panics if duplicate hooks are detected with the same type and priority,
293    ///   displaying the hook type and order in the error message.
294    #[inline(always)]
295    pub fn assert_unique_order(list: Vec<HookType>) {
296        let mut seen: HashSet<(HookType, isize)> = HashSet::new();
297        list.iter().for_each(|hook: &HookType| {
298            if let Some(order) = hook.try_get_order()
299                && !seen.insert((*hook, order))
300            {
301                panic!("Duplicate hook detected: {} with order {}", hook, order);
302            }
303        });
304    }
305}
306
307/// Implements `ServerHook` for `DefaultServerHook`
308///
309/// This implementation provides default no-op handlers for server hook operations.
310impl ServerHook for DefaultServerHook {
311    /// Creates a new `DefaultServerHook` instance.
312    ///
313    /// # Arguments
314    ///
315    /// - `&mut Stream` - The stream object providing server configuration and state
316    /// - `&mut Context` - The context object providing server configuration and state
317    ///
318    /// # Returns
319    ///
320    /// - `Self` - A new instance of `DefaultServerHook`
321    async fn new(_: &mut Stream, _: &mut Context) -> Self {
322        Self
323    }
324
325    /// Handles server hook operations with a no-op implementation.
326    ///
327    /// # Arguments
328    ///
329    /// - `&mut Stream` - The stream object providing server configuration and state
330    /// - `&mut Context` - The context object providing server configuration and state
331    ///
332    /// # Returns
333    ///
334    /// - `Status` - `Status::Reject` by default, indicating the pipeline should be aborted.
335    async fn handle(self, _: &mut Stream, _: &mut Context) -> Status {
336        Status::default()
337    }
338}