ifc_lite_geometry_runtime/
supervision.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Bounded native execution with cancellation independent of blocking IPC.
3//! Limits bound queue depth and elapsed time. They do not impose process RAM
4//! limits; deployment OS job/cgroup limits are a separate responsibility.
5use crate::protocol::BooleanOperation;
6use crate::{BrepHandle, MeshLimits, SmlibWorker, TessellatedMesh, WorkerError};
7use std::ffi::OsString;
8use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
9use std::sync::{mpsc, Arc, Mutex};
10use std::thread::JoinHandle;
11use std::time::{Duration, Instant};
12
13mod controller;
14mod delivery;
15use delivery::{Claim, Envelope};
16
17/// Owned operations only: callers cannot run arbitrary code on the IO thread.
18#[derive(Debug, Clone)]
19pub enum WorkerCommand {
20    Incarnation,
21    CreateBox {
22        origin: [f64; 3],
23        size: [f64; 3],
24    },
25    CreateCylinder {
26        origin: [f64; 3],
27        radius: f64,
28        height: f64,
29    },
30    Boolean {
31        left: BrepHandle,
32        right: BrepHandle,
33        operation: BooleanOperation,
34    },
35    Volume {
36        solid: BrepHandle,
37        relative_accuracy: f64,
38    },
39    IsManifold {
40        solid: BrepHandle,
41    },
42    Release {
43        solid: BrepHandle,
44    },
45    Tessellate {
46        solid: BrepHandle,
47        chord_metres: f64,
48        angle_degrees: f64,
49        limits: MeshLimits,
50    },
51}
52
53#[derive(Debug)]
54pub enum WorkerResult {
55    Incarnation(u64),
56    Solid(BrepHandle),
57    Volume(f64),
58    Manifold(bool),
59    Released,
60    Mesh(TessellatedMesh),
61}
62
63#[derive(Debug)]
64pub enum SupervisionError {
65    Worker(WorkerError),
66    Deadline,
67    Cancelled,
68    QueueFull,
69    Stopped,
70    TransportPanicked,
71}
72
73impl std::fmt::Display for SupervisionError {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        match self {
76            Self::Worker(error) => error.fmt(f),
77            Self::Deadline => write!(f, "geometry worker deadline exceeded"),
78            Self::Cancelled => write!(f, "geometry worker command cancelled"),
79            Self::QueueFull => write!(f, "geometry worker queue is full"),
80            Self::Stopped => write!(f, "geometry worker supervisor stopped"),
81            Self::TransportPanicked => write!(f, "geometry worker transport panicked"),
82        }
83    }
84}
85impl std::error::Error for SupervisionError {}
86
87struct Admission(Arc<AtomicUsize>);
88impl Drop for Admission {
89    fn drop(&mut self) {
90        self.0.fetch_sub(1, Ordering::AcqRel);
91    }
92}
93
94struct Request {
95    _admission: Admission,
96    command: WorkerCommand,
97    deadline: Instant,
98    claim: Arc<Claim>,
99    response: mpsc::Sender<Envelope>,
100}
101
102/// Cancelling or dropping a pending request retires an executing session. Its
103/// completion is sent only after the process has been killed and reaped.
104pub struct PendingCommand {
105    claim: Arc<Claim>,
106    response: mpsc::Receiver<Envelope>,
107}
108impl PendingCommand {
109    pub fn cancel(&self) {
110        self.claim.cancel();
111    }
112
113    pub fn wait(self) -> Result<WorkerResult, SupervisionError> {
114        let envelope = self
115            .response
116            .recv()
117            .map_err(|_| SupervisionError::Stopped)?;
118        envelope.claim(&self.claim)
119    }
120}
121impl Drop for PendingCommand {
122    fn drop(&mut self) {
123        self.cancel();
124    }
125}
126
127/// One active process plus at most `queue_capacity` waiting owned commands.
128/// Deadlines include queue wait and session startup. Restart is lazy after a
129/// transport failure, timeout or cancellation; all previous handles are stale.
130/// Drop cancels work, kills/reaps the owned process and joins transport threads.
131pub struct SupervisedWorker {
132    sender: Option<mpsc::SyncSender<Request>>,
133    admitted: Arc<AtomicUsize>,
134    capacity: usize,
135    stopping: Arc<AtomicBool>,
136    process_id: Arc<Mutex<Option<crate::process_control::ProcessControl>>>,
137    controller: Option<JoinHandle<()>>,
138}
139impl SupervisedWorker {
140    pub fn new(executable: impl Into<OsString>, queue_capacity: usize) -> std::io::Result<Self> {
141        let capacity = queue_capacity.checked_add(1).ok_or_else(|| {
142            std::io::Error::new(std::io::ErrorKind::InvalidInput, "queue capacity overflow")
143        })?;
144        let (sender, receiver) = mpsc::sync_channel(capacity);
145        let admitted = Arc::new(AtomicUsize::new(0));
146        let stopping = Arc::new(AtomicBool::new(false));
147        let process_id = Arc::new(Mutex::new(None));
148        let stop = Arc::clone(&stopping);
149        let pid = Arc::clone(&process_id);
150        let executable = executable.into();
151        let controller = std::thread::Builder::new()
152            .name("smlib-supervisor".into())
153            .spawn(move || controller::run(executable, receiver, stop, pid))?;
154        Ok(Self {
155            sender: Some(sender),
156            admitted,
157            capacity,
158            stopping,
159            process_id,
160            controller: Some(controller),
161        })
162    }
163
164    /// Nonblocking admission provides backpressure instead of growing a queue.
165    pub fn submit(
166        &self,
167        command: WorkerCommand,
168        timeout: Duration,
169    ) -> Result<PendingCommand, SupervisionError> {
170        let deadline = Instant::now()
171            .checked_add(timeout)
172            .ok_or(SupervisionError::Deadline)?;
173        self.admitted
174            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |count| {
175                (count < self.capacity).then_some(count + 1)
176            })
177            .map_err(|_| SupervisionError::QueueFull)?;
178        let admission = Admission(Arc::clone(&self.admitted));
179        let claim = Arc::new(Claim::new(deadline));
180        let (response, receiver) = mpsc::channel();
181        let request = Request {
182            _admission: admission,
183            command,
184            deadline,
185            claim: Arc::clone(&claim),
186            response,
187        };
188        self.sender
189            .as_ref()
190            .ok_or(SupervisionError::Stopped)?
191            .try_send(request)
192            .map_err(|error| match error {
193                mpsc::TrySendError::Full(_) => SupervisionError::QueueFull,
194                mpsc::TrySendError::Disconnected(_) => SupervisionError::Stopped,
195            })?;
196        Ok(PendingCommand {
197            claim,
198            response: receiver,
199        })
200    }
201
202    /// Diagnostic identity only. Cancellation uses the owned Child, never a PID.
203    pub fn process_id(&self) -> Option<u32> {
204        self.process_id
205            .lock()
206            .unwrap_or_else(|e| e.into_inner())
207            .as_ref()
208            .filter(|control| control.is_live())
209            .map(|control| control.id())
210    }
211}
212impl Drop for SupervisedWorker {
213    fn drop(&mut self) {
214        self.stopping.store(true, Ordering::Release);
215        self.sender.take();
216        if let Some(controller) = self.controller.take() {
217            if controller.join().is_err() {
218                eprintln!("geometry worker controller panicked");
219            }
220        }
221    }
222}
223
224fn execute(worker: &mut SmlibWorker, command: WorkerCommand) -> Result<WorkerResult, WorkerError> {
225    worker.initialize()?;
226    match command {
227        WorkerCommand::Incarnation => match worker.incarnation() {
228            0 => Err(WorkerError::Protocol(
229                "worker exited before identity publication",
230            )),
231            identity => Ok(WorkerResult::Incarnation(identity)),
232        },
233        WorkerCommand::CreateBox { origin, size } => {
234            worker.create_box(origin, size).map(WorkerResult::Solid)
235        }
236        WorkerCommand::CreateCylinder {
237            origin,
238            radius,
239            height,
240        } => worker
241            .create_cylinder(origin, radius, height)
242            .map(WorkerResult::Solid),
243        WorkerCommand::Boolean {
244            left,
245            right,
246            operation,
247        } => worker
248            .boolean(left, right, operation)
249            .map(WorkerResult::Solid),
250        WorkerCommand::Volume {
251            solid,
252            relative_accuracy,
253        } => worker
254            .volume(solid, relative_accuracy)
255            .map(WorkerResult::Volume),
256        WorkerCommand::IsManifold { solid } => {
257            worker.is_manifold(solid).map(WorkerResult::Manifold)
258        }
259        WorkerCommand::Release { solid } => worker.release(solid).map(|()| WorkerResult::Released),
260        WorkerCommand::Tessellate {
261            solid,
262            chord_metres,
263            angle_degrees,
264            limits,
265        } => worker
266            .tessellate(solid, chord_metres, angle_degrees, limits)
267            .map(WorkerResult::Mesh),
268    }
269}