Skip to main content

vantage_table/
write_context.rs

1//! Who is making a write, carried to the table's lifecycle hooks.
2//!
3//! A host (an API server handling a request, a desktop app acting for its
4//! user) wraps the work in [`WriteContext::scope`]; every write awaited inside
5//! it hands the context to its hooks through their `context` field. Vantage
6//! doesn't interpret it: `principal` is whatever record the host identifies the
7//! actor with, and `group` ties together everything one request or action run
8//! caused.
9
10use std::fmt;
11use std::future::Future;
12use std::net::IpAddr;
13
14use indexmap::IndexMap;
15
16tokio::task_local! {
17    static CONTEXT: WriteContext;
18}
19
20/// Built with [`WriteContext::new`] and the `with_*` builders, so a field
21/// added later (request data, say) doesn't break existing hosts.
22#[derive(Clone, Debug, Default, PartialEq)]
23#[non_exhaustive]
24pub struct WriteContext {
25    /// The actor, as a CBOR map (name plus attributes).
26    pub principal: Option<ciborium::Value>,
27    /// Shared by every write one request or action run causes.
28    pub group: Option<String>,
29    /// The request the write came in on, filled by the host at its entry point.
30    pub request: Option<RequestContext>,
31}
32
33impl WriteContext {
34    /// An empty context: no principal, no group.
35    pub fn new() -> Self {
36        Self::default()
37    }
38
39    pub fn with_principal(mut self, principal: ciborium::Value) -> Self {
40        self.principal = Some(principal);
41        self
42    }
43
44    pub fn with_group(mut self, group: impl Into<String>) -> Self {
45        self.group = Some(group.into());
46        self
47    }
48
49    pub fn with_request(mut self, request: RequestContext) -> Self {
50        self.request = Some(request);
51        self
52    }
53
54    /// Run `fut` with this context in scope.
55    pub async fn scope<F: Future>(self, fut: F) -> F::Output {
56        CONTEXT.scope(self, fut).await
57    }
58
59    /// The context in scope for the current task, if any.
60    pub fn current() -> Option<WriteContext> {
61        CONTEXT.try_with(|c| c.clone()).ok()
62    }
63}
64
65/// Headers a host may copy into a [`RequestContext`]. Lowercase names. The
66/// host enforces it: [`RequestContext::with_header`] stores whatever it is
67/// given.
68pub const REQUEST_HEADER_ALLOW_LIST: &[&str] = &[
69    "user-agent",
70    "referer",
71    "accept-language",
72    "x-posthog-distinct-id",
73    "x-posthog-session-id",
74];
75
76/// The entry point a write came in through.
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78#[non_exhaustive]
79pub enum Transport {
80    Ws,
81    Rest,
82    Mcp,
83    Internal,
84}
85
86impl Transport {
87    pub fn as_str(&self) -> &'static str {
88        match self {
89            Transport::Ws => "ws",
90            Transport::Rest => "rest",
91            Transport::Mcp => "mcp",
92            Transport::Internal => "internal",
93        }
94    }
95}
96
97/// What the host saw of the request a write came in on. Built with
98/// [`RequestContext::new`] and the `with_*` builders. `Debug` shows cookie
99/// names only: their values are session credentials.
100#[derive(Clone, PartialEq)]
101#[non_exhaustive]
102pub struct RequestContext {
103    pub transport: Transport,
104    pub ip: Option<IpAddr>,
105    /// Keys are stored lowercase, so [`RequestContext::header`] ignores case.
106    pub headers: IndexMap<String, String>,
107    pub cookies: IndexMap<String, String>,
108}
109
110impl fmt::Debug for RequestContext {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        // Values stay out: a cookie is a session, a referer can carry a token.
113        let masked = |map: &IndexMap<String, String>| -> Vec<String> {
114            map.keys().map(|name| format!("{name}=***")).collect()
115        };
116        f.debug_struct("RequestContext")
117            .field("transport", &self.transport)
118            .field("ip", &self.ip)
119            .field("headers", &masked(&self.headers))
120            .field("cookies", &masked(&self.cookies))
121            .finish()
122    }
123}
124
125impl RequestContext {
126    pub fn new(transport: Transport) -> Self {
127        Self {
128            transport,
129            ip: None,
130            headers: IndexMap::new(),
131            cookies: IndexMap::new(),
132        }
133    }
134
135    pub fn with_ip(mut self, ip: IpAddr) -> Self {
136        self.ip = Some(ip);
137        self
138    }
139
140    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
141        self.headers
142            .insert(name.into().to_ascii_lowercase(), value.into());
143        self
144    }
145
146    pub fn with_cookie(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
147        self.cookies.insert(name.into(), value.into());
148        self
149    }
150
151    /// The header's value; the name is matched case-insensitively.
152    pub fn header(&self, name: &str) -> Option<&str> {
153        self.headers
154            .get(&name.to_ascii_lowercase())
155            .map(String::as_str)
156    }
157
158    /// The cookie's value; the name must match exactly, as cookie names are
159    /// case-sensitive (RFC 6265).
160    pub fn cookie(&self, name: &str) -> Option<&str> {
161        self.cookies.get(name).map(String::as_str)
162    }
163}