Skip to main content

feldera_types/
runtime_status.rs

1use crate::checkpoint::CheckpointMetadata;
2use crate::error::ErrorResponse;
3use crate::size::ConfigSize;
4use actix_web::body::BoxBody;
5use actix_web::http::StatusCode;
6use actix_web::{HttpRequest, HttpResponse, HttpResponseBuilder, Responder, ResponseError};
7use bytemuck::NoUninit;
8use clap::ValueEnum;
9use serde::{Deserialize, Serialize};
10use serde_json::json;
11use std::fmt;
12use std::fmt::Display;
13use utoipa::ToSchema;
14
15/// Runtime status of the pipeline.
16///
17/// Of the statuses, only `Unavailable` is determined by the runner. All other statuses are
18/// determined by the pipeline and taken over by the runner.
19#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize, ToSchema, NoUninit)]
20#[cfg_attr(feature = "testing", derive(proptest_derive::Arbitrary))]
21#[repr(u8)]
22pub enum RuntimeStatus {
23    /// The runner was unable to determine the pipeline runtime status. This status is never
24    /// returned by the pipeline endpoint itself, but only determined by the runner.
25    ///
26    /// It can notably occur in two scenarios:
27    /// 1. The runner is unable to (in time) receive a response for its sent request to the
28    ///    pipeline `/status` endpoint, or it is unable to parse the response.
29    /// 2. The runner received back a `503 Service Unavailable` as a response to the request.
30    ///    This can occur for example if the pipeline is unable to acquire a lock necessary to
31    ///    determine whether it is in any of the other runtime statuses.
32    Unavailable,
33
34    /// The pipeline is waiting for initialization instructions from the
35    /// coordinator.
36    Coordination,
37
38    /// The pipeline is constantly pulling the latest checkpoint from S3 but not processing any inputs.
39    Standby,
40
41    /// The input and output connectors are establishing connections to their data sources and sinks
42    /// respectively.
43    Initializing,
44
45    /// The pipeline was modified since the last checkpoint. User approval is required before
46    /// bootstrapping can proceed.
47    AwaitingApproval,
48
49    /// The pipeline was modified since the last checkpoint, and is currently bootstrapping modified
50    /// views.
51    Bootstrapping,
52
53    /// Input records that were stored in the journal but were not yet processed, are being
54    /// processed first.
55    Replaying,
56
57    /// The input connectors are paused.
58    Paused,
59
60    /// The input connectors are running.
61    Running,
62
63    /// The pipeline finished checkpointing and pausing.
64    Suspended,
65
66    /// A concurrent bootstrap is in progress: the pre-existing views are live
67    /// and serving while new/modified views backfill in the background.
68    ConcurrentBootstrapping,
69
70    /// A concurrent bootstrap is in its cutover window: inputs are briefly
71    /// paused while the backfilled views are synchronized and brought online.
72    Synchronizing,
73}
74
75impl From<RuntimeDesiredStatus> for RuntimeStatus {
76    fn from(value: RuntimeDesiredStatus) -> Self {
77        match value {
78            RuntimeDesiredStatus::Unavailable => Self::Unavailable,
79            RuntimeDesiredStatus::Coordination => Self::Coordination,
80            RuntimeDesiredStatus::Standby => Self::Standby,
81            RuntimeDesiredStatus::Paused => Self::Paused,
82            RuntimeDesiredStatus::Running => Self::Running,
83            RuntimeDesiredStatus::Suspended => Self::Suspended,
84        }
85    }
86}
87
88#[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize, Serialize, ToSchema, ValueEnum)]
89#[cfg_attr(feature = "testing", derive(proptest_derive::Arbitrary))]
90pub enum RuntimeDesiredStatus {
91    Unavailable,
92    Coordination,
93    Standby,
94    Paused,
95    Running,
96    Suspended,
97}
98
99impl RuntimeDesiredStatus {
100    pub fn may_transition_to(&self, target: Self) -> bool {
101        match (*self, target) {
102            (old, new) if old == new => true,
103            (Self::Standby, Self::Paused | Self::Running) => true,
104            (Self::Paused, Self::Running | Self::Suspended) => true,
105            (Self::Running, Self::Paused | Self::Suspended) => true,
106            _ => false,
107        }
108    }
109
110    pub fn may_transition_to_at_startup(&self, target: Self) -> bool {
111        match (*self, target) {
112            (_, Self::Coordination) => true,
113            (Self::Suspended, _) => {
114                // A suspended pipeline must transition to "paused" or
115                // "running".
116                matches!(target, Self::Paused | Self::Running)
117            }
118            (old, new) if old.may_transition_to(new) => true,
119            _ => false,
120        }
121    }
122}
123
124/// Some of our JSON interface uses capitalized status names, like `Paused`, but
125/// other parts use snake-case names, like `paused`.  To support the latter with
126/// `serde`, use this module in the field declaration, e.g.:
127///
128/// ```ignore
129/// #[serde(with = "feldera_types::runtime_status::snake_case_runtime_desired_status")]
130/// ```
131pub mod snake_case_runtime_desired_status {
132    use serde::{Deserialize, Deserializer, Serialize, Serializer};
133
134    use crate::runtime_status::RuntimeDesiredStatus;
135
136    #[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize, Serialize)]
137    #[serde(rename_all = "snake_case")]
138    enum SnakeRuntimeDesiredStatus {
139        Unavailable,
140        Coordination,
141        Standby,
142        Paused,
143        Running,
144        Suspended,
145    }
146
147    impl From<RuntimeDesiredStatus> for SnakeRuntimeDesiredStatus {
148        fn from(value: RuntimeDesiredStatus) -> Self {
149            match value {
150                RuntimeDesiredStatus::Unavailable => SnakeRuntimeDesiredStatus::Unavailable,
151                RuntimeDesiredStatus::Coordination => SnakeRuntimeDesiredStatus::Coordination,
152                RuntimeDesiredStatus::Standby => SnakeRuntimeDesiredStatus::Standby,
153                RuntimeDesiredStatus::Paused => SnakeRuntimeDesiredStatus::Paused,
154                RuntimeDesiredStatus::Running => SnakeRuntimeDesiredStatus::Running,
155                RuntimeDesiredStatus::Suspended => SnakeRuntimeDesiredStatus::Suspended,
156            }
157        }
158    }
159
160    impl From<SnakeRuntimeDesiredStatus> for RuntimeDesiredStatus {
161        fn from(value: SnakeRuntimeDesiredStatus) -> Self {
162            match value {
163                SnakeRuntimeDesiredStatus::Unavailable => RuntimeDesiredStatus::Unavailable,
164                SnakeRuntimeDesiredStatus::Coordination => RuntimeDesiredStatus::Coordination,
165                SnakeRuntimeDesiredStatus::Standby => RuntimeDesiredStatus::Standby,
166                SnakeRuntimeDesiredStatus::Paused => RuntimeDesiredStatus::Paused,
167                SnakeRuntimeDesiredStatus::Running => RuntimeDesiredStatus::Running,
168                SnakeRuntimeDesiredStatus::Suspended => RuntimeDesiredStatus::Suspended,
169            }
170        }
171    }
172
173    pub fn serialize<S>(value: &RuntimeDesiredStatus, serializer: S) -> Result<S::Ok, S::Error>
174    where
175        S: Serializer,
176    {
177        SnakeRuntimeDesiredStatus::from(*value).serialize(serializer)
178    }
179
180    pub fn deserialize<'de, D>(deserializer: D) -> Result<RuntimeDesiredStatus, D::Error>
181    where
182        D: Deserializer<'de>,
183    {
184        SnakeRuntimeDesiredStatus::deserialize(deserializer).map(|status| status.into())
185    }
186}
187
188#[derive(
189    Debug, Default, Clone, Copy, Eq, PartialEq, Deserialize, Serialize, ToSchema, NoUninit,
190)]
191#[repr(u8)]
192#[serde(rename_all = "snake_case")]
193pub enum BootstrapPolicy {
194    Allow,
195    Reject,
196    #[default]
197    AwaitApproval,
198}
199
200impl TryFrom<Option<String>> for BootstrapPolicy {
201    type Error = ();
202
203    fn try_from(value: Option<String>) -> Result<Self, Self::Error> {
204        match value.as_deref() {
205            Some("allow") => Ok(Self::Allow),
206            Some("reject") => Ok(Self::Reject),
207            Some("await_approval") | None => Ok(Self::AwaitApproval),
208            _ => Err(()),
209        }
210    }
211}
212
213impl From<String> for BootstrapPolicy {
214    fn from(value: String) -> Self {
215        match value.as_str() {
216            "allow" => Self::Allow,
217            "reject" => Self::Reject,
218            "await_approval" => Self::AwaitApproval,
219            _ => panic!("Invalid 'bootstrap_policy' value: {value}"),
220        }
221    }
222}
223
224impl Display for BootstrapPolicy {
225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226        let s = match self {
227            BootstrapPolicy::Allow => "allow",
228            BootstrapPolicy::Reject => "reject",
229            BootstrapPolicy::AwaitApproval => "await_approval",
230        };
231        write!(f, "{s}")
232    }
233}
234
235/// Bootstrap-related configuration for a deployment start request.
236#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, ToSchema, Default)]
237pub struct BootstrapConfig {
238    /// Bootstrap policy.
239    #[serde(default)]
240    pub bootstrap_policy: Option<BootstrapPolicy>,
241    /// Bootstrap the pipeline with output connectors disabled.
242    #[serde(default)]
243    pub silent_bootstrap: bool,
244    /// Bootstrap new and modified views concurrently, keeping the pre-existing
245    /// views live while the new ones backfill in the background.
246    ///
247    /// Mutually exclusive with `silent_bootstrap`. When set, a circuit that
248    /// cannot be bootstrapped concurrently fails the pipeline instead of
249    /// falling back to a stop-the-world bootstrap.
250    #[serde(default)]
251    pub concurrent_bootstrap: bool,
252}
253
254impl From<BootstrapPolicy> for BootstrapConfig {
255    fn from(bootstrap_policy: BootstrapPolicy) -> Self {
256        Self {
257            bootstrap_policy: Some(bootstrap_policy),
258            silent_bootstrap: false,
259            concurrent_bootstrap: false,
260        }
261    }
262}
263
264impl BootstrapConfig {
265    pub fn with_silent_bootstrap(self, silent_bootstrap: bool) -> Self {
266        Self {
267            silent_bootstrap,
268            ..self
269        }
270    }
271
272    pub fn with_concurrent_bootstrap(self, concurrent_bootstrap: bool) -> Self {
273        Self {
274            concurrent_bootstrap,
275            ..self
276        }
277    }
278
279    /// Validates that the bootstrap options are mutually consistent.
280    ///
281    /// `silent_bootstrap` and `concurrent_bootstrap` cannot both be set:
282    /// silent bootstrap suppresses outputs during a stop-the-world bootstrap,
283    /// whereas concurrent bootstrap keeps the old views (and their outputs)
284    /// live, so the two requests contradict each other.
285    pub fn validate(&self) -> Result<(), String> {
286        if self.silent_bootstrap && self.concurrent_bootstrap {
287            return Err(
288                "`silent_bootstrap` and `concurrent_bootstrap` are mutually exclusive; \
289                 set at most one"
290                    .to_string(),
291            );
292        }
293        Ok(())
294    }
295
296    /// Returns the bootstrap policy for an active deployment.
297    pub fn active_bootstrap_policy(&self) -> BootstrapPolicy {
298        self.bootstrap_policy
299            .expect("bootstrap policy must be set for an active deployment")
300    }
301}
302
303/// Details about pipeline storage, which are returned as part of the regular runtime status polling
304/// by the runner.
305#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
306pub struct StorageStatusDetails {
307    /// Present checkpoints.
308    pub checkpoints: Vec<CheckpointMetadata>,
309}
310
311#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
312pub struct ExtendedRuntimeStatus {
313    /// Runtime status of the pipeline.
314    pub runtime_status: RuntimeStatus,
315
316    /// Human-readable details about the runtime status. Its content can contain for instance an
317    /// explanation why it is in this status and any other additional information about it (e.g.,
318    /// progress).
319    pub runtime_status_details: serde_json::Value,
320
321    /// Runtime desired status of the pipeline.
322    pub runtime_desired_status: RuntimeDesiredStatus,
323
324    /// Details about the pipeline persistent storage.
325    ///
326    /// `None` indicates that the pipeline in its current runtime status is unable to check the
327    /// storage status details. Returning `None` _does not_ override the already existing storage
328    /// status details in the database of the runner.
329    pub storage_status_details: Option<StorageStatusDetails>,
330}
331
332impl Responder for ExtendedRuntimeStatus {
333    type Body = BoxBody;
334
335    fn respond_to(self, _req: &HttpRequest) -> HttpResponse<Self::Body> {
336        HttpResponseBuilder::new(StatusCode::OK).json(self)
337    }
338}
339
340impl From<ExtendedRuntimeStatus> for HttpResponse<BoxBody> {
341    fn from(value: ExtendedRuntimeStatus) -> Self {
342        HttpResponseBuilder::new(StatusCode::OK).json(value)
343    }
344}
345
346/// Error returned by the pipeline `/status` endpoint.
347#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
348pub struct ExtendedRuntimeStatusError {
349    /// Status code. Returning anything except `503 Service Unavailable` will cause the runner to
350    /// forcefully stop the pipeline.
351    #[serde(with = "status_code")]
352    pub status_code: StatusCode,
353
354    /// Error response.
355    pub error: ErrorResponse,
356}
357
358mod status_code {
359    use actix_web::http::StatusCode;
360    use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error};
361
362    pub fn serialize<S>(value: &StatusCode, serializer: S) -> Result<S::Ok, S::Error>
363    where
364        S: Serializer,
365    {
366        value.as_u16().serialize(serializer)
367    }
368
369    pub fn deserialize<'de, D>(deserializer: D) -> Result<StatusCode, D::Error>
370    where
371        D: Deserializer<'de>,
372    {
373        let value = u16::deserialize(deserializer)?;
374        StatusCode::from_u16(value).map_err(D::Error::custom)
375    }
376}
377
378impl Display for ExtendedRuntimeStatusError {
379    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380        write!(f, "{}: {:?}", self.status_code, self.error)
381    }
382}
383
384impl ResponseError for ExtendedRuntimeStatusError {
385    fn status_code(&self) -> StatusCode {
386        self.status_code
387    }
388
389    fn error_response(&self) -> HttpResponse<BoxBody> {
390        HttpResponseBuilder::new(self.status_code()).json(self.error.clone())
391    }
392}
393
394/// Details about the current runtime status. The fields in this struct should all be **optional**
395/// and set only by a runtime status when they are known. Otherwise, they can just be set `None`.
396#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default, Eq, ToSchema)]
397pub struct RuntimeStatusDetails {
398    /// Free form text giving an explanation why it is currently in this runtime status.
399    ///
400    /// Specifically useful for: `Unavailable`, `Initializing`.
401    #[serde(skip_serializing_if = "Option::is_none")]
402    pub reason: Option<String>,
403
404    /// Statistics across all connectors.
405    ///
406    /// Specifically useful for: `Paused`, `Running`.
407    #[serde(skip_serializing_if = "Option::is_none")]
408    pub connector_stats: Option<ConnectorStats>,
409
410    /// The `resources.memory_max` the pipeline uses, which a resize changes.
411    ///
412    /// Specifically useful for: `Paused`, `Running`.
413    #[serde(skip_serializing_if = "Option::is_none")]
414    #[schema(value_type = Option<String>)]
415    pub memory_max: Option<ConfigSize>,
416
417    /// The diff which is awaiting approval.
418    ///
419    /// Specifically useful for: `AwaitingApproval`.
420    #[serde(skip_serializing_if = "Option::is_none")]
421    pub approval_diff: Option<serde_json::Value>,
422    // Backward compatibility: in older versions, the approval diff was the runtime status details
423    // value itself. To distinguish between the old and new version, clients can check if the
424    // `program_diff` field (one of the fields within the `approval_diff`) is present if they
425    // expect there to be a diff (i.e., when the runtime status is `AwaitingApproval`). As such,
426    // `program_diff` is a reserved field name that cannot be added here in the future.
427}
428
429impl RuntimeStatusDetails {
430    pub fn new_only_reason(reason: &str) -> Self {
431        Self {
432            reason: Some(reason.to_string()),
433            ..Self::default()
434        }
435    }
436
437    /// Serializes the runtime status details to JSON. If the serialization errors, an error JSON
438    /// is returned instead. This makes sure this method does not panic unexpectedly and that the
439    /// error bubbles up. The details are only supplementary information, and as such are not
440    /// critical to operation.
441    pub fn serialize_guaranteed(self) -> serde_json::Value {
442        serde_json::to_value(self).unwrap_or_else(|e| {
443            json!({
444                "reason": format!("unable to serialize runtime status details due to: {e}")
445            })
446        })
447    }
448}
449
450/// Statistics across all connectors.
451#[derive(Serialize, Deserialize, ToSchema, Eq, PartialEq, Debug, Clone)]
452pub struct ConnectorStats {
453    /// Total number of errors across all connectors.
454    ///
455    /// - `num_transport_errors` from all input connectors
456    /// - `num_parse_errors` from all input connectors
457    /// - `num_encode_errors` from all output connectors
458    /// - `num_transport_errors` from all output connectors
459    pub num_errors: u64,
460}