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. When the report ships a
99/// phone layout — a `definition.mobile/` folder beside `definition/` — its
100/// pages are parsed into [`ReportModel::mobile_pages`] and bind the model
101/// exactly like desktop pages (issue #49). Unexpected drift is reported in
102/// [`Ingested::skips`]; only an unreadable or malformed `report.json` — the
103/// file that makes the folder a report — fails. A missing or anchor-less
104/// phone layout is the common case and is silent.
105pub fn report(path: &Path) -> Result<Ingested<ReportModel>> {
106    let definition = locate_report_definition(path)?;
107    // `.platform` (which carries the display name) sits beside `definition/`.
108    let item_root = definition.parent().unwrap_or(path);
109    let name = platform_display_name(item_root);
110    let mut skips = Vec::new();
111    let mut value = pbir::load_report(&definition, name, &mut skips)?;
112    if let Some(mobile) = locate_mobile_definition(&definition) {
113        value.mobile_pages = pbir::load_mobile_pages(&mobile, &mut skips);
114    }
115    Ok(Ingested { value, skips })
116}
117
118/// Reads a report item's `definition.pbir` dataset reference without parsing
119/// the rest of the report.
120///
121/// `item_root` is the `.Report` folder (the file sits beside `definition/`).
122/// Intended for callers that must pair many report items cheaply — a folder
123/// walk can read thousands of `definition.pbir` files while only the connected
124/// reports are ingested in full. Unexpected drift is returned as
125/// [`SkipNotice`]s, exactly as [`report`] would record it.
126#[must_use]
127pub fn dataset_reference(item_root: &Path) -> (DatasetReference, Vec<SkipNotice>) {
128    let mut skips = Vec::new();
129    let reference = pbir::dataset_reference(item_root, &mut skips);
130    (reference, skips)
131}
132
133/// Resolves the `definition/` folder of a semantic-model item.
134///
135/// Accepts the `.SemanticModel` folder itself, its `definition/` subfolder, or
136/// any directory that directly contains a `model.tmdl`.
137pub fn locate_definition(path: &Path) -> Result<PathBuf> {
138    if !path.is_dir() {
139        return Err(Error::UnsupportedFormat(format!(
140            "not a semantic model: {} is not a directory",
141            path.display()
142        )));
143    }
144    let nested = path.join("definition");
145    if nested.is_dir() {
146        return Ok(nested);
147    }
148    let looks_like_definition = path.join("model.tmdl").is_file()
149        || path
150            .file_name()
151            .is_some_and(|name| name.eq_ignore_ascii_case("definition"));
152    if looks_like_definition {
153        return Ok(path.to_path_buf());
154    }
155    Err(Error::UnsupportedFormat(format!(
156        "not a semantic model: no definition/ or model.tmdl under {}",
157        path.display()
158    )))
159}
160
161/// Resolves the `definition/` folder of a PBIR report item.
162///
163/// Accepts the `.Report` folder itself, its `definition/` subfolder, or any
164/// directory that directly contains a `report.json`.
165fn locate_report_definition(path: &Path) -> Result<PathBuf> {
166    if !path.is_dir() {
167        return Err(Error::UnsupportedFormat(format!(
168            "not a report: {} is not a directory",
169            path.display()
170        )));
171    }
172    let nested = path.join("definition");
173    if nested.join("report.json").is_file() {
174        return Ok(nested);
175    }
176    if path.join("report.json").is_file() {
177        return Ok(path.to_path_buf());
178    }
179    Err(Error::UnsupportedFormat(format!(
180        "not a report: no definition/report.json or report.json under {}",
181        path.display()
182    )))
183}
184
185/// Resolves the `definition.mobile/` phone layout of a report item, if it
186/// ships one.
187///
188/// The layout is optional and anchor-less — unlike `definition/`, it carries
189/// no `report.json` — so presence is decided by its `pages/` folder, and any
190/// absence is silent, never drift.
191fn locate_mobile_definition(definition: &Path) -> Option<PathBuf> {
192    let mobile = definition.parent()?.join("definition.mobile");
193    if mobile.join("pages").is_dir() {
194        Some(mobile)
195    } else {
196        None
197    }
198}
199
200/// Reads the item's display name from `.platform`, best-effort.
201///
202/// TMDL itself records no usable model name (`model.tmdl` names its root
203/// object `Model`), so the Fabric item metadata is the only source. Any
204/// absence or drift yields `None` — a name is provenance, never liveness.
205#[must_use]
206pub fn platform_display_name(item_root: &Path) -> Option<String> {
207    let text = fs::read_to_string(item_root.join(".platform")).ok()?;
208    let platform: serde_json::Value = serde_json::from_str(&text).ok()?;
209    platform
210        .get("metadata")?
211        .get("displayName")?
212        .as_str()
213        .map(str::to_string)
214}