koios_sdk/client/
mod.rs

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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Client implementation for the Koios API
//!
//! This module provides the main client implementation for interacting with the Koios API.
//! It includes the core [`Client`] struct, along with the builder pattern for configuration
//! via [`ClientBuilder`].
//!
//! # Examples
//!
//! Basic usage with default configuration (Mainnet):
//!
//! ```rust,no_run
//! use koios_sdk::Client;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let client = Client::new()?;
//!     let tip = client.get_tip().await?;
//!     println!("Current block: {:?}", tip);
//!     Ok(())
//! }
//! ```
//!
//! Using the builder pattern with network selection and custom configuration:
//!
//! ```rust,no_run
//! use koios_sdk::{ClientBuilder, Network};
//! use std::time::Duration;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let client = ClientBuilder::new()
//!         .network(Network::Preprod)
//!         .auth_token("your-jwt-token")
//!         .timeout(Duration::from_secs(60))
//!         .build()?;
//!     
//!     Ok(())
//! }
//! ```
//!
//! Custom base URL (overrides network setting):
//!
//! ```rust,no_run
//! use koios_sdk::ClientBuilder;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let client = ClientBuilder::new()
//!         .base_url("https://custom.api.com")
//!         .build()?;
//!     
//!     Ok(())
//! }
//! ```

mod builder;
mod config;
mod rate_limit;

pub use builder::ClientBuilder;
pub use config::{AuthConfig, Config};
use rate_limit::RateLimiter;

use crate::error::{Error, Result};
use reqwest::{Client as ReqwestClient, RequestBuilder, StatusCode};
use serde::{de::DeserializeOwned, Serialize};
use std::sync::Arc;
use tokio::sync::RwLock;

/// Client for interacting with the Koios API
#[derive(Debug, Clone)]
pub struct Client {
    http_client: ReqwestClient,
    base_url: String,
    auth: Arc<RwLock<Option<AuthConfig>>>,
    rate_limiter: Arc<RateLimiter>,
}

impl Client {
    /// Create a new client with default configuration
    pub fn new() -> Result<Self> {
        Self::builder().build()
    }

