use std::{sync::Arc, time::Duration};
use hyper::body::Bytes;
use payjp_client_core::{CustomizedPayjpRequest, BlockingClient, PayjpClient};
use crate::error::PayjpError;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Clone, Debug)]
pub struct Client {
inner: crate::Client,
runtime: Arc<tokio::runtime::Runtime>,
}
impl Client {
pub fn new(secret_key: impl Into<String>) -> Client {
Client::from_async(crate::Client::new(secret_key))
}
pub(crate) fn from_async(inner: crate::Client) -> Client {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_io()
.enable_time() .build()
.expect("should be able to get a runtime");
Client { inner, runtime: Arc::new(runtime) }
}
}
impl BlockingClient for Client {
type Err = PayjpError;
fn execute(&self, req: CustomizedPayjpRequest) -> Result<Bytes, Self::Err> {
let future = self.inner.execute(req);
match self.runtime.block_on(async {
tokio::time::timeout(DEFAULT_TIMEOUT, future).await
}) {
Ok(finished) => finished,
Err(_) => Err(PayjpError::Timeout),
}
}
}