ifc_lite_geometry_runtime/
worker.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Versioned IPC with the single-threaded owned-handle SMLib adapter.
3
4use crate::process_control::ProcessControl;
5use crate::protocol::{self, BooleanOperation, KernelCommand, KernelResponse, WireHandle, VERSION};
6use std::collections::HashMap;
7use std::ffi::OsStr;
8use std::io::{Read, Write};
9use std::process::{ChildStdin, ChildStdout, Command, Stdio};
10use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
11use std::sync::{Arc, Weak};
12
13#[path = "worker_error.rs"]
14mod error;
15pub use error::WorkerError;
16#[path = "worker_mesh.rs"]
17mod mesh;
18pub use mesh::{MeshLimits, TessellatedMesh};
19#[path = "worker_empty.rs"]
20mod empty;
21pub use empty::NumericalOutcome;
22#[path = "worker_handles.rs"]
23mod handles;
24#[path = "worker_upload.rs"]
25mod upload;
26#[path = "worker_qualification.rs"]
27mod qualification;
28pub use qualification::RegionQualificationReport;
29#[path = "worker_disk_qualification.rs"]
30mod disk_qualification;
31#[path = "worker_face_set_qualification.rs"]
32mod face_set_qualification;
33#[path = "worker_sweep.rs"]
34mod sweep;
35pub use sweep::RetainedRealization;
36#[cfg(feature = "retained-runtime")]
37pub use sweep::RetainedSourceFaceSet;
38#[path = "worker_objects.rs"]
39mod objects;
40#[path = "worker_dependencies.rs"]
41mod dependencies;
42pub use dependencies::{ RetainedDependency, RetainedDependencyResult, RetainedLineage};
43#[path = "worker_affine.rs"]
44mod affine;
45pub use affine::{AffineCertificate, AffineCopyIdentity, RetainedAffineCopy, RetainedTransformInput};
46
47static NEXT_WORKER: AtomicU64 = AtomicU64::new(1);
48
49/// Opaque BRep identity. Worker identity is host-local and never sent over IPC.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub struct BrepHandle {
52    worker: u64,
53    wire: WireHandle,
54}
55
56/// Owns one isolated serial SMLib process and session. A mutable receiver
57/// serializes requests; handles are rejected across workers even if their wire
58/// session IDs happen to coincide. Dropping the client kills/reaps its process.
59///
60/// Operations block. Use `SupervisedWorker` for bounded deadlines, cancellation
61/// and restart. This low-level client remains useful for serial tools.
62pub struct SmlibWorker {
63    process: ProcessControl,
64    input: ChildStdin,
65    output: ChildStdout,
66    identity: u64,
67    session: u64,
68    sequence: u32,
69    healthy: bool,
70    /// Same-incarnation numerical witnesses; never set by capability bits.
71    regions_qualified: bool,
72    disks_qualified: bool,
73    face_sets_qualified: bool,
74    /// Live objects; each flag is shared with the receipts that name it and
75    /// cleared before the object is released.
76    objects: HashMap<WireHandle, Arc<AtomicBool>>,
77    /// Managed objects whose final receipt was dropped, released before the
78    /// next command by this exact worker.
79    releases: Arc<objects::ReleaseQueue>,
80    /// One shared lease per managed object.
81    managed: HashMap<WireHandle, Weak<objects::ManagedObjectLease>>,
82}
83
84impl SmlibWorker {
85    pub fn spawn(executable: impl AsRef<OsStr>) -> Result<Self, WorkerError> {
86        let mut worker = Self::spawn_uninitialized(executable)?;
87        worker.initialize()?;
88        Ok(worker)
89    }
90
91    pub(crate) fn spawn_uninitialized(executable: impl AsRef<OsStr>) -> Result<Self, WorkerError> {
92        let identity = NEXT_WORKER
93            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
94                value.checked_add(1)
95            })
96            .map_err(|_| WorkerError::Protocol("worker IDs exhausted"))?;
97        let mut child = Command::new(executable)
98            .stdin(Stdio::piped())
99            .stdout(Stdio::piped())
100            .stderr(Stdio::inherit())
101            .spawn()?;
102        // Piped handles are guaranteed by the std::process configuration above.
103        let input = child.stdin.take().expect("piped worker stdin");
104        let output = child.stdout.take().expect("piped worker stdout");
105        Ok(Self {
106            process: ProcessControl::new(child),
107            input,
108            output,
109            identity,
110            session: 0,
111            sequence: 0,
112            healthy: true,
113            regions_qualified: false,
114            disks_qualified: false,
115            face_sets_qualified: false,
116            objects: HashMap::new(),
117            releases: Arc::new(objects::ReleaseQueue::default()),
118            managed: HashMap::new(),
119        })
120    }
121
122    pub(crate) fn is_live(&self) -> bool {
123        self.healthy && self.process.is_live()
124    }
125
126    pub(crate) fn process_control(&self) -> ProcessControl {
127        self.process.clone()
128    }
129
130    pub(crate) fn initialize(&mut self) -> Result<(), WorkerError> {
131        if !self.is_live() {
132            return Err(WorkerError::Protocol("worker requires restart"));
133        }
134        if self.session != 0 {
135            return Ok(());
136        }
137        let abi = self.call(KernelCommand::AbiVersion)?;
138        if abi.as_slice() != VERSION.to_le_bytes() {
139            return Err(WorkerError::Protocol("unsupported SMLib ABI"));
140        }
141        let bytes = self.call(KernelCommand::CreateSession)?;
142        self.session = u64::from_le_bytes(self.fixed(bytes)?);
143        if self.session == 0 {
144            return Err(self.poison("zero session"));
145        }
146        Ok(())
147    }
148
149    /// Host-local incarnation: nonzero while this exact process is live.
150    pub fn incarnation(&self) -> u64 {
151        if self.is_live() {
152            self.identity
153        } else {
154            0
155        }
156    }
157
158    /// OS process identity for supervisor diagnostics. Handles remain private.
159    pub fn process_id(&self) -> u32 {
160        self.process.id()
161    }
162
163    /// Terminate and reap this worker, invalidating its session and handles.
164    /// Idempotent after success. This cannot interrupt a concurrent blocking call
165    /// holding `&mut self`; a deadline supervisor must own process cancellation.
166    pub fn terminate(&mut self) -> Result<(), WorkerError> {
167        self.healthy = false;
168        self.process.terminate()?;
169        Ok(())
170    }
171
172    /// Create a positive-dimension box, with minimum corner in evaluation metres.
173    pub fn create_box(
174        &mut self,
175        origin: [f64; 3],
176        size: [f64; 3],
177    ) -> Result<BrepHandle, WorkerError> {
178        let bytes = self.call(KernelCommand::Box {
179            session: self.session,
180            origin,
181            size,
182        })?;
183        self.handle(bytes)
184    }
185
186    /// Create a positive-Z cylinder in evaluation metres.
187    pub fn create_cylinder(
188        &mut self,
189        origin: [f64; 3],
190        radius: f64,
191        height: f64,
192    ) -> Result<BrepHandle, WorkerError> {
193        let bytes = self.call(KernelCommand::Cylinder {
194            session: self.session,
195            origin,
196            radius,
197            height,
198        })?;
199        self.handle(bytes)
200    }
201
202    /// Tolerance-based retained-BRep operation. Exact-polyhedral callers use
203    /// GeometryDocument::evaluate_exact; this API never substitutes for it.
204    pub fn boolean(
205        &mut self,
206        left: BrepHandle,
207        right: BrepHandle,
208        operation: BooleanOperation,
209    ) -> Result<BrepHandle, WorkerError> {
210        let left = self.wire(left)?;
211        let right = self.wire(right)?;
212        let bytes = self.call(KernelCommand::Boolean {
213            session: self.session,
214            left,
215            right,
216            operation,
217        })?;
218        self.handle(bytes)
219    }
220
221    pub fn volume(
222        &mut self,
223        solid: BrepHandle,
224        relative_accuracy: f64,
225    ) -> Result<f64, WorkerError> {
226        let solid = self.wire(solid)?;
227        let bytes = self.call(KernelCommand::Volume {
228            session: self.session,
229            solid,
230            relative_accuracy,
231        })?;
232        let volume = f64::from_le_bytes(self.fixed(bytes)?);
233        if !volume.is_finite() {
234            return Err(self.poison("nonfinite volume"));
235        }
236        Ok(volume)
237    }
238
239    pub fn is_manifold(&mut self, solid: BrepHandle) -> Result<bool, WorkerError> {
240        let solid = self.wire(solid)?;
241        let bytes = self.call(KernelCommand::Manifold {
242            session: self.session,
243            solid,
244        })?;
245        match u32::from_le_bytes(self.fixed(bytes)?) {
246            0 => Ok(false),
247            1 => Ok(true),
248            _ => Err(self.poison("invalid manifold result")),
249        }
250    }
251
252    /// Copy before transforming; the input is never mutated. Matrices are
253    /// column-major metres and must be proper rigid (finite, orthonormal).
254    pub fn copy_transform(
255        &mut self,
256        solid: BrepHandle,
257        column_major: [f64; 16],
258    ) -> Result<BrepHandle, WorkerError> {
259        rigid(column_major).map_err(WorkerError::InvalidArgument)?;
260        let solid = self.wire(solid)?;
261        let bytes = self.call(KernelCommand::CopyTransform {
262            session: self.session,
263            solid,
264            column_major,
265        })?;
266        self.handle(bytes)
267    }
268
269    /// Additive adapter extension bits. They name implementations, never
270    /// same-incarnation numerical qualification.
271    fn capabilities(&mut self) -> Result<u32, WorkerError> {
272        match self.call(KernelCommand::Capabilities)?.as_slice() {
273            [1, 0, 0, 0, a, b, c, d] => Ok(u32::from_le_bytes([*a, *b, *c, *d])),
274            _ => Err(self.poison("invalid capability response")),
275        }
276    }
277
278    fn call(&mut self, command: KernelCommand) -> Result<Vec<u8>, WorkerError> {
279        if !self.is_live() {
280            return Err(WorkerError::Protocol("worker requires restart"));
281        }
282        self.flush_releases()?;
283        self.check_command_objects(&command)?;
284        let result = self.exchange(&command);
285        // Only known synchronized statuses 1..7 guarantee transactional refusal.
286        // Preserve the primary error while retiring any uncertain kernel domain.
287        if matches!(&result, Err(WorkerError::Io(_) | WorkerError::Protocol(_)))
288            || matches!(&result, Err(WorkerError::Kernel { status, .. }) if !(1..=7).contains(status))
289        {
290            self.retire();
291        }
292        result
293    }
294
295    fn exchange(&mut self, command: &KernelCommand) -> Result<Vec<u8>, WorkerError> {
296        self.sequence = self
297            .sequence
298            .checked_add(1)
299            .ok_or(WorkerError::Protocol("request IDs exhausted"))?;
300        let payload = protocol::encode_request(self.sequence, command)
301            .map_err(|error| WorkerError::Protocol(error.as_str()))?;
302        self.input
303            .write_all(&(payload.len() as u32).to_le_bytes())?;
304        self.input.write_all(&payload)?;
305        self.input.flush()?;
306        let mut size = [0; 4];
307        self.output.read_exact(&mut size)?;
308        let size = u32::from_le_bytes(size) as usize;
309        if !(12..=protocol::MAX_RESPONSE_BYTES).contains(&size) {
310            return Err(WorkerError::Protocol("invalid response length"));
311        }
312        let mut body = vec![0; size];
313        self.output.read_exact(&mut body)?;
314        match protocol::decode_response(self.sequence, &body)
315            .map_err(|error| WorkerError::Protocol(error.as_str()))?
316        {
317            KernelResponse::Success(data) => Ok(data.to_vec()),
318            KernelResponse::Failure { status, message } => Err(WorkerError::Kernel {
319                status,
320                message: message.to_owned(),
321            }),
322        }
323    }
324
325    fn fixed<const N: usize>(&mut self, bytes: Vec<u8>) -> Result<[u8; N], WorkerError> {
326        bytes
327            .try_into()
328            .map_err(|_| self.poison("unexpected result length"))
329    }
330
331    fn poison(&mut self, message: &'static str) -> WorkerError {
332        self.retire();
333        WorkerError::Protocol(message)
334    }
335
336    fn retire(&mut self) {
337        if let Err(error) = self.terminate() {
338            eprintln!("geometry worker termination/reap failed: {error}");
339        }
340    }
341}
342
343impl Drop for SmlibWorker {
344    fn drop(&mut self) {
345        if let Err(error) = self.terminate() {
346            eprintln!("geometry worker termination/reap failed: {error}");
347        }
348    }
349}
350
351/// Proper rigid check mirroring the adapter's admission: finite, bottom row
352/// (0,0,0,1), orthonormal right-handed rotation.
353fn rigid(m: [f64; 16]) -> Result<(), &'static str> {
354    let valid = m.iter().all(|v| v.is_finite())
355        && m[3] == 0.
356        && m[7] == 0.
357        && m[11] == 0.
358        && m[15] == 1.
359        && (0..3).all(|i| {
360            (0..3).all(|j| {
361                let dot: f64 = (0..3).map(|k| m[i * 4 + k] * m[j * 4 + k]).sum();
362                (dot - if i == j { 1. } else { 0. }).abs() <= 1e-12
363            })
364        });
365    let cross = [
366        m[1] * m[6] - m[2] * m[5],
367        m[2] * m[4] - m[0] * m[6],
368        m[0] * m[5] - m[1] * m[4],
369    ];
370    if valid && (0..3).all(|i| (cross[i] - m[8 + i]).abs() <= 1e-12) {
371        Ok(())
372    } else {
373        Err("transform must be a proper rigid metre frame")
374    }
375}
376
377#[cfg(all(feature = "retained-runtime", not(target_arch = "wasm32")))]
378pub use dependencies::RetainedBooleanIdentity;