Skip to main content

bsv_rs/storage/
types.rs

1//! Core types for storage operations.
2//!
3//! This module defines the data structures used for file upload, download,
4//! and management operations in the UHRP storage system.
5
6use serde::{Deserialize, Serialize};
7
8/// A file ready for upload to UHRP storage.
9///
10/// Contains the file content and MIME type for proper handling by storage hosts.
11#[derive(Debug, Clone)]
12pub struct UploadableFile {
13    /// File content as bytes.
14    pub data: Vec<u8>,
15    /// MIME type (e.g., "image/png", "application/pdf").
16    pub mime_type: String,
17}
18
19impl UploadableFile {
20    /// Create a new uploadable file.
21    ///
22    /// # Arguments
23    ///
24    /// * `data` - The file content as bytes
25    /// * `mime_type` - The MIME type of the file
26    ///
27    /// # Example
28    ///
29    /// ```rust
30    /// use bsv_rs::storage::UploadableFile;
31    ///
32    /// let file = UploadableFile::new(b"Hello, World!".to_vec(), "text/plain");
33    /// assert_eq!(file.mime_type, "text/plain");
34    /// ```
35    pub fn new(data: Vec<u8>, mime_type: impl Into<String>) -> Self {
36        Self {
37            data,
38            mime_type: mime_type.into(),
39        }
40    }
41
42    /// Get the size of the file in bytes.
43    pub fn size(&self) -> usize {
44        self.data.len()
45    }
46}
47
48/// Result of a file download.
49#[derive(Debug, Clone)]
50pub struct DownloadResult {
51    /// File content.
52    pub data: Vec<u8>,
53    /// MIME type of the downloaded content.
54    pub mime_type: String,
55}
56
57impl DownloadResult {
58    /// Create a new download result.
59    pub fn new(data: Vec<u8>, mime_type: impl Into<String>) -> Self {
60        Self {
61            data,
62            mime_type: mime_type.into(),
63        }
64    }
65}
66
67/// Result of a file upload operation.
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct UploadFileResult {
70    /// The UHRP URL for the uploaded file.
71    #[serde(rename = "uhrpUrl")]
72    pub uhrp_url: String,
73    /// Whether the file was successfully published.
74    pub published: bool,
75}
76
77impl UploadFileResult {
78    /// Create a new upload result.
79    pub fn new(uhrp_url: impl Into<String>, published: bool) -> Self {
80        Self {
81            uhrp_url: uhrp_url.into(),
82            published,
83        }
84    }
85}
86
87/// Information about a stored file retrieved via find operation.
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct FindFileData {
90    /// File name or path on the CDN.
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub name: Option<String>,
93    /// File size as returned by the service.
94    pub size: String,
95    /// MIME type of the file.
96    #[serde(rename = "mimeType")]
97    pub mime_type: String,
98    /// Expiration timestamp (Unix seconds).
99    #[serde(rename = "expiryTime")]
100    pub expiry_time: i64,
101}
102
103/// Metadata for an uploaded file in a list response.
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct UploadMetadata {
106    /// UHRP URL of the file.
107    #[serde(rename = "uhrpUrl")]
108    pub uhrp_url: String,
109    /// Expiration timestamp (Unix seconds).
110    #[serde(rename = "expiryTime")]
111    pub expiry_time: i64,
112}
113
114/// Result of a file renewal operation.
115#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct RenewFileResult {
117    /// Status returned by the service (e.g., "success").
118    pub status: String,
119    /// Previous expiration timestamp (Unix seconds).
120    #[serde(rename = "prevExpiryTime")]
121    pub previous_expiry: i64,
122    /// New expiration timestamp (Unix seconds).
123    #[serde(rename = "newExpiryTime")]
124    pub new_expiry: i64,
125    /// Amount charged or refilled.
126    pub amount: i64,
127}
128
129impl RenewFileResult {
130    /// Check if the renewal was successful.
131    pub fn is_success(&self) -> bool {
132        self.status == "success"
133    }
134}
135
136/// Response from upload info endpoint.
137#[cfg(feature = "http")]
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub(crate) struct UploadInfo {
140    /// Status of the request.
141    pub status: String,
142    /// URL to upload the file to.
143    #[serde(rename = "uploadURL")]
144    pub upload_url: String,
145    /// Required headers for the upload request.
146    #[serde(rename = "requiredHeaders", default)]
147    pub required_headers: std::collections::HashMap<String, String>,
148    /// Amount charged (optional).
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub amount: Option<i64>,
151}
152
153/// API response status constants.
154#[allow(dead_code)]
155pub(crate) const STATUS_SUCCESS: &str = "success";
156#[allow(dead_code)]
157pub(crate) const STATUS_ERROR: &str = "error";
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn test_uploadable_file_new() {
165        let file = UploadableFile::new(b"content".to_vec(), "text/plain");
166        assert_eq!(file.data, b"content");
167        assert_eq!(file.mime_type, "text/plain");
168        assert_eq!(file.size(), 7);
169    }
170
171    #[test]
172    fn test_download_result_new() {
173        let result = DownloadResult::new(vec![1, 2, 3], "application/octet-stream");
174        assert_eq!(result.data, vec![1, 2, 3]);
175        assert_eq!(result.mime_type, "application/octet-stream");
176    }
177
178    #[test]
179    fn test_upload_file_result_new() {
180        let result = UploadFileResult::new("uhrp://abc123", true);
181        assert_eq!(result.uhrp_url, "uhrp://abc123");
182        assert!(result.published);
183    }
184
185    #[test]
186    fn test_renew_file_result_is_success() {
187        let success = RenewFileResult {
188            status: "success".to_string(),
189            previous_expiry: 1000,
190            new_expiry: 2000,
191            amount: 100,
192        };
193        assert!(success.is_success());
194
195        let failure = RenewFileResult {
196            status: "error".to_string(),
197            previous_expiry: 1000,
198            new_expiry: 1000,
199            amount: 0,
200        };
201        assert!(!failure.is_success());
202    }
203}