use std::fmt;
use std::str::FromStr;
use std::sync::Arc;
use anyhow::Result;
use chrono::Utc;
use revision::revisioned;
use serde::{Deserialize, Serialize};
use surrealdb_types::ToSql;
use uuid::Uuid;
use crate::iam::{Auth, Level, Role};
use crate::kvs::impl_kv_value_revisioned;
use crate::types::{PublicValue, PublicVariables};
use crate::val::{Object, Value};
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct Session {
pub au: Arc<Auth>,
pub rt: bool,
pub ip: Option<String>,
pub or: Option<String>,
pub id: Option<Uuid>,
pub ns: Option<String>,
pub db: Option<String>,
pub ac: Option<String>,
pub tk: Option<PublicValue>,
pub rd: Option<PublicValue>,
pub exp: Option<i64>,
pub variables: PublicVariables,
pub new_planner_strategy: NewPlannerStrategy,
pub redact_volatile_explain_attrs: bool,
}
#[revisioned(revision = 1)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub enum NewPlannerStrategy {
#[default]
BestEffortReadOnlyStatements,
ComputeOnly,
AllReadOnlyStatements,
}
impl fmt::Display for NewPlannerStrategy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::BestEffortReadOnlyStatements => f.write_str("best-effort"),
Self::ComputeOnly => f.write_str("compute-only"),
Self::AllReadOnlyStatements => f.write_str("all-read-only"),
}
}
}
impl FromStr for NewPlannerStrategy {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"best-effort" => Ok(Self::BestEffortReadOnlyStatements),
"compute-only" => Ok(Self::ComputeOnly),
"all-read-only" => Ok(Self::AllReadOnlyStatements),
_ => Err(format!(
"unknown planner strategy: '{s}' (expected 'best-effort', 'compute-only', or 'all-read-only')"
)),
}
}
}
impl Session {
pub fn with_ns(mut self, ns: &str) -> Session {
self.ns = Some(ns.to_owned());
self
}
pub fn with_db(mut self, db: &str) -> Session {
self.db = Some(db.to_owned());
self
}
pub fn with_ac(mut self, ac: &str) -> Session {
self.ac = Some(ac.to_owned());
self
}
pub fn with_rt(mut self, rt: bool) -> Session {
self.rt = rt;
self
}
pub fn new_planner_strategy(mut self, strategy: NewPlannerStrategy) -> Session {
self.new_planner_strategy = strategy;
self
}
pub(crate) fn ns(&self) -> Option<Arc<str>> {
self.ns.as_deref().map(Into::into)
}
pub(crate) fn db(&self) -> Option<Arc<str>> {
self.db.as_deref().map(Into::into)
}
pub(crate) fn live(&self) -> bool {
self.rt
}
pub(crate) fn expired(&self) -> bool {
match self.exp {
Some(exp) => Utc::now().timestamp() > exp,
None => false,
}
}
pub(crate) fn values(&self) -> Vec<(&'static str, Value)> {
use crate::sql::expression::convert_public_value_to_internal;
let access = self.ac.as_deref().map(Value::from).unwrap_or(Value::None);
let auth = self.rd.clone().map(convert_public_value_to_internal).unwrap_or(Value::None);
let token = self.tk.clone().map(convert_public_value_to_internal).unwrap_or(Value::None);
let session = Value::from(map! {
"ac" => access.clone(),
"exp" => self.exp.map(Value::from).unwrap_or(Value::None),
"db" => self.db.as_deref().map(Value::from).unwrap_or(Value::None),
"id" => self.id.map(Value::from).unwrap_or(Value::None),
"ip" => self.ip.as_deref().map(Value::from).unwrap_or(Value::None),
"ns" => self.ns.as_deref().map(Value::from).unwrap_or(Value::None),
"or" => self.or.as_deref().map(Value::from).unwrap_or(Value::None),
"rd" => auth.clone(),
"tk" => token.clone(),
});
vec![("access", access), ("auth", auth), ("token", token), ("session", session)]
}
pub fn for_level(level: Level, role: Role) -> Session {
let mut sess = Session::default();
match level {
Level::Root => {
sess.au = Arc::new(Auth::for_root(role));
}
Level::Namespace(ns) => {
sess.au = Arc::new(Auth::for_ns(role, &ns));
sess.ns = Some(ns);
}
Level::Database(ns, db) => {
sess.au = Arc::new(Auth::for_db(role, &ns, &db));
sess.ns = Some(ns);
sess.db = Some(db);
}
_ => {}
}
sess
}
pub fn for_record(ns: &str, db: &str, ac: &str, rid: PublicValue) -> Session {
Session {
ac: Some(ac.to_owned()),
au: Arc::new(Auth::for_record(rid.to_sql(), ns, db, ac)),
rt: false,
ip: None,
or: None,
id: None,
ns: Some(ns.to_owned()),
db: Some(db.to_owned()),
tk: None,
rd: Some(rid),
exp: None,
variables: Default::default(),
new_planner_strategy: NewPlannerStrategy::default(),
redact_volatile_explain_attrs: false,
}
}
pub fn owner() -> Session {
Session::for_level(Level::Root, Role::Owner)
}
pub fn editor() -> Session {
Session::for_level(Level::Root, Role::Editor)
}
pub fn viewer() -> Session {
Session::for_level(Level::Root, Role::Viewer)
}
}
#[revisioned(revision = 1)]
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct DurableSession {
pub(crate) expires_at: u64,
pub(crate) au: Auth,
pub(crate) rt: bool,
pub(crate) ip: Option<String>,
pub(crate) or: Option<String>,
pub(crate) id: Option<Uuid>,
pub(crate) ns: Option<String>,
pub(crate) db: Option<String>,
pub(crate) ac: Option<String>,
pub(crate) tk: Option<Value>,
pub(crate) rd: Option<Value>,
pub(crate) exp: Option<i64>,
pub(crate) variables: Object,
pub(crate) new_planner_strategy: NewPlannerStrategy,
pub(crate) redact_volatile_explain_attrs: bool,
}
impl_kv_value_revisioned!(DurableSession);
impl DurableSession {
pub(crate) fn from_session(session: &Session, expires_at: u64) -> Self {
use crate::sql::expression::convert_public_value_to_internal;
Self {
expires_at,
au: (*session.au).clone(),
rt: session.rt,
ip: session.ip.clone(),
or: session.or.clone(),
id: session.id,
ns: session.ns.clone(),
db: session.db.clone(),
ac: session.ac.clone(),
tk: session.tk.clone().map(convert_public_value_to_internal),
rd: session.rd.clone().map(convert_public_value_to_internal),
exp: session.exp,
variables: session
.variables
.clone()
.into_iter()
.map(|(k, v)| (k, convert_public_value_to_internal(v)))
.collect(),
new_planner_strategy: session.new_planner_strategy,
redact_volatile_explain_attrs: session.redact_volatile_explain_attrs,
}
}
pub(crate) fn into_session(self) -> Result<Session> {
use crate::val::convert_value_to_public_value;
Ok(Session {
au: Arc::new(self.au),
rt: self.rt,
ip: self.ip,
or: self.or,
id: self.id,
ns: self.ns,
db: self.db,
ac: self.ac,
tk: self.tk.map(convert_value_to_public_value).transpose()?,
rd: self.rd.map(convert_value_to_public_value).transpose()?,
exp: self.exp,
variables: self
.variables
.into_iter()
.map(|(k, v)| Ok((k.into_string(), convert_value_to_public_value(v)?)))
.collect::<Result<PublicVariables>>()?,
new_planner_strategy: self.new_planner_strategy,
redact_volatile_explain_attrs: self.redact_volatile_explain_attrs,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn json_round_trip_preserves_auth_and_context() {
let original = Session {
id: Some(Uuid::from_u128(1)),
exp: Some(1_700_000_000),
..Session::owner().with_ns("app").with_db("app")
};
let json = serde_json::to_string(&original).expect("serialize");
let restored: Session = serde_json::from_str(&json).expect("deserialize");
assert_eq!(original, restored);
assert!(restored.au.is_root());
assert_eq!(restored.ns.as_deref(), Some("app"));
assert_eq!(restored.db.as_deref(), Some("app"));
}
#[test]
fn durable_session_round_trip_preserves_all_fields() {
use std::collections::BTreeMap;
use surrealdb_types::{Number, Value as PV};
let mut variables = PublicVariables::default();
variables.insert("str", PV::String("hello".to_owned()));
variables.insert("dec", PV::Number(Number::Decimal("1.5".parse().unwrap())));
variables.insert("rid", PV::RecordId(surrealdb_types::RecordId::new("person", "tobie")));
variables.insert("dt", PV::Datetime(surrealdb_types::Datetime::now()));
variables.insert(
"obj",
PV::Object(surrealdb_types::Object::from(BTreeMap::from([("nested", PV::Bool(true))]))),
);
let original = Session {
rt: true,
ip: Some("10.0.0.1".to_owned()),
or: Some("example.com".to_owned()),
id: Some(Uuid::from_u128(7)),
exp: Some(1_700_000_000),
tk: Some(PV::Object(surrealdb_types::Object::from(BTreeMap::from([(
"iss",
PV::String("surrealdb".to_owned()),
)])))),
rd: Some(PV::RecordId(surrealdb_types::RecordId::new("person", "tobie"))),
variables,
redact_volatile_explain_attrs: true,
..Session::for_record(
"app",
"app",
"account",
PublicValue::RecordId(surrealdb_types::RecordId::new("person", "tobie")),
)
};
let durable = DurableSession::from_session(&original, 123_456_789);
assert_eq!(durable.expires_at, 123_456_789);
let bytes = revision::to_vec(&durable).expect("revision encode");
let decoded: DurableSession = revision::from_slice(&bytes).expect("revision decode");
assert_eq!(durable, decoded);
let restored = decoded.into_session().expect("convert back");
assert_eq!(original, restored);
}
}