Skip to main content

ripbi_core/
ingest.rs

1//! Format ingestion: turning Power BI source folders into the crate's ASTs.
2//!
3//! Entry points return [`Ingested`] — the parsed value plus every
4//! [`SkipNotice`] the parser recorded. A notice is a warning carried as data,
5//! not control flow: this crate never prints, so the CLI decides how notices
6//! are presented. They are collected on every run, not only in debug builds,
7//! because a silently skipped object can surface later as a false "unused"
8//! finding — the failure mode this tool exists to prevent.
9//!
10//! Skips come in two tiers. *Deliberately unmodeled* metadata (annotations,
11//! lineage tags, display folders, cultures, …) is skipped silently, per the
12//! exclusions in `docs/semantic-model.md`. *Unexpected drift* — an unknown
13//! object, a property that is neither modeled nor ignored, a value that fails
14//! to parse — is recorded as a notice. The full policy, including the curated
15//! ignore list, lives in `docs/formats.md`.
16
17mod pbir;
18mod tmdl;
19
20use std::fs;
21use std::path::{Path, PathBuf};
22
23use crate::model::TabularDatabase;
24use crate::report::{DatasetReference, ReportModel};
25use crate::{Error, Result};
26
27/// One thing a parser skipped, and why.
28///
29/// Notices are warnings as data: this crate records them and moves on, never
30/// printing and never failing, so a single unexpected property cannot abort an
31/// analysis run. Presentation is the CLI's decision.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct SkipNotice {
34    /// The file the skip was found in, as ingest saw it.
35    pub path: PathBuf,
36    /// Where in the file the skip lives — a TMDL line number (`line 12`) or a
37    /// JSON pointer — when the parser can name one.
38    pub location: Option<String>,
39    /// What kind of skip this is.
40    pub kind: SkipKind,
41    /// What was skipped and why, in one sentence.
42    pub detail: String,
43}
44
45/// Why a parser skipped something.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum SkipKind {
48    /// An object the AST does not model and the ignore list does not cover.
49    UnknownObject,
50    /// A property the AST does not model and the ignore list does not cover.
51    UnknownProperty,
52    /// A modeled property whose value could not be parsed.
53    MalformedValue,
54    /// A query alias that could not be resolved (PBIR `SourceRef.Source`).
55    UnresolvedAlias,
56    /// Saved or indexed state that refers to objects which no longer exist —
57    /// e.g. a bookmark section whose page was deleted from the report.
58    StaleState,
59}
60
61/// A parsed value plus everything unexpected the parser skipped on the way.
62///
63/// A named wrapper rather than a tuple, so it can grow fields additively —
64/// a parse count, for instance — without breaking every call site.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct Ingested<T> {
67    /// The parsed value.
68    pub value: T,
69    /// Everything the parser skipped, in file order.
70    pub skips: Vec<SkipNotice>,
71}
72
73/// Parses a TMDL semantic model into a [`TabularDatabase`].
74///
75/// `path` is a `.SemanticModel` folder (its `definition/` subfolder is located
76/// automatically) or a `definition/` folder itself. Unknown-but-harmless TMDL
77/// drift is reported in [`Ingested::skips`]; only a file that cannot be parsed
78/// into a tree at all fails with [`Error::Tmdl`].
79///
80/// Table order follows `model.tmdl`'s `ref table` directives; tables present as
81/// files but never referenced are appended in file-name order. The `cultures/`
82/// folder is deliberately not read.
83pub fn semantic_model(path: &Path) -> Result<Ingested<TabularDatabase>> {
84    let definition = locate_definition(path)?;
85    // `.platform` (which carries the display name) sits beside `definition/`.
86    let item_root = definition.parent().unwrap_or(path);
87    let name = platform_display_name(item_root);
88    let mut skips = Vec::new();
89    let value = tmdl::load_database(&definition, name, &mut skips)?;
90    Ok(Ingested { value, skips })
91}
92
93/// Parses a PBIR report folder into a [`ReportModel`].
94///
95/// `path` is a `.Report` folder (its `definition/` subfolder is located
96/// automatically) or a `definition/` folder itself. A report is parsed
97/// standalone: the semantic model it connects to need not sit beside it, so
98/// one model can be scanned against several reports. Unexpected drift is
99/// reported in [`Ingested::skips`]; only an unreadable or malformed
100/// `report.json` — the file that makes the folder a report — fails.
101pub fn report(path: &Path) -> Result<Ingested<ReportModel>> {
102    let definition = locate_report_definition(path)?;
103    // `.platform` (which carries the display name) sits beside `definition/`.
104    let item_root = definition.parent().unwrap_or(path);
105    let name = platform_display_name(item_root);
106    let mut skips = Vec::new();
107    let value = pbir::load_report(&definition, name, &mut skips)?;
108    Ok(Ingested { value, skips })
109}
110
111/// Reads a report item's `definition.pbir` dataset reference without parsing
112/// the rest of the report.
113///
114/// `item_root` is the `.Report` folder (the file sits beside `definition/`).
115/// Intended for callers that must pair many report items cheaply — a folder
116/// walk can read thousands of `definition.pbir` files while only the connected
117/// reports are ingested in full. Unexpected drift is returned as
118/// [`SkipNotice`]s, exactly as [`report`] would record it.
119#[must_use]
120pub fn dataset_reference(item_root: &Path) -> (DatasetReference, Vec<SkipNotice>) {
121    let mut skips = Vec::new();
122    let reference = pbir::dataset_reference(item_root, &mut skips);
123    (reference, skips)
124}
125
126/// Resolves the `definition/` folder of a semantic-model item.
127///
128/// Accepts the `.SemanticModel` folder itself, its `definition/` subfolder, or
129/// any directory that directly contains a `model.tmdl`.
130pub fn locate_definition(path: &Path) -> Result<PathBuf> {
131    if !path.is_dir() {
132        return Err(Error::UnsupportedFormat(format!(
133            "not a semantic model: {} is not a directory",
134            path.display()
135        )));
136    }
137    let nested = path.join("definition");
138    if nested.is_dir() {
139        return Ok(nested);
140    }
141    let looks_like_definition = path.join("model.tmdl").is_file()
142        || path
143            .file_name()
144            .is_some_and(|name| name.eq_ignore_ascii_case("definition"));
145    if looks_like_definition {
146        return Ok(path.to_path_buf());
147    }
148    Err(Error::UnsupportedFormat(format!(
149        "not a semantic model: no definition/ or model.tmdl under {}",
150        path.display()
151    )))
152}
153
154/// Resolves the `definition/` folder of a PBIR report item.
155///
156/// Accepts the `.Report` folder itself, its `definition/` subfolder, or any
157/// directory that directly contains a `report.json`.
158fn locate_report_definition(path: &Path) -> Result<PathBuf> {
159    if !path.is_dir() {
160        return Err(Error::UnsupportedFormat(format!(
161            "not a report: {} is not a directory",
162            path.display()
163        )));
164    }
165    let nested = path.join("definition");
166    if nested.join("report.json").is_file() {
167        return Ok(nested);
168    }
169    if path.join("report.json").is_file() {
170        return Ok(path.to_path_buf());
171    }
172    Err(Error::UnsupportedFormat(format!(
173        "not a report: no definition/report.json or report.json under {}",
174        path.display()
175    )))
176}
177
178/// Reads the item's display name from `.platform`, best-effort.
179///
180/// TMDL itself records no usable model name (`model.tmdl` names its root
181/// object `Model`), so the Fabric item metadata is the only source. Any
182/// absence or drift yields `None` — a name is provenance, never liveness.
183#[must_use]
184pub fn platform_display_name(item_root: &Path) -> Option<String> {
185    let text = fs::read_to_string(item_root.join(".platform")).ok()?;
186    let platform: serde_json::Value = serde_json::from_str(&text).ok()?;
187    platform
188        .get("metadata")?
189        .get("displayName")?
190        .as_str()
191        .map(str::to_string)
192}