1use serde::Serialize;
2use std::fmt;
3
4pub const CLEANUP_TIMEOUT_MS: u64 = 30_000;
5pub const LOCK_TIMEOUT_MS: u64 = 10_000;
6
7pub struct TerminalSignals {
8 #[cfg(unix)]
9 interrupt: tokio::signal::unix::Signal,
10 #[cfg(unix)]
11 terminate: tokio::signal::unix::Signal,
12 #[cfg(unix)]
13 hangup: tokio::signal::unix::Signal,
14}
15
16impl TerminalSignals {
17 pub fn new() -> std::io::Result<Self> {
18 Ok(Self {
19 #[cfg(unix)]
20 interrupt: tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())?,
21 #[cfg(unix)]
22 terminate: tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?,
23 #[cfg(unix)]
24 hangup: tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())?,
25 })
26 }
27
28 pub async fn recv(&mut self) -> std::io::Result<u8> {
29 #[cfg(unix)]
30 {
31 let (received, code) = tokio::select! {
32 received = self.interrupt.recv() => (received, 130),
33 received = self.terminate.recv() => (received, 143),
34 received = self.hangup.recv() => (received, 129),
35 };
36 received.ok_or_else(|| std::io::Error::other("terminal signal stream ended"))?;
37 Ok(code)
38 }
39 #[cfg(not(unix))]
40 {
41 tokio::signal::ctrl_c().await?;
42 Ok(130)
43 }
44 }
45}
46
47pub fn exit_code_for_signal(signal: Option<&str>) -> Option<u8> {
48 match signal {
49 Some("SIGHUP") => Some(129),
50 Some("SIGINT") => Some(130),
51 Some("SIGTERM") => Some(143),
52 _ => None,
53 }
54}
55#[derive(Debug, Clone, Copy, Serialize)]
56#[serde(rename_all = "snake_case")]
57pub enum Effect {
58 Unchanged,
59 ArtifactCachedStateUnchanged,
60 SpawnedProcessCleaned,
61 PriorServerStoppedReplacementNotStarted,
62 StateRollbackAttempted,
63 StateCommitted,
64 TargetCommittedSourceRetained,
65 FullyCompleted,
66}
67impl fmt::Display for Effect {
68 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
69 formatter.write_str(match self {
70 Self::Unchanged => "unchanged",
71 Self::ArtifactCachedStateUnchanged => "artifact_cached_state_unchanged",
72 Self::SpawnedProcessCleaned => "spawned_process_cleaned",
73 Self::PriorServerStoppedReplacementNotStarted => {
74 "prior_server_stopped_replacement_not_started"
75 }
76 Self::StateRollbackAttempted => "state_rollback_attempted",
77 Self::StateCommitted => "state_committed",
78 Self::TargetCommittedSourceRetained => "target_committed_source_retained",
79 Self::FullyCompleted => "fully_completed",
80 })
81 }
82}
83#[derive(Debug, Serialize)]
84#[serde(tag = "type", rename_all = "lowercase")]
85pub enum Termination<'phase> {
86 Success {
87 phase: &'phase str,
88 effect: Effect,
89 },
90 Cancelled {
91 phase: &'phase str,
92 effect: Effect,
93 },
94 Partial {
95 phase: &'phase str,
96 effect: Effect,
97 remediation: String,
98 },
99 Failed {
100 phase: &'phase str,
101 effect: Effect,
102 code: String,
103 },
104}
105impl fmt::Display for Termination<'_> {
106 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
107 match self {
108 Self::Success { phase, .. } => {
109 write!(formatter, "Completed successfully at phase: {phase}")
110 }
111 Self::Cancelled { phase, effect } => {
112 write!(formatter, "Cancelled at phase: {phase} (effect: {effect})")
113 }
114 Self::Partial {
115 phase, remediation, ..
116 } => write!(
117 formatter,
118 "Partial completion at phase: {phase} \u{2014} {remediation}"
119 ),
120 Self::Failed {
121 phase,
122 effect,
123 code,
124 } => write!(
125 formatter,
126 "Failed at phase: {phase} ({code}; effect: {effect})"
127 ),
128 }
129 }
130}
131pub fn remediation_prior_stopped(model: &str) -> String {
132 format!(
133 "The prior server was stopped but its replacement failed to start. Run `rigspark up {model}` to restore service."
134 )
135}
136pub fn remediation_rollback(model: &str) -> String {
137 format!(
138 "State was cleared but stopping {model} failed; state was restored. Inspect the process manually or retry `rigspark down`."
139 )
140}
141pub fn remediation_source_retained() -> &'static str {
142 "Migration target is valid; source was retained. Re-run `rigspark migrate --move` to complete source deletion."
143}
144pub fn classify_up(phase: &str, prior_stopped: bool, spawned: bool) -> Termination<'_> {
145 if phase == "state-commit" {
146 return Termination::Success {
147 phase,
148 effect: Effect::StateCommitted,
149 };
150 }
151 if prior_stopped && !spawned {
152 return Termination::Partial {
153 phase,
154 effect: Effect::PriorServerStoppedReplacementNotStarted,
155 remediation: remediation_prior_stopped("the target model"),
156 };
157 }
158 let effect = if spawned {
159 Effect::SpawnedProcessCleaned
160 } else if ["acquire", "verify"].contains(&phase) {
161 Effect::ArtifactCachedStateUnchanged
162 } else {
163 Effect::Unchanged
164 };
165 Termination::Cancelled { phase, effect }
166}
167pub fn classify_down(phase: &str, rollback: bool) -> Termination<'_> {
168 if rollback {
169 return Termination::Partial {
170 phase,
171 effect: Effect::StateRollbackAttempted,
172 remediation: remediation_rollback("the active model"),
173 };
174 }
175 if phase == "stop-detach" {
176 Termination::Success {
177 phase,
178 effect: Effect::StateCommitted,
179 }
180 } else {
181 Termination::Cancelled {
182 phase,
183 effect: Effect::Unchanged,
184 }
185 }
186}
187pub fn classify_switch(phase: &str) -> Termination<'_> {
188 if phase == "state-commit" {
189 return Termination::Success {
190 phase,
191 effect: Effect::StateCommitted,
192 };
193 }
194 let effect = if ["prepare", "readiness"].contains(&phase) {
195 Effect::ArtifactCachedStateUnchanged
196 } else {
197 Effect::Unchanged
198 };
199 Termination::Cancelled { phase, effect }
200}