use super::context::{Fiber, FiberState};
use chrono::Utc;
use dashmap::DashMap;
use serde_json::Value;
use std::sync::{Arc, Mutex};
use std::time::Instant;
pub type DynamicFunctionBinding = Arc<
dyn Fn(&Value, &DashMap<String, String>) -> Result<Value, String> + Send + Sync + 'static,
>;
pub type PreVerificationCheck = Arc<
dyn Fn(&DashMap<String, String>) -> bool + Send + Sync + 'static,
>;
#[derive(Debug, Clone)]
pub struct BitemporalExecutionRecord {
pub handle: String,
pub epoch: u64,
pub transaction_time: String, pub valid_time: String, pub input: Value,
pub output: Value,
pub fiber_id: String,
}
#[derive(Debug, Clone)]
pub struct HmrMigrationReport {
pub handle: String,
pub previous_epoch: u64,
pub new_epoch: u64,
pub migration_latency_ms: f64,
pub session_preserved: bool,
pub success: bool,
pub rollback_occurred: bool,
pub failure_reason: Option<String>,
}
pub struct RegisteredBinding {
pub handle: String,
pub epoch: u64,
pub fiber: Arc<Fiber>,
pub binding: DynamicFunctionBinding,
pub g_time: String,
}
pub struct HmrReloader {
bindings: DashMap<String, RegisteredBinding>,
session_store: Arc<DashMap<String, String>>,
execution_log: Mutex<Vec<BitemporalExecutionRecord>>,
}
impl Default for HmrReloader {
fn default() -> Self {
Self::new()
}
}
impl HmrReloader {
pub fn new() -> Self {
Self {
bindings: DashMap::new(),
session_store: Arc::new(DashMap::new()),
execution_log: Mutex::new(Vec::new()),
}
}
pub fn set_session_var(&self, key: impl Into<String>, value: impl Into<String>) {
self.session_store.insert(key.into(), value.into());
}
pub fn get_session_var(&self, key: &str) -> Option<String> {
self.session_store.get(key).map(|v| v.value().clone())
}
pub fn get_epoch(&self, handle: &str) -> Option<u64> {
self.bindings.get(handle).map(|b| b.epoch)
}
pub fn get_execution_log(&self) -> Vec<BitemporalExecutionRecord> {
self.execution_log.lock().unwrap().clone()
}
pub fn register<F>(
&self,
handle: impl Into<String>,
binding: F,
g_time: Option<String>,
) -> Result<u64, String>
where
F: Fn(&Value, &DashMap<String, String>) -> Result<Value, String> + Send + Sync + 'static,
{
let handle_str = handle.into();
let epoch = 1;
let fiber = Arc::new(Fiber::new(format!("{}:epoch_{}", handle_str, epoch), vec![]));
fiber.transition_to(FiberState::Active)?;
let registered = RegisteredBinding {
handle: handle_str.clone(),
epoch,
fiber,
binding: Arc::new(binding),
g_time: g_time.unwrap_or_else(|| Utc::now().to_rfc3339()),
};
self.bindings.insert(handle_str, registered);
Ok(epoch)
}
pub fn execute(&self, handle: &str, input: &Value) -> Result<Value, String> {
let binding_entry = self
.bindings
.get(handle)
.ok_or_else(|| format!("HmrReloader: handle '{}' not registered", handle))?;
if binding_entry.fiber.get_state() != FiberState::Active {
return Err(format!(
"HmrReloader: fiber for '{}' is not Active ({:?})",
handle,
binding_entry.fiber.get_state()
));
}
let valid_time = Utc::now().to_rfc3339();
let output = (binding_entry.binding)(input, &self.session_store)?;
let record = BitemporalExecutionRecord {
handle: handle.to_string(),
epoch: binding_entry.epoch,
transaction_time: binding_entry.g_time.clone(),
valid_time,
input: input.clone(),
output: output.clone(),
fiber_id: binding_entry.fiber.id.clone(),
};
self.execution_log.lock().unwrap().push(record);
Ok(output)
}
pub fn migrate_epoch<F>(
&self,
handle: &str,
new_binding: F,
g_time: Option<String>,
pre_check: Option<PreVerificationCheck>,
) -> Result<HmrMigrationReport, String>
where
F: Fn(&Value, &DashMap<String, String>) -> Result<Value, String> + Send + Sync + 'static,
{
let current_binding = self
.bindings
.get(handle)
.ok_or_else(|| format!("HmrReloader: handle '{}' not registered", handle))?;
let t0 = Instant::now();
let prev_epoch = current_binding.epoch;
let next_epoch = prev_epoch + 1;
let g_time_str = g_time.unwrap_or_else(|| Utc::now().to_rfc3339());
if let Some(ref check) = pre_check
&& !check(&self.session_store) {
let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0;
return Ok(HmrMigrationReport {
handle: handle.to_string(),
previous_epoch: prev_epoch,
new_epoch: prev_epoch,
migration_latency_ms: elapsed_ms,
session_preserved: true,
success: false,
rollback_occurred: true,
failure_reason: Some(format!("Pre-verification V_pre failed for epoch {}", next_epoch)),
});
}
current_binding.fiber.transition_to(FiberState::Unloading)?;
let _ = current_binding.fiber.unwind_disposables();
current_binding.fiber.transition_to(FiberState::Disposed)?;
drop(current_binding);
let next_fiber = Arc::new(Fiber::new(format!("{}:epoch_{}", handle, next_epoch), vec![]));
next_fiber.transition_to(FiberState::Loading)?;
next_fiber.transition_to(FiberState::Active)?;
let updated = RegisteredBinding {
handle: handle.to_string(),
epoch: next_epoch,
fiber: next_fiber,
binding: Arc::new(new_binding),
g_time: g_time_str,
};
self.bindings.insert(handle.to_string(), updated);
let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0;
Ok(HmrMigrationReport {
handle: handle.to_string(),
previous_epoch: prev_epoch,
new_epoch: next_epoch,
migration_latency_ms: elapsed_ms,
session_preserved: true,
success: true,
rollback_occurred: false,
failure_reason: None,
})
}
}