Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add async for I/O calls #372

Merged
merged 9 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions bindings/web5_uniffi_wrapper/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ repository.workspace = true
license-file.workspace = true

[dependencies]
futures = "0.3.30"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When we chatted at standup, you were getting an error similar to this mozilla/uniffi-rs#2223. The solution may be that we have to specify async_runtime = tokio using uniffi proc macros as described here mozilla/uniffi-rs#2219.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indeed! good catch, we can improve this later

serde_json = { workspace = true }
thiserror = { workspace = true }
web5 = { path = "../../crates/web5" }
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::errors::Result;
use futures::executor::block_on;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why futures::executor::block_on vs alternatives like tokio::task::spawn_blocking?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

futures has a slightly more streamlined error handling, whereas with tokio I would have to add a mapper into our error type, see the unwrap below

    pub fn resolve(uri: &str) -> Self {
        let inner_result = task::spawn_blocking(move || {
            tokio::runtime::Handle::current().block_on(InnerResolutionResult::resolve(uri))
        }).unwrap(); // Handle unwrap or any error handling as required.

        Self(inner_result)
    }

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Weird, I guess uniffi requires tokio? I could've sworn I tested with futures, but oh well, guess I have to go the tokio route

use web5::credentials::presentation_definition::PresentationDefinition as InnerPresentationDefinition;

pub struct PresentationDefinition(pub InnerPresentationDefinition);
Expand All @@ -13,11 +14,11 @@ impl PresentationDefinition {
}

pub fn select_credentials(&self, vc_jwts: &Vec<String>) -> Result<Vec<String>> {
Ok(self.0.select_credentials(vc_jwts)?)
Ok(block_on(self.0.select_credentials(vc_jwts))?)
}

pub fn create_presentation_from_credentials(&self, vc_jwts: &Vec<String>) -> Result<String> {
let presentation_result = self.0.create_presentation_from_credentials(vc_jwts)?;
let presentation_result = block_on(self.0.create_presentation_from_credentials(vc_jwts))?;
let json_serialized_presentation_result = serde_json::to_string(&presentation_result)?;

Ok(json_serialized_presentation_result)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::credentials::verifiable_credential_1_1::VerifiableCredential;
use crate::errors::Result;
use futures::executor::block_on;
use std::sync::Arc;
use web5::credentials::Issuer;
use web5::{
Expand All @@ -25,11 +26,11 @@ impl StatusListCredential {
.collect()
});

Ok(Self(InnerStatusListCredential::create(
Ok(Self(block_on(InnerStatusListCredential::create(
issuer,
status_purpose,
inner_vcs,
)?))
))?))
}

