use crate::PlainEventSource;
#[cfg(target_arch = "wasm32")]
use crate::tokio;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventInjectorError {
Full,
Closed,
}
impl std::fmt::Display for EventInjectorError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Full => write!(f, "inbox full"),
Self::Closed => write!(f, "inbox closed"),
}
}
}
impl std::error::Error for EventInjectorError {}
pub trait EventInjector: Send + Sync {
fn inject(&self, body: String, source: PlainEventSource) -> Result<(), EventInjectorError>;
}
pub struct InteractionSubscription {
pub id: crate::interaction::InteractionId,
pub events: tokio::sync::mpsc::Receiver<crate::event::AgentEvent>,
}
pub trait SubscribableInjector: EventInjector {
fn inject_with_subscription(
&self,
body: String,
source: PlainEventSource,
) -> Result<InteractionSubscription, EventInjectorError>;
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::Mutex;
struct MockEventInjector {
events: Mutex<Vec<(String, PlainEventSource)>>,
}
impl MockEventInjector {
fn new() -> Self {
Self {
events: Mutex::new(Vec::new()),
}
}
}
impl EventInjector for MockEventInjector {
fn inject(&self, body: String, source: PlainEventSource) -> Result<(), EventInjectorError> {
self.events.lock().unwrap().push((body, source));
Ok(())
}
}
#[test]
fn test_event_injector_trait_compiles() {
let injector = MockEventInjector::new();
injector
.inject("hello".to_string(), PlainEventSource::Tcp)
.unwrap();
let events = injector.events.lock().unwrap();
assert_eq!(events.len(), 1);
assert_eq!(events[0].0, "hello");
assert_eq!(events[0].1, PlainEventSource::Tcp);
}
#[test]
fn test_event_injector_as_dyn_trait() {
let injector: Arc<dyn EventInjector> = Arc::new(MockEventInjector::new());
injector
.inject("test".to_string(), PlainEventSource::Webhook)
.unwrap();
}
#[test]
fn test_event_injector_error_display() {
assert_eq!(EventInjectorError::Full.to_string(), "inbox full");
assert_eq!(EventInjectorError::Closed.to_string(), "inbox closed");
}
}