Skip to main content

sql_splitter/synthetic/
config.rs

1//! Loads a `model`/`overrides` document together with its local imports.
2//!
3//! The document formats themselves (see [`super::model`] and
4//! [`super::overrides`]) know nothing about imports beyond carrying an
5//! `imports: Vec<PathBuf>` field — resolving them, rejecting anything
6//! unsafe (remote, recursive, or role-mismatched), and merging them with
7//! deterministic root-wins semantics is this module's job.
8//!
9//! See the design doc's "### Imports" section for the merge rules this
10//! implements: imported files are always `kind: overrides`, resolve
11//! relative to the importing file, and cannot themselves import; two
12//! imports may never define the same configuration path; the root
13//! document may freely override anything an import defines; maps merge by
14//! key while lists replace wholesale.
15
16use std::collections::BTreeMap;
17use std::fs;
18use std::path::{Path, PathBuf};
19
20use serde::Deserialize;
21use serde_yaml_ng::Value;
22
23use crate::diagnostic::{DiagnosticBag, SourceLocation};
24
25use super::model::SyntheticFile;
26
27/// Envelope fields read generically off any document (root or imported)
28/// before it is known to satisfy its full role-specific schema. Unknown
29/// fields are intentionally allowed; the eventual typed parse enforces
30/// them.
31#[derive(Debug, Default, Deserialize)]
32struct ImportEnvelope {
33    #[serde(default)]
34    kind: Option<String>,
35    #[serde(default)]
36    imports: Vec<String>,
37}
38
39/// Loads a root synthetic-data document plus its resolved local imports,
40/// producing a single [`SyntheticFile`] ready for compilation.
41pub struct ConfigLoader;
42
43impl ConfigLoader {
44    /// Reads `path`, resolves and merges any `imports:` it declares, and
45    /// typed-deserializes the merged document into the role (`model` or
46    /// `overrides`) the root document declares.
47    ///
48    /// Import resolution happens before the typed parse so a root document
49    /// that only becomes complete once its imports are merged in (the
50    /// common case — splitting a large `tables:` map across files) still
51    /// validates successfully.
52    pub fn load(path: &Path) -> Result<SyntheticFile, DiagnosticBag> {
53        let root_value = read_yaml(path)?;
54        let base_dir = path.parent().unwrap_or_else(|| Path::new("."));
55
56        let envelope: ImportEnvelope =
57            serde_yaml_ng::from_value(root_value.clone()).map_err(|err| {
58                single_error(
59                    crate::diagnostic::codes::CONFIG_PARSE.code,
60                    &path.display().to_string(),
61                    &err,
62                )
63            })?;
64
65        let mut bag = DiagnosticBag::default();
66        let mut imports = Vec::with_capacity(envelope.imports.len());
67        for raw in &envelope.imports {
68            match resolve_import(base_dir, raw) {
69                Ok(resolved) => imports.push(resolved),
70                Err(mut import_bag) => bag.diagnostics.append(&mut import_bag.diagnostics),
71            }
72        }
73        if bag.has_errors() {
74            return Err(bag);
75        }
76
77        let merged = merge_yaml(root_value, imports)?;
78        SyntheticFile::parse_value(merged).map_err(|err| {
79            single_error(
80                crate::diagnostic::codes::CONFIG_ROLE.code,
81                &path.display().to_string(),
82                &err,
83            )
84        })
85    }
86}
87
88/// Rejects remote/absolute import paths, then loads and validates the
89/// imported file itself: it must be `kind: overrides` and must not declare
90/// any imports of its own.
91fn resolve_import(base_dir: &Path, raw: &str) -> Result<(PathBuf, Value), DiagnosticBag> {
92    let traverses_up = Path::new(raw)
93        .components()
94        .any(|component| matches!(component, std::path::Component::ParentDir));
95    if raw.contains("://") || Path::new(raw).is_absolute() || traverses_up {
96        let mut bag = DiagnosticBag::default();
97        bag.error(
98            crate::diagnostic::codes::IMPORT_REMOTE.code,
99            "imports",
100            format!("import path `{raw}` must be local and relative and must stay within the model directory; remote, absolute, or `..`-traversing paths are rejected"),
101        );
102        return Err(bag);
103    }
104
105    let resolved = base_dir.join(raw);
106    let value = read_yaml(&resolved)?;
107    let envelope: ImportEnvelope = serde_yaml_ng::from_value(value.clone()).map_err(|err| {
108        single_error(
109            crate::diagnostic::codes::CONFIG_PARSE.code,
110            &resolved.display().to_string(),
111            &err,
112        )
113    })?;
114
115    if envelope.kind.as_deref() != Some("overrides") {
116        let mut bag = DiagnosticBag::default();
117        bag.error(
118            crate::diagnostic::codes::IMPORT_KIND.code,
119            "imports",
120            format!(
121                "imported file `{}` must be `kind: overrides`, found `kind: {}`",
122                resolved.display(),
123                envelope.kind.as_deref().unwrap_or("<missing>")
124            ),
125        );
126        return Err(bag);
127    }
128    if !envelope.imports.is_empty() {
129        let mut bag = DiagnosticBag::default();
130        bag.error(
131            crate::diagnostic::codes::IMPORT_NESTED.code,
132            "imports",
133            format!(
134                "imported file `{}` declares its own `imports:`; imported files cannot themselves import",
135                resolved.display()
136            ),
137        );
138        return Err(bag);
139    }
140
141    Ok((resolved, value))
142}
143
144/// Reads and parses `path` as a YAML [`Value`], surfacing I/O and parse
145/// failures (including `serde_yaml_ng`'s duplicate-key rejection) as
146/// diagnostics.
147fn read_yaml(path: &Path) -> Result<Value, DiagnosticBag> {
148    let text = fs::read_to_string(path).map_err(|err| {
149        single_error(
150            crate::diagnostic::codes::CONFIG_IO.code,
151            &path.display().to_string(),
152            &err,
153        )
154    })?;
155    // TODO(deferred, L15): serde_yaml_ng expands anchors/aliases with no depth
156    // or size limit, so a crafted "billion laughs" model file can blow up memory
157    // here. A size/expansion guard (or documenting the trust boundary) would
158    // close it. Deferred because model files are the user's own inputs, not
159    // untrusted network input.
160    serde_yaml_ng::from_str(&text).map_err(|err| {
161        single_error(
162            crate::diagnostic::codes::CONFIG_PARSE.code,
163            &path.display().to_string(),
164            &err,
165        )
166    })
167}
168
169fn single_error(code: &str, path: &str, err: &impl std::fmt::Display) -> DiagnosticBag {
170    let mut bag = DiagnosticBag::default();
171    bag.error(code, path, err.to_string());
172    bag
173}
174
175/// Merges a root document's imports (in declaration order, with
176/// path-level collision detection) and then merges the root document
177/// itself on top with no collision checking — the root always wins.
178///
179/// Returns the merged [`Value`], still untyped: [`SyntheticFile::parse_value`]
180/// performs the final role-specific validation.
181pub fn merge_yaml(root: Value, imports: Vec<(PathBuf, Value)>) -> Result<Value, DiagnosticBag> {
182    let mut bag = DiagnosticBag::default();
183    let mut merged = Value::Mapping(Default::default());
184    let mut occupied = BTreeMap::<String, (PathBuf, NodeShape)>::new();
185
186    for (source, value) in imports {
187        let content = strip_envelope_keys(value);
188        merge_import(&mut merged, content, "", &mut occupied, &source, &mut bag);
189    }
190    bag.into_result(())?;
191
192    merge_root(&mut merged, root);
193    Ok(merged)
194}
195
196/// The shape a config path was last assigned by an import: a terminal
197/// value (scalar, `null`, or a whole list — lists always replace
198/// wholesale, never merge) or a map whose children may still be extended
199/// by another import.
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201enum NodeShape {
202    Leaf,
203    Map,
204}
205
206/// Whether writing `incoming_shape` at a path already occupied with
207/// `prior_shape` (by a *different* import) constitutes a collision.
208///
209/// A leaf write always collides — it silently clobbers whatever the other
210/// import defined there, whether that was itself a leaf or a whole
211/// subtree. A map write only collides if the path was previously a leaf:
212/// two imports both contributing a map at the same path is the ordinary,
213/// legal case of merging disjoint child keys.
214fn shape_collision(prior_shape: NodeShape, incoming_shape: NodeShape) -> bool {
215    match incoming_shape {
216        NodeShape::Leaf => true,
217        NodeShape::Map => prior_shape == NodeShape::Leaf,
218    }
219}
220
221/// Removes the envelope-only keys (`version`, `kind`, `imports`) from an
222/// imported document before it is merged. These are validated separately
223/// in [`resolve_import`] and must never leak into the merged body — the
224/// root's own `version`/`kind` must win unconditionally, and an import's
225/// `imports` list (always empty by the time we get here) carries no
226/// content.
227fn strip_envelope_keys(value: Value) -> Value {
228    let Value::Mapping(mut mapping) = value else {
229        return value;
230    };
231    for key in ["version", "kind", "imports"] {
232        mapping.remove(key);
233    }
234    Value::Mapping(mapping)
235}
236
237/// Merges one import's content into the shared accumulator, recording the
238/// shape ([`NodeShape`]) of every path it touches — leaf or map — in
239/// `occupied`. A later import that redefines the same path with an
240/// incompatible shape (see [`shape_collision`]) is reported as
241/// [`DiagnosticBag`] error `GEN-IMPORT-COLLISION` naming both source files
242/// and the exact path. Two imports contributing disjoint keys to the same
243/// map path is not a collision — that is the ordinary case this function
244/// exists to support.
245fn merge_import(
246    target: &mut Value,
247    incoming: Value,
248    path: &str,
249    occupied: &mut BTreeMap<String, (PathBuf, NodeShape)>,
250    source: &Path,
251    bag: &mut DiagnosticBag,
252) {
253    let Value::Mapping(incoming_map) = incoming else {
254        check_path_collision(path, NodeShape::Leaf, occupied, source, bag);
255        occupied
256            .entry(path.to_string())
257            .or_insert_with(|| (source.to_path_buf(), NodeShape::Leaf));
258        *target = incoming;
259        return;
260    };
261
262    check_path_collision(path, NodeShape::Map, occupied, source, bag);
263    occupied
264        .entry(path.to_string())
265        .or_insert_with(|| (source.to_path_buf(), NodeShape::Map));
266
267    if !target.is_mapping() {
268        *target = Value::Mapping(Default::default());
269    }
270    let target_map = target.as_mapping_mut().expect("just ensured mapping");
271
272    for (key, incoming_value) in incoming_map {
273        let child_path = join_path(path, key.as_str().unwrap_or_default());
274        let slot = target_map.entry(key).or_insert(Value::Null);
275        merge_import(slot, incoming_value, &child_path, occupied, source, bag);
276    }
277}
278
279/// Reports `GEN-IMPORT-COLLISION` if `path` was already assigned by a
280/// *different* import with a shape incompatible with `incoming_shape` (see
281/// [`shape_collision`]). Does nothing if `path` is unoccupied, was set by
282/// the same import (impossible within one import — `serde_yaml_ng` already
283/// rejects duplicate keys — but harmless to check), or was set by a
284/// different import with a compatible shape.
285fn check_path_collision(
286    path: &str,
287    incoming_shape: NodeShape,
288    occupied: &BTreeMap<String, (PathBuf, NodeShape)>,
289    source: &Path,
290    bag: &mut DiagnosticBag,
291) {
292    let Some((prior_source, prior_shape)) = occupied.get(path) else {
293        return;
294    };
295    if prior_source == source || !shape_collision(*prior_shape, incoming_shape) {
296        return;
297    }
298    bag.error(
299        crate::diagnostic::codes::IMPORT_COLLISION.code,
300        path,
301        format!("`{path}` is defined by more than one import"),
302    )
303    .related = vec![
304        SourceLocation {
305            path: prior_source.display().to_string(),
306            description: None,
307        },
308        SourceLocation {
309            path: source.display().to_string(),
310            description: None,
311        },
312    ];
313}
314
315/// Merges the root document on top of the already-merged imports. Unlike
316/// [`merge_import`], this never checks for collisions: the root document
317/// is always allowed to override whatever its imports defined.
318fn merge_root(target: &mut Value, incoming: Value) {
319    let Value::Mapping(incoming_map) = incoming else {
320        *target = incoming;
321        return;
322    };
323
324    if !target.is_mapping() {
325        *target = Value::Mapping(Default::default());
326    }
327    let target_map = target.as_mapping_mut().expect("just ensured mapping");
328
329    for (key, incoming_value) in incoming_map {
330        if incoming_value.is_mapping() {
331            let slot = target_map
332                .entry(key)
333                .or_insert(Value::Mapping(Default::default()));
334            merge_root(slot, incoming_value);
335        } else {
336            target_map.insert(key, incoming_value);
337        }
338    }
339}
340
341fn join_path(prefix: &str, key: &str) -> String {
342    if prefix.is_empty() {
343        key.to_string()
344    } else {
345        format!("{prefix}.{key}")
346    }
347}
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352
353    #[test]
354    fn merge_root_replaces_lists_wholesale() {
355        let root: Value =
356            serde_yaml_ng::from_str("tables: { orders: { relationships: [1, 2] } }").unwrap();
357        let mut merged: Value =
358            serde_yaml_ng::from_str("tables: { orders: { relationships: [9] } }").unwrap();
359        merge_root(&mut merged, root);
360        let rendered = serde_yaml_ng::to_string(&merged).unwrap();
361        assert!(rendered.contains("- 1"));
362        assert!(rendered.contains("- 2"));
363        assert!(!rendered.contains("- 9"));
364    }
365
366    #[test]
367    fn strip_envelope_keys_drops_version_kind_and_imports() {
368        let value: Value =
369            serde_yaml_ng::from_str("version: 1\nkind: overrides\nimports: []\ntables: {}\n")
370                .unwrap();
371        let stripped = strip_envelope_keys(value);
372        let mapping = stripped.as_mapping().unwrap();
373        assert!(!mapping.contains_key("version"));
374        assert!(!mapping.contains_key("kind"));
375        assert!(!mapping.contains_key("imports"));
376        assert!(mapping.contains_key("tables"));
377    }
378}