1use crate::config::ResourceConfig;
5use crate::size::ConfigSize;
6use chrono::{DateTime, Utc};
7use serde::{Deserialize, Serialize};
8use utoipa::ToSchema;
9
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
12pub struct PipelineDeployment {
13 pub spec: DeploymentSpec,
14 #[serde(default, skip_serializing_if = "Option::is_none")]
16 pub status: Option<DeploymentStatus>,
17}
18
19#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
21pub struct DeploymentSpec {
22 pub resources: DeploymentSpecResources,
23}
24
25#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
27pub struct DeploymentSpecResources {
28 pub cpu_cores_min: Option<f64>,
29 pub cpu_cores_max: Option<f64>,
30 #[schema(value_type = Option<String>)]
31 pub memory_min: Option<ConfigSize>,
32 #[schema(value_type = Option<String>)]
33 pub memory_max: Option<ConfigSize>,
34 #[schema(value_type = Option<String>)]
35 pub storage_min: Option<ConfigSize>,
36 #[schema(value_type = Option<String>)]
37 pub storage_max: Option<ConfigSize>,
38}
39
40impl From<&ResourceConfig> for DeploymentSpecResources {
41 fn from(r: &ResourceConfig) -> Self {
42 Self {
43 cpu_cores_min: r.cpu_cores_min,
44 cpu_cores_max: r.cpu_cores_max,
45 memory_min: r.memory_min,
46 memory_max: r.memory_max,
47 storage_min: r.storage_min,
48 storage_max: r.storage_max,
49 }
50 }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
56pub enum DeploymentState {
57 Current,
59 InProgress,
61 Failed,
63 Terminating,
65 NotFound,
67 #[serde(other)]
69 Unknown,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
74pub enum ResourceManager {
75 User,
77 Autoscaler,
79}
80
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
83pub struct Transition {
84 pub state: DeploymentState,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub reason: Option<String>,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub message: Option<String>,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub last_transition_time: Option<DateTime<Utc>>,
95}
96
97impl Transition {
98 pub fn new(state: DeploymentState) -> Self {
99 Self {
100 state,
101 reason: None,
102 message: None,
103 last_transition_time: None,
104 }
105 }
106
107 pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
108 self.reason = Some(reason.into());
109 self
110 }
111
112 pub fn with_message(mut self, message: impl Into<String>) -> Self {
113 self.message = Some(message.into());
114 self
115 }
116
117 pub fn with_last_transition_time(mut self, since: Option<DateTime<Utc>>) -> Self {
118 self.last_transition_time = since;
119 self
120 }
121}
122
123#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
124pub struct ComputeResources {
125 pub cpu_cores_min: Option<f64>,
126 pub cpu_cores_max: Option<f64>,
127 pub memory_mb_min: Option<u64>,
128 pub memory_mb_max: Option<u64>,
129}
130
131#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
132pub struct StorageResources {
133 pub storage_mb: Option<u64>,
134}
135
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
138pub struct HostCompute {
139 #[serde(flatten)]
140 pub transition: Transition,
141 pub manager: ResourceManager,
142 pub desired: Option<ComputeResources>,
144 pub current: Option<ComputeResources>,
147}
148
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
151pub struct HostStorage {
152 #[serde(flatten)]
153 pub transition: Transition,
154 pub manager: ResourceManager,
155 pub desired: Option<StorageResources>,
157 pub current: Option<StorageResources>,
159}
160
161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
162pub struct HostStatus {
163 pub ordinal: usize,
165 pub compute: HostCompute,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
168 pub storage: Option<HostStorage>,
169}
170
171#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
173pub struct DeploymentStatus {
174 pub state: DeploymentState,
175 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub reason: Option<String>,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub message: Option<String>,
179 pub hosts: Vec<HostStatus>,
180}
181
182impl DeploymentStatus {
183 pub fn aggregate(
190 hosts: Vec<HostStatus>,
191 compute_expected: DeploymentState,
192 storage_expected: DeploymentState,
193 ) -> Self {
194 let objects: Vec<(&Transition, DeploymentState)> = hosts
195 .iter()
196 .flat_map(|host| {
197 std::iter::once((&host.compute.transition, compute_expected)).chain(
198 host.storage
199 .as_ref()
200 .map(|storage| (&storage.transition, storage_expected)),
201 )
202 })
203 .collect();
204 let desired = if compute_expected == DeploymentState::NotFound
205 && objects
206 .iter()
207 .all(|(_, expected)| *expected == DeploymentState::NotFound)
208 {
209 DeploymentState::NotFound
210 } else {
211 DeploymentState::Current
212 };
213 let first = |matches: &dyn Fn(&Transition, DeploymentState) -> bool| {
214 objects
215 .iter()
216 .find(|(transition, expected)| matches(transition, *expected))
217 .map(|(transition, _)| *transition)
218 };
219 let (state, decider) = if let Some(t) = first(&|t, _| t.state == DeploymentState::Failed) {
220 (DeploymentState::Failed, Some(t))
221 } else if let Some(t) = first(&|t, _| t.state == DeploymentState::Unknown) {
222 (DeploymentState::Unknown, Some(t))
223 } else if let Some(t) = first(&|t, expected| t.state != expected) {
224 (DeploymentState::InProgress, Some(t))
225 } else {
226 (desired, None)
227 };
228 Self {
229 state,
230 reason: decider.and_then(|t| t.reason.clone()),
231 message: decider.and_then(|t| t.message.clone()),
232 hosts,
233 }
234 }
235}
236
237#[cfg(test)]
238mod test {
239 use super::*;
240 use DeploymentState::*;
241
242 fn host(compute: Transition, storage: Option<Transition>) -> HostStatus {
243 HostStatus {
244 ordinal: 0,
245 compute: HostCompute {
246 transition: compute,
247 manager: ResourceManager::User,
248 desired: None,
249 current: None,
250 },
251 storage: storage.map(|transition| HostStorage {
252 transition,
253 manager: ResourceManager::User,
254 desired: None,
255 current: None,
256 }),
257 }
258 }
259
260 fn summary(status: &DeploymentStatus) -> (DeploymentState, Option<&str>) {
261 (status.state, status.reason.as_deref())
262 }
263
264 #[test]
265 fn all_objects_as_expected_is_current() {
266 let running = DeploymentStatus::aggregate(
267 vec![host(
268 Transition::new(Current),
269 Some(Transition::new(Current)),
270 )],
271 Current,
272 Current,
273 );
274 assert_eq!(summary(&running), (Current, None));
275
276 let stopped = DeploymentStatus::aggregate(
278 vec![host(
279 Transition::new(NotFound),
280 Some(Transition::new(Current)),
281 )],
282 NotFound,
283 Current,
284 );
285 assert_eq!(summary(&stopped), (Current, None));
286 }
287
288 #[test]
289 fn object_not_as_expected_is_in_progress() {
290 let stopping = DeploymentStatus::aggregate(
292 vec![host(
293 Transition::new(Terminating).with_reason("Deleting"),
294 None,
295 )],
296 NotFound,
297 Current,
298 );
299 assert_eq!(summary(&stopping), (InProgress, Some("Deleting")));
300
301 let starting = DeploymentStatus::aggregate(
303 vec![host(Transition::new(NotFound), None)],
304 Current,
305 Current,
306 );
307 assert_eq!(summary(&starting), (InProgress, None));
308 }
309
310 #[test]
311 fn failed_wins_over_unknown_and_in_progress() {
312 let status = DeploymentStatus::aggregate(
313 vec![
314 host(
315 Transition::new(InProgress).with_reason("Deferred"),
316 Some(Transition::new(Unknown).with_reason("ListFailed")),
317 ),
318 host(
319 Transition::new(Current),
320 Some(
321 Transition::new(Failed)
322 .with_reason("ControllerResizeInfeasible")
323 .with_message("too big"),
324 ),
325 ),
326 ],
327 Current,
328 Current,
329 );
330 assert_eq!(
331 summary(&status),
332 (Failed, Some("ControllerResizeInfeasible"))
333 );
334 assert_eq!(status.message.as_deref(), Some("too big"));
335 }
336
337 #[test]
338 fn unknown_wins_over_in_progress() {
339 let status = DeploymentStatus::aggregate(
340 vec![
341 host(Transition::new(InProgress).with_reason("Deferred"), None),
342 host(Transition::new(Unknown).with_reason("GetFailed"), None),
343 ],
344 Current,
345 Current,
346 );
347 assert_eq!(summary(&status), (Unknown, Some("GetFailed")));
348 }
349
350 #[test]
351 fn first_deciding_object_gives_the_reason() {
352 let status = DeploymentStatus::aggregate(
353 vec![
354 host(Transition::new(Current), None),
355 host(
356 Transition::new(InProgress).with_reason("Deferred"),
357 Some(Transition::new(InProgress).with_reason("NodeResizePending")),
358 ),
359 ],
360 Current,
361 Current,
362 );
363 assert_eq!(summary(&status), (InProgress, Some("Deferred")));
364 }
365
366 #[test]
367 fn no_hosts_is_the_desired_state() {
368 let status = DeploymentStatus::aggregate(vec![], Current, Current);
369 assert_eq!(summary(&status), (Current, None));
370 let status = DeploymentStatus::aggregate(vec![], NotFound, NotFound);
371 assert_eq!(summary(&status), (NotFound, None));
372 }
373
374 #[test]
376 fn nothing_expected_to_exist_is_not_found() {
377 let cleared = DeploymentStatus::aggregate(
378 vec![host(
379 Transition::new(NotFound),
380 Some(Transition::new(NotFound)),
381 )],
382 NotFound,
383 NotFound,
384 );
385 assert_eq!(summary(&cleared), (NotFound, None));
386
387 let stopped = DeploymentStatus::aggregate(
389 vec![host(Transition::new(NotFound), None)],
390 NotFound,
391 Current,
392 );
393 assert_eq!(summary(&stopped), (NotFound, None));
394 }
395
396 #[test]
397 fn unknown_state_reads_as_unknown() {
398 let state: DeploymentState = serde_json::from_str("\"Suspended\"").unwrap();
399 assert_eq!(state, Unknown);
400 }
401
402 #[test]
403 fn serializes_flat() {
404 let status = DeploymentStatus::aggregate(
405 vec![host(
406 Transition::new(InProgress).with_reason("InProgress"),
407 None,
408 )],
409 Current,
410 Current,
411 );
412 assert_eq!(
413 serde_json::to_value(&status).unwrap(),
414 serde_json::json!({
415 "state": "InProgress",
416 "reason": "InProgress",
417 "hosts": [{
418 "ordinal": 0,
419 "compute": {
420 "state": "InProgress",
421 "reason": "InProgress",
422 "manager": "User",
423 "desired": null,
424 "current": null
425 }
426 }]
427 })
428 );
429 }
430}