1use std::env;
13use std::fmt::{self, Debug};
14use std::sync::LazyLock;
15use std::time::Duration;
16
17use anyhow::bail;
18use futures::future::Either;
19use http::{HeaderMap, HeaderValue, header};
20use jsonrpsee::core::ClientError;
21use jsonrpsee::core::client::ClientT as _;
22use jsonrpsee::core::params::{ArrayParams, ObjectParams};
23use jsonrpsee::core::traits::ToRpcParams;
24use serde::de::DeserializeOwned;
25use tracing::{Instrument, Level, debug};
26use url::Url;
27
28use super::{ApiPaths, MAX_REQUEST_BODY_SIZE, MAX_RESPONSE_BODY_SIZE, Request};
29
30pub struct Client {
32 base_url: Url,
34 token: Option<String>,
35 v0: tokio::sync::OnceCell<UrlClient>,
37 v1: tokio::sync::OnceCell<UrlClient>,
38 v2: tokio::sync::OnceCell<UrlClient>,
39}
40
41impl Client {
42 pub fn default_or_from_env(token: Option<&str>) -> anyhow::Result<Self> {
46 static DEFAULT: LazyLock<Url> = LazyLock::new(|| {
47 "http://127.0.0.1:2345/"
48 .parse()
49 .expect("hardcoded default RPC URL is valid")
50 });
51
52 let mut base_url = match env::var("FULLNODE_API_INFO") {
53 Ok(it) => {
54 let crate::utils::UrlFromMultiAddr(url) = it.parse()?;
55 url
56 }
57 Err(env::VarError::NotPresent) => DEFAULT.clone(),
58 Err(e @ env::VarError::NotUnicode(_)) => bail!(e),
59 };
60 if token.is_some() && base_url.set_password(token).is_err() {
61 bail!("couldn't set override password")
62 }
63 if token.is_none() && base_url.password().is_none() {
65 let default_token_path = crate::cli_shared::default_token_path();
68 if default_token_path.is_file() {
69 if let Ok(token) = std::fs::read_to_string(&default_token_path) {
70 if base_url.set_password(Some(token.trim())).is_ok() {
71 tracing::debug!("Loaded the default RPC token");
72 } else {
73 tracing::warn!("Failed to set the default RPC token");
74 }
75 } else {
76 tracing::warn!("Failed to load the default token file");
77 }
78 }
79 }
80 Ok(Self::from_url(base_url))
81 }
82 pub fn from_url(mut base_url: Url) -> Self {
83 let token = base_url.password().map(Into::into);
84 let _defer = base_url.set_password(None);
85 Self {
86 token,
87 base_url,
88 v0: Default::default(),
89 v1: Default::default(),
90 v2: Default::default(),
91 }
92 }
93 pub fn base_url(&self) -> &Url {
94 &self.base_url
95 }
96 pub async fn call<T: crate::lotus_json::HasLotusJson + std::fmt::Debug>(
97 &self,
98 req: Request<T>,
99 ) -> Result<T, ClientError> {
100 let api_path = req.api_path;
101 let Request {
102 method_name,
103 params,
104 timeout,
105 ..
106 } = req;
107 let method_name = method_name.as_ref();
108 let client = self.get_or_init_client(api_path).await?;
109 let span = tracing::debug_span!("request", method = %method_name, url = %client.url);
110 let work = async {
111 let result_or_timeout = tokio::time::timeout(
115 timeout,
116 match params {
117 serde_json::Value::Null => Either::Left(Either::Left(
118 client.request::<T::LotusJson, _>(method_name, ArrayParams::new()),
119 )),
120 serde_json::Value::Array(it) => {
121 let mut params = ArrayParams::new();
122 for param in it {
123 params.insert(param)?
124 }
125 trace_params(params.clone());
126 Either::Left(Either::Right(client.request(method_name, params)))
127 }
128 serde_json::Value::Object(it) => {
129 let mut params = ObjectParams::new();
130 for (name, param) in it {
131 params.insert(&name, param)?
132 }
133 trace_params(params.clone());
134 Either::Right(client.request(method_name, params))
135 }
136 prim @ (serde_json::Value::Bool(_)
137 | serde_json::Value::Number(_)
138 | serde_json::Value::String(_)) => {
139 return Err(ClientError::Custom(format!(
140 "invalid parameter type: `{prim}`"
141 )));
142 }
143 },
144 )
145 .await;
146 let result = match result_or_timeout {
147 Ok(Ok(it)) => Ok(T::from_lotus_json(it)),
148 Ok(Err(e)) => Err(e),
149 Err(_) => Err(ClientError::RequestTimeout),
150 };
151 debug!(?result);
152 result
153 };
154 work.instrument(span.or_current()).await
155 }
156 async fn get_or_init_client(&self, path: ApiPaths) -> Result<&UrlClient, ClientError> {
157 match path {
158 ApiPaths::V0 => &self.v0,
159 ApiPaths::V1 => &self.v1,
160 ApiPaths::V2 => &self.v2,
161 }
162 .get_or_try_init(|| async {
163 let url = self.base_url.join(path.path()).map_err(|it| {
164 ClientError::Custom(format!("creating url for endpoint failed: {it}"))
165 })?;
166 UrlClient::new(url, self.token.clone()).await
167 })
168 .await
169 }
170}
171
172fn trace_params(params: impl jsonrpsee::core::traits::ToRpcParams) {
173 if tracing::enabled!(Level::TRACE) {
174 match params.to_rpc_params() {
175 Ok(Some(it)) => tracing::trace!(params = %it),
176 Ok(None) => tracing::trace!("no params"),
177 Err(error) => tracing::trace!(%error, "couldn't decode params"),
178 }
179 }
180}
181
182pub struct UrlClient {
185 url: Url,
186 inner: UrlClientInner,
187}
188
189impl Debug for UrlClient {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 f.debug_struct("OneClient")
192 .field("url", &self.url)
193 .finish_non_exhaustive()
194 }
195}
196
197impl UrlClient {
198 pub async fn new(url: Url, token: impl Into<Option<String>>) -> Result<Self, ClientError> {
199 const ONE_DAY: Duration = Duration::from_secs(24 * 3600); let mut headers = HeaderMap::from_iter([(
201 header::USER_AGENT,
202 HeaderValue::from_static(crate::utils::version::FOREST_USER_AGENT),
203 )]);
204 if let Some(token) = token.into() {
205 let value = HeaderValue::try_from(format!("Bearer {token}"))
206 .map_err(|e| ClientError::Custom(format!("Invalid authorization token: {e}")))?;
207 headers.insert(header::AUTHORIZATION, value);
208 }
209 let inner = match url.scheme() {
210 "ws" | "wss" => UrlClientInner::Ws(
211 jsonrpsee::ws_client::WsClientBuilder::new()
212 .set_headers(headers)
213 .max_request_size(MAX_REQUEST_BODY_SIZE)
214 .max_response_size(*MAX_RESPONSE_BODY_SIZE)
215 .request_timeout(ONE_DAY)
216 .build(&url)
217 .await?,
218 ),
219 "http" | "https" => UrlClientInner::Https(
220 jsonrpsee::http_client::HttpClientBuilder::new()
221 .set_headers(headers)
222 .max_request_size(MAX_REQUEST_BODY_SIZE)
223 .max_response_size(*MAX_RESPONSE_BODY_SIZE)
224 .request_timeout(ONE_DAY)
225 .build(&url)?,
226 ),
227 it => {
228 return Err(ClientError::Custom(format!("Unsupported URL scheme: {it}")));
229 }
230 };
231 Ok(Self { url, inner })
232 }
233}
234
235#[allow(clippy::large_enum_variant)]
236enum UrlClientInner {
237 Ws(jsonrpsee::ws_client::WsClient),
238 Https(jsonrpsee::http_client::HttpClient),
239}
240
241impl jsonrpsee::core::client::ClientT for UrlClient {
242 fn notification<Params>(
243 &self,
244 method: &str,
245 params: Params,
246 ) -> impl Future<Output = Result<(), jsonrpsee::core::client::Error>> + Send
247 where
248 Params: ToRpcParams + Send,
249 {
250 match &self.inner {
251 UrlClientInner::Ws(it) => Either::Left(it.notification(method, params)),
252 UrlClientInner::Https(it) => Either::Right(it.notification(method, params)),
253 }
254 }
255
256 fn request<R, Params>(
257 &self,
258 method: &str,
259 params: Params,
260 ) -> impl Future<Output = Result<R, jsonrpsee::core::client::Error>> + Send
261 where
262 R: DeserializeOwned,
263 Params: ToRpcParams + Send,
264 {
265 match &self.inner {
266 UrlClientInner::Ws(it) => Either::Left(it.request(method, params)),
267 UrlClientInner::Https(it) => Either::Right(it.request(method, params)),
268 }
269 }
270
271 fn batch_request<'a, R>(
272 &self,
273 batch: jsonrpsee::core::params::BatchRequestBuilder<'a>,
274 ) -> impl Future<
275 Output = Result<
276 jsonrpsee::core::client::BatchResponse<'a, R>,
277 jsonrpsee::core::client::Error,
278 >,
279 > + Send
280 where
281 R: DeserializeOwned + fmt::Debug + 'a,
282 {
283 match &self.inner {
284 UrlClientInner::Ws(it) => Either::Left(it.batch_request(batch)),
285 UrlClientInner::Https(it) => Either::Right(it.batch_request(batch)),
286 }
287 }
288}
289
290impl jsonrpsee::core::client::SubscriptionClientT for UrlClient {
291 fn subscribe<'a, N, Params>(
292 &self,
293 subscribe_method: &'a str,
294 params: Params,
295 unsubscribe_method: &'a str,
296 ) -> impl Future<
297 Output = Result<jsonrpsee::core::client::Subscription<N>, jsonrpsee::core::client::Error>,
298 >
299 where
300 Params: ToRpcParams + Send,
301 N: DeserializeOwned,
302 {
303 match &self.inner {
304 UrlClientInner::Ws(it) => {
305 Either::Left(it.subscribe(subscribe_method, params, unsubscribe_method))
306 }
307 UrlClientInner::Https(it) => {
308 Either::Right(it.subscribe(subscribe_method, params, unsubscribe_method))
309 }
310 }
311 }
312
313 fn subscribe_to_method<N>(
314 &self,
315 method: &str,
316 ) -> impl Future<
317 Output = Result<jsonrpsee::core::client::Subscription<N>, jsonrpsee::core::client::Error>,
318 >
319 where
320 N: DeserializeOwned,
321 {
322 match &self.inner {
323 UrlClientInner::Ws(it) => Either::Left(it.subscribe_to_method(method)),
324 UrlClientInner::Https(it) => Either::Right(it.subscribe_to_method(method)),
325 }
326 }
327}
328
329pub fn humanize_rpc_error(e: anyhow::Error) -> anyhow::Error {
332 match e.downcast_ref::<ClientError>() {
333 Some(ClientError::Call(obj)) => {
334 let contexts: Vec<String> = e
335 .chain()
336 .take_while(|cause| cause.downcast_ref::<ClientError>().is_none())
337 .map(ToString::to_string)
338 .collect();
339 let mut out = match obj.data() {
340 Some(data) => anyhow::anyhow!("{} (data: {data})", obj.message()),
341 None => anyhow::anyhow!("{}", obj.message()),
342 };
343 for context in contexts.into_iter().rev() {
344 out = out.context(context);
345 }
346 out
347 }
348 _ => e,
349 }
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355 use crate::cli_shared::FOREST_DATA_DIR_ENV;
356 use jsonrpsee::types::ErrorObject;
357
358 fn call_error() -> ClientError {
359 ClientError::Call(ErrorObject::owned(1, "export already running", None::<()>))
360 }
361
362 #[test]
363 fn rpc_call_errors_render_as_their_message() {
364 assert_eq!(
365 format!("{:#}", humanize_rpc_error(call_error().into())),
366 "export already running"
367 );
368
369 let wrapped = anyhow::Error::from(call_error()).context("failed to check F3 sync status");
370 assert_eq!(
371 format!("{:#}", humanize_rpc_error(wrapped)),
372 "failed to check F3 sync status: export already running"
373 );
374
375 let other = anyhow::anyhow!("inner").context("outer");
377 assert_eq!(format!("{:#}", humanize_rpc_error(other)), "outer: inner");
378 }
379
380 #[test]
384 #[serial_test::serial]
385 fn default_token_is_loaded_from_forest_path_data_dir() {
386 let tmp_dir = tempfile::tempdir().unwrap();
387 std::fs::write(tmp_dir.path().join("token"), "secret-token").unwrap();
388
389 unsafe {
390 env::remove_var("FULLNODE_API_INFO");
391 env::set_var(FOREST_DATA_DIR_ENV, tmp_dir.path());
392 }
393 let client = Client::default_or_from_env(None).unwrap();
394 unsafe { env::remove_var(FOREST_DATA_DIR_ENV) };
395
396 assert_eq!(client.token.as_deref(), Some("secret-token"));
397 }
398}