Skip to main content

greentic_types/
session.rs

1//! Session identity and cursor helpers.
2
3use alloc::borrow::ToOwned;
4use alloc::string::String;
5
6#[cfg(feature = "schemars")]
7use schemars::JsonSchema;
8#[cfg(feature = "serde")]
9use serde::{Deserialize, Serialize};
10
11use crate::{FlowId, PackId, TenantCtx};
12
13use sha2::{Digest, Sha256};
14
15/// Unique key referencing a persisted session.
16#[derive(Clone, Debug, PartialEq, Eq, Hash)]
17#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
18#[cfg_attr(feature = "schemars", derive(JsonSchema))]
19#[cfg_attr(feature = "serde", serde(transparent))]
20pub struct SessionKey(pub String);
21
22impl SessionKey {
23    /// Returns the session key as a string slice.
24    pub fn as_str(&self) -> &str {
25        &self.0
26    }
27
28    /// Creates a new session key from the supplied string.
29    pub fn new(value: impl Into<String>) -> Self {
30        Self(value.into())
31    }
32
33    /// Generates a random session key using [`uuid`], when enabled.
34    #[cfg(feature = "uuid")]
35    pub fn generate() -> Self {
36        Self(uuid::Uuid::new_v4().to_string())
37    }
38}
39
40impl From<String> for SessionKey {
41    fn from(value: String) -> Self {
42        Self(value)
43    }
44}
45
46impl From<&str> for SessionKey {
47    fn from(value: &str) -> Self {
48        Self(value.to_owned())
49    }
50}
51
52impl core::fmt::Display for SessionKey {
53    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
54        f.write_str(self.as_str())
55    }
56}
57
58#[cfg(feature = "uuid")]
59impl From<uuid::Uuid> for SessionKey {
60    fn from(value: uuid::Uuid) -> Self {
61        Self(value.to_string())
62    }
63}
64
65const DEFAULT_CANONICAL_ANCHOR: &str = "conversation";
66const DEFAULT_CANONICAL_USER: &str = "user";
67
68/// Build the canonical `{tenant}:{provider}:{anchor}:{user}` session key.
69///
70/// All canonical adapters are expected to follow this format so pause/resume semantics remain
71/// deterministic across ingress providers. The anchor defaults to `conversation` and the user
72/// defaults to `user` when those fields are not supplied.
73pub fn canonical_session_key(
74    tenant: impl AsRef<str>,
75    provider: impl AsRef<str>,
76    anchor: Option<&str>,
77    user: Option<&str>,
78) -> SessionKey {
79    SessionKey::new(format!(
80        "{}:{}:{}:{}",
81        tenant.as_ref(),
82        provider.as_ref(),
83        anchor.unwrap_or(DEFAULT_CANONICAL_ANCHOR),
84        user.unwrap_or(DEFAULT_CANONICAL_USER)
85    ))
86}
87
88/// Cursor pointing at a session's position in a flow graph.
89#[derive(Clone, Debug, PartialEq, Eq, Hash)]
90#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
91#[cfg_attr(feature = "schemars", derive(JsonSchema))]
92pub struct SessionCursor {
93    /// Identifier of the node currently owning the session.
94    pub node_pointer: String,
95    /// Optional wait reason emitted by the node.
96    #[cfg_attr(
97        feature = "serde",
98        serde(default, skip_serializing_if = "Option::is_none")
99    )]
100    pub wait_reason: Option<String>,
101    /// Optional marker describing pending outbox operations.
102    #[cfg_attr(
103        feature = "serde",
104        serde(default, skip_serializing_if = "Option::is_none")
105    )]
106    pub outbox_marker: Option<String>,
107}
108
109impl SessionCursor {
110    /// Creates a new cursor pointing at the provided node identifier.
111    pub fn new(node_pointer: impl Into<String>) -> Self {
112        Self {
113            node_pointer: node_pointer.into(),
114            wait_reason: None,
115            outbox_marker: None,
116        }
117    }
118
119    /// Assigns a wait reason to the cursor.
120    pub fn with_wait_reason(mut self, reason: impl Into<String>) -> Self {
121        self.wait_reason = Some(reason.into());
122        self
123    }
124
125    /// Assigns an outbox marker to the cursor.
126    pub fn with_outbox_marker(mut self, marker: impl Into<String>) -> Self {
127        self.outbox_marker = Some(marker.into());
128        self
129    }
130}
131
132/// Persisted session payload describing how to resume a flow.
133#[derive(Clone, Debug, PartialEq, Eq)]
134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
135#[cfg_attr(feature = "schemars", derive(JsonSchema))]
136pub struct SessionData {
137    /// Tenant context associated with the session.
138    pub tenant_ctx: TenantCtx,
139    /// Flow identifier being executed.
140    pub flow_id: FlowId,
141    /// Optional pack identifier tied to the session.
142    #[cfg_attr(
143        feature = "serde",
144        serde(default, skip_serializing_if = "Option::is_none")
145    )]
146    pub pack_id: Option<PackId>,
147    /// Cursor pinpointing where execution paused.
148    pub cursor: SessionCursor,
149    /// Serialized execution context/state snapshot.
150    pub context_json: String,
151}
152
153/// Stable scope describing where a wait is anchored (conversation/thread/reply).
154#[derive(Clone, Debug, PartialEq, Eq, Hash)]
155#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
156#[cfg_attr(feature = "schemars", derive(JsonSchema))]
157pub struct WaitScope {
158    /// Provider identifier (telegram, msgraph, webchat, etc).
159    pub provider_id: String,
160    /// Conversation or chat identifier.
161    pub conversation_id: String,
162    /// Optional thread/topic identifier.
163    #[cfg_attr(
164        feature = "serde",
165        serde(default, skip_serializing_if = "Option::is_none")
166    )]
167    pub thread_id: Option<String>,
168    /// Optional reply-to identifier.
169    #[cfg_attr(
170        feature = "serde",
171        serde(default, skip_serializing_if = "Option::is_none")
172    )]
173    pub reply_to_id: Option<String>,
174    /// Optional correlation identifier.
175    #[cfg_attr(
176        feature = "serde",
177        serde(default, skip_serializing_if = "Option::is_none")
178    )]
179    pub correlation_id: Option<String>,
180}
181
182impl WaitScope {
183    /// Returns a deterministic hash for the scope.
184    pub fn scope_hash(&self) -> String {
185        let mut canonical = String::new();
186        let _ = core::fmt::write(
187            &mut canonical,
188            format_args!(
189                "provider_id={}|conversation_id={}|thread_id={}|reply_to_id={}|correlation_id={}",
190                self.provider_id,
191                self.conversation_id,
192                self.thread_id.as_deref().unwrap_or(""),
193                self.reply_to_id.as_deref().unwrap_or(""),
194                self.correlation_id.as_deref().unwrap_or("")
195            ),
196        );
197
198        let digest = Sha256::digest(canonical.as_bytes());
199        hex_encode(digest.as_slice())
200    }
201}
202
203fn hex_encode(bytes: &[u8]) -> String {
204    const HEX: &[u8; 16] = b"0123456789abcdef";
205    let mut out = String::with_capacity(bytes.len() * 2);
206    for &byte in bytes {
207        out.push(HEX[(byte >> 4) as usize] as char);
208        out.push(HEX[(byte & 0x0f) as usize] as char);
209    }
210    out
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[cfg(feature = "serde")]
218    use serde_json::Value;
219
220    #[test]
221    fn canonical_session_key_includes_components() {
222        let key = canonical_session_key("tenant", "webhook", Some("room-1"), Some("user-5"));
223        assert_eq!(key.as_str(), "tenant:webhook:room-1:user-5");
224    }
225
226    #[test]
227    fn canonical_session_key_defaults_anchor_and_user() {
228        let key = canonical_session_key("tenant", "webhook", None, None);
229        assert_eq!(key.as_str(), "tenant:webhook:conversation:user");
230    }
231
232    #[test]
233    fn wait_scope_hash_is_deterministic() {
234        let scope = WaitScope {
235            provider_id: "telegram".to_owned(),
236            conversation_id: "chat-1".to_owned(),
237            thread_id: Some("topic-9".to_owned()),
238            reply_to_id: Some("msg-3".to_owned()),
239            correlation_id: Some("cid-7".to_owned()),
240        };
241
242        assert_eq!(
243            scope.scope_hash(),
244            "53ef85dad25d5836477a5e6a11cd13527c45163bd82de3bd1fd524dbf7d826d6"
245        );
246    }
247
248    #[test]
249    fn wait_scope_hash_changes_with_fields() {
250        let base = WaitScope {
251            provider_id: "telegram".to_owned(),
252            conversation_id: "chat-1".to_owned(),
253            thread_id: Some("topic-9".to_owned()),
254            reply_to_id: Some("msg-3".to_owned()),
255            correlation_id: Some("cid-7".to_owned()),
256        };
257
258        let mut altered = base.clone();
259        altered.reply_to_id = Some("msg-4".to_owned());
260
261        assert_ne!(base.scope_hash(), altered.scope_hash());
262    }
263
264    #[cfg(feature = "serde")]
265    #[test]
266    fn session_data_pack_id_is_optional() {
267        let data = SessionData {
268            tenant_ctx: TenantCtx::new(
269                "env"
270                    .parse()
271                    .unwrap_or_else(|err| panic!("parse env failed: {err}")),
272                "tenant"
273                    .parse()
274                    .unwrap_or_else(|err| panic!("parse tenant failed: {err}")),
275            ),
276            flow_id: "flow-1"
277                .parse()
278                .unwrap_or_else(|err| panic!("parse flow failed: {err}")),
279            pack_id: None,
280            cursor: SessionCursor::new("node-1"),
281            context_json: "{}".to_owned(),
282        };
283
284        let value = serde_json::to_value(&data)
285            .unwrap_or_else(|err| panic!("serialize session failed: {err}"));
286        assert!(
287            value.get("pack_id").is_none(),
288            "pack_id should be omitted when None"
289        );
290
291        let mut data_with_pack = data.clone();
292        data_with_pack.pack_id = Some(
293            "greentic.demo.pack"
294                .parse()
295                .unwrap_or_else(|err| panic!("parse pack id failed: {err}")),
296        );
297
298        let value = serde_json::to_value(&data_with_pack)
299            .unwrap_or_else(|err| panic!("serialize session failed: {err}"));
300        assert!(value.get("pack_id").is_some());
301
302        let object = value
303            .as_object()
304            .cloned()
305            .unwrap_or_else(|| panic!("expected session value to be a JSON object"));
306        let roundtrip: SessionData = serde_json::from_value(Value::Object(object))
307            .unwrap_or_else(|err| panic!("deserialize session failed: {err}"));
308        assert_eq!(roundtrip.pack_id, data_with_pack.pack_id);
309    }
310}