systemprompt_identifiers/
session.rs

1//! Session identifier type.
2
3use crate::{DbValue, ToDbValue};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use std::fmt;
7
8#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
9#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
10#[cfg_attr(feature = "sqlx", sqlx(transparent))]
11#[serde(transparent)]
12pub struct SessionId(String);
13
14impl SessionId {
15    pub fn new(id: impl Into<String>) -> Self {
16        Self(id.into())
17    }
18
19    pub fn system() -> Self {
20        Self("system".to_string())
21    }
22
23    pub fn as_str(&self) -> &str {
24        &self.0
25    }
26}
27
28impl fmt::Display for SessionId {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        write!(f, "{}", self.0)
31    }
32}
33
34impl From<String> for SessionId {
35    fn from(s: String) -> Self {
36        Self(s)
37    }
38}
39
40impl From<&str> for SessionId {
41    fn from(s: &str) -> Self {
42        Self(s.to_string())
43    }
44}
45
46impl AsRef<str> for SessionId {
47    fn as_ref(&self) -> &str {
48        &self.0
49    }
50}
51
52impl ToDbValue for SessionId {
53    fn to_db_value(&self) -> DbValue {
54        DbValue::String(self.0.clone())
55    }
56}
57
58impl ToDbValue for &SessionId {
59    fn to_db_value(&self) -> DbValue {
60        DbValue::String(self.0.clone())
61    }
62}
63
64#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
65#[serde(rename_all = "lowercase")]
66pub enum SessionSource {
67    Web,
68    Api,
69    Cli,
70    Tui,
71    Oauth,
72    #[default]
73    Unknown,
74}
75
76impl SessionSource {
77    pub const fn as_str(self) -> &'static str {
78        match self {
79            Self::Web => "web",
80            Self::Api => "api",
81            Self::Cli => "cli",
82            Self::Tui => "tui",
83            Self::Oauth => "oauth",
84            Self::Unknown => "unknown",
85        }
86    }
87
88    pub fn from_client_id(client_id: &str) -> Self {
89        match client_id {
90            "sp_web" => Self::Web,
91            "sp_cli" => Self::Cli,
92            "sp_tui" => Self::Tui,
93            _ => Self::Unknown,
94        }
95    }
96}
97
98impl fmt::Display for SessionSource {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        write!(f, "{}", self.as_str())
101    }
102}
103
104impl std::str::FromStr for SessionSource {
105    type Err = std::convert::Infallible;
106
107    fn from_str(s: &str) -> Result<Self, Self::Err> {
108        Ok(match s.to_lowercase().as_str() {
109            "web" => Self::Web,
110            "api" => Self::Api,
111            "cli" => Self::Cli,
112            "tui" => Self::Tui,
113            "oauth" => Self::Oauth,
114            _ => Self::Unknown,
115        })
116    }
117}