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        // Retain the Incurs 0.13 identity domain across package releases. Engine
69        // sources, compiler configuration, host ABI and program still participate.
70        let identity = program_identity(&source, "0.13.0");
71        let saved = host.checkpoint().await?;
72        let identity = match saved.as_ref() {
73            Some(saved) if saved.identity != identity => {
74                // The previous Incurs engine release used its own package
75                // version in the identity. Verify its full fingerprint too.
76                if saved.identity != program_identity(&source, "0.12.1") {
77                    return Err("Checkpoint identity mismatch; refusing to replay source".into());
78                }
79                saved.identity.clone()
80            }
81            _ => identity,
82        };
83        let engine = Engine::new(
84            &self.options,
85            &source,
86            saved.as_ref().map(|value| value.bytes.as_slice()),
87        )?;
88        run(engine, host, identity).await
89    }
90}
91
92fn program_identity(source: &str, version_domain: &str) -> String {
93    let mut fingerprint = Sha256::new();
94    fingerprint.update(env!("MULTICAST_ENGINE_BUILD"));
95    fingerprint.update(format!(
96        "native-v1/{}/{}/{}/{}/{}",
97        version_domain,
98        std::env::consts::OS,
99        std::env::consts::ARCH,
100        usize::BITS,
101        cfg!(debug_assertions)
102    ));
103    fingerprint.update(source.as_bytes());
104    format!("dquickts/{:x}", fingerprint.finalize())
105}
106
107async fn run(
108    engine: Engine,
109    host: Arc<ExecutionHost>,
110    identity: String,
111) -> Result<ExecuteResult, String> {
112    loop {
113        engine.pump()?;
114        let state: State = serde_json::from_str(&engine.state()?).map_err(error)?;
115        host.save_checkpoint(&ExecutionCheckpoint {
116            identity: identity.clone(),
117            bytes: engine.snapshot()?,
118        })
119        .await?;
120        if let Some(output) = state.output {
121            return serde_json::from_str(&output).map_err(error);
122        }
123        if let Some(failure) = state.failure {
124            return Err(failure);
125        }
126        let Some(pending) = state.pending else {
127            // The heap is durable while an unresolved promise awaits cancellation.
128            return std::future::pending().await;
129        };
130        let response = dispatch(&host, pending).await;
131        if response["__codemode_control__"] == "pause" || response["kind"] == "pause" {
132            return Ok(ExecuteResult {
133                result: None,
134                error: None,
135                logs: Vec::new(),
136            });
137        }
138        engine.respond(&serde_json::to_string(&response).map_err(error)?)?;
139    }
140}
141
142#[derive(Deserialize)]
143#[serde(tag = "kind", rename_all = "snake_case")]
144enum Request {
145    Call {
146        seq: u64,
147        connector: String,
148        method: String,
149        arguments: Value,
150    },
151    BeginStep {
152        seq: u64,
153        name: String,
154    },
155    RecordStep {
156        seq: u64,
157        result: Value,
158    },
159}
160
161async fn dispatch(host: &ExecutionHost, payload: Value) -> Value {
162    let response = match serde_json::from_value::<Request>(payload) {
163        Ok(Request::Call {
164            seq,
165            connector,
166            method,
167            arguments,
168        }) => serde_json::to_value(host.call(seq, &connector, &method, arguments).await)
169            .map_err(error),
170        Ok(Request::BeginStep { seq, name }) => host
171            .begin_step(seq, &name)
172            .await
173            .and_then(|response| serde_json::to_value(response).map_err(error)),
174        Ok(Request::RecordStep { seq, result }) => host
175            .record_step(seq, result)
176            .await
177            .map(|()| json!({"ok":true})),
178        Err(e) => Err(error(e)),
179    };
180    response.unwrap_or_else(|message| json!({"__codemode_control__":"error", "message":message}))
181}
182
183fn error(value: impl std::fmt::Display) -> String {
184    value.to_string()
185}