zero-trust-sdk 0.1.0

Rust SDK for Zero Trust Blockchain Database - Secure, programmable access to zero-trust data storage
Documentation
//! Common types used throughout the Zero Trust SDK

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// User information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    /// User ID
    pub id: String,
    /// Email address
    pub email: String,
    /// User role
    pub role: String,
    /// Account creation timestamp
    pub created_at: String,
    /// Blockchain wallet address (optional)
    pub wallet_address: Option<String>,
}

/// Authentication response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthResponse {
    /// JWT token
    pub token: String,
    /// User information
    pub user: User,
    /// Token expiration timestamp
    pub expires_at: Option<String>,
}

/// Database information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Database {
    /// Database name
    pub name: String,
    /// List of tables in the database
    pub tables: Vec<String>,
    /// Database creation timestamp
    pub created_at: Option<String>,
    /// Database size in bytes
    pub size: Option<u64>,
    /// Number of records across all tables
    pub record_count: Option<u64>,
}

/// Table information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Table {
    /// Table name
    pub name: String,
    /// Column definitions
    pub columns: Vec<Column>,
    /// Number of rows in the table
    pub row_count: Option<u64>,
    /// Table size in bytes
    pub size: Option<u64>,
    /// Table creation timestamp
    pub created_at: Option<String>,
}

/// Column definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Column {
    /// Column name
    pub name: String,
    /// Column data type
    pub data_type: String,
    /// Whether the column allows NULL values
    pub nullable: bool,
    /// Default value (if any)
    pub default_value: Option<String>,
    /// Whether this is a primary key column
    pub is_primary_key: bool,
}

/// Query result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryResult {
    /// Result data
    pub data: QueryData,
    /// Query execution metadata
    pub meta: QueryMeta,
}

/// Query data structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryData {
    /// Column names
    pub columns: Option<Vec<String>>,
    /// Row data
    pub rows: Vec<Vec<serde_json::Value>>,
}

/// Query execution metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryMeta {
    /// Number of rows affected/returned
    pub row_count: u64,
    /// Query execution time in milliseconds
    pub execution_time_ms: Option<u64>,
    /// Whether this was a read or write operation
    pub operation_type: OperationType,
}

/// Type of database operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OperationType {
    /// Read operation (SELECT)
    Read,
    /// Write operation (INSERT, UPDATE, DELETE)
    Write,
    /// Schema operation (CREATE, ALTER, DROP)
    Schema,
}

/// System health status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthStatus {
    /// Overall system status
    pub status: String,
    /// API version
    pub version: String,
    /// Database connection status
    pub database: String,
    /// Blockchain connection status
    pub blockchain: String,
    /// System uptime in seconds
    pub uptime: Option<u64>,
}

/// System statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemStats {
    /// Number of databases
    pub databases: u64,
    /// Total number of tables
    pub tables: u64,
    /// Total number of rows across all tables
    pub rows: u64,
    /// Total storage used in bytes
    pub storage_bytes: Option<u64>,
    /// Number of active connections
    pub active_connections: Option<u64>,
}

/// Migration status
#[cfg(feature = "migration")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationStatus {
    /// Migration ID
    pub id: String,
    /// Current status
    pub status: MigrationState,
    /// Number of records processed
    pub records_processed: u64,
    /// Total number of records to process
    pub total_records: Option<u64>,
    /// Migration start time
    pub started_at: String,
    /// Migration completion time
    pub completed_at: Option<String>,
    /// Error message (if failed)
    pub error: Option<String>,
}

/// Migration state
#[cfg(feature = "migration")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MigrationState {
    /// Migration is pending
    Pending,
    /// Migration is running
    Running,
    /// Migration completed successfully
    Completed,
    /// Migration failed
    Failed,
    /// Migration was cancelled
    Cancelled,
}

/// Sync configuration
#[cfg(feature = "sync")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncConfig {
    /// Unique sync configuration name
    pub name: String,
    /// Source type (postgres, mysql, api, etc.)
    pub source_type: String,
    /// Source connection string or URL
    pub source: String,
    /// Target database
    pub target: String,
    /// Sync interval in seconds
    pub interval: u64,
    /// Configuration creation timestamp
    pub created_at: String,
    /// Last sync timestamp
    pub last_sync: Option<String>,
    /// Current sync status
    pub status: SyncStatus,
}

/// Sync status
#[cfg(feature = "sync")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SyncStatus {
    /// Sync is stopped
    Stopped,
    /// Sync is running
    Running,
    /// Sync encountered an error
    Error {
        /// Error message
        message: String,
    },
}

/// Pagination parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Pagination {
    /// Number of records to skip
    pub offset: u64,
    /// Maximum number of records to return
    pub limit: u64,
}

impl Default for Pagination {
    fn default() -> Self {
        Self {
            offset: 0,
            limit: 100,
        }
    }
}

/// Query options
#[derive(Debug, Clone, Default)]
pub struct QueryOptions {
    /// Maximum number of rows to return
    pub max_rows: Option<u64>,
    /// Query timeout in milliseconds
    pub timeout_ms: Option<u64>,
    /// Whether to include execution metadata
    pub include_meta: bool,
}

/// Batch operation result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchResult {
    /// Number of successful operations
    pub successful: u64,
    /// Number of failed operations
    pub failed: u64,
    /// List of errors (if any)
    pub errors: Vec<BatchError>,
}

/// Individual error in a batch operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchError {
    /// Index of the failed operation in the batch
    pub index: u64,
    /// Error message
    pub message: String,
}

/// API response wrapper
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiResponse<T> {
    /// Response data
    pub data: T,
    /// Success flag
    pub success: bool,
    /// Optional message
    pub message: Option<String>,
    /// Response metadata
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

/// Request metadata
#[derive(Debug, Clone)]
pub struct RequestMeta {
    /// Request ID for tracing
    pub request_id: Option<String>,
    /// Request timestamp
    pub timestamp: chrono::DateTime<chrono::Utc>,
    /// Request timeout
    pub timeout: std::time::Duration,
}

impl Default for RequestMeta {
    fn default() -> Self {
        Self {
            request_id: Some(uuid::Uuid::new_v4().to_string()),
            timestamp: chrono::Utc::now(),
            timeout: std::time::Duration::from_secs(30),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_pagination_default() {
        let pagination = Pagination::default();
        assert_eq!(pagination.offset, 0);
        assert_eq!(pagination.limit, 100);
    }
    
    #[test]
    fn test_query_options_default() {
        let options = QueryOptions::default();
        assert!(options.max_rows.is_none());
        assert!(options.timeout_ms.is_none());
        assert!(!options.include_meta);
    }
    
    #[test]
    fn test_user_serialization() {
        let user = User {
            id: "123".to_string(),
            email: "test@example.com".to_string(),
            role: "user".to_string(),
            created_at: "2023-01-01T00:00:00Z".to_string(),
            wallet_address: Some("0x1234567890abcdef".to_string()),
        };
        
        let json = serde_json::to_string(&user).unwrap();
        let deserialized: User = serde_json::from_str(&json).unwrap();
        
        assert_eq!(user.id, deserialized.id);
        assert_eq!(user.email, deserialized.email);
        assert_eq!(user.wallet_address, deserialized.wallet_address);
    }
}