use std::fmt;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use uuid::Uuid;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WorkstreamId(pub Uuid);
impl WorkstreamId {
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn as_uuid(&self) -> &Uuid {
&self.0
}
}
impl Default for WorkstreamId {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for WorkstreamId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl From<Uuid> for WorkstreamId {
fn from(uuid: Uuid) -> Self {
Self(uuid)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkstreamState {
Active,
Idle,
Closed,
}
impl fmt::Display for WorkstreamState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::Active => "active",
Self::Idle => "idle",
Self::Closed => "closed",
};
write!(f, "{s}")
}
}
const CLOSED_METADATA_KEY: &str = "closed";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Workstream {
pub id: WorkstreamId,
pub name: String,
#[serde(default)]
pub session_ids: Vec<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
#[serde(default)]
pub metadata: Map<String, Value>,
}
impl Workstream {
pub fn new(name: impl Into<String>) -> Self {
let now = Utc::now();
Self {
id: WorkstreamId::new(),
name: name.into(),
session_ids: Vec::new(),
created_at: now,
updated_at: now,
metadata: Map::new(),
}
}
pub fn is_closed(&self) -> bool {
self.metadata
.get(CLOSED_METADATA_KEY)
.and_then(Value::as_bool)
.unwrap_or(false)
}
pub fn state(&self, active_workstream_id: Option<WorkstreamId>) -> WorkstreamState {
if active_workstream_id == Some(self.id) {
WorkstreamState::Active
} else if self.is_closed() {
WorkstreamState::Closed
} else {
WorkstreamState::Idle
}
}
pub fn touch(&mut self) {
self.updated_at = Utc::now();
}
pub fn mark_closed(&mut self) {
self.metadata
.insert(CLOSED_METADATA_KEY.to_string(), Value::Bool(true));
self.touch();
}
}
#[cfg(test)]
#[path = "model_tests.rs"]
mod model_tests;