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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
use std::{cmp, time::Duration};

use anyhow::{anyhow, Context, Result};
use arrow2::{array::Array, chunk::Chunk};
use futures::StreamExt;
use reqwest::Method;
use skar_net_types::{skar_net_types_capnp, ArchiveHeight, Query, RollbackGuard};

mod column_mapping;
pub mod config;
mod decode;
mod parquet_out;
mod rayon_async;
mod transport_format;
mod types;

pub use column_mapping::{ColumnMapping, DataType};
pub use config::Config;
pub use decode::Decoder;
pub use skar_format as format;
use tokio::sync::mpsc;
pub use transport_format::{ArrowIpc, TransportFormat};
pub use types::{ArrowBatch, ParquetConfig, QueryResponse, QueryResponseData, StreamConfig};

pub type ArrowChunk = Chunk<Box<dyn Array>>;

#[derive(Clone)]
pub struct Client {
    http_client: reqwest::Client,
    cfg: Config,
}

impl Client {
    /// Create a new client with given config
    pub fn new(cfg: Config) -> Result<Self> {
        let http_client = reqwest::Client::builder()
            .no_gzip()
            .http1_only()
            .timeout(Duration::from_millis(cfg.http_req_timeout_millis.get()))
            .tcp_keepalive(Duration::from_secs(7200))
            .connect_timeout(Duration::from_millis(cfg.http_req_timeout_millis.get()))
            .build()
            .unwrap();

        Ok(Self { http_client, cfg })
    }

    /// Create a parquet file by executing a query.
    ///
    /// Path should point to a folder that will contain the parquet files in the end.
    pub async fn create_parquet_folder(&self, query: Query, config: ParquetConfig) -> Result<()> {
        parquet_out::create_parquet_folder(self, query, config).await
    }

    /// Get the height of the source hypersync instance
    pub async fn get_height(&self) -> Result<u64> {
        let mut url = self.cfg.url.clone();
        let mut segments = url.path_segments_mut().ok().context("get path segments")?;
        segments.push("height");
        std::mem::drop(segments);
        let mut req = self.http_client.request(Method::GET, url);

        if let Some(bearer_token) = &self.cfg.bearer_token {
            req = req.bearer_auth(bearer_token);
        }

        let res = req.send().await.context("execute http req")?;

        let status = res.status();
        if !status.is_success() {
            return Err(anyhow!("http response status code {}", status));
        }

        let height: ArchiveHeight = res.json().await.context("read response body json")?;

        Ok(height.height.unwrap_or(0))
    }

    /// Get the height of the source hypersync instance
    /// Internally calls get_height.
    /// On an error from the source hypersync instance, sleeps for
    /// 1 second (increasing by 1 each failure up to max of 5 seconds)
    /// and retries query until success.
    pub async fn get_height_with_retry(&self) -> Result<u64> {
        let mut base = 1;

        loop {
            match self.get_height().await {
                Ok(res) => return Ok(res),
                Err(e) => {
                    log::error!("failed to send request to skar server: {:?}", e);
                }
            }

            let secs = Duration::from_secs(base);
            let millis = Duration::from_millis(fastrange_rs::fastrange_64(rand::random(), 1000));

            tokio::time::sleep(secs + millis).await;

            base = std::cmp::min(base + 1, 5);
        }
    }

    pub async fn stream<Format: TransportFormat>(
        &self,
        query: Query,
        config: StreamConfig,
    ) -> Result<mpsc::Receiver<Result<QueryResponse>>> {
        let (tx, rx) = mpsc::channel(config.concurrency);

        let to_block = match query.to_block {
            Some(to_block) => to_block,
            None => {
                if config.retry {
                    self.get_height_with_retry().await.context("get height")?
                } else {
                    self.get_height().await.context("get height")?
                }
            }
        };

        let client = self.clone();
        let step = usize::try_from(config.batch_size).unwrap();
        tokio::spawn(async move {
            let futs = (query.from_block..to_block)
                .step_by(step)
                .map(move |start| {
                    let end = cmp::min(start + config.batch_size, to_block);
                    let mut query = query.clone();
                    query.from_block = start;
                    query.to_block = Some(end);

                    Self::run_query_to_end(client.clone(), query, config.retry)
                });

            let mut stream = futures::stream::iter(futs).buffered(config.concurrency);

            while let Some(resps) = stream.next().await {
                let resps = match resps {
                    Ok(resps) => resps,
                    Err(e) => {
                        tx.send(Err(e)).await.ok();
                        return;
                    }
                };

                for resp in resps {
                    if tx.send(Ok(resp)).await.is_err() {
                        return;
                    }
                }
            }
        });

        Ok(rx)
    }

