Skip to main content

multicast_codemode_local/
quickjs.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use multicast_codemode::{
5    CodeExecutor, ConnectorDescription, ExecuteResult, ExecutionCheckpoint, ExecutionHost,
6    build_checkpoint_source,
7};
8use serde::Deserialize;
9use serde_json::{Value, json};
10use sha2::{Digest, Sha256};
11
12use super::native::Engine;
13
14/// Resource limits for JavaScript intervals between durable host calls.
15#[derive(Debug, Clone)]
16pub struct LocalExecutorOptions {
17    /// Maximum uninterrupted wall-clock time spent evaluating JavaScript.
18    pub timeout: Duration,
19    /// Maximum guest JavaScript heap in bytes.
20    pub memory_limit: usize,
21    /// Maximum guest stack in bytes.
22    pub stack_size: usize,
23}
24
25impl Default for LocalExecutorOptions {
26    fn default() -> Self {
27        Self {
28            timeout: Duration::from_secs(60),
29            memory_limit: 64 * 1024 * 1024,
30            stack_size: 512 * 1024,
31        }
32    }
33}
34
35/// Executes Code Mode in a dquickts runtime checkpointed before every host call.
36///
37/// The runtime store supplies continuations. A persistent store enables recovery
38/// across host restarts; `MemoryStore` retains checkpoints only in memory.
39#[derive(Debug, Clone, Default)]
40pub struct LocalExecutor {
41    options: LocalExecutorOptions,
42}
43
44impl LocalExecutor {
45    /// Creates a checkpointing executor with explicit resource limits.
46    pub fn new(options: LocalExecutorOptions) -> Self {
47        Self { options }
48    }
49}
50
51#[derive(Deserialize)]
52struct State {
53    output: Option<String>,
54    failure: Option<String>,
55    pending: Option<Value>,
56}
57
58#[async_trait::async_trait(?Send)]
59impl CodeExecutor for LocalExecutor {
60    async fn execute(
61        &self,
62        code: &str,
63        connectors: &[ConnectorDescription],
64        execution_id: &str,
65        host: Arc<ExecutionHost>,
66    ) -> Result<ExecuteResult, String> {
67        let source = build_checkpoint_source(code, connectors, execution_id)?;
68        let identity = program_identity(&source);
69        let saved = host.checkpoint().await?;
70        if saved
71            .as_ref()
72            .is_some_and(|saved| saved.identity != identity)
73        {
74            return Err("Checkpoint identity mismatch; refusing to replay source".into());
75        }
76        let engine = Engine::new(
77            &self.options,
78            &source,
79            saved.as_ref().map(|value| value.bytes.as_slice()),
80        )?;
81        run(engine, host, identity).await
82    }
83}
84
85fn program_identity(source: &str) -> String {
86    let mut fingerprint = Sha256::new();
87    fingerprint.update(env!("MULTICAST_ENGINE_BUILD"));
88    fingerprint.update(format!(
89        "native-v1/{}/{}/{}/{}/{}",
90        env!("CARGO_PKG_VERSION"),
91        std::env::consts::OS,
92        std::env::consts::ARCH,
93        usize::BITS,
94        cfg!(debug_assertions)
95    ));
96    fingerprint.update(source.as_bytes());
97    format!("dquickts/{:x}", fingerprint.finalize())
98}
99
100async fn run(
101    engine: Engine,
102    host: Arc<ExecutionHost>,
103    identity: String,
104) -> Result<ExecuteResult, String> {
105    loop {
106        engine.pump()?;
107        let state: State = serde_json::from_str(&engine.state()?).map_err(error)?;
108        host.save_checkpoint(&ExecutionCheckpoint {
109            identity: identity.clone(),
110            bytes: engine.snapshot()?,
111        })
112        .await?;
113        if let Some(output) = state.output {
114            return serde_json::from_str(&output).map_err(error);
115        }
116        if let Some(failure) = state.failure {
117            return Err(failure);
118        }
119        let Some(pending) = state.pending else {
120            // The heap is durable while an unresolved promise awaits cancellation.
121            return std::future::pending().await;
122        };
123        let response = dispatch(&host, pending).await;
124        if response["__codemode_control__"] == "pause" || response["kind"] == "pause" {
125            return Ok(ExecuteResult {
126                result: None,
127                error: None,
128                logs: Vec::new(),
129            });
130        }
131        engine.respond(&serde_json::to_string(&response).map_err(error)?)?;
132    }
133}
134
135#[derive(Deserialize)]
136#[serde(tag = "kind", rename_all = "snake_case")]
137enum Request {
138    Call {
139        seq: u64,
140        connector: String,
141        method: String,
142        arguments: Value,
143    },
144    BeginStep {
145        seq: u64,
146        name: String,
147    },
148    RecordStep {
149        seq: u64,
150        result: Value,
151    },
152}
153
154async fn dispatch(host: &ExecutionHost, payload: Value) -> Value {
155    let response = match serde_json::from_value::<Request>(payload) {
156        Ok(Request::Call {
157            seq,
158            connector,
159            method,
160            arguments,
161        }) => serde_json::to_value(host.call(seq, &connector, &method, arguments).await)
162            .map_err(error),
163        Ok(Request::BeginStep { seq, name }) => host
164            .begin_step(seq, &name)
165            .await
166            .and_then(|response| serde_json::to_value(response).map_err(error)),
167        Ok(Request::RecordStep { seq, result }) => host
168            .record_step(seq, result)
169            .await
170            .map(|()| json!({"ok":true})),
171        Err(e) => Err(error(e)),
172    };
173    response.unwrap_or_else(|message| json!({"__codemode_control__":"error", "message":message}))
174}
175
176fn error(value: impl std::fmt::Display) -> String {
177    value.to_string()
178}