use std::fmt;
use std::future::Future;
use std::net::IpAddr;
use indexmap::IndexMap;
tokio::task_local! {
static CONTEXT: WriteContext;
}
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct WriteContext {
pub principal: Option<ciborium::Value>,
pub group: Option<String>,
pub request: Option<RequestContext>,
}
impl WriteContext {
pub fn new() -> Self {
Self::default()
}
pub fn with_principal(mut self, principal: ciborium::Value) -> Self {
self.principal = Some(principal);
self
}
pub fn with_group(mut self, group: impl Into<String>) -> Self {
self.group = Some(group.into());
self
}
pub fn with_request(mut self, request: RequestContext) -> Self {
self.request = Some(request);
self
}
pub async fn scope<F: Future>(self, fut: F) -> F::Output {
CONTEXT.scope(self, fut).await
}
pub fn current() -> Option<WriteContext> {
CONTEXT.try_with(|c| c.clone()).ok()
}
}
pub const REQUEST_HEADER_ALLOW_LIST: &[&str] = &[
"user-agent",
"referer",
"accept-language",
"x-posthog-distinct-id",
"x-posthog-session-id",
];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Transport {
Ws,
Rest,
Mcp,
Internal,
}
impl Transport {
pub fn as_str(&self) -> &'static str {
match self {
Transport::Ws => "ws",
Transport::Rest => "rest",
Transport::Mcp => "mcp",
Transport::Internal => "internal",
}
}
}
#[derive(Clone, PartialEq)]
#[non_exhaustive]
pub struct RequestContext {
pub transport: Transport,
pub ip: Option<IpAddr>,
pub headers: IndexMap<String, String>,
pub cookies: IndexMap<String, String>,
}
impl fmt::Debug for RequestContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let masked = |map: &IndexMap<String, String>| -> Vec<String> {
map.keys().map(|name| format!("{name}=***")).collect()
};
f.debug_struct("RequestContext")
.field("transport", &self.transport)
.field("ip", &self.ip)
.field("headers", &masked(&self.headers))
.field("cookies", &masked(&self.cookies))
.finish()
}
}
impl RequestContext {
pub fn new(transport: Transport) -> Self {
Self {
transport,
ip: None,
headers: IndexMap::new(),
cookies: IndexMap::new(),
}
}
pub fn with_ip(mut self, ip: IpAddr) -> Self {
self.ip = Some(ip);
self
}
pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers
.insert(name.into().to_ascii_lowercase(), value.into());
self
}
pub fn with_cookie(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.cookies.insert(name.into(), value.into());
self
}
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.get(&name.to_ascii_lowercase())
.map(String::as_str)
}
pub fn cookie(&self, name: &str) -> Option<&str> {
self.cookies.get(name).map(String::as_str)
}
}