tatara-core 0.2.74

Shared domain types, config, and cluster types for tatara
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Universal workload lifecycle — the distributed state machine.
//!
//! Every workload (task, allocation, job, node) follows:
//!   Initial → Warming → Executing → Contracting → Terminal
//!
//! This applies at every level with type-specific detail structs.
//! The generic `WorkloadPhase<W, E, C, T>` is parameterized by
//! detail types for each phase.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

// ── Generic Phase Enum ─────────────────────────────────────────

/// The universal workload lifecycle phase.
///
/// State transitions form a strict DAG:
/// ```text
///   Initial → Warming → Executing → Contracting → Terminal
///                     ↘ Contracting (warm failed)
///                     ↘ Terminal (fast-fail, no cleanup needed)
///                                  → Initial (successful contraction, restart)
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "phase", rename_all = "snake_case")]
pub enum WorkloadPhase<W, E, C, T> {
    /// Defined but not active. Zero resources allocated.
    Initial,
    /// Preparing to execute. Resources being acquired.
    Warming(W),
    /// Active and serving.
    Executing(E),
    /// Gracefully winding down.
    Contracting(C),
    /// Final state. Will not transition again (unless recycled to Initial).
    Terminal(T),
}

impl<W, E, C, T> WorkloadPhase<W, E, C, T> {
    pub fn phase_name(&self) -> &'static str {
        match self {
            Self::Initial => "initial",
            Self::Warming(_) => "warming",
            Self::Executing(_) => "executing",
            Self::Contracting(_) => "contracting",
            Self::Terminal(_) => "terminal",
        }
    }

    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::Terminal(_))
    }

    pub fn is_active(&self) -> bool {
        matches!(self, Self::Warming(_) | Self::Executing(_))
    }

    pub fn is_initial(&self) -> bool {
        matches!(self, Self::Initial)
    }
}

/// Validate that a phase transition is legal.
pub fn is_valid_transition(from: &str, to: &str) -> bool {
    matches!(
        (from, to),
        ("initial", "warming")
            | ("warming", "executing")
            | ("warming", "contracting")
            | ("warming", "terminal")
            | ("executing", "contracting")
            | ("contracting", "terminal")
            | ("contracting", "initial")
    )
}

// ── Shared Types ───────────────────────────────────────────────

/// Why a workload is contracting.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ContractReason {
    Stopped,
    Superseded { new_version: u64 },
    NodeDrain,
    ScaleDown,
    HealthFailure,
    ResourcePressure,
}

/// Final outcome of a workload.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
    Success,
    Failed,
    Lost,
    Cancelled,
}

/// Health status (used across levels).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "snake_case")]
pub enum HealthStatus {
    #[default]
    Unknown,
    Passing,
    Warning {
        message: String,
    },
    Critical {
        message: String,
    },
}

/// Desired phase for an allocation (what the scheduler wants).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum DesiredPhase {
    Active,
    Stopped { reason: ContractReason },
}

// ── Task-Level Detail Types ────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TaskWarmProgress {
    pub fetch_progress: f64,
    pub deps_resolved: bool,
    pub port_allocated: bool,
    pub warmup_checks_passed: u32,
    pub warmup_checks_required: u32,
}

