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#[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 Unavailable,
33
34 Coordination,
37
38 Standby,
40
41 Initializing,
44
45 AwaitingApproval,
48
49 Bootstrapping,
52
53 Replaying,
56
57 Paused,
59
60 Running,
62
63 Suspended,
65
66 ConcurrentBootstrapping,
69
70 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 matches!(target, Self::Paused | Self::Running)
117 }
118 (old, new) if old.may_transition_to(new) => true,
119 _ => false,
120 }
121 }
122}
123
124pub 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#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, ToSchema, Default)]
237pub struct BootstrapConfig {
238 #[serde(default)]
240 pub bootstrap_policy: Option<BootstrapPolicy>,
241 #[serde(default)]
243 pub silent_bootstrap: bool,
244 #[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 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 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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
306pub struct StorageStatusDetails {
307 pub checkpoints: Vec<CheckpointMetadata>,
309}
310
311#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
312pub struct ExtendedRuntimeStatus {
313 pub runtime_status: RuntimeStatus,
315
316 pub runtime_status_details: serde_json::Value,
320
321 pub runtime_desired_status: RuntimeDesiredStatus,
323
324 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
348pub struct ExtendedRuntimeStatusError {
349 #[serde(with = "status_code")]
352 pub status_code: StatusCode,
353
354 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default, Eq, ToSchema)]
397pub struct RuntimeStatusDetails {
398 #[serde(skip_serializing_if = "Option::is_none")]
402 pub reason: Option<String>,
403
404 #[serde(skip_serializing_if = "Option::is_none")]
408 pub connector_stats: Option<ConnectorStats>,
409
410 #[serde(skip_serializing_if = "Option::is_none")]
414 #[schema(value_type = Option<String>)]
415 pub memory_max: Option<ConfigSize>,
416
417 #[serde(skip_serializing_if = "Option::is_none")]
421 pub approval_diff: Option<serde_json::Value>,
422 }
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 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#[derive(Serialize, Deserialize, ToSchema, Eq, PartialEq, Debug, Clone)]
452pub struct ConnectorStats {
453 pub num_errors: u64,
460}