use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
pub use orchestral_core::store::ThreadId;
fn default_scope() -> String {
"user:anonymous".to_string()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Thread {
pub id: ThreadId,
#[serde(default = "default_scope")]
pub scope: String,
#[serde(default)]
pub metadata: HashMap<String, Value>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
impl Thread {
pub fn new() -> Self {
let now = Utc::now();
Self {
id: ThreadId::from(uuid::Uuid::new_v4().to_string()),
scope: default_scope(),
metadata: HashMap::new(),
created_at: now,
updated_at: now,
}
}
pub fn with_id(id: impl Into<ThreadId>) -> Self {
let now = Utc::now();
Self {
id: id.into(),
scope: default_scope(),
metadata: HashMap::new(),
created_at: now,
updated_at: now,
}
}
pub fn with_metadata(metadata: HashMap<String, Value>) -> Self {
let now = Utc::now();
Self {
id: ThreadId::from(uuid::Uuid::new_v4().to_string()),
scope: default_scope(),
metadata,
created_at: now,
updated_at: now,
}
}
pub fn with_scope(scope: impl Into<String>) -> Self {
let now = Utc::now();
Self {
id: ThreadId::from(uuid::Uuid::new_v4().to_string()),
scope: scope.into(),
metadata: HashMap::new(),
created_at: now,
updated_at: now,
}
}
pub fn set_scope(&mut self, scope: impl Into<String>) {
self.scope = scope.into();
self.updated_at = Utc::now();
}
pub fn set_metadata(&mut self, key: impl Into<String>, value: Value) {
self.metadata.insert(key.into(), value);
self.updated_at = Utc::now();
}
pub fn get_metadata(&self, key: &str) -> Option<&Value> {
self.metadata.get(key)
}
pub fn remove_metadata(&mut self, key: &str) -> Option<Value> {
let result = self.metadata.remove(key);
if result.is_some() {
self.updated_at = Utc::now();
}
result
}
pub fn touch(&mut self) {
self.updated_at = Utc::now();
}
}
impl Default for Thread {
fn default() -> Self {
Self::new()
}
}