Skip to main content

phala_tee_deploy_rs/
types.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3
4/// Docker registry authentication configuration.
5///
6/// Used to access private Docker registries when deploying containers.
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct DockerConfig {
9    /// Docker registry username
10    pub username: String,
11
12    /// Docker registry password
13    pub password: String,
14
15    /// Optional custom registry URL
16    pub registry: Option<String>,
17}
18
19/// Advanced features configuration for TEE deployments.
20///
21/// Controls security and visibility settings for deployed applications.
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct AdvancedFeatures {
24    /// Enable transparent proxy support
25    pub tproxy: bool,
26
27    /// Enable Key Management System integration
28    pub kms: bool,
29
30    /// Make system information publicly accessible
31    pub public_sys_info: bool,
32
33    /// Make application logs publicly accessible
34    pub public_logs: bool,
35
36    /// Docker registry authentication settings
37    pub docker_config: DockerConfig,
38
39    /// List this deployment in public directories
40    pub listed: bool,
41}
42
43/// Docker Compose manifest configuration.
44///
45/// Defines the application structure using Docker Compose format.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct ComposeManifest {
48    /// Name of the application
49    pub name: String,
50
51    /// Enabled features for this deployment
52    pub features: Vec<String>,
53
54    /// Docker Compose file content
55    pub docker_compose_file: String,
56}
57
58/// Virtual Machine configuration for a TEE deployment.
59///
60/// Defines the resources and settings for the VM that will run the containerized application.
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct VmConfig {
63    /// Name of the deployment
64    pub name: String,
65
66    /// Docker Compose manifest configuration
67    pub compose_manifest: ComposeManifest,
68
69    /// Number of virtual CPU cores
70    pub vcpu: u32,
71
72    /// Memory allocation in MB
73    pub memory: u32,
74
75    /// Disk size allocation in GB
76    pub disk_size: u32,
77
78    /// ID of the TEEPod to deploy to
79    pub teepod_id: u64,
80
81    /// Container image to use
82    pub image: String,
83
84    /// Advanced features configuration
85    pub advanced_features: AdvancedFeatures,
86}
87
88/// Encrypted environment variable entry.
89///
90/// Used for secure transmission of sensitive environment variables.
91#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct EncryptedEnv {
93    /// Environment variable name
94    pub key: String,
95
96    /// Encrypted environment variable value
97    pub value: String,
98}
99
100/// Response from a deployment operation.
101///
102/// Contains information about the created deployment including its ID and status.
103/// This struct uses custom deserialization to handle variations in API responses.
104#[derive(Debug, Clone, Serialize)]
105pub struct DeploymentResponse {
106    /// Unique identifier for the deployment
107    pub id: u64,
108
109    /// Current status of the deployment (e.g., "pending", "running")
110    pub status: String,
111
112    /// Additional deployment details as key-value pairs
113    pub details: Option<HashMap<String, serde_json::Value>>,
114}
115
116// Implement custom deserialization to handle different API response formats
117impl<'de> Deserialize<'de> for DeploymentResponse {
118    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
119    where
120        D: serde::Deserializer<'de>,
121    {
122        use serde::de::Error;
123
124        // First, try to deserialize as a generic Value
125        let value = serde_json::Value::deserialize(deserializer)?;
126
127        // If it's not an object, return an error
128        let obj = match value.as_object() {
129            Some(obj) => obj,
130            None => return Err(D::Error::custom("Expected object for DeploymentResponse")),
131        };
132
133        // Try to extract the ID field from various possible formats
134        let id = if let Some(id_value) = obj.get("id") {
135            if let Some(id_num) = id_value.as_u64() {
136                id_num
137            } else if let Some(id_str) = id_value.as_str() {
138                id_str.parse::<u64>().unwrap_or(0)
139            } else {
140                0 // Default ID if can't parse
141            }
142        } else if let Some(id_value) = obj.get("uuid") {
143            if let Some(id_num) = id_value.as_u64() {
144                id_num
145            } else if let Some(id_str) = id_value.as_str() {
146                id_str.parse::<u64>().unwrap_or(0)
147            } else {
148                0 // Default ID if can't parse
149            }
150        } else if let Some(id_value) = obj.get("app_id") {
151            if let Some(id_str) = id_value.as_str() {
152                // Extract numeric part from "app_123" format
153                if id_str.starts_with("app_") {
154                    id_str[4..].parse::<u64>().unwrap_or(0)
155                } else {
156                    id_str.parse::<u64>().unwrap_or(0)
157                }
158            } else {
159                0 // Default ID if can't parse
160            }
161        } else {
162            // If no ID field is found, generate a random one
163            use rand::Rng;
164            rand::thread_rng().gen()
165        };
166
167        // Extract status field
168        let status = obj
169            .get("status")
170            .and_then(|v| v.as_str())
171            .unwrap_or("pending")
172            .to_string();
173
174        // Create details map with all fields from the response
175        let mut details = HashMap::new();
176        for (k, v) in obj {
177            details.insert(k.clone(), v.clone());
178        }
179
180        Ok(DeploymentResponse {
181            id,
182            status,
183            details: Some(details),
184        })
185    }
186}
187
188/// Response when retrieving a compose configuration.
189///
190/// Contains both the compose configuration and the public key needed for
191/// encrypting environment variables for updates.
192#[derive(Debug, Clone, Serialize, Deserialize)]
193pub struct ComposeResponse {
194    /// The compose file configuration
195    pub compose_file: serde_json::Value,
196
197    /// Public key for encrypting environment variables
198    pub env_pubkey: String,
199}
200
201/// Response from a pubkey request.
202///
203/// Contains the public key and other configuration details needed for deployment.
204#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct PubkeyResponse {
206    /// Public key for encrypting environment variables
207    pub app_env_encrypt_pubkey: String,
208
209    /// Generated application ID
210    pub app_id: String,
211
212    /// Salt used in app ID generation
213    pub app_id_salt: String,
214
215    /// Compose manifest configuration
216    pub compose_manifest: ComposeManifest,
217
218    /// Disk size in GB
219    pub disk_size: u64,
220
221    /// Encrypted environment variables
222    pub encrypted_env: String,
223
224    /// Container image to use
225    pub image: String,
226
227    /// Whether the deployment should be listed publicly
228    pub listed: bool,
229
230    /// Memory allocation in MB
231    pub memory: u64,
232
233    /// Name of the deployment
234    pub name: String,
235
236    /// Port mappings
237    pub ports: Option<Vec<String>>,
238
239    /// ID of the TEEPod to deploy to
240    pub teepod_id: u64,
241
242    /// User ID associated with deployment
243    pub user_id: Option<String>,
244
245    /// Number of virtual CPUs
246    pub vcpu: u64,
247}
248
249/// Compose manifest configuration.
250///
251/// Contains Docker Compose and related deployment settings.
252#[derive(Debug, Clone, Serialize, Deserialize)]
253pub struct ComposeManifestResponse {
254    /// Optional bash script
255    pub bash_script: Option<String>,
256
257    /// Docker Compose file contents
258    pub docker_compose_file: String,
259
260    /// Docker registry configuration
261    pub docker_config: DockerConfig,
262
263    /// Enabled features for the deployment
264    pub features: Vec<String>,
265
266    /// Whether KMS is enabled
267    pub kms_enabled: bool,
268
269    /// Manifest version number
270    pub manifest_version: u64,
271
272    /// Name of the deployment
273    pub name: String,
274
275    /// Pre-launch script contents
276    pub pre_launch_script: String,
277
278    /// Whether logs should be public
279    pub public_logs: bool,
280
281    /// Whether system info should be public
282    pub public_sysinfo: bool,
283
284    /// Runner type (e.g. "docker-compose")
285    pub runner: String,
286
287    /// Salt for configuration
288    pub salt: String,
289
290    /// Whether transparent proxy is enabled
291    pub tproxy_enabled: bool,
292
293    /// Version of the manifest
294    pub version: String,
295}
296
297/// Response from the TEEPod discovery API endpoint.
298#[derive(Debug, Clone, Serialize, Deserialize)]
299pub struct TeePodDiscoveryResponse {
300    /// Capacity limits for the TEEPod cluster
301    pub capacity: TeePodCapacity,
302
303    /// List of available TEEPod nodes
304    pub nodes: Vec<TeePodNode>,
305
306    /// Service tier (e.g. "pro")
307    pub tier: String,
308}
309
310/// Capacity configuration for a TEEPod cluster.
311#[derive(Debug, Clone, Serialize, Deserialize)]
312pub struct TeePodCapacity {
313    /// Maximum disk space in GB
314    pub max_disk: u64,
315
316    /// Maximum number of instances
317    pub max_instances: u64,
318
319    /// Maximum memory in MB
320    pub max_memory: u64,
321
322    /// Maximum number of virtual CPUs
323    pub max_vcpu: u64,
324}
325
326/// Information about a TEEPod node.
327#[derive(Debug, Clone, Serialize, Deserialize)]
328pub struct TeePodNode {
329    /// Available VM images
330    pub images: Vec<TeePodImage>,
331
332    /// Whether the node is publicly listed
333    pub listed: bool,
334
335    /// Node name
336    pub name: String,
337
338    /// Number of remaining CVM slots
339    pub remaining_cvm_slots: u64,
340
341    /// Remaining memory in MB
342    pub remaining_memory: f64,
343
344    /// Remaining virtual CPU capacity
345    pub remaining_vcpu: f64,
346
347    /// Resource availability score (0.0-1.0)
348    pub resource_score: f64,
349
350    /// Unique identifier for the TEEPod
351    pub teepod_id: u64,
352}
353
354/// VM image configuration for a TEEPod.
355#[derive(Debug, Clone, Serialize, Deserialize)]
356pub struct TeePodImage {
357    /// BIOS file name
358    pub bios: String,
359
360    /// Kernel command line parameters
361    pub cmdline: String,
362
363    /// Image configuration description
364    pub description: String,
365
366    /// Hard disk image path (if any)
367    pub hda: Option<String>,
368
369    /// Initial ramdisk file name
370    pub initrd: String,
371
372    /// Whether this is a development image
373    pub is_dev: bool,
374
375    /// Kernel image file name
376    pub kernel: String,
377
378    /// Image name
379    pub name: String,
380
381    /// Root filesystem image name
382    pub rootfs: String,
383
384    /// Root filesystem hash
385    pub rootfs_hash: String,
386
387    /// Whether root filesystem is shared read-only
388    pub shared_ro: bool,
389
390    /// Image version numbers [major, minor, patch]
391    pub version: Vec<u64>,
392}
393
394/// Response containing network information for a deployment.
395///
396/// Provides details about connectivity, IP addresses, and public URLs
397/// for accessing the deployed application.
398#[derive(Debug, Clone, Serialize, Deserialize)]
399pub struct NetworkInfoResponse {
400    /// Whether the deployment is online and responding
401    pub is_online: bool,
402
403    /// Whether the deployment is publicly accessible
404    pub is_public: bool,
405
406    /// Error message if there's a connectivity issue (null if no error)
407    pub error: Option<String>,
408
409    /// Internal IP address of the deployment
410    pub internal_ip: String,
411
412    /// Timestamp of the latest connectivity handshake
413    pub latest_handshake: String,
414
415    /// Public URLs for accessing the deployment
416    pub public_urls: PublicUrls,
417}
418
419/// Public URLs for accessing a deployment.
420///
421/// Contains URLs for different parts of the deployment.
422#[derive(Debug, Clone, Serialize, Deserialize)]
423pub struct PublicUrls {
424    /// URL for the main application
425    pub app: String,
426
427    /// URL for the instance/container
428    pub instance: String,
429}
430
431/// System information for a disk in a virtual machine.
432///
433/// Contains details about a disk's name, mount point, and size information.
434#[derive(Debug, Clone, Serialize, Deserialize)]
435pub struct DiskInfo {
436    /// Name of the disk (e.g., "sda1")
437    pub name: String,
438
439    /// Mount point of the disk (e.g., "/", "/home")
440    pub mount_point: Option<String>,
441
442    /// Total size of the disk in bytes
443    pub total_size: u64,
444
445    /// Free space available on the disk in bytes
446    pub free_size: u64,
447}
448
449/// Detailed system information for a virtual machine.
450///
451/// Contains comprehensive details about the operating system, hardware,
452/// and resource utilization of a deployed container VM.
453#[derive(Debug, Clone, Serialize, Deserialize)]
454pub struct SystemInfo {
455    /// Operating system name (e.g., "Linux")
456    pub os_name: String,
457
458    /// Operating system version
459    pub os_version: String,
460
461    /// Linux kernel version
462    pub kernel_version: String,
463
464    /// CPU model name
465    pub cpu_model: String,
466
467    /// Number of CPU cores
468    pub num_cpus: u32,
469
470    /// Total physical memory in bytes
471    pub total_memory: u64,
472
473    /// Available memory in bytes
474    pub available_memory: u64,
475
476    /// Used memory in bytes
477    pub used_memory: u64,
478
479    /// Free memory in bytes
480    pub free_memory: u64,
481
482    /// Total swap space in bytes
483    pub total_swap: u64,
484
485    /// Used swap space in bytes
486    pub used_swap: u64,
487
488    /// Free swap space in bytes
489    pub free_swap: u64,
490
491    /// System uptime in seconds
492    pub uptime: u64,
493
494    /// 1-minute load average
495    pub loadavg_one: f32,
496
497    /// 5-minute load average
498    pub loadavg_five: f32,
499
500    /// 15-minute load average
501    pub loadavg_fifteen: f32,
502
503    /// Information about mounted disks
504    pub disks: Vec<DiskInfo>,
505}
506
507/// Response containing system statistics for a container VM.
508///
509/// Provides details about the operational status and system resource usage
510/// of a deployed application in the Phala TEE Cloud.
511#[derive(Debug, Clone, Serialize, Deserialize)]
512pub struct SystemStatsResponse {
513    /// Whether the VM is online and responding
514    pub is_online: bool,
515
516    /// Whether the VM is publicly accessible
517    pub is_public: bool,
518
519    /// Error message if there's an issue (null if no error)
520    pub error: Option<String>,
521
522    /// Detailed system information
523    pub sysinfo: SystemInfo,
524}
525
526// ─────────────────────────────────────────────────────────────────────────────
527// CVM lifecycle types
528// ─────────────────────────────────────────────────────────────────────────────
529
530/// Full CVM info from `GET /api/v1/cvms/{cvm_id}`.
531#[derive(Debug, Clone, Serialize, Deserialize)]
532pub struct CvmInfo {
533    pub id: u64,
534    pub status: String,
535    pub name: String,
536    #[serde(flatten)]
537    pub extra: HashMap<String, serde_json::Value>,
538}
539
540/// CVM state from `GET /api/v1/cvms/{cvm_id}/state`.
541#[derive(Debug, Clone, Serialize, Deserialize)]
542pub struct CvmStateResponse {
543    pub status: String,
544    pub is_running: bool,
545}
546
547/// TEE attestation from `GET /api/v1/cvms/{cvm_id}/attestation`.
548#[derive(Debug, Clone, Serialize, Deserialize)]
549pub struct AttestationResponse {
550    #[serde(default)]
551    pub tcb_info: serde_json::Value,
552    #[serde(default)]
553    pub app_certificates: serde_json::Value,
554    #[serde(flatten)]
555    pub extra: HashMap<String, serde_json::Value>,
556}