citum_schema_style/style/
resolution.rs1use std::collections::HashSet;
9
10use crate::{ResolutionError, StyleInfo, StyleResolver, options, registry, style_base};
11
12use super::Style;
13use super::overlay::merge_style_overlay;
14
15impl Style {
16 #[must_use]
30 #[allow(
31 clippy::panic,
32 reason = "Convenience API for infallible resolution contexts"
33 )]
34 pub fn into_resolved(self) -> Self {
35 self.try_into_resolved()
36 .unwrap_or_else(|err| panic!("style resolution failed: {err}"))
37 }
38
39 pub fn try_into_resolved(self) -> Result<Self, ResolutionError> {
50 self.try_into_resolved_with(None)
51 }
52
53 pub fn try_into_resolved_with(
63 self,
64 resolver: Option<&StyleResolver>,
65 ) -> Result<Self, ResolutionError> {
66 self.try_into_resolved_recursive_with_depth(resolver, &mut HashSet::new(), 0)
67 }
68
69 #[must_use]
76 #[allow(
77 clippy::panic,
78 reason = "Convenience API for infallible resolution contexts"
79 )]
80 pub fn into_resolved_recursive(self, visited: &mut HashSet<String>) -> Self {
81 self.try_into_resolved_recursive(visited)
82 .unwrap_or_else(|err| panic!("style resolution failed: {err}"))
83 }
84
85 pub fn try_into_resolved_recursive(
93 self,
94 visited: &mut HashSet<String>,
95 ) -> Result<Self, ResolutionError> {
96 self.try_into_resolved_recursive_with(None, visited)
97 }
98
99 pub fn try_into_resolved_recursive_with(
106 self,
107 resolver: Option<&StyleResolver>,
108 visited: &mut HashSet<String>,
109 ) -> Result<Self, ResolutionError> {
110 self.try_into_resolved_recursive_with_depth(resolver, visited, 0)
111 }
112
113 fn try_into_resolved_recursive_with_depth(
115 self,
116 resolver: Option<&StyleResolver>,
117 visited: &mut HashSet<String>,
118 depth: usize,
119 ) -> Result<Self, ResolutionError> {
120 const MAX_DEPTH: usize = 5;
121
122 let root_label = self
125 .info
126 .id
127 .as_deref()
128 .or(self.info.title.as_deref())
129 .unwrap_or("<root>");
130 check_citum_version(root_label, &self.info)?;
131
132 let Some(base_ref) = self.extends.clone() else {
133 let mut style = self;
134 crate::template::resolve_style_template_variants(&mut style, None)?;
135 options::scoped::apply_scoped_style_options(&mut style);
136 return Ok(style);
137 };
138
139 if depth >= MAX_DEPTH {
140 let uri = base_ref.key();
141 return Err(ResolutionError::UriResolutionFailed {
142 uri: uri.to_string(),
143 reason: format!("inheritance chain exceeds maximum depth of {MAX_DEPTH}"),
144 });
145 }
146
147 let key = base_ref.key().to_string();
148 if visited.contains(&key) {
149 return Err(ResolutionError::InheritanceLoop { base: key });
150 }
151 visited.insert(key);
152
153 let is_profile = self.resolves_as_profile();
154 let pin = self.extends_pin.clone();
155 let mut effective = match base_ref {
156 style_base::StyleReference::Base(base) => {
157 if pin.is_some() {
158 return Err(ResolutionError::UriResolutionFailed {
159 uri: base.key().to_string(),
160 reason:
161 "extends-pin is only supported for URI-based parents (https://, cid:); \
162 builtin StyleBase parents are content-fixed already"
163 .to_string(),
164 });
165 }
166 base.try_resolve_with_visited(resolver, visited)?
167 }
168 style_base::StyleReference::Uri(ref uri) => {
169 let base_style = resolve_style_reference_uri(uri, resolver)?;
170 if let Some(ref expected) = pin {
171 verify_parent_pin(uri, &base_style, expected)?;
172 }
173 base_style.try_into_resolved_recursive_with_depth(resolver, visited, depth + 1)?
174 }
175 };
176 if is_profile {
177 self.validate_profile_shape()?;
178 }
179
180 let inherited_variants = crate::template::inherited_variant_context(&effective);
181 merge_style_overlay(&mut effective, &self);
182 effective.scoped_raw_options =
183 std::mem::take(&mut effective.scoped_raw_options).merged_with_child(&self);
184 effective.version = self.version;
185 effective.extends = self.extends;
186 effective.extends_pin = self.extends_pin;
187 effective.raw_yaml = self.raw_yaml;
188 crate::template::resolve_style_template_variants(
189 &mut effective,
190 inherited_variants.as_ref(),
191 )?;
192 options::scoped::apply_scoped_style_options(&mut effective);
193 if is_profile {
194 effective.extends = None;
195 }
196
197 Ok(effective)
198 }
199 fn style_kind(&self) -> Option<registry::StyleKind> {
200 let id = self.info.id.as_deref()?;
201 registry::StyleRegistry::load_default()
202 .resolve(id)
203 .and_then(|entry| entry.kind.clone())
204 }
205
206 fn resolves_as_profile(&self) -> bool {
207 self.style_kind() == Some(registry::StyleKind::Profile)
208 }
209}
210
211#[allow(
212 clippy::panic,
213 reason = "Multihash::wrap on a 32-byte SHA-256 digest is infallible by construction"
214)]
215fn schema_compute_style_cid(bytes: &[u8]) -> String {
216 use cid::Cid;
217 use multihash::Multihash;
218 use sha2::{Digest, Sha256};
219
220 const RAW_CODEC: u64 = 0x55;
221 const SHA256_CODE: u64 = 0x12;
222
223 let digest: [u8; 32] = Sha256::digest(bytes).into();
224 let mh = Multihash::<64>::wrap(SHA256_CODE, &digest)
225 .unwrap_or_else(|_| panic!("32-byte SHA-256 digest fits in Multihash<64>"));
226 Cid::new_v1(RAW_CODEC, mh).to_string()
227}
228
229fn schema_canonicalize_cid(s: &str) -> Result<String, ResolutionError> {
231 use cid::Cid;
232 let trimmed = s.strip_prefix("cid:").unwrap_or(s);
233 let cid: Cid =
234 trimmed
235 .parse()
236 .map_err(|err: cid::Error| ResolutionError::UriResolutionFailed {
237 uri: s.to_string(),
238 reason: format!("invalid CID '{s}': {err}"),
239 })?;
240 Ok(cid.to_string())
241}
242
243fn verify_parent_pin(uri: &str, parent: &Style, expected_pin: &str) -> Result<(), ResolutionError> {
251 let expected = schema_canonicalize_cid(expected_pin)?;
252 let bytes =
253 serde_yaml::to_string(parent).map_err(|err| ResolutionError::UriResolutionFailed {
254 uri: uri.to_string(),
255 reason: format!("re-serialize for extends-pin verification: {err}"),
256 })?;
257 let actual = schema_compute_style_cid(bytes.as_bytes());
258 if actual == expected {
259 Ok(())
260 } else {
261 Err(ResolutionError::IntegrityFailure {
262 uri: uri.to_string(),
263 expected,
264 actual,
265 })
266 }
267}
268
269pub fn check_citum_version(uri: &str, info: &StyleInfo) -> Result<(), ResolutionError> {
285 let Some(req_str) = info.citum_version.as_ref() else {
286 return Ok(());
287 };
288 let req =
289 semver::VersionReq::parse(req_str).map_err(|err| ResolutionError::UriResolutionFailed {
290 uri: uri.to_string(),
291 reason: format!("invalid `info.citum-version` requirement '{req_str}': {err}"),
292 })?;
293 let engine_str = env!("CARGO_PKG_VERSION");
294 let engine =
295 semver::Version::parse(engine_str).map_err(|err| ResolutionError::UriResolutionFailed {
296 uri: uri.to_string(),
297 reason: format!("unparseable engine version `{engine_str}`: {err}"),
298 })?;
299 if req.matches(&engine) {
300 Ok(())
301 } else {
302 Err(ResolutionError::VersionMismatch {
303 uri: uri.to_string(),
304 required: req_str.clone(),
305 declared: engine_str.to_string(),
306 })
307 }
308}
309
310fn resolve_style_reference_uri(
311 uri: &str,
312 resolver: Option<&StyleResolver>,
313) -> Result<Style, ResolutionError> {
314 if let Some(resolver) = resolver {
315 let style = resolver
316 .resolve_style(uri)
317 .map_err(|e| ResolutionError::from_resolver_error(uri, e))?;
318 check_citum_version(uri, &style.info)?;
319 return Ok(style);
320 }
321
322 let Some(raw_path) = uri.strip_prefix("file://") else {
323 return Err(ResolutionError::UriResolutionFailed {
324 uri: uri.to_string(),
325 reason: "unsupported scheme; an external style resolver is required".to_string(),
326 });
327 };
328 let path = std::path::Path::new(raw_path);
329 let bytes = std::fs::read(path).map_err(|e| ResolutionError::UriResolutionFailed {
330 uri: uri.to_string(),
331 reason: e.to_string(),
332 })?;
333 let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("yaml");
334 let doc_format = match ext {
335 "cbor" => super::model::StyleDocumentFormat::Cbor,
336 "json" => super::model::StyleDocumentFormat::Json,
337 _ => super::model::StyleDocumentFormat::Yaml,
338 };
339 let style = Style::from_document_bytes(&bytes, doc_format).map_err(|e| {
340 ResolutionError::UriResolutionFailed {
341 uri: uri.to_string(),
342 reason: e.to_string(),
343 }
344 })?;
345 check_citum_version(uri, &style.info)?;
346 Ok(style)
347}