systemprompt_identifiers/
session.rs1use 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 generate() -> Self {
20 Self(format!("sess_{}", uuid::Uuid::new_v4()))
21 }
22
23 pub fn system() -> Self {
24 Self("system".to_string())
25 }
26
27 pub fn as_str(&self) -> &str {
28 &self.0
29 }
30}
31
32impl fmt::Display for SessionId {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 write!(f, "{}", self.0)
35 }
36}
37
38impl From<String> for SessionId {
39 fn from(s: String) -> Self {
40 Self(s)
41 }
42}
43
44impl From<&str> for SessionId {
45 fn from(s: &str) -> Self {
46 Self(s.to_string())
47 }
48}
49
50impl AsRef<str> for SessionId {
51 fn as_ref(&self) -> &str {
52 &self.0
53 }
54}
55
56impl ToDbValue for SessionId {
57 fn to_db_value(&self) -> DbValue {
58 DbValue::String(self.0.clone())
59 }
60}
61
62impl ToDbValue for &SessionId {
63 fn to_db_value(&self) -> DbValue {
64 DbValue::String(self.0.clone())
65 }
66}
67
68#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
69#[serde(rename_all = "lowercase")]
70pub enum SessionSource {
71 Web,
72 Api,
73 Cli,
74 Tui,
75 Oauth,
76 #[default]
77 Unknown,
78}
79
80impl SessionSource {
81 pub const fn as_str(self) -> &'static str {
82 match self {
83 Self::Web => "web",
84 Self::Api => "api",
85 Self::Cli => "cli",
86 Self::Tui => "tui",
87 Self::Oauth => "oauth",
88 Self::Unknown => "unknown",
89 }
90 }
91
92 pub fn from_client_id(client_id: &str) -> Self {
93 match client_id {
94 "sp_web" => Self::Web,
95 "sp_cli" => Self::Cli,
96 "sp_tui" => Self::Tui,
97 _ => Self::Unknown,
98 }
99 }
100}
101
102impl fmt::Display for SessionSource {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 write!(f, "{}", self.as_str())
105 }
106}
107
108impl std::str::FromStr for SessionSource {
109 type Err = std::convert::Infallible;
110
111 fn from_str(s: &str) -> Result<Self, Self::Err> {
112 Ok(match s.to_lowercase().as_str() {
113 "web" => Self::Web,
114 "api" => Self::Api,
115 "cli" => Self::Cli,
116 "tui" => Self::Tui,
117 "oauth" => Self::Oauth,
118 _ => Self::Unknown,
119 })
120 }
121}