Skip to main content

multicast_codemode/
engine.rs

1use std::sync::Arc;
2
3use async_trait::async_trait;
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7use crate::{
8    ConnectorDescription, DispatchResponse, DispatchSession, ExecutionCheckpoint, StepResponse,
9};
10
11/// Result returned by a Code Mode program executor.
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct ExecuteResult {
14    /// Successful program result.
15    pub result: Option<Value>,
16    /// Program or sandbox error.
17    pub error: Option<String>,
18    /// Captured console output.
19    pub logs: Vec<String>,
20}
21
22/// Host request emitted by an executing Code Mode program.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24#[serde(tag = "kind", rename_all = "snake_case")]
25pub enum DispatchRequest {
26    /// Load the active execution's engine continuation.
27    LoadCheckpoint {
28        /// Durable execution identifier.
29        execution_id: String,
30    },
31    /// Commit the active execution's engine continuation before dispatch.
32    SaveCheckpoint {
33        /// Durable execution identifier.
34        execution_id: String,
35        /// Engine-owned continuation.
36        checkpoint: ExecutionCheckpoint,
37    },
38    /// Execute or replay one connector call.
39    Call {
40        /// Durable execution identifier.
41        execution_id: String,
42        /// Program-assigned deterministic sequence.
43        seq: u64,
44        /// Connector namespace.
45        connector: String,
46        /// Connector method.
47        method: String,
48        /// JSON-safe tagged arguments.
49        arguments: Value,
50    },
51    /// Decide whether a local `codemode.step` callback should run.
52    BeginStep {
53        /// Durable execution identifier.
54        execution_id: String,
55        /// Program-assigned deterministic sequence.
56        seq: u64,
57        /// Stable step name.
58        name: String,
59    },
60    /// Record a completed local `codemode.step` callback.
61    RecordStep {
62        /// Durable execution identifier.
63        execution_id: String,
64        /// Program-assigned deterministic sequence.
65        seq: u64,
66        /// JSON-safe tagged callback result.
67        result: Value,
68    },
69}
70
71/// Executes model-generated JavaScript for one replay pass.
72///
73/// Executors provide isolation and host bridging. The durable lifecycle,
74/// connector policy, approvals, replay, and rollback remain in [`crate::CodeMode`].
75#[async_trait(?Send)]
76#[allow(
77    clippy::double_must_use,
78    reason = "async_trait annotates generated futures"
79)]
80pub trait CodeExecutor {
81    /// Executes one pass and returns its result or captured program error.
82    async fn execute(
83        &self,
84        code: &str,
85        connectors: &[ConnectorDescription],
86        execution_id: &str,
87        host: Arc<ExecutionHost>,
88    ) -> Result<ExecuteResult, String>;
89}
90
91/// Supplies monotonic-enough Unix millisecond timestamps to Code Mode.
92pub trait Clock: Send + Sync {
93    /// Returns the current Unix timestamp in milliseconds.
94    fn now_ms(&self) -> u64;
95    /// Waits cooperatively for a deadline check. Worker hosts must override this timer.
96    fn sleep(
97        &self,
98        milliseconds: u64,
99    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + '_>> {
100        #[cfg(not(target_arch = "wasm32"))]
101        {
102            Box::pin(tokio::time::sleep(std::time::Duration::from_millis(
103                milliseconds,
104            )))
105        }
106        #[cfg(target_arch = "wasm32")]
107        {
108            let _ = milliseconds;
109            Box::pin(std::future::pending())
110        }
111    }
112}
113
114/// Native system clock used by default.
115#[derive(Debug, Clone, Copy, Default)]
116pub struct SystemClock;
117
118impl Clock for SystemClock {
119    fn now_ms(&self) -> u64 {
120        std::time::SystemTime::now()
121            .duration_since(std::time::UNIX_EPOCH)
122            .unwrap_or_default()
123            .as_millis() as u64
124    }
125}
126
127/// Execution-scoped bridge from a local engine into durable dispatch.
128pub struct ExecutionHost {
129    session: Arc<DispatchSession>,
130    clock: Arc<dyn Clock>,
131}
132
133impl ExecutionHost {
134    /// Loads this active pass's engine continuation.
135    pub async fn checkpoint(&self) -> Result<Option<ExecutionCheckpoint>, String> {
136        self.session.checkpoint().await
137    }
138
139    /// Commits this active pass's engine continuation before an external call.
140    pub async fn save_checkpoint(&self, checkpoint: &ExecutionCheckpoint) -> Result<(), String> {
141        self.session.save_checkpoint(checkpoint).await
142    }
143    pub(crate) fn new(session: Arc<DispatchSession>, clock: Arc<dyn Clock>) -> Self {
144        Self { session, clock }
145    }
146
147    /// Executes or replays one connector call.
148    pub async fn call(
149        &self,
150        seq: u64,
151        connector: &str,
152        method: &str,
153        arguments: Value,
154    ) -> DispatchResponse {
155        self.session
156            .call_at(seq, connector, method, arguments, self.clock.now_ms())
157            .await
158    }
159
160    /// Begins a durable local callback step.
161    pub async fn begin_step(&self, seq: u64, name: &str) -> Result<StepResponse, String> {
162        self.session
163            .begin_step_at(seq, name, self.clock.now_ms())
164            .await
165            .map_err(|error| error.to_string())
166    }
167
168    /// Records a completed durable local callback step.
169    pub async fn record_step(&self, seq: u64, result: Value) -> Result<(), String> {
170        self.session
171            .record_step(seq, result, self.clock.now_ms())
172            .await
173            .map_err(|error| error.to_string())
174    }
175}