omni_orchestrator/app_autoscaler/
app.rs1use std::collections::HashMap;
2use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
3use serde::{Serialize, Deserialize, Serializer, Deserializer};
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct AppInstance {
8 pub id: String,
10 pub name: String,
12 pub node_id: String,
14 pub cpu: u32,
16 pub memory: u32,
18 pub storage: u32,
20 pub state: AppInstanceState,
22 #[serde(with = "timestamp_serde")]
24 pub created_at: Instant,
25 #[serde(with = "timestamp_serde")]
27 pub updated_at: Instant,
28 pub properties: HashMap<String, String>,
30}
31
32mod timestamp_serde {
33 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
34 use serde::{Deserialize, Deserializer, Serializer};
35
36 pub fn serialize<S>(instant: &Instant, serializer: S) -> Result<S::Ok, S::Error>
37 where
38 S: Serializer,
39 {
40 let duration = instant.duration_since(Instant::now()) + SystemTime::now()
41 .duration_since(UNIX_EPOCH)
42 .unwrap_or(Duration::from_secs(0));
43 serializer.serialize_u64(duration.as_millis() as u64)
44 }
45
46 pub fn deserialize<'de, D>(deserializer: D) -> Result<Instant, D::Error>
47 where
48 D: Deserializer<'de>,
49 {
50 let millis = u64::deserialize(deserializer)?;
51 let duration = Duration::from_millis(millis);
52 let system_now = SystemTime::now()
53 .duration_since(UNIX_EPOCH)
54 .unwrap_or(Duration::from_secs(0));
55 Ok(Instant::now() - (system_now - duration))
56 }
57}
58
59impl AppInstance {
60 pub fn new(id: String, name: String, node_id: String, cpu: u32, memory: u32, storage: u32) -> Self {
62 let now = Instant::now();
63 Self {
64 id,
65 name,
66 node_id,
67 cpu,
68 memory,
69 storage,
70 state: AppInstanceState::Creating,
71 created_at: now,
72 updated_at: now,
73 properties: HashMap::new(),
74 }
75 }
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
80pub enum AppInstanceState {
81 Creating,
83 Running,
85 Stopped,
87 Terminating,
89 Terminated,
91 Error,
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct AppConfig {
98 pub cpu: u32,
100 pub memory: u32,
102 pub storage: u32,
104 pub options: HashMap<String, String>,
106}
107
108impl Default for AppConfig {
109 fn default() -> Self {
110 Self {
111 cpu: 2,
112 memory: 4096, storage: 80, options: HashMap::new(),
115 }
116 }
117}
118
119#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct AppTemplate {
122 pub base_name: String,
124 pub config: AppConfig,
126 pub tags: HashMap<String, String>,
128}
129
130impl Default for AppTemplate {
131 fn default() -> Self {
132 Self {
133 base_name: "worker".to_string(),
134 config: AppConfig::default(),
135 tags: HashMap::new(),
136 }
137 }
138}