1use std::path::{Path, PathBuf};
8use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
9use std::sync::{Arc, Mutex, mpsc};
10
11use serde_json::{Value, json};
12use speccoder_core::actions::{Runnable, Via};
13use speccoder_core::{CommandResult, CommandStatus};
14use speccoder_runtime::service::approvals::{Answer, Approver, Presentation, Who};
15use speccoder_runtime::service::progress::{Event, Progress};
16use tokio::sync::broadcast;
17
18#[derive(Debug)]
20pub enum Reply {
21 Answer(Answer),
23 Text(Option<String>),
25}
26
27#[derive(Debug)]
28struct Waiting {
29 id: u64,
30 reply: mpsc::Sender<Reply>,
31 event: Value,
32}
33
34#[derive(Debug, Clone, serde::Serialize)]
36pub struct JobView {
37 pub id: u64,
39 pub command: String,
41 pub running: bool,
43 pub result: Option<Value>,
45}
46
47#[derive(Debug)]
49pub struct Hub {
50 root: crate::Root,
51 events: broadcast::Sender<String>,
52 next: AtomicU64,
53 job: Mutex<Option<JobView>>,
54 waiting: Mutex<Option<Waiting>>,
55 cancel: Mutex<Option<Arc<AtomicBool>>>,
56}
57
58impl Hub {
59 #[must_use]
61 pub fn new(root: crate::Root) -> Arc<Self> {
62 let (events, _) = broadcast::channel(1024);
63 Arc::new(Self {
64 root,
65 events,
66 next: AtomicU64::new(1),
67 job: Mutex::new(None),
68 waiting: Mutex::new(None),
69 cancel: Mutex::new(None),
70 })
71 }
72
73 #[must_use]
75 pub fn subscribe(&self) -> broadcast::Receiver<String> {
76 self.events.subscribe()
77 }
78
79 fn send(&self, v: &Value) {
80 let _ = self.events.send(v.to_string());
81 }
82
83 #[must_use]
85 pub fn job(&self) -> Option<JobView> {
86 self.job.lock().ok().and_then(|j| j.clone())
87 }
88
89 #[must_use]
91 pub fn waiting(&self) -> Option<Value> {
92 self.waiting
93 .lock()
94 .ok()
95 .and_then(|w| w.as_ref().map(|w| w.event.clone()))
96 }
97
98 pub fn answer(&self, id: u64, reply: Reply) -> Result<(), String> {
100 let w = self
101 .waiting
102 .lock()
103 .map_err(|_| "the host is broken".to_owned())?
104 .take();
105 match w {
106 Some(w) if w.id == id => {
107 let _ = w.reply.send(reply);
108 self.send(&json!({ "type": "answered", "id": id }));
109 Ok(())
110 }
111 Some(w) => {
112 let other = w.id;
113 if let Ok(mut slot) = self.waiting.lock() {
114 *slot = Some(w);
115 }
116 Err(format!("{other} waits, not {id}"))
117 }
118 None => Err("nothing waits for an answer".to_owned()),
119 }
120 }
121
122 pub fn stop(&self) {
125 if let Some(c) = self.cancel.lock().ok().and_then(|c| c.clone()) {
126 c.store(true, Ordering::SeqCst);
127 }
128 let who = Who::local_in(&self.root.get(), Via::Web);
129 if let Some(w) = self.waiting.lock().ok().and_then(|mut w| w.take()) {
130 let _ = w.reply.send(match w.event["type"].as_str() {
131 Some("question") => Reply::Text(None),
132 _ => Reply::Answer(Answer::stop(Some(who))),
133 });
134 }
135 self.send(&json!({ "type": "stopping" }));
136 }
137
138 fn wait_for(&self, mut event: Value) -> Option<Reply> {
139 let id = self.next.fetch_add(1, Ordering::SeqCst);
140 event["id"] = json!(id);
141 let (tx, rx) = mpsc::channel();
142 if let Ok(mut w) = self.waiting.lock() {
143 *w = Some(Waiting {
144 id,
145 reply: tx,
146 event: event.clone(),
147 });
148 }
149 self.send(&event);
150 rx.recv().ok()
151 }
152
153 pub fn exclusive<T>(&self, f: impl FnOnce() -> T) -> Result<T, String> {
160 let job = self
161 .job
162 .lock()
163 .map_err(|_| "the host is broken".to_owned())?;
164 if job.as_ref().is_some_and(|j| j.running) {
165 return Err("a job is working; do this when it ends".to_owned());
166 }
167 let out = f();
168 drop(job);
169 Ok(out)
170 }
171
172 pub fn start(
176 self: &Arc<Self>,
177 run: Runnable,
178 input: Option<String>,
179 feature: Option<String>,
180 command: String,
181 root: PathBuf,
182 ) -> Result<u64, String> {
183 let id = self.next.fetch_add(1, Ordering::SeqCst);
184 {
185 let mut job = self
186 .job
187 .lock()
188 .map_err(|_| "the host is broken".to_owned())?;
189 if job.as_ref().is_some_and(|j| j.running) {
190 return Err("a job is working; stop it or wait for it".to_owned());
191 }
192 *job = Some(JobView {
193 id,
194 command: command.clone(),
195 running: true,
196 result: None,
197 });
198 }
199 let cancel = Arc::new(AtomicBool::new(false));
200 if let Ok(mut c) = self.cancel.lock() {
201 *c = Some(Arc::clone(&cancel));
202 }
203 self.send(&json!({ "type": "started", "id": id, "command": command }));
204 let hub = Arc::clone(self);
205 std::thread::spawn(move || {
206 let peer: Arc<Peer> = Arc::new(Peer {
207 hub: Arc::clone(&hub),
208 who: Who::local_in(&root, Via::Web),
209 });
210 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
211 execute(
212 &root,
213 feature.as_deref(),
214 &run,
215 input.as_deref(),
216 &peer,
217 cancel,
218 )
219 }))
220 .unwrap_or_else(|_| {
221 CommandResult::new("job", CommandStatus::Error, "the job stopped unexpectedly")
222 });
223 let result = speccoder_runtime::service::next::attach(result, feature.as_deref());
224 if let Some(bound) = crate::welcome::bind_after(&hub.root, &run, &result) {
227 hub.send(&json!({ "type": "bound", "root": bound.display().to_string() }));
228 }
229 let value = serde_json::to_value(&result).unwrap_or(Value::Null);
230 if let Ok(mut job) = hub.job.lock()
231 && let Some(j) = job.as_mut()
232 {
233 j.running = false;
234 j.result = Some(value.clone());
235 }
236 if let Ok(mut c) = hub.cancel.lock() {
237 *c = None;
238 }
239 hub.send(&json!({ "type": "done", "id": id, "result": value }));
240 });
241 Ok(id)
242 }
243}
244
245#[derive(Debug)]
247struct Peer {
248 hub: Arc<Hub>,
249 who: Who,
250}
251
252impl Progress for Peer {
253 fn event(&self, event: &Event) {
254 self.hub
255 .send(&json!({ "type": "progress", "event": event }));
256 }
257}
258
259impl Approver for Peer {
260 fn ask(&self, p: &Presentation) -> Answer {
261 match self
262 .hub
263 .wait_for(json!({ "type": "ask", "presentation": p }))
264 {
265 Some(Reply::Answer(mut a)) => {
266 a.by = Some(self.who.clone());
267 a
268 }
269 _ => Answer::stop(Some(self.who.clone())),
270 }
271 }
272
273 fn answer(&self, question: &str) -> Option<String> {
274 match self
275 .hub
276 .wait_for(json!({ "type": "question", "question": question }))
277 {
278 Some(Reply::Text(t)) => t,
279 _ => None,
280 }
281 }
282
283 fn via(&self) -> Via {
284 Via::Web
285 }
286}
287
288fn execute(
289 root: &Path,
290 feature: Option<&str>,
291 run: &Runnable,
292 input: Option<&str>,
293 peer: &Arc<Peer>,
294 cancel: Arc<AtomicBool>,
295) -> CommandResult {
296 use speccoder_runtime::service::actions::{Dispatch, Interface, Offer, offered, perform};
297 if offered(Interface::WebJobs, run.kind()) == Offer::Refuse {
298 return Interface::WebJobs.refusal();
299 }
300 let options = speccoder_runtime::service::RunOptions {
301 approver: Some(Arc::clone(peer) as Arc<dyn Approver>),
302 progress: Some(Arc::clone(peer) as Arc<dyn Progress>),
303 cancel: Some(cancel),
304 ..speccoder_runtime::service::RunOptions::default()
305 };
306 perform(
307 root,
308 feature,
309 Dispatch {
310 run,
311 input,
312 via: Via::Web,
313 options,
314 },
315 )
316}