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 crate::template::resolve_style_template_variants_with_overlay(
185 &mut effective,
186 inherited_variants.as_ref(),
187 &self,
188 )?;
189 effective.version = self.version;
190 effective.extends = self.extends;
191 effective.extends_pin = self.extends_pin;
192 effective.raw_yaml = self.raw_yaml;
193 options::scoped::apply_scoped_style_options(&mut effective);
194 if is_profile {
195 effective.extends = None;
196 }
197
198 Ok(effective)
199 }
200 fn style_kind(&self) -> Option<registry::StyleKind> {
201 let id = self.info.id.as_deref()?;
202 registry::StyleRegistry::load_default()
203 .resolve(id)
204 .and_then(|entry| entry.kind.clone())
205 }
206
207 fn resolves_as_profile(&self) -> bool {
208 self.style_kind() == Some(registry::StyleKind::Profile)
209 }
210}
211
212#[allow(
213 clippy::panic,
214 reason = "Multihash::wrap on a 32-byte SHA-256 digest is infallible by construction"
215)]
216fn schema_compute_style_cid(bytes: &[u8]) -> String {
217 use cid::Cid;
218 use multihash::Multihash;
219 use sha2::{Digest, Sha256};
220
221 const RAW_CODEC: u64 = 0x55;
222 const SHA256_CODE: u64 = 0x12;
223
224 let digest: [u8; 32] = Sha256::digest(bytes).into();
225 let mh = Multihash::<64>::wrap(SHA256_CODE, &digest)
226 .unwrap_or_else(|_| panic!("32-byte SHA-256 digest fits in Multihash<64>"));
227 Cid::new_v1(RAW_CODEC, mh).to_string()
228}
229
230fn schema_canonicalize_cid(s: &str) -> Result<String, ResolutionError> {
232 use cid::Cid;
233 let trimmed = s.strip_prefix("cid:").unwrap_or(s);
234 let cid: Cid =
235 trimmed
236 .parse()
237 .map_err(|err: cid::Error| ResolutionError::UriResolutionFailed {
238 uri: s.to_string(),
239 reason: format!("invalid CID '{s}': {err}"),
240 })?;
241 Ok(cid.to_string())
242}
243
244fn verify_parent_pin(uri: &str, parent: &Style, expected_pin: &str) -> Result<(), ResolutionError> {
252 let expected = schema_canonicalize_cid(expected_pin)?;
253 let bytes =
254 serde_yaml::to_string(parent).map_err(|err| ResolutionError::UriResolutionFailed {
255 uri: uri.to_string(),
256 reason: format!("re-serialize for extends-pin verification: {err}"),
257 })?;
258 let actual = schema_compute_style_cid(bytes.as_bytes());
259 if actual == expected {
260 Ok(())
261 } else {
262 Err(ResolutionError::IntegrityFailure {
263 uri: uri.to_string(),
264 expected,
265 actual,
266 })
267 }
268}
269
270pub fn check_citum_version(uri: &str, info: &StyleInfo) -> Result<(), ResolutionError> {
286 let Some(req_str) = info.citum_version.as_ref() else {
287 return Ok(());
288 };
289 let req =
290 semver::VersionReq::parse(req_str).map_err(|err| ResolutionError::UriResolutionFailed {
291 uri: uri.to_string(),
292 reason: format!("invalid `info.citum-version` requirement '{req_str}': {err}"),
293 })?;
294 let engine_str = env!("CARGO_PKG_VERSION");
295 let engine =
296 semver::Version::parse(engine_str).map_err(|err| ResolutionError::UriResolutionFailed {
297 uri: uri.to_string(),
298 reason: format!("unparseable engine version `{engine_str}`: {err}"),
299 })?;
300 if req.matches(&engine) {
301 Ok(())
302 } else {
303 Err(ResolutionError::VersionMismatch {
304 uri: uri.to_string(),
305 required: req_str.clone(),
306 declared: engine_str.to_string(),
307 })
308 }
309}
310
311fn resolve_style_reference_uri(
312 uri: &str,
313 resolver: Option<&StyleResolver>,
314) -> Result<Style, ResolutionError> {
315 if let Some(resolver) = resolver {
316 let style = resolver
317 .resolve_style(uri)
318 .map_err(|e| ResolutionError::from_resolver_error(uri, e))?;
319 check_citum_version(uri, &style.info)?;
320 return Ok(style);
321 }
322
323 let Some(raw_path) = uri.strip_prefix("file://") else {
324 return Err(ResolutionError::UriResolutionFailed {
325 uri: uri.to_string(),
326 reason: "unsupported scheme; an external style resolver is required".to_string(),
327 });
328 };
329 let path = std::path::Path::new(raw_path);
330 let bytes = std::fs::read(path).map_err(|e| ResolutionError::UriResolutionFailed {
331 uri: uri.to_string(),
332 reason: e.to_string(),
333 })?;
334 let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("yaml");
335 let doc_format = match ext {
336 "cbor" => super::model::StyleDocumentFormat::Cbor,
337 "json" => super::model::StyleDocumentFormat::Json,
338 _ => super::model::StyleDocumentFormat::Yaml,
339 };
340 let style = Style::from_document_bytes(&bytes, doc_format).map_err(|e| {
341 ResolutionError::UriResolutionFailed {
342 uri: uri.to_string(),
343 reason: e.to_string(),
344 }
345 })?;
346 check_citum_version(uri, &style.info)?;
347 Ok(style)
348}