files-sdk 0.4.1

Rust SDK for the Files.com API
Documentation
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Files.com API client core implementation
//!
//! This module contains the core HTTP client for interacting with the Files.com REST API.
//! It provides authentication handling, request/response processing, and error management.
//!
//! The client is designed around a builder pattern for flexible configuration and supports
//! both typed and untyped API interactions.

use crate::{FilesError, Result};
use reqwest::Client;
use serde::Serialize;
use std::sync::Arc;
use std::time::Duration;

#[cfg(feature = "tracing")]
use tracing::{debug, error, instrument, warn};

/// User-Agent header value
/// Format: "Files.com Rust SDK {version}"
const USER_AGENT: &str = concat!("Files.com Rust SDK ", env!("CARGO_PKG_VERSION"));

/// Builder for constructing a FilesClient with custom configuration
///
/// Provides a fluent interface for configuring API credentials, base URL, timeouts,
/// and other client settings before creating the final FilesClient instance.
///
/// # Examples
///
/// ```rust,no_run
/// use files_sdk::FilesClient;
///
/// // Basic configuration
/// let client = FilesClient::builder()
///     .api_key("your-api-key")
///     .build()?;
///
/// // Advanced configuration
/// let client = FilesClient::builder()
///     .api_key("your-api-key")
///     .base_url("https://app.files.com/api/rest/v1".to_string())
///     .timeout(std::time::Duration::from_secs(120))
///     .build()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
pub struct FilesClientBuilder {
    api_key: Option<String>,
    base_url: String,
    timeout: Duration,
}

impl Default for FilesClientBuilder {
    fn default() -> Self {
        Self {
            api_key: None,
            base_url: "https://app.files.com/api/rest/v1".to_string(),
            timeout: Duration::from_secs(60),
        }
    }
}

impl FilesClientBuilder {
    /// Sets the API key for authentication
    ///
    /// # Arguments
    ///
    /// * `api_key` - Your Files.com API key
    pub fn api_key<S: Into<String>>(mut self, api_key: S) -> Self {
        self.api_key = Some(api_key.into());
        self
    }

    /// Sets a custom base URL for the API
    ///
    /// # Arguments
    ///
    /// * `base_url` - Custom base URL (useful for testing or regional endpoints)
    pub fn base_url<S: Into<String>>(mut self, base_url: S) -> Self {
        self.base_url = base_url.into();
        self
    }

    /// Sets the request timeout duration
    ///
    /// # Arguments
    ///
    /// * `timeout` - Maximum duration for API requests
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Builds the FilesClient instance
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - API key is not set
    /// - HTTP client cannot be constructed
    pub fn build(self) -> Result<FilesClient> {
        let api_key = self
            .api_key
            .ok_or_else(|| FilesError::ConfigError("API key is required".to_string()))?;

        let client = Client::builder()
            .timeout(self.timeout)
            .build()
            .map_err(|e| FilesError::ConfigError(format!("Failed to build HTTP client: {}", e)))?;

        Ok(FilesClient {
            inner: Arc::new(FilesClientInner {
                api_key,
                base_url: self.base_url,
                client,
            }),
        })
    }
}

/// Internal client state
#[derive(Debug)]
pub(crate) struct FilesClientInner {
    pub(crate) api_key: String,
    pub(crate) base_url: String,
    pub(crate) client: Client,
}

/// Files.com API client
///
/// The main client for interacting with the Files.com API. Handles authentication,
/// request construction, and response processing.
///
/// # Examples
///
/// ```rust,no_run
/// use files_sdk::FilesClient;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = FilesClient::builder()
///     .api_key("your-api-key")
///     .build()?;
///
/// // Use with handlers
/// let file_handler = files_sdk::FileHandler::new(client.clone());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct FilesClient {
    pub(crate) inner: Arc<FilesClientInner>,
}

impl FilesClient {
    /// Creates a new FilesClientBuilder
    pub fn builder() -> FilesClientBuilder {
        FilesClientBuilder::default()
    }

