use crate::error::{LiterLlmError, Result};
pub const SSE_BUFFER_MAX_BYTES: usize = 1024 * 1024;
pub const EVENT_STREAM_BUFFER_MAX_BYTES: usize = 16 * 1024 * 1024;
pub const RESPONSE_BODY_MAX_BYTES: usize = 32 * 1024 * 1024;
pub const CHUNK_ACCUMULATION_MAX_BYTES: usize = RESPONSE_BODY_MAX_BYTES;
pub fn check_bound(context: &str, current_len: usize, incoming: usize, limit: usize) -> Result<()> {
if current_len.saturating_add(incoming) > limit {
#[cfg(feature = "tracing")]
tracing::warn!(
context,
current_len,
incoming,
limit,
"buffer limit exceeded; aborting stream"
);
return Err(LiterLlmError::Streaming {
message: format!("{context} buffer exceeded {limit} bytes; aborting"),
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn check_bound_passes_when_within_limit() {
assert!(check_bound("test", 100, 50, 200).is_ok());
}
#[test]
fn check_bound_passes_at_exact_limit() {
assert!(check_bound("test", 100, 100, 200).is_ok());
}
#[test]
fn check_bound_fails_when_exceeds_limit() {
let err = check_bound("test ctx", 100, 101, 200).unwrap_err();
assert!(err.to_string().contains("test ctx"));
assert!(err.to_string().contains("200"));
}
#[test]
fn check_bound_saturating_add_does_not_overflow() {
let err = check_bound("overflow", usize::MAX, 1, 1024).unwrap_err();
assert!(err.to_string().contains("overflow"));
}
#[test]
fn sse_constant_is_one_mib() {
assert_eq!(SSE_BUFFER_MAX_BYTES, 1024 * 1024);
}
#[test]
fn event_stream_constant_is_sixteen_mib() {
assert_eq!(EVENT_STREAM_BUFFER_MAX_BYTES, 16 * 1024 * 1024);
}
#[test]
fn response_body_constant_is_thirty_two_mib() {
assert_eq!(RESPONSE_BODY_MAX_BYTES, 32 * 1024 * 1024);
}
}