swarm repositories / source
summaryrefslogtreecommitdiff
path: root/crates/ra-mcp-domain/src/lifecycle.rs
blob: 91007ac66920d66fa60b68b6fd9c9a63550c7f89 (plain)
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
//! Typestate machine for worker lifecycle.

use crate::{
    fault::Fault,
    types::{Generation, InvariantViolation},
};
use serde::{Deserialize, Serialize};

/// A worker in cold state (no process).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cold;

/// A worker in startup handshake.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Starting;

/// A healthy worker ready to serve requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Ready;

/// A worker currently recovering from failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Recovering {
    last_fault: Fault,
}

impl Recovering {
    /// Constructs recovering state from the most recent fault.
    #[must_use]
    pub fn new(last_fault: Fault) -> Self {
        Self { last_fault }
    }

    /// Returns the most recent fault.
    #[must_use]
    pub fn last_fault(&self) -> &Fault {
        &self.last_fault
    }
}

/// Lifecycle state with a typestate payload.
#[derive(Debug, Clone)]
pub struct Lifecycle<S> {
    generation: Generation,
    state: S,
}

impl Lifecycle<Cold> {
    /// Constructs a cold lifecycle.
    #[must_use]
    pub fn cold() -> Self {
        Self {
            generation: Generation::genesis(),
            state: Cold,
        }
    }

    /// Begins startup sequence.
    #[must_use]
    pub fn ignite(self) -> Lifecycle<Starting> {
        Lifecycle {
            generation: self.generation,
            state: Starting,
        }
    }
}

impl Lifecycle<Starting> {
    /// Marks startup as successful.
    #[must_use]
    pub fn arm(self) -> Lifecycle<Ready> {
        Lifecycle {
            generation: self.generation,
            state: Ready,
        }
    }

    /// Marks startup as failed and enters recovery.
    #[must_use]
    pub fn fracture(self, fault: Fault) -> Lifecycle<Recovering> {
        Lifecycle {
            generation: self.generation,
            state: Recovering::new(fault),
        }
    }
}

impl Lifecycle<Ready> {
    /// Moves from ready to recovering after a fault.
    #[must_use]
    pub fn fracture(self, fault: Fault) -> Lifecycle<Recovering> {
        Lifecycle {
            generation: self.generation,
            state: Recovering::new(fault),
        }
    }
}

impl Lifecycle<Recovering> {
    /// Advances generation and retries startup.
    #[must_use]
    pub fn respawn(self) -> Lifecycle<Starting> {
        Lifecycle {
            generation: self.generation.next(),
            state: Starting,
        }
    }

    /// Returns the most recent fault.
    #[must_use]
    pub fn last_fault(&self) -> &Fault {
        self.state.last_fault()
    }
}

impl<S> Lifecycle<S> {
    /// Returns the active generation.
    #[must_use]
    pub fn generation(&self) -> Generation {
        self.generation
    }

    /// Returns the typestate payload.
    #[must_use]
    pub fn state(&self) -> &S {
        &self.state
    }
}

/// Serializable lifecycle snapshot for diagnostics.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum LifecycleSnapshot {
    /// No worker is currently running.
    Cold {
        /// Current generation counter.
        generation: Generation,
    },
    /// Worker startup is in progress.
    Starting {
        /// Current generation counter.
        generation: Generation,
    },
    /// Worker is ready for requests.
    Ready {
        /// Current generation counter.
        generation: Generation,
    },
    /// Worker is recovering after a fault.
    Recovering {
        /// Current generation counter.
        generation: Generation,
        /// Most recent fault.
        last_fault: Fault,
    },
}

/// Dynamically typed lifecycle state for runtime storage.
#[derive(Debug, Clone)]
pub enum DynamicLifecycle {
    /// Cold typestate wrapper.
    Cold(Lifecycle<Cold>),
    /// Starting typestate wrapper.
    Starting(Lifecycle<Starting>),
    /// Ready typestate wrapper.
    Ready(Lifecycle<Ready>),
    /// Recovering typestate wrapper.
    Recovering(Lifecycle<Recovering>),
}

impl DynamicLifecycle {
    /// Creates a cold dynamic lifecycle.
    #[must_use]
    pub fn cold() -> Self {
        Self::Cold(Lifecycle::cold())
    }

    /// Returns the serializable snapshot.
    #[must_use]
    pub fn snapshot(&self) -> LifecycleSnapshot {
        match self {
            Self::Cold(state) => LifecycleSnapshot::Cold {
                generation: state.generation(),
            },
            Self::Starting(state) => LifecycleSnapshot::Starting {
                generation: state.generation(),
            },
            Self::Ready(state) => LifecycleSnapshot::Ready {
                generation: state.generation(),
            },
            Self::Recovering(state) => LifecycleSnapshot::Recovering {
                generation: state.generation(),
                last_fault: state.last_fault().clone(),
            },
        }
    }

    /// Enters startup from cold or recovering.
    pub fn begin_startup(self) -> Result<Self, InvariantViolation> {
        match self {
            Self::Cold(state) => Ok(Self::Starting(state.ignite())),
            Self::Recovering(state) => Ok(Self::Starting(state.respawn())),
            Self::Starting(_) | Self::Ready(_) => Err(InvariantViolation::new(
                "invalid lifecycle transition to starting",
            )),
        }
    }

    /// Marks startup as complete.
    pub fn complete_startup(self) -> Result<Self, InvariantViolation> {
        match self {
            Self::Starting(state) => Ok(Self::Ready(state.arm())),
            _ => Err(InvariantViolation::new(
                "invalid lifecycle transition to ready",
            )),
        }
    }

    /// Records a fault and enters recovering state.
    pub fn fracture(self, fault: Fault) -> Result<Self, InvariantViolation> {
        match self {
            Self::Starting(state) => Ok(Self::Recovering(state.fracture(fault))),
            Self::Ready(state) => Ok(Self::Recovering(state.fracture(fault))),
            Self::Recovering(state) => Ok(Self::Recovering(Lifecycle {
                generation: state.generation(),
                state: Recovering::new(fault),
            })),
            Self::Cold(_) => Err(InvariantViolation::new("cannot fracture cold lifecycle")),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{DynamicLifecycle, Lifecycle, LifecycleSnapshot};
    use crate::fault::{Fault, FaultClass, FaultCode, FaultDetail};

    #[test]
    fn typestate_chain_advances_generation_on_recovery() {
        let cold = Lifecycle::cold();
        let starting = cold.ignite();
        let ready = starting.arm();
        let ready_generation = ready.generation();
        let fault = Fault::new(
            ready_generation,
            FaultClass::Transport,
            FaultCode::BrokenPipe,
            FaultDetail::new("broken pipe"),
        );
        let recovering = ready.fracture(fault);
        let restarted = recovering.respawn();
        assert!(restarted.generation() > ready_generation);
    }

    #[test]
    fn dynamic_snapshot_of_recovering_is_infallible() {
        let cold = DynamicLifecycle::cold();
        assert!(matches!(cold.snapshot(), LifecycleSnapshot::Cold { .. }));
    }
}