1use std::sync::Arc;
3
4pub const GATEWAY_REQUEST_ID_HEADER: &str = "X-Acosmi-Request-Id";
7pub type UpstreamActivityCallback = Arc<dyn Fn() + Send + Sync>;
8pub type GatewayRequestIDCallback = Arc<dyn Fn(&str) + Send + Sync>;
9
10#[derive(Clone, Default)]
20pub struct ChatOptions {
21 pub on_upstream_activity: Option<UpstreamActivityCallback>,
22 pub on_gateway_request_id: Option<GatewayRequestIDCallback>,
23}
24
25pub fn read_gateway_request_id(headers: &http::header::HeaderMap) -> Option<&str> {
29 let mut values = headers.get_all(GATEWAY_REQUEST_ID_HEADER).iter();
30 let value = values.next()?.to_str().ok()?.trim();
31 if values.next().is_some()
32 || value.is_empty()
33 || value.len() > 256
34 || !value
35 .bytes()
36 .all(|b| b.is_ascii_alphanumeric() || b"-_.:".contains(&b))
37 {
38 return None;
39 }
40 Some(value)
41}
42
43impl ChatOptions {
44 pub(crate) fn activity(&mut self) {
45 if let Some(callback) = self.on_upstream_activity.take() {
46 if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback())).is_ok() {
47 self.on_upstream_activity = Some(callback);
48 }
49 }
50 }
51
52 pub(crate) fn response(&mut self, headers: &http::header::HeaderMap) {
53 if let (Some(callback), Some(id)) = (
54 self.on_gateway_request_id.take(),
55 read_gateway_request_id(headers),
56 ) {
57 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback(id)));
58 }
59 }
60}