use crate::config::Config;
use std::sync::Arc;
use tokio::sync::RwLock;
#[derive(Debug, Clone)]
pub struct Runtime {
config: Config,
checkpoint_id: Option<String>,
step: usize,
}
impl Runtime {
pub fn new(config: Config) -> Self {
Self {
config,
checkpoint_id: None,
step: 0,
}
}
pub fn config(&self) -> &Config {
&self.config
}
pub fn checkpoint_id(&self) -> Option<&str> {
self.checkpoint_id.as_deref()
}
pub fn step(&self) -> usize {
self.step
}
pub fn set_checkpoint_id(&mut self, id: impl Into<String>) {
self.checkpoint_id = Some(id.into());
}
pub fn increment_step(&mut self) {
self.step += 1;
}
pub fn thread_id(&self) -> Option<&str> {
self.config.thread_id.as_deref()
}
}
pub type SharedRuntime = Arc<RwLock<Runtime>>;
pub fn shared_runtime(config: Config) -> SharedRuntime {
Arc::new(RwLock::new(Runtime::new(config)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_runtime_creation() {
let config = Config::new().with_thread_id("test");
let runtime = Runtime::new(config);
assert_eq!(runtime.thread_id(), Some("test"));
assert_eq!(runtime.step(), 0);
assert!(runtime.checkpoint_id().is_none());
}
#[test]
fn test_runtime_mutations() {
let config = Config::new();
let mut runtime = Runtime::new(config);
runtime.set_checkpoint_id("checkpoint-1");
assert_eq!(runtime.checkpoint_id(), Some("checkpoint-1"));
runtime.increment_step();
assert_eq!(runtime.step(), 1);
runtime.increment_step();
assert_eq!(runtime.step(), 2);
}
#[tokio::test]
async fn test_shared_runtime() {
let config = Config::new();
let runtime = shared_runtime(config);
{
let mut rt = runtime.write().await;
rt.increment_step();
}
{
let rt = runtime.read().await;
assert_eq!(rt.step(), 1);
}
}
}