ifc_lite_geometry/router/
mapped_cache_ownership.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Cache storage retains request accounts independently of failed later work.
3use super::{GeometryRouter, SharedMappedItemCache};
4use crate::resource::{self, Cost, ExecutionAccount, ProgramStop};
5use crate::{Error, Mesh};
6use std::sync::{Arc, Mutex};
7
8/// Opt-in mapped source cache ownership. Unlike the legacy shared cache alias,
9/// this handle never exposes naked cached mesh Arcs. Completed entries keep the
10/// publishing request account alive, conservatively retaining its full pooled
11/// allowance. This is not exact cache-byte reconciliation or a process bound.
12#[derive(Clone)]
13pub struct AccountedMappedItemCache {
14    cache: SharedMappedItemCache,
15    accounts: Arc<Mutex<Vec<ExecutionAccount>>>,
16}
17
18impl AccountedMappedItemCache {
19    pub fn new() -> Self {
20        Self {
21            cache: GeometryRouter::new_mapped_item_cache(),
22            accounts: Arc::new(Mutex::new(Vec::new())),
23        }
24    }
25}
26impl Default for AccountedMappedItemCache {
27    fn default() -> Self {
28        Self::new()
29    }
30}
31
32fn retain_account(
33    accounts: &mut Vec<ExecutionAccount>,
34    account: ExecutionAccount,
35) -> Result<(), ProgramStop> {
36    // One owner record per reached publication; source identity is not used to
37    // deduplicate real concurrent work or refund already copied allocations.
38    let width = std::mem::size_of::<ExecutionAccount>() as u64;
39    let count = u64::try_from(accounts.len()).map_err(|_| resource::overflow())?;
40    let growth = accounts.len() == accounts.capacity();
41    let live_bytes = if growth {
42        count
43            .checked_add(1)
44            .and_then(|v| v.checked_mul(width))
45            .ok_or_else(resource::overflow)?
46    } else {
47        0
48    };
49    if live_bytes > isize::MAX as u64 {
50        return Err(resource::overflow());
51    }
52    let copy_bytes = if growth {
53        count.checked_mul(width).ok_or_else(resource::overflow)?
54    } else {
55        0
56    };
57    let permit = resource::charge(Cost {
58        work: 1,
59        copy_bytes,
60        live_bytes,
61        ..Cost::default()
62    })?;
63    accounts
64        .try_reserve_exact(1)
65        .map_err(|_| resource::allocation_failure())?;
66    accounts.push(account);
67    permit.retain();
68    Ok(())
69}
70
71#[cold]
72#[inline(never)]
73fn unsupported_coverage() -> ProgramStop {
74    resource::refused(
75        resource::Dimension::Coverage,
76        0,
77        0,
78        resource::RefusalReason::UnsupportedCoverage,
79    )
80}
81
82impl GeometryRouter {
83    /// A fresh empty shared `IfcMappedItem` source cache, to be cloned into every
84    /// per-element / per-batch router of ONE loaded model so a mapped source shared
85    /// across owning elements is meshed once model-wide (#1623). Mirrors
86    /// [`Self::new_dedup_cache`]. Keep one per model/pass: the cached meshes bake in
87    /// this pass's unit scale / tessellation quality.
88    pub fn new_mapped_item_cache() -> SharedMappedItemCache {
89        Arc::new(Mutex::new(rustc_hash::FxHashMap::default()))
90    }
91
92    /// Inject a shared `IfcMappedItem` source cache (see
93    /// [`Self::new_mapped_item_cache`]) into this router. All routers given the
94    /// SAME `Arc` mesh each unique `IfcRepresentationMap` source once across the
95    /// whole model, instead of once per owning element (a fresh router is built per
96    /// element). Takes precedence over the per-router RefCell `mapped_item_cache`;
97    /// leaving it unset keeps the per-router fallback for single-shot callers.
98    pub fn enable_shared_mapped_item_cache(&mut self, cache: SharedMappedItemCache) {
99        // A different cache is different configuration for outstanding work.
100        self.execution_owner.changed();
101        self.shared_mapped_item_cache = Some(cache);
102        self.accounted_mapped_cache = None;
103    }
104
105    /// Bind retained cache storage to its admission owner. Ordinary borrowed
106    /// cache APIs remain compatible and cannot qualify bounded publication.
107    pub fn enable_accounted_mapped_item_cache(&mut self, cache: AccountedMappedItemCache) {
108        self.execution_owner.changed();
109        self.shared_mapped_item_cache = Some(Arc::clone(&cache.cache));
110        self.accounted_mapped_cache = Some(cache);
111    }
112
113    /// Router-local caches (the hash cache and the RefCell mapped fallback) keep
114    /// their publishing accounts alive for exactly the router's lifetime.
115    #[cold]
116    #[inline(never)]
117    pub(crate) fn retain_local_resource_account(&self) -> Result<(), ProgramStop> {
118        if let Some(account) = resource::current_account() {
119            retain_account(&mut self.mapped_cache_accounts.borrow_mut(), account)?;
120        }
121        Ok(())
122    }
123
124    pub(crate) fn check_mapped_cache_coverage(&self) -> Result<(), ProgramStop> {
125        resource::check_current()?;
126        if resource::is_active()
127            && self.shared_mapped_item_cache.is_some()
128            && self.accounted_mapped_cache.is_none()
129        {
130            return Err(unsupported_coverage());
131        }
132        Ok(())
133    }
134
135    /// The shared content-dedup cache stores unaccounted deep copies with no
136    /// admission owner: bounded execution refuses it rather than claim coverage.
137    pub(super) fn check_item_dedup_coverage(&self) -> Result<(), ProgramStop> {
138        if self.item_dedup_cache.is_some() && resource::is_active() {
139            return Err(unsupported_coverage());
140        }
141        Ok(())
142    }
143
144    /// Call after complete source production but before inserting the owned
145    /// cache payload. A later branch failure cannot discard this retained owner.
146    #[cold]
147    #[inline(never)]
148    pub(crate) fn retain_mapped_cache_account(&self) -> Result<(), ProgramStop> {
149        self.check_mapped_cache_coverage()?;
150        let Some(account) = resource::current_account() else {
151            return Ok(());
152        };
153        match &self.accounted_mapped_cache {
154            Some(cache) => retain_account(
155                &mut cache.accounts.lock().unwrap_or_else(|e| e.into_inner()),
156                account,
157            ),
158            None => retain_account(&mut self.mapped_cache_accounts.borrow_mut(), account),
159        }
160    }
161
162    /// Deep-copy a source mesh for a mapped-item cache. Without an installed
163    /// account this is `Mesh::clone`; with one, cache coverage is checked and the
164    /// copy admitted before any allocation, so a zero or overflowing allowance
165    /// refuses it with the cache untouched. The published storage stays charged
166    /// for the cache's lifetime: the cache owner retains the publishing account.
167    pub(super) fn clone_source_for_cache(&self, mesh: &Mesh) -> crate::Result<Arc<Mesh>> {
168        if !crate::resource::is_active() {
169            return Ok(Arc::new(mesh.clone()));
170        }
171        self.clone_source_for_cache_accounted(mesh)
172    }
173
174    /// The accounted branch of [`Self::clone_source_for_cache`], out of line.
175    #[cold]
176    #[inline(never)]
177    fn clone_source_for_cache_accounted(&self, mesh: &Mesh) -> crate::Result<Arc<Mesh>> {
178        self.check_mapped_cache_coverage()?;
179        let (copy, permit) = crate::resource::mesh::clone_mesh(mesh)?;
180        self.retain_mapped_cache_account()?;
181        permit.retain();
182        Ok(Arc::new(copy))
183    }
184
185    /// A program stop reached by a source item is terminal for the whole walk;
186    /// any other item failure stays an ordinary recoverable drop.
187    #[cold]
188    #[inline(never)]
189    pub(crate) fn recoverable_source_error(error: Error) -> crate::Result<Error> {
190        match crate::resource::observe::<()>(Err(error)) {
191            Err(stop @ Error::ProgramStopped(_)) => Err(stop),
192            Err(error) => Ok(error),
193            Ok(()) => Ok(Error::geometry("source item failed")),
194        }
195    }
196
197    /// Accounted copy for both cache population and every cache hit, so a
198    /// repeated occurrence is charged (or refused) like the first one.
199    pub(crate) fn clone_cached_mesh(&self, mesh: &Mesh) -> crate::Result<Mesh> {
200        // A hit is coverage too: under a bounded account an ordinary
201        // (unaccounted) shared cache is refused on lookup, not only on insert.
202        if self.shared_mapped_item_cache.is_some() {
203            self.check_mapped_cache_coverage()?;
204        }
205        if !crate::resource::is_active() {
206            return Ok(mesh.clone());
207        }
208        Self::clone_cached_mesh_accounted(mesh)
209    }
210
211    /// The accounted branch of [`Self::clone_cached_mesh`], out of line.
212    #[cold]
213    #[inline(never)]
214    fn clone_cached_mesh_accounted(mesh: &Mesh) -> crate::Result<Mesh> {
215        let (copy, permit) = crate::resource::mesh::clone_mesh(mesh)?;
216        permit.retain();
217        Ok(copy)
218    }
219}
220
221#[cfg(test)]
222#[path = "mapped_cache_ownership_tests.rs"]
223mod tests;