HiRoFa / quickjs_es_runtime

this is a wrapper library for the javascript runtime quickjs written in rust which works with typescript, modules, promises, async, await and much more
https://github.com/HiRoFa/quickjs_es_runtime
MIT License
104 stars 12 forks source link

Can't get rust async code to work with promise #79

Closed FlondorDev closed 9 months ago

FlondorDev commented 9 months ago

hi, i'm trying to use rust async code with js promises but the code stop executing before the promise can deliver a value (this doesn't happen with rust sync code in promise)

main.rs

use serde_json::Value;
use quickjs_runtime::builder::*;
use quickjs_runtime::jsutils::JsError;
use quickjs_runtime::jsutils::Script;

use elasticsearch::{
    auth::Credentials,
    cert::CertificateValidation,
    http::transport::{SingleNodeConnectionPool, TransportBuilder},
    http::Url,
    Elasticsearch,
};
use tokio::runtime::Runtime;

fn client() -> Elasticsearch {
    let credentials = Credentials::Basic("elastic".to_string(), "elastic".to_string());
    let conn_pool = SingleNodeConnectionPool::new(Url::parse("https://localhost:9200").unwrap());
    let transport = TransportBuilder::new(conn_pool)
        .disable_proxy()
        .auth(credentials)
        .cert_validation(CertificateValidation::None)
        .build()
        .unwrap();

    Elasticsearch::new(transport)
}

async fn cat_index() -> Result<Value, JsError> {
    let elastic = client();
    let indexes = elastic
        .indices()
        .get(elasticsearch::indices::IndicesGetParts::Index(&[
            "care_index",
        ]))
        .send()
        .await
        .unwrap();
    let index = indexes.json::<Value>().await.unwrap();
    Ok(index)
}

#[tokio::main]
async fn main() {
    let rt = QuickJsRuntimeBuilder::new().build();

    rt.loop_realm(None, |rt, realm| {
        realm
        .install_function(
            &[],
            "cat_elastic",
            |_rt, realm, _this, _args| {
                    realm.create_resolving_promise_async(cat_index(), |realm, value| {
                        realm.serde_value_to_value_adapter(value)
                    })
                },
                0,
            )
            .unwrap();

        realm
            .install_function(
                &[],
                "log",
                |_rt, realm, _this, args| {
                    println!("{:?}", args[0].to_string());
                    realm.create_undefined()
                },
                1,
            )
            .unwrap();

        realm
            .eval(Script::new("", include_str!("../code.js")))
            .unwrap();
    })
    .await;
}

code.js

cat_elastic().then(p => {
    log(p);
})

what am i doing wrong?

P.S: if i use tokio runtime to block_on the async code (removing the promise part) i can get the result, also using create_resolving_promise not the async one and returning a dummy value i can also get the promise to work

andrieshiemstra commented 9 months ago

Well, i'll look into the code but my first guess is that the runtime is allready dropped when the async code runs.. just for the test, try to add a thread::sleep(Duration::from_secs(1)) after your last .await; in main()

andrieshiemstra commented 9 months ago

yeah, try something like this.... return promise from qjs and await it before exiting async main

use quickjs_runtime::builder::QuickJsRuntimeBuilder;
use quickjs_runtime::jsutils::{JsError, Script};
use quickjs_runtime::values::JsValueFacade;
use serde_json::Value;

async fn cat_index() -> Result<Value, JsError> {
    let value = serde_json::from_str("{\"abc\": \"i'm a obj made rusty\"}").unwrap();
    println!("cat_index running");
    Ok(value)
}

#[tokio::main]
async fn main() {
    println!("Hello, world!");

    let rt = QuickJsRuntimeBuilder::new().build();

    rt.loop_realm(None, |_rt, realm| {
        realm
            .install_function(
                &[],
                "cat_elastic",
                |_rt, realm, _this, _args| {
                    realm.create_resolving_promise_async(cat_index(), |realm, value| {
                        realm.serde_value_to_value_adapter(value)
                    })
                },
                0,
            )
            .unwrap();

        realm
            .install_function(
                &[],
                "log",
                |_rt, realm, _this, args| {
                    println!("{:?}", args[0].to_string());
                    realm.create_undefined()
                },
                1,
            )
            .unwrap();
    })
    .await;

    let promise_jsvf = rt
        .eval(
            None,
            Script::new(
                "promiseMeThis.js",
                r#"
        async function myCode(){
            let res = await cat_elastic();
            return res;
        };
        // eval statement, thus returning the promise
        myCode()
    "#,
            ),
        )
        .await
        .expect("Script failed misserably");

    if let JsValueFacade::JsPromise { cached_promise } = promise_jsvf {
        // of boy oh boy we got a promise
        let resolved_value = cached_promise
            .get_promise_result()
            .await
            .expect("Promise timed out?");

        match resolved_value {
            Ok(prom_resolved) => {
                println!(
                    "Promise resolved to {:?}",
                    prom_resolved
                        .to_json_string()
                        .await
                        .expect("no not so stringable?")
                );
            }
            Err(_prom_rejected) => {
                panic!("Promise was rejected");
            }
        }
    }
}
andrieshiemstra commented 9 months ago

Ps just for clarity, this doesn't mean you always have to .await promises for them to run or anything, the problem in this case was just that the runtime would be destroyed before the async code ran...

FlondorDev commented 9 months ago

ok, this last piece of code solved my issue

if let JsValueFacade::JsPromise { cached_promise } = promise_jsvf {
        // of boy oh boy we got a promise
        let resolved_value = cached_promise
            .get_promise_result()
            .await
            .expect("Promise timed out?");

        match resolved_value {
            Ok(prom_resolved) => {
                println!(
                    "Promise resolved to {:?}",
                    prom_resolved
                        .to_json_string()
                        .await
                        .expect("no not so stringable?")
                );
            }
            Err(_prom_rejected) => {
                panic!("Promise was rejected");
            }
        }
    }

basically yeah the code execution dropped before promise completion, i searched for a while a way to wait for the promise to end but i found the docs a bit lacking