    /// Create a new client builder
    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }

    /// Create a new client with custom configuration
    pub(crate) fn with_config(config: Config) -> Result<Self> {
        let http_client = ReqwestClient::builder().timeout(config.timeout).build()?;

        let base_url = config.base_url();

        Ok(Self {
            http_client,
            base_url,
            auth: Arc::new(RwLock::new(config.auth)),
            rate_limiter: Arc::new(RateLimiter::new(config.rate_limit)),
        })
    }

    /// Get the base URL of the client
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Get the authentication token if set (async version)
    pub async fn get_auth_token(&self) -> Option<String> {
        let auth = self.auth.read().await;
        auth.as_ref().and_then(|auth| {
            if auth.is_valid() {
                Some(auth.token.clone())
            } else {
                None
            }
        })
    }

    /// Get the authentication token if set (for compatibility)
    pub fn auth_token(&self) -> Option<String> {
        futures::executor::block_on(self.get_auth_token())
    }

    /// Set authentication token with optional expiry
    pub async fn set_auth_token(&self, token: String) {
        let mut auth = self.auth.write().await;
        *auth = Some(AuthConfig::new(token));
    }

    /// Set authentication token with expiry
    pub async fn set_auth_token_with_expiry(
        &self,
        token: String,
        expiry: chrono::DateTime<chrono::Utc>,
    ) {
        let mut auth = self.auth.write().await;
        *auth = Some(AuthConfig::with_expiry(token, expiry));
    }

    /// Clear authentication token
    pub async fn clear_auth_token(&self) {
        let mut auth = self.auth.write().await;
        *auth = None;
    }

    /// Check if client has valid authentication
    pub async fn has_valid_auth(&self) -> bool {
        let auth = self.auth.read().await;
        auth.as_ref().map_or(false, |auth| auth.is_valid())
    }

    /// Build request with authentication if available
    async fn build_request(&self, request: RequestBuilder) -> RequestBuilder {
        let auth = self.auth.read().await;
        if let Some(auth) = auth.as_ref() {
            if auth.is_valid() {
                return request.header("Authorization", format!("Bearer {}", auth.token));
            }
        }
        request
    }

    /// Make a GET request to the API
    pub(crate) async fn get<T>(&self, endpoint: &str) -> Result<T>
    where
        T: DeserializeOwned,
    {
        // Apply rate limiting
        self.rate_limiter
            .check()
            .await
            .map_err(|e| Error::RateLimit(e.wait_time().as_secs()))?;

        let url = format!("{}{}", self.base_url, endpoint);
        let request = self.http_client.get(&url);
        let request = self.build_request(request).await;

        let response = request.send().await?;

        match response.status() {
            StatusCode::OK => Ok(response.json().await?),
            status => {
                let message = response
                    .text()
                    .await
                    .unwrap_or_else(|_| "Unknown error".to_string());
                Err(Error::Api {
                    status: status.as_u16(),
                    message,
                })
            }
        }
    }

    /// Make a POST request to the API
    pub(crate) async fn post<T, B>(&self, endpoint: &str, body: &B) -> Result<T>
    where
        T: DeserializeOwned,
        B: Serialize,
    {
        // Apply rate limiting
        self.rate_limiter
            .check()
            .await
            .map_err(|e| Error::RateLimit(e.wait_time().as_secs()))?;

        let url = format!("{}{}", self.base_url, endpoint);
        let request = self.http_client.post(&url).json(body);
        let request = self.build_request(request).await;

        let response = request.send().await?;
        let status = response.status();
        let text = response.text().await?;

        // Parse JSON-RPC error response
        if !status.is_success() {
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) {
                if let Some(error) = json.get("error") {
                    if let Some(message) = error.get("message").and_then(|m| m.as_str()) {
                        return Err(Error::Api {
                            status: status.as_u16(),
                            message: message.to_string(),
                        });
                    }
                }
            }
            return Err(Error::Api {
                status: status.as_u16(),
                message: text,
            });
        }

        // Parse successful response
        match serde_json::from_str(&text) {
            Ok(value) => Ok(value),
            Err(e) => Err(Error::Json(e)),
        }
    }

    /// Make a POST request with CBOR data to the API
    pub(crate) async fn post_cbor<T>(&self, endpoint: &str, data: &[u8]) -> Result<T>
    where
        T: DeserializeOwned,
    {
        // Apply rate limiting
        self.rate_limiter
            .check()
            .await
            .map_err(|e| Error::RateLimit(e.wait_time().as_secs()))?;

        let url = format!("{}{}", self.base_url, endpoint);
        let request = self
            .http_client
            .post(&url)
            .header("Content-Type", "application/cbor")
            .body(data.to_vec());

        let request = self.build_request(request).await;

        let response = request.send().await?;

        match response.status() {
            StatusCode::OK | StatusCode::ACCEPTED => Ok(response.json().await?),
            status => {
                let message = response
                    .text()
                    .await
                    .unwrap_or_else(|_| "Unknown error".to_string());
                Err(Error::Api {
                    status: status.as_u16(),
                    message,
                })
            }
        }
    }

    /// Check if response indicates a rate limit error
    fn is_rate_limit_error(status: StatusCode, _text: &str) -> Option<u64> {
        if status == StatusCode::TOO_MANY_REQUESTS {
            // Try to parse retry-after header or default to 60 seconds
            return Some(60);
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use wiremock::matchers::{header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn test_get_request() {
        let mock_server = MockServer::start().await;
        let client = Client::builder()
            .base_url(mock_server.uri())
            .build()
            .unwrap();

        let mock_response = json!({
            "data": "test"
        });

        Mock::given(method("GET"))
            .and(path("/test"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .mount(&mock_server)
            .await;

        let response: serde_json::Value = client.get("/test").await.unwrap();
        assert_eq!(response, mock_response);
    }

    #[tokio::test]
    async fn test_post_request() {
        let mock_server = MockServer::start().await;
        let client = Client::builder()
            .base_url(mock_server.uri())
            .build()
            .unwrap();

        let request_body = json!({
            "test": "data"
        });

        let mock_response = json!({
            "result": "success"
        });

        Mock::given(method("POST"))
            .and(path("/test"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .mount(&mock_server)
            .await;

        let response: serde_json::Value = client.post("/test", &request_body).await.unwrap();
        assert_eq!(response, mock_response);
    }

    #[tokio::test]
    async fn test_auth_token() {
        let mock_server = MockServer::start().await;
        let client = Client::builder()
            .base_url(mock_server.uri())
            .build()
            .unwrap();

        client.set_auth_token("test-token".to_string()).await;
        assert!(client.has_valid_auth().await);
        assert_eq!(
            client.get_auth_token().await,
            Some("test-token".to_string())
        );

        let mock_response = json!({
            "data": "test"
        });

        Mock::given(method("GET"))
            .and(path("/test"))
            .and(header("Authorization", "Bearer test-token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .mount(&mock_server)
            .await;

        let response: serde_json::Value = client.get("/test").await.unwrap();
        assert_eq!(response, mock_response);
    }

    #[tokio::test]
    async fn test_error_handling() {
        let mock_server = MockServer::start().await;
        let client = Client::builder()
            .base_url(mock_server.uri())
            .build()
            .unwrap();

        Mock::given(method("GET"))
            .and(path("/test"))
            .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
            .mount(&mock_server)
            .await;

        let error = client.get::<serde_json::Value>("/test").await.unwrap_err();
        match error {
            Error::Api { status, message } => {
                assert_eq!(status, 404);
                assert_eq!(message, "Not Found");
            }
            _ => panic!("Expected API error"),
        }
    }

    #[tokio::test]
    async fn test_rate_limit() {
        let mock_server = MockServer::start().await;
        let client = Client::builder()
            .base_url(mock_server.uri())
            .build()
            .unwrap();

        Mock::given(method("GET"))
            .and(path("/test"))
            .respond_with(ResponseTemplate::new(429).set_body_string("Too Many Requests"))
            .mount(&mock_server)
            .await;

        let error = client.get::<serde_json::Value>("/test").await.unwrap_err();
        match error {
            Error::Api { status, message } => {
                assert_eq!(status, 429);
                assert_eq!(message, "Too Many Requests");
            }
            _ => panic!("Expected rate limit error"),
        }
    }
}