feldera-types 0.387.0

Public API types for Feldera
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! What exists for a pipeline deployment: desired versus current resources per host, and the
//! state of each transition. State names follow the Kubernetes kstatus library.

use crate::config::ResourceConfig;
use crate::size::ConfigSize;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

/// Spec and observed status of a pipeline deployment.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct PipelineDeployment {
    pub spec: DeploymentSpec,
    /// Absent when the runner does not observe its resources.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<DeploymentStatus>,
}

/// What the deployment asks for, from the pipeline's `deployment_config`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct DeploymentSpec {
    pub resources: DeploymentSpecResources,
}

/// Each `*_min` is a Kubernetes request and each `*_max` a limit.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct DeploymentSpecResources {
    pub cpu_cores_min: Option<f64>,
    pub cpu_cores_max: Option<f64>,
    #[schema(value_type = Option<String>)]
    pub memory_min: Option<ConfigSize>,
    #[schema(value_type = Option<String>)]
    pub memory_max: Option<ConfigSize>,
    #[schema(value_type = Option<String>)]
    pub storage_min: Option<ConfigSize>,
    #[schema(value_type = Option<String>)]
    pub storage_max: Option<ConfigSize>,
}

impl From<&ResourceConfig> for DeploymentSpecResources {
    fn from(r: &ResourceConfig) -> Self {
        Self {
            cpu_cores_min: r.cpu_cores_min,
            cpu_cores_max: r.cpu_cores_max,
            memory_min: r.memory_min,
            memory_max: r.memory_max,
            storage_min: r.storage_min,
            storage_max: r.storage_max,
        }
    }
}

/// Status of an object or of the whole deployment, from
/// [kstatus](https://github.com/kubernetes-sigs/cli-utils/blob/master/pkg/kstatus/status/status.go).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub enum DeploymentState {
    /// Matches its desired state.
    Current,
    /// On its way to the desired state.
    InProgress,
    /// Will not reach the desired state without a change.
    Failed,
    /// Being deleted.
    Terminating,
    /// Does not exist.
    NotFound,
    /// Cannot be determined. Clients read a state they do not know as this one.
    #[serde(other)]
    Unknown,
}

/// Who sets the desired value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub enum ResourceManager {
    /// The pipeline's configuration.
    User,
    /// The runner's autoscaler, within the configured bounds.
    Autoscaler,
}

/// State of one Kubernetes object, with its cause.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct Transition {
    pub state: DeploymentState,
    /// Machine-readable cause, passed through from the runner's platform.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    /// When the platform last changed the condition behind `state` (Kubernetes
    /// `lastTransitionTime`, or `deletionTimestamp` for `Terminating`). If only `reason` changes,
    /// for example from `ContainerCreating` to `CrashLoopBackOff`, the time stays.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_transition_time: Option<DateTime<Utc>>,
}

impl Transition {
    pub fn new(state: DeploymentState) -> Self {
        Self {
            state,
            reason: None,
            message: None,
            last_transition_time: None,
        }
    }

    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }

    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }

    pub fn with_last_transition_time(mut self, since: Option<DateTime<Utc>>) -> Self {
        self.last_transition_time = since;
        self
    }
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct ComputeResources {
    pub cpu_cores_min: Option<f64>,
    pub cpu_cores_max: Option<f64>,
    pub memory_mb_min: Option<u64>,
    pub memory_mb_max: Option<u64>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct StorageResources {
    pub storage_mb: Option<u64>,
}

/// CPU and memory of one host.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct HostCompute {
    #[serde(flatten)]
    pub transition: Transition,
    pub manager: ResourceManager,
    /// Absent when the pipeline's `resources` are invalid.
    pub desired: Option<ComputeResources>,
    /// Absent when there is no pod, it cannot be read, or the kubelet has not reported its
    /// resources.
    pub current: Option<ComputeResources>,
}

