1use serde::{Deserialize, Serialize};
22use serde_json::{Value, json};
23
24use super::HiveError;
25use super::convert::ConvertApi;
26
27pub const MAX_SPLIT_CHILDREN: usize = 50;
29
30pub fn eligible(goal: &Value, worker_id: &str) -> bool {
32 ["conductor_workers", "delegates"].iter().any(|list| {
33 goal["swarm"][list]
34 .as_array()
35 .is_some_and(|ids| ids.iter().any(|id| id.as_str() == Some(worker_id)))
36 })
37}
38
39#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
41pub struct Lease {
42 pub epoch: u64,
43 pub expires_at: u64,
44 pub holder: Holder,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
48pub struct Holder {
49 pub worker_id: String,
50 pub name: String,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct Child {
56 pub title: String,
57 pub text: String,
58 pub acceptance: Vec<String>,
59 pub kind: String,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
66pub enum Action {
67 Split {
68 parent: String,
69 children: Vec<Child>,
70 },
71 Assign {
72 goal: String,
73 assignee: String,
74 },
75 Synthesize {
76 parent: String,
77 title: String,
78 },
79 Block {
80 goal: String,
81 reason: String,
82 },
83 Unblock {
84 goal: String,
85 },
86 Drop {
87 goal: String,
88 reason: String,
89 },
90 Reopen {
91 goal: String,
92 reason: String,
93 },
94 Edit {
95 goal: String,
96 #[serde(skip_serializing_if = "Option::is_none")]
97 title: Option<String>,
98 #[serde(skip_serializing_if = "Option::is_none")]
99 text: Option<String>,
100 #[serde(skip_serializing_if = "Option::is_none")]
101 acceptance: Option<Vec<String>>,
102 },
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
107pub enum Refusal {
108 NotConductor,
110 WorkerNotOwned,
112 Busy { holder: Option<String> },
114 StaleEpoch,
116 Other { status: u16, code: String },
118}
119
120impl Refusal {
121 pub fn code(&self) -> &str {
122 match self {
123 Self::NotConductor => "not_conductor",
124 Self::WorkerNotOwned => "worker_not_owned",
125 Self::Busy { .. } => "conductor_busy",
126 Self::StaleEpoch => "stale_epoch",
127 Self::Other { code, .. } => code,
128 }
129 }
130
131 fn of(status: u16, body: &Value) -> Self {
132 let e = &body["error"];
133 let reason = e["reason"].as_str().unwrap_or_default();
134 let code = e["code"].as_str().unwrap_or_default();
135 match (status, code, reason) {
136 (403, _, "not_conductor") => Self::NotConductor,
137 (403, _, "worker_not_owned") => Self::WorkerNotOwned,
138 (409, _, "conductor_busy") => Self::Busy {
139 holder: e["holder"]["worker_id"].as_str().map(str::to_string),
140 },
141 (409, "stale_epoch", _) => Self::StaleEpoch,
142 _ => Self::Other {
143 status,
144 code: if reason.is_empty() { code } else { reason }.to_string(),
145 },
146 }
147 }
148}
149
150impl From<Refusal> for HiveError {
151 fn from(r: Refusal) -> Self {
152 HiveError::Refused(format!("conductor: {}", r.code()))
153 }
154}
155
156pub struct Conductor<'a> {
158 pub api: &'a dyn ConvertApi,
159 pub swarm_id: &'a str,
160 pub worker_id: &'a str,
161 pub eligible: bool,
163}
164
165fn ok_or(status: u16, body: Value) -> Result<Value, Result<Refusal, HiveError>> {
166 if (200..300).contains(&status) {
167 Ok(body)
168 } else {
169 Err(Ok(Refusal::of(status, &body)))
170 }
171}
172
173pub type Answer<T> = Result<T, Result<Refusal, HiveError>>;
176
177impl Conductor<'_> {
178 fn gate(&self) -> Answer<()> {
179 if self.eligible {
180 Ok(())
181 } else {
182 Err(Ok(Refusal::NotConductor))
184 }
185 }
186
187 fn base(&self) -> String {
188 format!("/swarms/{}/conductor", self.swarm_id)
189 }
190
191 fn lease_from(body: Value) -> Answer<Lease> {
192 serde_json::from_value(body)
193 .map_err(|e| Err(HiveError::Protocol(format!("conductor lease: {e}"))))
194 }
195
196 pub fn acquire(&self) -> Answer<Lease> {
198 self.gate()?;
199 let (status, body) = self
200 .api
201 .answer(
202 "POST",
203 &format!("{}/lease", self.base()),
204 Some(&json!({ "worker_id": self.worker_id })),
205 )
206 .map_err(Err)?;
207 Self::lease_from(ok_or(status, body)?)
208 }
209
210 pub fn renew(&self, epoch: u64) -> Answer<Lease> {
212 self.gate()?;
213 let (status, body) = self
214 .api
215 .answer(
216 "POST",
217 &format!("{}/lease/renew", self.base()),
218 Some(&json!({ "worker_id": self.worker_id, "epoch": epoch })),
219 )
220 .map_err(Err)?;
221 Self::lease_from(ok_or(status, body)?)
222 }
223
224 pub fn release(&self, epoch: u64) -> Answer<()> {
226 self.gate()?;
227 let (status, body) = self
228 .api
229 .answer(
230 "DELETE",
231 &format!(
232 "{}/lease?epoch={epoch}&worker_id={}",
233 self.base(),
234 self.worker_id
235 ),
236 None,
237 )
238 .map_err(Err)?;
239 ok_or(status, body).map(|_| ())
240 }
241
242 pub fn action_body(&self, epoch: u64, action: &Action) -> Result<Value, HiveError> {
244 if let Action::Split { children, .. } = action
245 && !(1..=MAX_SPLIT_CHILDREN).contains(&children.len())
246 {
247 return Err(HiveError::Config(format!(
248 "a split has 1 to {MAX_SPLIT_CHILDREN} children"
249 )));
250 }
251 let mut body = serde_json::to_value(action).map_err(|e| HiveError::Local(e.to_string()))?;
252 body["worker_id"] = self.worker_id.into();
253 body["epoch"] = epoch.into();
254 Ok(body)
255 }
256
257 pub fn act(&self, epoch: u64, action: &Action) -> Answer<Value> {
260 self.gate()?;
261 let body = self.action_body(epoch, action).map_err(Err)?;
262 let (status, answer) = self
263 .api
264 .answer("POST", &format!("{}/actions", self.base()), Some(&body))
265 .map_err(Err)?;
266 ok_or(status, answer)
267 }
268}
269
270pub fn cli(
275 session: &crate::core::hive::auth::Session,
276 args: &[String],
277) -> Result<String, HiveError> {
278 let usage = || {
279 HiveError::Config(
280 "usage: lean-ctx hive swarm plan <swarm> --worker <wkr_…> lease | renew <epoch> | release <epoch> | act <epoch> --action '<json>'"
281 .into(),
282 )
283 };
284 let mut positional = Vec::new();
285 let (mut worker, mut action) = (None, None);
286 let mut it = args.iter();
287 while let Some(a) = it.next() {
288 match a.as_str() {
289 "--worker" => worker = it.next().cloned(),
290 "--action" => action = it.next().cloned(),
291 _ => positional.push(a.clone()),
292 }
293 }
294 let (Some(swarm), Some(worker)) = (positional.first(), worker) else {
295 return Err(usage());
296 };
297 let epoch = |i: usize| -> Result<u64, HiveError> {
298 positional
299 .get(i)
300 .and_then(|e| e.parse().ok())
301 .ok_or_else(usage)
302 };
303 let goal =
304 session.with_client(|c| c.get(&format!("/swarms/{swarm}/goal?worker_id={worker}")))?;
305 let c = Conductor {
306 api: session,
307 swarm_id: swarm,
308 worker_id: &worker,
309 eligible: eligible(&goal, &worker),
310 };
311 let flat = |r: Result<Refusal, HiveError>| match r {
312 Ok(refusal) => HiveError::from(refusal),
313 Err(e) => e,
314 };
315 match positional.get(1).map(String::as_str) {
316 Some("lease") => {
317 let l = c.acquire().map_err(flat)?;
318 Ok(format!(
319 "Conductor lease epoch {} until {} (renew within 5 min)",
320 l.epoch, l.expires_at
321 ))
322 }
323 Some("renew") => {
324 let l = c.renew(epoch(2)?).map_err(flat)?;
325 Ok(format!(
326 "Conductor lease epoch {} until {}",
327 l.epoch, l.expires_at
328 ))
329 }
330 Some("release") => {
331 c.release(epoch(2)?).map_err(flat)?;
332 Ok("Conductor lease released".into())
333 }
334 Some("act") => {
335 let action: Action = serde_json::from_str(action.as_deref().ok_or_else(usage)?)
336 .map_err(|e| HiveError::Config(format!("--action: {e}")))?;
337 let answer = c.act(epoch(2)?, &action).map_err(flat)?;
338 Ok(format!(
339 "Done: {} goal node(s) changed, swarm log seq(s) {}",
340 answer["nodes"].as_array().map_or(0, Vec::len),
341 answer["seqs"]
342 ))
343 }
344 _ => Err(usage()),
345 }
346}
347
348#[cfg(test)]
349#[path = "conductor_tests.rs"]
350mod tests;