Skip to main content

hooksmith_core/
sender.rs

1use std::future::Future;
2
3/// Common interface implemented by every hooksmith webhook client.
4///
5/// Each service crate defines its own [`Message`](WebhookSender::Message) and
6/// [`Error`](WebhookSender::Error) types and implements this trait.  Application
7/// code can then be generic over the notification backend:
8///
9/// ```rust,ignore
10/// use hooksmith_core::WebhookSender;
11///
12/// async fn notify<S>(sender: &S, msg: &S::Message) -> Result<(), S::Error>
13/// where
14///     S: WebhookSender,
15/// {
16///     sender.send(msg).await
17/// }
18/// ```
19pub trait WebhookSender {
20    /// The message type accepted by this sender.
21    type Message;
22
23    /// The error type returned on failure.
24    type Error: std::error::Error;
25
26    /// Send a single message to the configured webhook endpoint.
27    fn send(&self, message: &Self::Message)
28    -> impl Future<Output = Result<(), Self::Error>> + Send;
29
30    /// Send multiple messages sequentially, collecting one `Result` per message
31    /// in the same order as the input slice.
32    /// A failure for one message does **not** abort the others.
33    ///
34    /// # Example
35    ///
36    /// ```rust,ignore
37    /// let results = sender.send_batch(&[&msg_a, &msg_b, &msg_c]).await;
38    /// for result in results {
39    ///     result?;
40    /// }
41    /// ```
42    fn send_batch<'a>(
43        &'a self,
44        messages: &'a [&'a Self::Message],
45    ) -> impl Future<Output = Vec<Result<(), Self::Error>>> + Send + 'a
46    where
47        Self: Sync,
48        Self::Error: Send,
49    {
50        // Build the futures outside the async block so the slice iterator is
51        // not captured (which would require Self::Message: Sync).
52        let futs: Vec<_> = messages.iter().copied().map(|m| self.send(m)).collect();
53        async move {
54            let mut results = Vec::with_capacity(futs.len());
55            for fut in futs {
56                results.push(fut.await);
57            }
58            results
59        }
60    }
61}