    async fn run_query_to_end(self, query: Query, retry: bool) -> Result<Vec<QueryResponse>> {
        let mut resps = Vec::new();

        let to_block = query.to_block.unwrap();

        let mut query = query;

        loop {
            let resp = if retry {
                self.send_with_retry::<crate::ArrowIpc>(&query)
                    .await
                    .context("send query")?
            } else {
                self.send::<crate::ArrowIpc>(&query)
                    .await
                    .context("send query")?
            };

            let next_block = resp.next_block;

            resps.push(resp);

            if next_block >= to_block {
                break;
            } else {
                query.from_block = next_block;
            }
        }

        Ok(resps)
    }

    /// Send a query request to the source hypersync instance.
    ///
    /// Returns a query response which contains block, tx and log data.
    /// Format can be ArrowIpc or Parquet.
    pub async fn send<Format: TransportFormat>(&self, query: &Query) -> Result<QueryResponse> {
        let mut url = self.cfg.url.clone();
        let mut segments = url.path_segments_mut().ok().context("get path segments")?;
        segments.push("query");
        segments.push(Format::path());
        std::mem::drop(segments);
        let mut req = self.http_client.request(Method::POST, url);

        if let Some(bearer_token) = &self.cfg.bearer_token {
            req = req.bearer_auth(bearer_token);
        }

        let res = req.json(&query).send().await.context("execute http req")?;

        let status = res.status();
        if !status.is_success() {
            let text = res.text().await.context("read text to see error")?;

            return Err(anyhow!(
                "http response status code {}, err body: {}",
                status,
                text
            ));
        }

        let bytes = res.bytes().await.context("read response body bytes")?;

        let res = tokio::task::block_in_place(|| {
            Self::parse_query_response::<Format>(&bytes).context("parse query response")
        })?;

        Ok(res)
    }

    /// Send a query request to the source hypersync instance.
    /// Internally calls send.
    /// On an error from the source hypersync instance, sleeps for
    /// 1 second (increasing by 1 each failure up to max of 5 seconds)
    /// and retries query until success.
    ///
    /// Returns a query response which contains block, tx and log data.
    /// Format can be ArrowIpc or Parquet.
    pub async fn send_with_retry<Format: TransportFormat>(
        &self,
        query: &Query,
    ) -> Result<QueryResponse> {
        let mut base = 1;

        loop {
            match self.send::<Format>(query).await {
                Ok(res) => return Ok(res),
                Err(e) => {
                    log::error!("failed to send request to skar server: {:?}", e);
                }
            }

            let secs = Duration::from_secs(base);
            let millis = Duration::from_millis(fastrange_rs::fastrange_64(rand::random(), 1000));

            tokio::time::sleep(secs + millis).await;

            base = std::cmp::min(base + 1, 5);
        }
    }

    fn parse_query_response<Format: TransportFormat>(bytes: &[u8]) -> Result<QueryResponse> {
        let mut opts = capnp::message::ReaderOptions::new();
        opts.nesting_limit(i32::MAX).traversal_limit_in_words(None);
        let message_reader =
            capnp::serialize_packed::read_message(bytes, opts).context("create message reader")?;

        let query_response = message_reader
            .get_root::<skar_net_types_capnp::query_response::Reader>()
            .context("get root")?;

        let archive_height = match query_response.get_archive_height() {
            -1 => None,
            h => Some(
                h.try_into()
                    .context("invalid archive height returned from server")?,
            ),
        };

        let rollback_guard = if query_response.has_rollback_guard() {
            let rg = query_response
                .get_rollback_guard()
                .context("get rollback guard")?;

            Some(RollbackGuard {
                block_number: rg.get_block_number(),
                timestamp: rg.get_timestamp(),
                hash: rg
                    .get_hash()
                    .context("get rollback guard hash")?
                    .try_into()
                    .context("hash size")?,
                first_block_number: rg.get_first_block_number(),
                first_parent_hash: rg
                    .get_first_parent_hash()
                    .context("get rollback guard first parent hash")?
                    .try_into()
                    .context("hash size")?,
            })
        } else {
            None
        };

        let data = query_response.get_data().context("read data")?;

        let blocks = Format::read_chunks(data.get_blocks().context("get data")?)
            .context("parse block data")?;
        let transactions = Format::read_chunks(data.get_transactions().context("get data")?)
            .context("parse tx data")?;
        let logs =
            Format::read_chunks(data.get_logs().context("get data")?).context("parse log data")?;
        let traces = if data.has_traces() {
            Format::read_chunks(data.get_traces().context("get data")?)
                .context("parse traces data")?
        } else {
            Vec::new()
        };

        Ok(QueryResponse {
            archive_height,
            next_block: query_response.get_next_block(),
            total_execution_time: query_response.get_total_execution_time(),
            data: QueryResponseData {
                blocks,
                transactions,
                logs,
                traces,
            },
            rollback_guard,
        })
    }
}