cyfs_lib/requestor/
surf.rs1use super::requestor::*;
2use cyfs_base::*;
3
4use http_types::{Request, Response};
5use std::sync::Arc;
6use surf::{Client, Config};
7
8const DEFAULT_MAX_CONNECTIONS_PER_HOST: usize = 50;
18
19#[derive(Clone)]
20pub struct SurfHttpRequestor {
21 service_addr: String,
22 client: Arc<Client>,
23}
24
25impl SurfHttpRequestor {
26 pub fn new(service_addr: &str, mut http_max_connections_per_host: usize) -> Self {
27 if http_max_connections_per_host == 0 {
28 http_max_connections_per_host = DEFAULT_MAX_CONNECTIONS_PER_HOST;
29 }
30
31 let client = Config::new()
32 .set_max_connections_per_host(http_max_connections_per_host)
33 .try_into()
34 .unwrap();
35
36 Self {
37 service_addr: service_addr.to_owned(),
38 client: Arc::new(client),
39 }
40 }
41}
42
43#[async_trait::async_trait]
44impl HttpRequestor for SurfHttpRequestor {
45 async fn request_ext(
46 &self,
47 req: &mut Option<Request>,
48 _conn_info: Option<&mut HttpRequestConnectionInfo>,
49 ) -> BuckyResult<Response> {
50 debug!(
51 "will http request to {}, url={}",
52 self.remote_addr(),
53 req.as_ref().unwrap().url()
54 );
55
56 let begin = std::time::Instant::now();
57 let req = req.take().unwrap();
58 let req = self.add_default_headers(req);
59 match self.client.send(req).await {
60 Ok(resp) => {
61 info!(
62 "http request to {} success! during={}ms",
63 self.remote_addr(),
64 begin.elapsed().as_millis()
65 );
66 Ok(resp.into())
67 }
68 Err(e) => {
69 let msg = format!(
70 "http request to {} failed! during={}ms, {}",
71 self.remote_addr(),
72 begin.elapsed().as_millis(),
73 e,
74 );
75 error!("{}", msg);
76 Err(BuckyError::from(msg))
77 }
78 }
79 }
80
81 fn remote_addr(&self) -> String {
82 self.service_addr.to_string()
83 }
84
85 fn remote_device(&self) -> Option<DeviceId> {
86 None
87 }
88
89 fn clone_requestor(&self) -> Box<dyn HttpRequestor> {
90 Box::new(self.clone())
91 }
92
93 async fn stop(&self) {
94 }
97}