ifc_lite_processing/
execution.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Shared scheduler boundaries around the owned element transaction. Worker
3//! caches, batch source ownership and output encoding remain with the callers.
4use ifc_lite_core::{DecodedEntity, EntityDecoder, IfcType};
5use ifc_lite_geometry::{
6    GeometryRouter, ItemDedupCache, MappedInstancePlan, MaterialLayerIndex, RouterConfig,
7    SharedBrepSignatureCache, SharedMappedItemCache,
8};
9use rustc_hash::{FxHashMap, FxHashSet};
10use std::sync::Arc;
11
12/// Native jobs choose the model-wide template; serial browser batches choose
13/// their first occurrence. The policy also selects uncached versus warm decode.
14#[derive(Clone, Copy)]
15pub enum SchedulerPolicy {
16    PerJob,
17    PerBatch,
18}
19
20/// Model-owned cache handles, transferred into the router without extra clones.
21pub struct RouterCaches {
22    pub items: ItemDedupCache,
23    pub brep_signatures: SharedBrepSignatureCache,
24    pub mapped_items: SharedMappedItemCache,
25}
26
27/// Arm a router completely before the first owned product leases it. Native
28/// callers forward the model material-layer index; browser callers retain their
29/// merge toggle. Indexed-colour exclusion is meaningful only with instancing armed.
30pub fn build_router(
31    mut config: RouterConfig,
32    policy: SchedulerPolicy,
33    caches: RouterCaches,
34    layers: Option<Arc<MaterialLayerIndex>>,
35    instances: Option<&MappedInstancePlan>,
36    indexed_colours: Option<&Arc<FxHashSet<u32>>>,
37) -> GeometryRouter {
38    config.instancing_batch_local =
39        instances.is_some() && matches!(policy, SchedulerPolicy::PerBatch);
40    // Preserve the caller's world-frame rebase.
41    let mut router = GeometryRouter::from_config(config);
42    router.enable_content_dedup_shared(caches.items);
43    router.enable_shared_brep_signature_cache(caches.brep_signatures);
44    router.enable_shared_mapped_item_cache(caches.mapped_items);
45    if let Some(layers) = layers {
46        router.set_material_layer_index(layers);
47    }
48    if let Some(plan) = instances {
49        router.enable_output_instancing(plan.clone());
50        if let Some(ids) = indexed_colours {
51            router.enable_indexed_colour_split_guard(ids.clone());
52        }
53    }
54    router
55}
56
57/// A job's original byte span. Cached browser decode may return without reading
58/// it, so keyword recovery must use a checked slice even after successful decode.
59#[derive(Clone, Copy)]
60pub struct JobSpan {
61    pub id: u32,
62    pub start: usize,
63    pub end: usize,
64}
65
66/// No new allocation for native jobs; browser cache hits keep their Arc.
67pub enum JobEntity {
68    Owned(DecodedEntity),
69    Cached(Arc<DecodedEntity>),
70}
71impl std::ops::Deref for JobEntity {
72    type Target = DecodedEntity;
73    fn deref(&self) -> &Self::Target {
74        match self {
75            Self::Owned(entity) => entity,
76            Self::Cached(entity) => entity,
77        }
78    }
79}
80
81/// Shared decode admission. Error accounting stays scheduler-scoped: per-job
82/// decoder on native, cumulative refused-record set on a browser batch.
83pub fn decode_job(
84    decoder: &mut EntityDecoder,
85    span: JobSpan,
86    policy: SchedulerPolicy,
87) -> ifc_lite_core::Result<JobEntity> {
88    match policy {
89        SchedulerPolicy::PerJob => decoder
90            .decode_at(span.start, span.end)
91            .map(JobEntity::Owned),
92        SchedulerPolicy::PerBatch => decoder
93            .decode_and_cache(span.id, span.start, span.end)
94            .map(JobEntity::Cached),
95    }
96}
97
98/// Native scanning already resolved the exact keyword. Browser jobs carry only
99/// spans and recover it here, including on warm-decoder cache hits (#3179).
100pub fn job_type(
101    entity: &DecodedEntity,
102    source: &[u8],
103    span: JobSpan,
104    scanned: Option<&IfcType>,
105) -> IfcType {
106    scanned.cloned().unwrap_or_else(|| {
107        ifc_lite_core::ifc_type_from_record(
108            entity.ifc_type.clone(),
109            source.get(span.start..span.end).unwrap_or_default(),
110        )
111    })
112}
113
114/// Router-wide counters are taken once per native job or once per browser
115/// batch. Per-element CSG failures and unsupported-item audit remain at their
116/// existing owned-production/publication boundaries.
117pub struct RouterDrain {
118    pub classification: ifc_lite_geometry::ClassificationStats,
119    pub hosts: FxHashMap<u32, ifc_lite_geometry::HostOpeningDiagnostic>,
120    pub oversized_refs: u64,
121    pub rect_fast: ifc_lite_geometry::RectFastStats,
122}
123impl RouterDrain {
124    pub fn take(router: &GeometryRouter) -> Self {
125        Self::take_with_hosts(router, router.take_host_opening_diagnostics())
126    }
127
128    /// Drain the same counters alongside the measured rectangular no-op count.
129    pub fn take_with_rectangular_no_ops(router: &GeometryRouter) -> (Self, u64) {
130        let (hosts, no_ops) = router.take_host_opening_report();
131        (Self::take_with_hosts(router, hosts), no_ops)
132    }
133
134    fn take_with_hosts(
135        router: &GeometryRouter,
136        hosts: FxHashMap<u32, ifc_lite_geometry::HostOpeningDiagnostic>,
137    ) -> Self {
138        Self {
139            classification: router.take_classification_stats(),
140            hosts,
141            oversized_refs: router.take_content_hash_oversized_ref_drops() as u64,
142            rect_fast: router.take_rect_fast_stats(),
143        }
144    }
145}
146
147#[cfg(test)]
148#[path = "execution_tests.rs"]
149mod tests;