1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
// This file is part of Gear.
//
// Copyright (C) 2021-2024 Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! RPC client for Gear API.
use crate::{
    config::GearConfig,
    result::{Error, Result},
};
use futures_util::{StreamExt, TryStreamExt};
use jsonrpsee::{
    core::{
        client::{ClientT, Subscription, SubscriptionClientT, SubscriptionKind},
        traits::ToRpcParams,
    },
    http_client::{HttpClient, HttpClientBuilder},
    types::SubscriptionId,
    ws_client::{WsClient, WsClientBuilder},
};
use sp_runtime::DeserializeOwned;
use std::{ops::Deref, result::Result as StdResult, time::Duration};
use subxt::{
    backend::{
        legacy::LegacyRpcMethods,
        rpc::{
            RawRpcFuture as RpcFuture, RawRpcSubscription as RpcSubscription, RawValue,
            RpcClient as SubxtRpcClient, RpcClientT, RpcParams,
        },
    },
    error::RpcError,
};

const ONE_HUNDRED_MEGA_BYTES: u32 = 100 * 1024 * 1024;

struct Params(Option<Box<RawValue>>);

impl ToRpcParams for Params {
    fn to_rpc_params(self) -> StdResult<Option<Box<RawValue>>, serde_json::Error> {
        Ok(self.0)
    }
}

/// Either http or websocket RPC client
pub enum RpcClient {
    Ws(WsClient),
    Http(HttpClient),
}

impl RpcClient {
    /// Create RPC client from url and timeout.
    pub async fn new(uri: &str, timeout: u64) -> Result<Self> {
        log::info!("Connecting to {uri} ...");

        if uri.starts_with("ws") {
            Ok(Self::Ws(
                WsClientBuilder::default()
                    .max_request_size(ONE_HUNDRED_MEGA_BYTES)
                    .connection_timeout(Duration::from_millis(timeout))
                    .request_timeout(Duration::from_millis(timeout))
                    .build(uri)
                    .await
                    .map_err(Error::SubxtRpc)?,
            ))
        } else if uri.starts_with("http") {
            Ok(Self::Http(
                HttpClientBuilder::default()
                    .request_timeout(Duration::from_millis(timeout))
                    .build(uri)
                    .map_err(Error::SubxtRpc)?,
            ))
        } else {
            Err(Error::InvalidUrl)
        }
    }
}

impl RpcClientT for RpcClient {
    fn request_raw<'a>(
        &'a self,
        method: &'a str,
        params: Option<Box<RawValue>>,
    ) -> RpcFuture<'a, Box<RawValue>> {
        Box::pin(async move {
            let res = match self {
                RpcClient::Http(c) => ClientT::request(c, method, Params(params))
                    .await
                    .map_err(|e| RpcError::ClientError(Box::new(e)))?,
                RpcClient::Ws(c) => ClientT::request(c, method, Params(params))
                    .await
                    .map_err(|e| RpcError::ClientError(Box::new(e)))?,
            };
            Ok(res)
        })
    }

    fn subscribe_raw<'a>(
        &'a self,
        sub: &'a str,
        params: Option<Box<RawValue>>,
        unsub: &'a str,
    ) -> RpcFuture<'a, RpcSubscription> {
        Box::pin(async move {
            let stream = match self {
                RpcClient::Http(c) => subscription_stream(c, sub, params, unsub).await?,
                RpcClient::Ws(c) => subscription_stream(c, sub, params, unsub).await?,
            };

            let id = match stream.kind() {
                SubscriptionKind::Subscription(SubscriptionId::Str(id)) => {
                    Some(id.clone().into_owned())
                }
                _ => None,
            };

            let stream = stream
                .map_err(|e| RpcError::ClientError(Box::new(e)))
                .boxed();

            Ok(RpcSubscription { stream, id })
        })
    }
}

// This is a support fn to create a subscription stream for a generic client
async fn subscription_stream<C: SubscriptionClientT>(
    client: &C,
    sub: &str,
    params: Option<Box<RawValue>>,
    unsub: &str,
) -> StdResult<Subscription<Box<RawValue>>, RpcError> {
    SubscriptionClientT::subscribe::<Box<RawValue>, _>(client, sub, Params(params), unsub)
        .await
        .map_err(|e| RpcError::ClientError(Box::new(e)))
}

/// RPC client for Gear API.
#[derive(Clone)]
pub struct Rpc {
    rpc: SubxtRpcClient,
    methods: LegacyRpcMethods<GearConfig>,
    retries: u8,
}

impl Rpc {
    /// Create RPC client from url and timeout.
    pub async fn new(uri: &str, timeout: u64, retries: u8) -> Result<Self> {
        let rpc = SubxtRpcClient::new(RpcClient::new(uri, timeout).await?);
        let methods = LegacyRpcMethods::new(rpc.clone());
        Ok(Self {
            rpc,
            methods,
            retries,
        })
    }

    /// Get RPC client.
    pub fn client(&self) -> SubxtRpcClient {
        self.rpc.clone()
    }

    /// Raw RPC request
    pub async fn request<Res: DeserializeOwned>(
        &self,
        method: &str,
        params: RpcParams,
    ) -> Result<Res> {
        let mut retries = 0;

        loop {
            let r = self
                .rpc
                .request(method, params.clone())
                .await
                .map_err(Into::into);

            if retries == self.retries || r.is_ok() {
                return r;
            }

            retries += 1;
            log::warn!("Failed to send request: {:?}, retries: {retries}", r.err());
        }
    }
}

impl Deref for Rpc {
    type Target = LegacyRpcMethods<GearConfig>;

    fn deref(&self) -> &Self::Target {
        &self.methods
    }
}