zero_trust_sdk/
types.rs

1//! Common types used throughout the Zero Trust SDK
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6/// User information
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct User {
9    /// User ID
10    pub id: String,
11    /// Email address
12    pub email: String,
13    /// User role
14    pub role: String,
15    /// Account creation timestamp
16    pub created_at: String,
17    /// Blockchain wallet address (optional)
18    pub wallet_address: Option<String>,
19}
20
21/// Authentication response
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct AuthResponse {
24    /// JWT token
25    pub token: String,
26    /// User information
27    pub user: User,
28    /// Token expiration timestamp
29    pub expires_at: Option<String>,
30}
31
32/// Database information
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct Database {
35    /// Database name
36    pub name: String,
37    /// List of tables in the database
38    pub tables: Vec<String>,
39    /// Database creation timestamp
40    pub created_at: Option<String>,
41    /// Database size in bytes
42    pub size: Option<u64>,
43    /// Number of records across all tables
44    pub record_count: Option<u64>,
45}
46
47/// Table information
48#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct Table {
50    /// Table name
51    pub name: String,
52    /// Column definitions
53    pub columns: Vec<Column>,
54    /// Number of rows in the table
55    pub row_count: Option<u64>,
56    /// Table size in bytes
57    pub size: Option<u64>,
58    /// Table creation timestamp
59    pub created_at: Option<String>,
60}
61
62/// Column definition
63#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct Column {
65    /// Column name
66    pub name: String,
67    /// Column data type
68    pub data_type: String,
69    /// Whether the column allows NULL values
70    pub nullable: bool,
71    /// Default value (if any)
72    pub default_value: Option<String>,
73    /// Whether this is a primary key column
74    pub is_primary_key: bool,
75}
76
77/// Query result
78#[derive(Debug, Clone, Serialize, Deserialize)]
79pub struct QueryResult {
80    /// Result data
81    pub data: QueryData,
82    /// Query execution metadata
83    pub meta: QueryMeta,
84}
85
86/// Query data structure
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct QueryData {
89    /// Column names
90    pub columns: Option<Vec<String>>,
91    /// Row data
92    pub rows: Vec<Vec<serde_json::Value>>,
93}
94
95/// Query execution metadata
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct QueryMeta {
98    /// Number of rows affected/returned
99    pub row_count: u64,
100    /// Query execution time in milliseconds
101    pub execution_time_ms: Option<u64>,
102    /// Whether this was a read or write operation
103    pub operation_type: OperationType,
104}
105
106/// Type of database operation
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub enum OperationType {
109    /// Read operation (SELECT)
110    Read,
111    /// Write operation (INSERT, UPDATE, DELETE)
112    Write,
113    /// Schema operation (CREATE, ALTER, DROP)
114    Schema,
115}
116
117/// System health status
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct HealthStatus {
120    /// Overall system status
121    pub status: String,
122    /// API version
123    pub version: String,
124    /// Database connection status
125    pub database: String,
126    /// Blockchain connection status
127    pub blockchain: String,
128    /// System uptime in seconds
129    pub uptime: Option<u64>,
130}
131
132/// System statistics
133#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct SystemStats {
135    /// Number of databases
136    pub databases: u64,
137    /// Total number of tables
138    pub tables: u64,
139    /// Total number of rows across all tables
140    pub rows: u64,
141    /// Total storage used in bytes
142    pub storage_bytes: Option<u64>,
143    /// Number of active connections
144    pub active_connections: Option<u64>,
145}
146
147/// Migration status
148#[cfg(feature = "migration")]
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct MigrationStatus {
151    /// Migration ID
152    pub id: String,
153    /// Current status
154    pub status: MigrationState,
155    /// Number of records processed
156    pub records_processed: u64,
157    /// Total number of records to process
158    pub total_records: Option<u64>,
159    /// Migration start time
160    pub started_at: String,
161    /// Migration completion time
162    pub completed_at: Option<String>,
163    /// Error message (if failed)
164    pub error: Option<String>,
165}
166
167/// Migration state
168#[cfg(feature = "migration")]
169#[derive(Debug, Clone, Serialize, Deserialize)]
170pub enum MigrationState {
171    /// Migration is pending
172    Pending,
173    /// Migration is running
174    Running,
175    /// Migration completed successfully
176    Completed,
177    /// Migration failed
178    Failed,
179    /// Migration was cancelled
180    Cancelled,
181}
182
183/// Sync configuration
184#[cfg(feature = "sync")]
185#[derive(Debug, Clone, Serialize, Deserialize)]
186pub struct SyncConfig {
187    /// Unique sync configuration name
188    pub name: String,
189    /// Source type (postgres, mysql, api, etc.)
190    pub source_type: String,
191    /// Source connection string or URL
192    pub source: String,
193    /// Target database
194    pub target: String,
195    /// Sync interval in seconds
196    pub interval: u64,
197    /// Configuration creation timestamp
198    pub created_at: String,
199    /// Last sync timestamp
200    pub last_sync: Option<String>,
201    /// Current sync status
202    pub status: SyncStatus,
203}
204
205/// Sync status
206#[cfg(feature = "sync")]
207#[derive(Debug, Clone, Serialize, Deserialize)]
208pub enum SyncStatus {
209    /// Sync is stopped
210    Stopped,
211    /// Sync is running
212    Running,
213    /// Sync encountered an error
214    Error {
215        /// Error message
216        message: String,
217    },
218}
219
220/// Pagination parameters
221#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct Pagination {
223    /// Number of records to skip
224    pub offset: u64,
225    /// Maximum number of records to return
226    pub limit: u64,
227}
228
229impl Default for Pagination {
230    fn default() -> Self {
231        Self {
232            offset: 0,
233            limit: 100,
234        }
235    }
236}
237
238/// Query options
239#[derive(Debug, Clone, Default)]
240pub struct QueryOptions {
241    /// Maximum number of rows to return
242    pub max_rows: Option<u64>,
243    /// Query timeout in milliseconds
244    pub timeout_ms: Option<u64>,
245    /// Whether to include execution metadata
246    pub include_meta: bool,
247}
248
249/// Batch operation result
250#[derive(Debug, Clone, Serialize, Deserialize)]
251pub struct BatchResult {
252    /// Number of successful operations
253    pub successful: u64,
254    /// Number of failed operations
255    pub failed: u64,
256    /// List of errors (if any)
257    pub errors: Vec<BatchError>,
258}
259
260/// Individual error in a batch operation
261#[derive(Debug, Clone, Serialize, Deserialize)]
262pub struct BatchError {
263    /// Index of the failed operation in the batch
264    pub index: u64,
265    /// Error message
266    pub message: String,
267}
268
269/// API response wrapper
270#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct ApiResponse<T> {
272    /// Response data
273    pub data: T,
274    /// Success flag
275    pub success: bool,
276    /// Optional message
277    pub message: Option<String>,
278    /// Response metadata
279    pub meta: Option<HashMap<String, serde_json::Value>>,
280}
281
282/// Request metadata
283#[derive(Debug, Clone)]
284pub struct RequestMeta {
285    /// Request ID for tracing
286    pub request_id: Option<String>,
287    /// Request timestamp
288    pub timestamp: chrono::DateTime<chrono::Utc>,
289    /// Request timeout
290    pub timeout: std::time::Duration,
291}
292
293impl Default for RequestMeta {
294    fn default() -> Self {
295        Self {
296            request_id: Some(uuid::Uuid::new_v4().to_string()),
297            timestamp: chrono::Utc::now(),
298            timeout: std::time::Duration::from_secs(30),
299        }
300    }
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306    
307    #[test]
308    fn test_pagination_default() {
309        let pagination = Pagination::default();
310        assert_eq!(pagination.offset, 0);
311        assert_eq!(pagination.limit, 100);
312    }
313    
314    #[test]
315    fn test_query_options_default() {
316        let options = QueryOptions::default();
317        assert!(options.max_rows.is_none());
318        assert!(options.timeout_ms.is_none());
319        assert!(!options.include_meta);
320    }
321    
322    #[test]
323    fn test_user_serialization() {
324        let user = User {
325            id: "123".to_string(),
326            email: "test@example.com".to_string(),
327            role: "user".to_string(),
328            created_at: "2023-01-01T00:00:00Z".to_string(),
329            wallet_address: Some("0x1234567890abcdef".to_string()),
330        };
331        
332        let json = serde_json::to_string(&user).unwrap();
333        let deserialized: User = serde_json::from_str(&json).unwrap();
334        
335        assert_eq!(user.id, deserialized.id);
336        assert_eq!(user.email, deserialized.email);
337        assert_eq!(user.wallet_address, deserialized.wallet_address);
338    }
339}