ifc_lite_core/decoder/
source_caches.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Opaque cache moves carry the provenance of their producing decoder. Raw
3//! compatibility imports are trusted inputs, never proof of source identity.
4use super::EntityDecoder;
5use crate::{DecodedEntity, SourceBundle};
6use rustc_hash::FxHashMap;
7use std::sync::{
8    atomic::{AtomicU64, Ordering},
9    Arc,
10};
11
12/// A cache produced by a decoder. Entries and authority cannot be supplied
13/// independently. Moving a worker cache moves only a map header and Arc.
14pub struct SourceCache<T> {
15    source: Option<Arc<SourceBundle>>,
16    revision: u64,
17    entries: FxHashMap<u32, T>,
18}
19impl<T> Default for SourceCache<T> {
20    fn default() -> Self {
21        Self {
22            source: None,
23            revision: 0,
24            entries: Default::default(),
25        }
26    }
27}
28
29/// Explicit acceptance of a decoder's current externally authored inputs.
30/// This is a trusted configuration revision, NOT source authentication. Later
31/// raw imports invalidate it. It cannot be manufactured from an index/token.
32#[derive(Clone)]
33pub struct TrustedDecoderInputs {
34    source: Arc<SourceBundle>,
35    revision: u64,
36}
37impl TrustedDecoderInputs {
38    pub fn source(&self) -> &Arc<SourceBundle> {
39        &self.source
40    }
41    pub fn matches(&self, decoder: &EntityDecoder<'_>) -> bool {
42        decoder.cache_revision == self.revision
43            && decoder
44                .source_bundle
45                .as_ref()
46                .is_some_and(|source| Arc::ptr_eq(source, &self.source))
47    }
48}
49
50impl EntityDecoder<'_> {
51    pub(crate) fn revoke_cache_authority(&mut self) {
52        self.execution_owner.publish_cache_source(None);
53        self.uniform_precision_cache = Default::default();
54        // An unbound decoder has no source authority to protect: any nonzero
55        // revision already blocks a later bind, and unbound caches never
56        // compare revisions. Skip the process-wide counter on that path, which
57        // the per-element cache hoisting in processing hits for every element.
58        if self.source_bundle.is_none() {
59            self.cache_revision = self.cache_revision.max(1);
60            return;
61        }
62        static NEXT: AtomicU64 = AtomicU64::new(1);
63        self.cache_revision = NEXT
64            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1))
65            .expect("decoder cache revision exhausted");
66    }
67    pub(crate) fn can_bind_source(&self) -> bool {
68        self.cache_revision == 0
69            && self.cache.is_empty()
70            && self.point_cache.is_empty()
71            && self.placement_transform_cache.is_empty()
72            && self.project_id_cache.is_none()
73            && self.length_unit_scale_cache.is_none()
74            && self.plane_angle_to_radians_cache.is_none()
75            && self.geometric_precision_cache.is_none()
76            && self.uniform_precision_cache.local.is_none()
77            && self.schema_version_cache.is_none()
78            && self.styled_item_index.get().is_none()
79    }
80    /// Call only when the caller explicitly trusts all current external inputs.
81    /// This does not restore `SourceBundle::owns_decoder` authentication.
82    pub fn trusted_inputs(&self) -> Option<TrustedDecoderInputs> {
83        self.source_bundle
84            .as_ref()
85            .map(|source| TrustedDecoderInputs {
86                source: Arc::clone(source),
87                revision: self.cache_revision,
88            })
89    }
90    fn accepts_cache<T>(&self, cache: &SourceCache<T>) -> bool {
91        if cache.entries.is_empty() && cache.source.is_none() && cache.revision == 0 {
92            return true;
93        }
94        match (&self.source_bundle, &cache.source) {
95            (Some(a), Some(b)) => self.cache_revision == cache.revision && Arc::ptr_eq(a, b),
96            (None, None) => true, // explicit borrowed caller precondition remains
97            _ => false,
98        }
99    }
100    pub fn take_source_point_cache(&mut self) -> SourceCache<(f64, f64, f64)> {
101        SourceCache {
102            source: self.source_bundle.clone(),
103            revision: self.cache_revision,
104            entries: self.take_point_cache(),
105        }
106    }
107    /// False leaves this decoder unchanged; the foreign cache is not installed.
108    pub fn set_source_point_cache(&mut self, cache: SourceCache<(f64, f64, f64)>) -> bool {
109        if !self.accepts_cache(&cache) {
110            return false;
111        }
112        self.execution_owner.cache_changed();
113        self.execution_owner.changed();
114        self.point_cache = cache.entries;
115        true
116    }
117    pub fn take_source_placement_cache(&mut self) -> SourceCache<[f64; 16]> {
118        SourceCache {
119            source: self.source_bundle.clone(),
120            revision: self.cache_revision,
121            entries: self.take_placement_transform_cache(),
122        }
123    }
124    /// The memo writer retains its documented canonical-transform precondition;
125    /// this checks transfer provenance, not the correctness of extension code.
126    pub fn set_source_placement_cache(&mut self, cache: SourceCache<[f64; 16]>) -> bool {
127        if !self.accepts_cache(&cache) {
128            return false;
129        }
130        self.execution_owner.cache_changed();
131        self.execution_owner.changed();
132        self.placement_transform_cache = cache.entries;
133        true
134    }
135    pub fn drain_source_cache(&mut self) -> SourceCache<Arc<DecodedEntity>> {
136        SourceCache {
137            source: self.source_bundle.clone(),
138            revision: self.cache_revision,
139            entries: self.drain_cache(),
140        }
141    }
142    /// Share canonically prewarmed records without a source/index scan. The
143    /// entry cloning cost is the same as the existing raw injection API.
144    pub fn inject_source_cache(&mut self, cache: &SourceCache<Arc<DecodedEntity>>) -> bool {
145        if !self.accepts_cache(cache) {
146            return false;
147        }
148        self.execution_owner.cache_changed();
149        self.execution_owner.changed();
150        self.cache.extend(
151            cache
152                .entries
153                .iter()
154                .map(|(&id, entity)| (id, Arc::clone(entity))),
155        );
156        true
157    }
158}
159
160#[cfg(test)]
161#[path = "source_caches_tests.rs"]
162mod tests;
163
164#[cfg(test)]
165#[path = "resource_retention_tests.rs"]
166mod resource_retention_tests;