/// Storage volume of one host.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct HostStorage {
    #[serde(flatten)]
    pub transition: Transition,
    pub manager: ResourceManager,
    /// Absent when the pipeline's `resources` are invalid.
    pub desired: Option<StorageResources>,
    /// Absent when there is no volume, it cannot be read, or it is not bound yet.
    pub current: Option<StorageResources>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct HostStatus {
    /// Host index, from 0 to `hosts - 1`. Kubernetes names the pod `<statefulset>-<ordinal>`.
    pub ordinal: usize,
    pub compute: HostCompute,
    /// Absent when the pipeline has no storage.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub storage: Option<HostStorage>,
}

/// Observed status of the deployment. `state`, `reason` and `message` summarize `hosts`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct DeploymentStatus {
    pub state: DeploymentState,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    pub hosts: Vec<HostStatus>,
}

impl DeploymentStatus {
    /// Summarizes `hosts` like kstatus `AggregateStatus`: `Failed` if any object failed, else
    /// `Unknown` if any is unknown, else the desired state if every object reached the state it
    /// is expected to (compute `compute_expected`, storage `storage_expected`), else
    /// `InProgress`. The desired state is `NotFound` when nothing is expected to exist, else
    /// `Current`. Reason and message come from the first object that decides the result.
    /// <https://github.com/kubernetes-sigs/cli-utils/blob/master/pkg/kstatus/polling/aggregator/aggregator.go>
    pub fn aggregate(
        hosts: Vec<HostStatus>,
        compute_expected: DeploymentState,
        storage_expected: DeploymentState,
    ) -> Self {
        let objects: Vec<(&Transition, DeploymentState)> = hosts
            .iter()
            .flat_map(|host| {
                std::iter::once((&host.compute.transition, compute_expected)).chain(
                    host.storage
                        .as_ref()
                        .map(|storage| (&storage.transition, storage_expected)),
                )
            })
            .collect();
        let desired = if compute_expected == DeploymentState::NotFound
            && objects
                .iter()
                .all(|(_, expected)| *expected == DeploymentState::NotFound)
        {
            DeploymentState::NotFound
        } else {
            DeploymentState::Current
        };
        let first = |matches: &dyn Fn(&Transition, DeploymentState) -> bool| {
            objects
                .iter()
                .find(|(transition, expected)| matches(transition, *expected))
                .map(|(transition, _)| *transition)
        };
        let (state, decider) = if let Some(t) = first(&|t, _| t.state == DeploymentState::Failed) {
            (DeploymentState::Failed, Some(t))
        } else if let Some(t) = first(&|t, _| t.state == DeploymentState::Unknown) {
            (DeploymentState::Unknown, Some(t))
        } else if let Some(t) = first(&|t, expected| t.state != expected) {
            (DeploymentState::InProgress, Some(t))
        } else {
            (desired, None)
        };
        Self {
            state,
            reason: decider.and_then(|t| t.reason.clone()),
            message: decider.and_then(|t| t.message.clone()),
            hosts,
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use DeploymentState::*;

    fn host(compute: Transition, storage: Option<Transition>) -> HostStatus {
        HostStatus {
            ordinal: 0,
            compute: HostCompute {
                transition: compute,
                manager: ResourceManager::User,
                desired: None,
                current: None,
            },
            storage: storage.map(|transition| HostStorage {
                transition,
                manager: ResourceManager::User,
                desired: None,
                current: None,
            }),
        }
    }

    fn summary(status: &DeploymentStatus) -> (DeploymentState, Option<&str>) {
        (status.state, status.reason.as_deref())
    }

    #[test]
    fn all_objects_as_expected_is_current() {
        let running = DeploymentStatus::aggregate(
            vec![host(
                Transition::new(Current),
                Some(Transition::new(Current)),
            )],
            Current,
            Current,
        );
        assert_eq!(summary(&running), (Current, None));

        // A stopped pipeline keeps its storage and has no pod.
        let stopped = DeploymentStatus::aggregate(
            vec![host(
                Transition::new(NotFound),
                Some(Transition::new(Current)),
            )],
            NotFound,
            Current,
        );
        assert_eq!(summary(&stopped), (Current, None));
    }

    #[test]
    fn object_not_as_expected_is_in_progress() {
        // Stopping: the pod is still there.
        let stopping = DeploymentStatus::aggregate(
            vec![host(
                Transition::new(Terminating).with_reason("Deleting"),
                None,
            )],
            NotFound,
            Current,
        );
        assert_eq!(summary(&stopping), (InProgress, Some("Deleting")));

        // Starting: the pod is not there yet.
        let starting = DeploymentStatus::aggregate(
            vec![host(Transition::new(NotFound), None)],
            Current,
            Current,
        );
        assert_eq!(summary(&starting), (InProgress, None));
    }

    #[test]
    fn failed_wins_over_unknown_and_in_progress() {
        let status = DeploymentStatus::aggregate(
            vec![
                host(
                    Transition::new(InProgress).with_reason("Deferred"),
                    Some(Transition::new(Unknown).with_reason("ListFailed")),
                ),
                host(
                    Transition::new(Current),
                    Some(
                        Transition::new(Failed)
                            .with_reason("ControllerResizeInfeasible")
                            .with_message("too big"),
                    ),
                ),
            ],
            Current,
            Current,
        );
        assert_eq!(
            summary(&status),
            (Failed, Some("ControllerResizeInfeasible"))
        );
        assert_eq!(status.message.as_deref(), Some("too big"));
    }

    #[test]
    fn unknown_wins_over_in_progress() {
        let status = DeploymentStatus::aggregate(
            vec![
                host(Transition::new(InProgress).with_reason("Deferred"), None),
                host(Transition::new(Unknown).with_reason("GetFailed"), None),
            ],
            Current,
            Current,
        );
        assert_eq!(summary(&status), (Unknown, Some("GetFailed")));
    }

    #[test]
    fn first_deciding_object_gives_the_reason() {
        let status = DeploymentStatus::aggregate(
            vec![
                host(Transition::new(Current), None),
                host(
                    Transition::new(InProgress).with_reason("Deferred"),
                    Some(Transition::new(InProgress).with_reason("NodeResizePending")),
                ),
            ],
            Current,
            Current,
        );
        assert_eq!(summary(&status), (InProgress, Some("Deferred")));
    }

    #[test]
    fn no_hosts_is_the_desired_state() {
        let status = DeploymentStatus::aggregate(vec![], Current, Current);
        assert_eq!(summary(&status), (Current, None));
        let status = DeploymentStatus::aggregate(vec![], NotFound, NotFound);
        assert_eq!(summary(&status), (NotFound, None));
    }

    /// Stopped and cleared: kstatus reports `NotFound` when that is the desired state.
    #[test]
    fn nothing_expected_to_exist_is_not_found() {
        let cleared = DeploymentStatus::aggregate(
            vec![host(
                Transition::new(NotFound),
                Some(Transition::new(NotFound)),
            )],
            NotFound,
            NotFound,
        );
        assert_eq!(summary(&cleared), (NotFound, None));

        // Without storage, the pod alone decides.
        let stopped = DeploymentStatus::aggregate(
            vec![host(Transition::new(NotFound), None)],
            NotFound,
            Current,
        );
        assert_eq!(summary(&stopped), (NotFound, None));
    }

    #[test]
    fn unknown_state_reads_as_unknown() {
        let state: DeploymentState = serde_json::from_str("\"Suspended\"").unwrap();
        assert_eq!(state, Unknown);
    }

    #[test]
    fn serializes_flat() {
        let status = DeploymentStatus::aggregate(
            vec![host(
                Transition::new(InProgress).with_reason("InProgress"),
                None,
            )],
            Current,
            Current,
        );
        assert_eq!(
            serde_json::to_value(&status).unwrap(),
            serde_json::json!({
                "state": "InProgress",
                "reason": "InProgress",
                "hosts": [{
                    "ordinal": 0,
                    "compute": {
                        "state": "InProgress",
                        "reason": "InProgress",
                        "manager": "User",
                        "desired": null,
                        "current": null
                    }
                }]
            })
        );
    }
}