impl Default for TaskWarmProgress {
    fn default() -> Self {
        Self {
            fetch_progress: 0.0,
            deps_resolved: false,
            port_allocated: false,
            warmup_checks_passed: 0,
            warmup_checks_required: 1,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TaskExecuteDetail {
    pub pid: Option<u32>,
    pub container_id: Option<String>,
    pub health: HealthStatus,
    pub started_at: DateTime<Utc>,
    pub health_check_epoch: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TaskContractDetail {
    pub reason: ContractReason,
    pub signal_sent_at: Option<DateTime<Utc>>,
    pub grace_period_secs: u64,
    pub drain_connections: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TaskTerminalDetail {
    pub outcome: Outcome,
    pub exit_code: Option<i32>,
    pub finished_at: DateTime<Utc>,
    pub restarts: u32,
}

/// Concrete task lifecycle phase.
pub type TaskPhase =
    WorkloadPhase<TaskWarmProgress, TaskExecuteDetail, TaskContractDetail, TaskTerminalDetail>;

// ── Allocation-Level Detail Types ──────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AllocWarmProgress {
    pub secrets_resolved: bool,
    pub volumes_mounted: bool,
    pub task_progress: HashMap<String, TaskWarmProgress>,
    /// Network identity assigned in the routing table.
    #[serde(default)]
    pub network_identity_assigned: bool,
    /// Endpoint registered in the networking plane.
    #[serde(default)]
    pub endpoint_registered: bool,
}

impl Default for AllocWarmProgress {
    fn default() -> Self {
        Self {
            secrets_resolved: false,
            volumes_mounted: false,
            task_progress: HashMap::new(),
            network_identity_assigned: false,
            endpoint_registered: false,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AllocExecuteDetail {
    pub registered_in_catalog: bool,
    pub health: HealthStatus,
    pub task_states: HashMap<String, TaskPhase>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AllocContractDetail {
    pub reason: ContractReason,
    pub deregistered_from_catalog: bool,
    pub task_states: HashMap<String, TaskPhase>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AllocTerminalDetail {
    pub outcome: Outcome,
    pub finished_at: DateTime<Utc>,
}

/// Concrete allocation lifecycle phase.
pub type AllocationPhase =
    WorkloadPhase<AllocWarmProgress, AllocExecuteDetail, AllocContractDetail, AllocTerminalDetail>;

// ── Node-Level Detail Types ────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NodeWarmProgress {
    pub raft_joined: bool,
    pub gossip_converged: bool,
    pub drivers_ready: Vec<String>,
    /// WireGuard mesh tunnel established.
    #[serde(default)]
    pub wireguard_tunnel_up: bool,
    /// Number of mesh peers connected.
    #[serde(default)]
    pub mesh_peers_connected: u32,
}

impl Default for NodeWarmProgress {
    fn default() -> Self {
        Self {
            raft_joined: false,
            gossip_converged: false,
            drivers_ready: Vec::new(),
            wireguard_tunnel_up: false,
            mesh_peers_connected: 0,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NodeExecuteDetail {
    pub eligible: bool,
    pub allocation_count: u32,
    pub last_heartbeat: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NodeContractDetail {
    pub reason: ContractReason,
    pub draining_allocations: Vec<Uuid>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NodeTerminalDetail {
    pub departed_at: DateTime<Utc>,
    pub reason: ContractReason,
}

/// Concrete node lifecycle phase.
pub type NodePhase =
    WorkloadPhase<NodeWarmProgress, NodeExecuteDetail, NodeContractDetail, NodeTerminalDetail>;

// ── Desired/Observed State (for Raft replication) ──────────────

/// What the scheduler declares an allocation should be.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DesiredAllocationState {
    pub alloc_id: Uuid,
    pub job_id: String,
    pub group_name: String,
    pub node_id: String,
    pub job_version: u64,
    pub desired_phase: DesiredPhase,
    pub generation: u64,
}

/// What a node observes an allocation to actually be.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObservedAllocationState {
    pub alloc_id: Uuid,
    pub node_id: String,
    pub phase: AllocationPhase,
    pub observed_at: DateTime<Utc>,
    pub observation_seq: u64,
}

// ── Migration from legacy enums ────────────────────────────────

use super::allocation::{AllocationState, TaskRunState};

impl From<AllocationState> for AllocationPhase {
    fn from(state: AllocationState) -> Self {
        match state {
            AllocationState::Pending => AllocationPhase::Initial,
            AllocationState::Running => AllocationPhase::Executing(AllocExecuteDetail {
                registered_in_catalog: false,
                health: HealthStatus::Unknown,
                task_states: HashMap::new(),
            }),
            AllocationState::Complete => AllocationPhase::Terminal(AllocTerminalDetail {
                outcome: Outcome::Success,
                finished_at: Utc::now(),
            }),
            AllocationState::Failed => AllocationPhase::Terminal(AllocTerminalDetail {
                outcome: Outcome::Failed,
                finished_at: Utc::now(),
            }),
            AllocationState::Lost => AllocationPhase::Terminal(AllocTerminalDetail {
                outcome: Outcome::Lost,
                finished_at: Utc::now(),
            }),
        }
    }
}

impl From<TaskRunState> for TaskPhase {
    fn from(state: TaskRunState) -> Self {
        match state {
            TaskRunState::Pending => TaskPhase::Initial,
            TaskRunState::Running => TaskPhase::Executing(TaskExecuteDetail {
                pid: None,
                container_id: None,
                health: HealthStatus::Unknown,
                started_at: Utc::now(),
                health_check_epoch: 0,
            }),
            TaskRunState::Dead => TaskPhase::Terminal(TaskTerminalDetail {
                outcome: Outcome::Failed,
                exit_code: None,
                finished_at: Utc::now(),
                restarts: 0,
            }),
        }
    }
}

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

    #[test]
    fn test_phase_names() {
        let phase: TaskPhase = TaskPhase::Initial;
        assert_eq!(phase.phase_name(), "initial");

        let phase: TaskPhase = TaskPhase::Warming(TaskWarmProgress::default());
        assert_eq!(phase.phase_name(), "warming");
        assert!(phase.is_active());

        let phase: TaskPhase = TaskPhase::Terminal(TaskTerminalDetail {
            outcome: Outcome::Success,
            exit_code: Some(0),
            finished_at: Utc::now(),
            restarts: 0,
        });
        assert!(phase.is_terminal());
        assert!(!phase.is_active());
    }

    #[test]
    fn test_valid_transitions() {
        assert!(is_valid_transition("initial", "warming"));
        assert!(is_valid_transition("warming", "executing"));
        assert!(is_valid_transition("executing", "contracting"));
        assert!(is_valid_transition("contracting", "terminal"));
        assert!(is_valid_transition("contracting", "initial")); // restart
        assert!(is_valid_transition("warming", "terminal")); // fast-fail

        assert!(!is_valid_transition("initial", "executing")); // skip warm
        assert!(!is_valid_transition("executing", "warming")); // backward
        assert!(!is_valid_transition("terminal", "initial")); // dead is dead
        assert!(!is_valid_transition("initial", "contracting")); // nothing to contract
    }

    #[test]
    fn test_allocation_phase_from_legacy() {
        let phase: AllocationPhase = AllocationState::Pending.into();
        assert!(phase.is_initial());

        let phase: AllocationPhase = AllocationState::Running.into();
        assert_eq!(phase.phase_name(), "executing");

        let phase: AllocationPhase = AllocationState::Failed.into();
        assert!(phase.is_terminal());
    }

    #[test]
    fn test_task_phase_from_legacy() {
        let phase: TaskPhase = TaskRunState::Pending.into();
        assert!(phase.is_initial());

        let phase: TaskPhase = TaskRunState::Running.into();
        assert!(phase.is_active());

        let phase: TaskPhase = TaskRunState::Dead.into();
        assert!(phase.is_terminal());
    }

    #[test]
    fn test_serde_roundtrip() {
        let phase = AllocationPhase::Warming(AllocWarmProgress {
            secrets_resolved: true,
            volumes_mounted: false,
            network_identity_assigned: true,
            endpoint_registered: false,
            task_progress: HashMap::from([(
                "web".to_string(),
                TaskWarmProgress {
                    fetch_progress: 0.75,
                    deps_resolved: true,
                    port_allocated: true,
                    warmup_checks_passed: 2,
                    warmup_checks_required: 3,
                },
            )]),
        });

        let json = serde_json::to_string(&phase).unwrap();
        let back: AllocationPhase = serde_json::from_str(&json).unwrap();
        assert_eq!(phase, back);
    }

    #[test]
    fn test_desired_phase_serde() {
        let desired = DesiredPhase::Stopped {
            reason: ContractReason::ScaleDown,
        };
        let json = serde_json::to_string(&desired).unwrap();
        let back: DesiredPhase = serde_json::from_str(&json).unwrap();
        assert_eq!(desired, back);
    }
}