build: allow to switch async runtime

This commit is contained in:
mokurin000
2025-07-30 17:55:19 +08:00
parent 7670e6f3ae
commit 19a0d53624
9 changed files with 517 additions and 22 deletions

View File

@@ -3,24 +3,36 @@ use snafu::Snafu;
#[derive(Debug, Snafu)]
pub enum ApiError {
JoinError,
#[snafu(display("api returned nothing!"))]
EmptyResponse,
#[snafu(display("encrypt data: {error}"))]
Pad { error: PadError },
Pad {
error: PadError,
},
#[snafu(display("decrypt data: {error}"))]
Unpad { error: UnpadError },
Unpad {
error: UnpadError,
},
#[snafu(display("io error: {source}"))]
#[snafu(context(false))]
IO { source: std::io::Error },
IO {
source: std::io::Error,
},
#[snafu(display("json error: {source}"))]
#[snafu(context(false))]
JSON { source: serde_json::Error },
JSON {
source: serde_json::Error,
},
#[snafu(display("request error: {source}"))]
#[snafu(context(false))]
Request { source: nyquest::Error },
Request {
source: nyquest::Error,
},
}
impl From<UnpadError> for ApiError {

View File

@@ -62,16 +62,25 @@ pub trait MaiVersionExt: MaiVersion {
fn request_raw<D>(
client: &AsyncClient,
api: APIMethod,
agent_extra: impl Display,
agent_extra: impl Display + Send + 'static,
data: D,
) -> impl Future<Output = Result<Vec<u8>, ApiError>>
where
D: Serialize,
D: Serialize + Send + 'static,
{
#[cfg(feature = "compio")]
use compio::runtime::spawn_blocking;
#[cfg(feature = "tokio")]
use tokio::task::spawn_blocking;
async {
let req = Self::api_call(api, agent_extra, data)?;
let req = spawn_blocking(move || Self::api_call(api, agent_extra, data))
.await
.map_err(|_| ApiError::JoinError)??;
let data = client.request(req).await?.bytes().await?;
let decoded = Self::decode(data)?;
let decoded = spawn_blocking(move || Self::decode(data))
.await
.map_err(|_| ApiError::JoinError)??;
Ok(decoded)
}
}
@@ -79,11 +88,11 @@ pub trait MaiVersionExt: MaiVersion {
fn request<D, R>(
client: &AsyncClient,
api: APIMethod,
agent_extra: impl Display,
agent_extra: impl Display + Send + 'static,
data: D,
) -> impl Future<Output = Result<R, ApiError>>
where
D: Serialize,
D: Serialize + Send + 'static,
R: for<'a> Deserialize<'a>,
{
async {