    /// Performs a GET request to the Files.com API
    ///
    /// # Arguments
    ///
    /// * `path` - API endpoint path (without base URL)
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or returns a non-success status code
    #[cfg_attr(feature = "tracing", instrument(skip(self), fields(method = "GET")))]
    pub async fn get_raw(&self, path: &str) -> Result<serde_json::Value> {
        let url = format!("{}{}", self.inner.base_url, path);

        #[cfg(feature = "tracing")]
        debug!("Making GET request to {}", path);

        let response = self
            .inner
            .client
            .get(&url)
            .header("X-FilesAPI-Key", &self.inner.api_key)
            .header("User-Agent", USER_AGENT)
            .send()
            .await?;

        #[cfg(feature = "tracing")]
        debug!("GET response status: {}", response.status());

        self.handle_response(response).await
    }

    /// Performs a POST request to the Files.com API
    ///
    /// # Arguments
    ///
    /// * `path` - API endpoint path (without base URL)
    /// * `body` - Request body (will be serialized to JSON)
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or returns a non-success status code
    #[cfg_attr(
        feature = "tracing",
        instrument(skip(self, body), fields(method = "POST"))
    )]
    pub async fn post_raw<T: Serialize>(&self, path: &str, body: T) -> Result<serde_json::Value> {
        let url = format!("{}{}", self.inner.base_url, path);

        #[cfg(feature = "tracing")]
        debug!("Making POST request to {}", path);

        let json_body = serde_json::to_string(&body).map_err(FilesError::JsonError)?;

        let response = self
            .inner
            .client
            .post(&url)
            .header("X-FilesAPI-Key", &self.inner.api_key)
            .header("User-Agent", USER_AGENT)
            .header("Content-Type", "application/json")
            .body(json_body)
            .send()
            .await?;

        #[cfg(feature = "tracing")]
        debug!("POST response status: {}", response.status());

        self.handle_response(response).await
    }

    /// Performs a PATCH request to the Files.com API
    ///
    /// # Arguments
    ///
    /// * `path` - API endpoint path (without base URL)
    /// * `body` - Request body (will be serialized to JSON)
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or returns a non-success status code
    #[cfg_attr(
        feature = "tracing",
        instrument(skip(self, body), fields(method = "PATCH"))
    )]
    pub async fn patch_raw<T: Serialize>(&self, path: &str, body: T) -> Result<serde_json::Value> {
        let url = format!("{}{}", self.inner.base_url, path);

        #[cfg(feature = "tracing")]
        debug!("Making PATCH request to {}", path);

        let json_body = serde_json::to_string(&body).map_err(FilesError::JsonError)?;

        let response = self
            .inner
            .client
            .patch(&url)
            .header("X-FilesAPI-Key", &self.inner.api_key)
            .header("User-Agent", USER_AGENT)
            .header("Content-Type", "application/json")
            .body(json_body)
            .send()
            .await?;

        #[cfg(feature = "tracing")]
        debug!("PATCH response status: {}", response.status());

        self.handle_response(response).await
    }

    /// Performs a DELETE request to the Files.com API
    ///
    /// # Arguments
    ///
    /// * `path` - API endpoint path (without base URL)
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or returns a non-success status code
    #[cfg_attr(feature = "tracing", instrument(skip(self), fields(method = "DELETE")))]
    pub async fn delete_raw(&self, path: &str) -> Result<serde_json::Value> {
        let url = format!("{}{}", self.inner.base_url, path);

        #[cfg(feature = "tracing")]
        debug!("Making DELETE request to {}", path);

        let response = self
            .inner
            .client
            .delete(&url)
            .header("X-FilesAPI-Key", &self.inner.api_key)
            .header("User-Agent", USER_AGENT)
            .send()
            .await?;

        #[cfg(feature = "tracing")]
        debug!("DELETE response status: {}", response.status());

        self.handle_response(response).await
    }

    /// Performs a POST request with form data to the Files.com API
    ///
    /// # Arguments
    ///
    /// * `path` - API endpoint path (without base URL)
    /// * `form` - Form data as key-value pairs
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or returns a non-success status code
    pub async fn post_form<T: Serialize>(&self, path: &str, form: T) -> Result<serde_json::Value> {
        let url = format!("{}{}", self.inner.base_url, path);

        let response = self
            .inner
            .client
            .post(&url)
            .header("X-FilesAPI-Key", &self.inner.api_key)
            .header("User-Agent", USER_AGENT)
            .form(&form)
            .send()
            .await?;

        self.handle_response(response).await
    }

    /// Handles HTTP response and converts to Result
    ///
    /// Processes status codes and extracts error information when applicable
    async fn handle_response(&self, response: reqwest::Response) -> Result<serde_json::Value> {
        let status = response.status();

        if status.is_success() {
            // Handle 204 No Content
            if status.as_u16() == 204 {
                #[cfg(feature = "tracing")]
                debug!("Received 204 No Content response");
                return Ok(serde_json::Value::Null);
            }

            // Use serde_path_to_error for better error messages
            let text = response.text().await?;
            let deserializer = &mut serde_json::Deserializer::from_str(&text);
            let value: serde_json::Value =
                serde_path_to_error::deserialize(deserializer).map_err(|e| {
                    FilesError::JsonPathError {
                        path: e.path().to_string(),
                        source: e.into_inner(),
                    }
                })?;
            Ok(value)
        } else {
            let status_code = status.as_u16();
            let error_body = response.text().await.unwrap_or_default();

            #[cfg(feature = "tracing")]
            warn!(
                status_code = status_code,
                error_body = %error_body,
                "API request failed"
            );

            // Try to parse error message from JSON
            let message = if let Ok(json) = serde_json::from_str::<serde_json::Value>(&error_body) {
                json.get("error")
                    .or_else(|| json.get("message"))
                    .and_then(|v| v.as_str())
                    .unwrap_or(&error_body)
                    .to_string()
            } else {
                error_body
            };

            let error = match status_code {
                400 => FilesError::BadRequest {
                    message,
                    field: None,
                },
                401 => FilesError::AuthenticationFailed {
                    message,
                    auth_type: None,
                },
                403 => FilesError::Forbidden {
                    message,
                    resource: None,
                },
                404 => FilesError::NotFound {
                    message,
                    resource_type: None,
                    path: None,
                },
                409 => FilesError::Conflict {
                    message,
                    resource: None,
                },
                412 => FilesError::PreconditionFailed {
                    message,
                    condition: None,
                },
                422 => FilesError::UnprocessableEntity {
                    message,
                    field: None,
                    value: None,
                },
                423 => FilesError::Locked {
                    message,
                    resource: None,
                },
                429 => FilesError::RateLimited {
                    message,
                    retry_after: None, // TODO: Parse Retry-After header
                },
                500 => FilesError::InternalServerError {
                    message,
                    request_id: None, // TODO: Parse request ID from headers
                },
                503 => FilesError::ServiceUnavailable {
                    message,
                    retry_after: None, // TODO: Parse Retry-After header
                },
                _ => FilesError::ApiError {
                    code: status_code,
                    message,
                    endpoint: None,
                },
            };

            #[cfg(feature = "tracing")]
            error!(error = ?error, "Returning error to caller");

            Err(error)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder_default() {
        let builder = FilesClientBuilder::default();
        assert_eq!(
            builder.base_url,
            "https://app.files.com/api/rest/v1".to_string()
        );
        assert_eq!(builder.timeout, Duration::from_secs(60));
    }

    #[test]
    fn test_builder_custom() {
        let builder = FilesClientBuilder::default()
            .api_key("test-key")
            .base_url("https://custom.example.com")
            .timeout(Duration::from_secs(120));

        assert_eq!(builder.api_key, Some("test-key".to_string()));
        assert_eq!(builder.base_url, "https://custom.example.com");
        assert_eq!(builder.timeout, Duration::from_secs(120));
    }

    #[test]
    fn test_builder_missing_api_key() {
        let result = FilesClientBuilder::default().build();
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), FilesError::ConfigError(_)));
    }

    #[test]
    fn test_builder_success() {
        let result = FilesClientBuilder::default().api_key("test-key").build();
        assert!(result.is_ok());
    }
}