#![cfg_attr(
feature = "sse",
doc = "[`sse::SseFormatter`] is the one every AG-UI implementation supports."
)]
#![cfg_attr(
not(feature = "sse"),
doc = "`sse::SseFormatter` is the one every AG-UI implementation supports, and the",
doc = "`sse` feature is off in this build."
)]
#[cfg(feature = "protobuf")]
pub mod protobuf;
#[cfg(feature = "sse")]
pub mod sse;
use crate::error::{Error, Result};
use crate::event::Event;
pub const SSE_MEDIA_TYPE: &str = "text/event-stream";
pub const PROTOBUF_MEDIA_TYPE: &str = "application/vnd.ag-ui.event+proto";
#[cfg(feature = "sse")]
const SUPPORTED: &[&str] = &[SSE_MEDIA_TYPE];
#[cfg(not(feature = "sse"))]
const SUPPORTED: &[&str] = &[];
pub trait EventStreamFormatter {
fn content_type(&self) -> &'static str;
fn encode(&self, event: &Event) -> Result<Vec<u8>>;
}
pub const fn supported_media_types() -> &'static [&'static str] {
SUPPORTED
}
pub fn media_type(accept: Option<&str>) -> Result<&'static str> {
let header = accept
.map(str::trim)
.filter(|value| !value.is_empty())
.unwrap_or("*/*");
let specs: Vec<AcceptSpec<'_>> = header.split(',').filter_map(AcceptSpec::parse).collect();
let mut best: Option<(&'static str, f32)> = None;
for candidate in SUPPORTED {
let quality = quality_of(candidate, &specs);
if quality > 0.0 && best.is_none_or(|(_, best_quality)| quality > best_quality) {
best = Some((candidate, quality));
}
}
best.map(|(media_type, _)| media_type)
.ok_or_else(|| Error::UnsupportedMediaType(header.to_owned()))
}
struct AcceptSpec<'a> {
kind: &'a str,
subtype: &'a str,
quality: f32,
}
impl<'a> AcceptSpec<'a> {
fn parse(entry: &'a str) -> Option<Self> {
let mut parts = entry.split(';');
let (kind, subtype) = split_media_type(parts.next()?.trim())?;
let quality = parts
.find_map(|param| {
let (key, value) = param.split_once('=')?;
key.trim().eq_ignore_ascii_case("q").then_some(value)
})
.and_then(|value| value.trim().trim_matches('"').parse::<f32>().ok())
.unwrap_or(1.0);
Some(Self {
kind,
subtype,
quality,
})
}
fn specificity(&self, kind: &str, subtype: &str) -> Option<u8> {
let mut score = 0;
if self.kind.eq_ignore_ascii_case(kind) {
score |= 4;
} else if self.kind != "*" {
return None;
}
if self.subtype.eq_ignore_ascii_case(subtype) {
score |= 2;
} else if self.subtype != "*" {
return None;
}
Some(score)
}
}
fn quality_of(candidate: &str, specs: &[AcceptSpec<'_>]) -> f32 {
let Some((kind, subtype)) = split_media_type(candidate) else {
return 0.0;
};
let mut best: Option<(u8, f32)> = None;
for spec in specs {
let Some(specificity) = spec.specificity(kind, subtype) else {
continue;
};
if best.is_none_or(|(best_specificity, _)| specificity > best_specificity) {
best = Some((specificity, spec.quality));
}
}
best.map_or(0.0, |(_, quality)| quality)
}
fn split_media_type(value: &str) -> Option<(&str, &str)> {
let value = value.split(';').next()?.trim();
let (kind, subtype) = value.split_once('/')?;
(!kind.is_empty() && !subtype.is_empty()).then_some((kind, subtype))
}