pub fn get_base(&self) -> Result<Arc<VerifiableCredential>> {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{dids::bearer_did::BearerDid, errors::Result};
use futures::executor::block_on;
use std::{sync::Arc, time::SystemTime};
use web5::credentials::CredentialStatus;
use web5::credentials::Issuer;
Expand Down Expand Up @@ -60,8 +61,11 @@ impl VerifiableCredential {
evidence,
};

let inner_vc =
InnerVerifiableCredential::create(issuer, credential_subject, Some(inner_options))?;
let inner_vc = block_on(InnerVerifiableCredential::create(
issuer,
credential_subject,
Some(inner_options),
))?;

Ok(Self {
inner_vc,
Expand Down Expand Up @@ -91,7 +95,7 @@ impl VerifiableCredential {
}

pub fn from_vc_jwt(vc_jwt: String, verify: bool) -> Result<Self> {
let inner_vc = InnerVerifiableCredential::from_vc_jwt(&vc_jwt, verify)?;
let inner_vc = block_on(InnerVerifiableCredential::from_vc_jwt(&vc_jwt, verify))?;
let json_serialized_issuer = serde_json::to_string(&inner_vc.issuer)?;
let json_serialized_credential_subject =
serde_json::to_string(&inner_vc.credential_subject)?;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{dids::bearer_did::BearerDid, errors::Result};
use futures::executor::block_on;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
Expand Down Expand Up @@ -44,7 +45,11 @@ impl VerifiablePresentation {
additional_data,
};

let inner_vp = InnerVerifiablePresentation::create(holder, vc_jwts, Some(inner_options))?;
let inner_vp = block_on(InnerVerifiablePresentation::create(
holder,
vc_jwts,
Some(inner_options),
))?;

Ok(Self { inner_vp })
}
Expand All @@ -68,7 +73,7 @@ impl VerifiablePresentation {
}

pub fn from_vp_jwt(vp_jwt: String, verify: bool) -> Result<Self> {
let inner_vp = InnerVerifiablePresentation::from_vp_jwt(&vp_jwt, verify)?;
let inner_vp = block_on(InnerVerifiablePresentation::from_vp_jwt(&vp_jwt, verify))?;

Ok(Self { inner_vp })
}
Expand Down
10 changes: 7 additions & 3 deletions bindings/web5_uniffi_wrapper/src/dids/methods/did_dht.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ use crate::{
dids::{bearer_did::BearerDid, resolution::resolution_result::ResolutionResult},
errors::Result,
};
use futures::executor::block_on;
use std::sync::Arc;
use web5::dids::{
data_model::{service::Service, verification_method::VerificationMethod},
methods::did_dht::{DidDht as InnerDidDht, DidDhtCreateOptions as InnerDidDhtCreateOptions},
};

pub fn did_dht_resolve(uri: &str, gateway_url: Option<String>) -> Arc<ResolutionResult> {
let resolution_result = InnerDidDht::resolve(uri, gateway_url);
let resolution_result = block_on(InnerDidDht::resolve(uri, gateway_url));
Arc::new(ResolutionResult(resolution_result))
}

Expand Down Expand Up @@ -39,10 +40,13 @@ pub fn did_dht_create(options: Option<DidDhtCreateOptions>) -> Result<Arc<Bearer
verification_method: o.verification_method,
});

let inner_bearer_did = InnerDidDht::create(inner_options)?;
let inner_bearer_did = block_on(InnerDidDht::create(inner_options))?;
Ok(Arc::new(BearerDid(inner_bearer_did)))
}

