zombienet_orchestrator/
pjs_helper.rs

1use anyhow::anyhow;
2pub use pjs_rs::ReturnValue;
3use serde_json::json;
4use tracing::trace;
5
6pub fn pjs_build_template(
7    ws_uri: &str,
8    content: &str,
9    args: Vec<serde_json::Value>,
10    user_types: Option<serde_json::Value>,
11) -> String {
12    let types = if let Some(user_types) = user_types {
13        if let Some(types) = user_types.pointer("/types") {
14            // if the user_types includes the `types` key use the inner value
15            types.clone()
16        } else {
17            user_types.clone()
18        }
19    } else {
20        // No custom types, just an emtpy json
21        json!({})
22    };
23
24    let tmpl = format!(
25        r#"
26    const {{ util, utilCrypto, keyring, types }} = pjs;
27    ( async () => {{
28        const api = await pjs.api.ApiPromise.create({{
29            provider: new pjs.api.WsProvider('{}'),
30            types: {}
31         }});
32        const _run = async (api, hashing, keyring, types, util, arguments) => {{
33            {}
34        }};
35        return await _run(api, utilCrypto, keyring, types, util, {});
36    }})()
37    "#,
38        ws_uri,
39        types,
40        content,
41        json!(args),
42    );
43    trace!(tmpl = tmpl, "code to execute");
44    tmpl
45}
46
47// Since pjs-rs run a custom javascript runtime (using deno_core) we need to
48// execute in an isolated thread.
49pub fn pjs_exec(code: String) -> Result<ReturnValue, anyhow::Error> {
50    let rt = tokio::runtime::Builder::new_current_thread()
51        .enable_all()
52        .build()?;
53
54    std::thread::spawn(move || {
55        rt.block_on(async move {
56            let value = pjs_rs::run_ts_code(code, None).await;
57            trace!("ts_code return: {:?}", value);
58            value
59        })
60    })
61    .join()
62    .map_err(|_| anyhow!("[pjs] Thread panicked"))?
63}
64
65/// pjs-rs success [Result] type
66///
67/// Represent the possible states returned from a successfully call to pjs-rs
68///
69/// Ok(value) -> Deserialized return value into a [serde_json::Value]
70/// Err(msg) -> Execution of the script finish Ok, but the returned value
71/// can't be deserialize into a [serde_json::Value]
72pub type PjsResult = Result<serde_json::Value, String>;