pub fn did_dht_publish(bearer_did: Arc<BearerDid>, gateway_url: Option<String>) -> Result<()> {
Ok(InnerDidDht::publish(bearer_did.0.clone(), gateway_url)?)
Ok(block_on(InnerDidDht::publish(
bearer_did.0.clone(),
gateway_url,
))?)
}
3 changes: 2 additions & 1 deletion bindings/web5_uniffi_wrapper/src/dids/methods/did_web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::{
dids::{bearer_did::BearerDid, resolution::resolution_result::ResolutionResult},
errors::Result,
};
use futures::executor::block_on;
use std::sync::Arc;
use web5::{
crypto::dsa::Dsa,
Expand All @@ -15,7 +16,7 @@ use web5::{
};

pub fn did_web_resolve(uri: &str) -> Arc<ResolutionResult> {
let resolution_result = InnerDidWeb::resolve(uri);
let resolution_result = block_on(InnerDidWeb::resolve(uri));
Arc::new(ResolutionResult(resolution_result))
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use futures::executor::block_on;
use web5::dids::resolution::resolution_result::ResolutionResult as InnerResolutionResult;

pub struct ResolutionResult(pub InnerResolutionResult);

impl ResolutionResult {
pub fn resolve(uri: &str) -> Self {
Self(InnerResolutionResult::resolve(uri))
Self(block_on(InnerResolutionResult::resolve(uri)))
}

pub fn get_data(&self) -> InnerResolutionResult {
Expand Down
1 change: 1 addition & 0 deletions crates/http-std/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ repository.workspace = true
license-file.workspace = true

[dependencies]
async-trait = "0.1.83"
lazy_static = { workspace = true }
thiserror = { workspace = true }
url = "2.5.0"
Expand Down
4 changes: 3 additions & 1 deletion crates/http-std/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use crate::Result;
use async_trait::async_trait;
use std::collections::HashMap;

#[async_trait]
pub trait Client: Send + Sync {
fn fetch(&self, url: &str, options: Option<FetchOptions>) -> Result<Response>;
async fn fetch(&self, url: &str, options: Option<FetchOptions>) -> Result<Response>;
}

#[derive(Default)]
Expand Down
4 changes: 3 additions & 1 deletion crates/http-std/src/default_client.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{Client, Error, FetchOptions, Method, Response, Result};
use async_trait::async_trait;
use rustls::pki_types::ServerName;
use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned};
use rustls_native_certs::load_native_certs;
Expand Down Expand Up @@ -158,8 +159,9 @@ fn parse_response(response_bytes: &[u8]) -> Result<Response> {

pub struct DefaultClient;

#[async_trait]
impl Client for DefaultClient {
fn fetch(&self, url: &str, options: Option<FetchOptions>) -> Result<Response> {
async fn fetch(&self, url: &str, options: Option<FetchOptions>) -> Result<Response> {
let options = options.unwrap_or_default();
let destination = parse_destination(url)?;
let method = options.method.unwrap_or(Method::Get);
Expand Down
9 changes: 6 additions & 3 deletions crates/http-std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ mod error;
#[cfg(not(target_arch = "wasm32"))]
mod reqwest_client;

#[cfg(target_arch = "wasm32")]
use async_trait::async_trait;
use lazy_static::lazy_static;
use std::sync::{Arc, Mutex};

Expand Down Expand Up @@ -32,17 +34,18 @@ pub fn get_client() -> Arc<dyn Client> {
client.clone()
}

pub fn fetch(url: &str, options: Option<FetchOptions>) -> Result<Response> {
pub async fn fetch(url: &str, options: Option<FetchOptions>) -> Result<Response> {
let client = get_client();
client.fetch(url, options)
client.fetch(url, options).await
}

#[cfg(target_arch = "wasm32")]
pub struct ForeignEmptyClient;

#[cfg(target_arch = "wasm32")]
#[async_trait]
impl Client for ForeignEmptyClient {
fn fetch(&self, _url: &str, _options: Option<FetchOptions>) -> Result<Response> {
async fn fetch(&self, _url: &str, _options: Option<FetchOptions>) -> Result<Response> {
return Err(Error::Unknown("global client not set".to_string()));
}
}
13 changes: 7 additions & 6 deletions crates/http-std/src/reqwest_client.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
use crate::{Client, FetchOptions, Method, Response, Result};
use reqwest::blocking::Client as ReqwestBlockingClient;
use async_trait::async_trait;
use reqwest::header::HeaderMap;
use std::collections::HashMap;
use std::convert::TryFrom;

pub struct ReqwestClient {
client: ReqwestBlockingClient,
client: reqwest::Client,
}

impl ReqwestClient {
pub fn new() -> Self {
ReqwestClient {
client: ReqwestBlockingClient::new(),
client: reqwest::Client::new(),
}
}
}

#[async_trait]
impl Client for ReqwestClient {
fn fetch(&self, url: &str, options: Option<FetchOptions>) -> Result<Response> {
async fn fetch(&self, url: &str, options: Option<FetchOptions>) -> Result<Response> {
let options = options.unwrap_or_default();
let method = options.method.unwrap_or(Method::Get).to_string();

Expand All @@ -43,15 +44,15 @@ impl Client for ReqwestClient {
req = req.body(body);
}

let res = req.send().map_err(crate::Error::from)?;
let res = req.send().await.map_err(crate::Error::from)?;

let status_code = res.status().as_u16();
let mut headers = HashMap::new();
for (key, value) in res.headers().iter() {
headers.insert(key.to_string(), value.to_str().unwrap().to_string());
}

let body = res.bytes().map_err(crate::Error::from)?.to_vec();
let body = res.bytes().await.map_err(crate::Error::from)?.to_vec();

Ok(Response {
status_code,
Expand Down
Loading
Loading