dsp_cli/model/vocabulary.rs
1//! Vocabulary domain shapes — shared across the client → action → render
2//! boundary for `dsp vre vocabulary list` / `describe` (DSP-API "list" /
3//! "list node").
4//!
5//! Types here are the dsp-cli vocabulary for DSP-API's list/list-node wire
6//! shapes. Wire (de)serialization stays in `src/client/http.rs`; nothing
7//! here derives `serde`. See dsp-cli/ADR-0001 and dsp-cli/ADR-0008.
8
9/// One language-tagged string, as DSP-API returns it in a list's `labels` /
10/// `comments`. ALL languages are kept (plan 034 D4) — no preferred-language
11/// collapsing anywhere in this crate. `language` is `None` for DSP-API's
12/// untagged `PlainStringLiteralV2` variant (D9b).
13///
14/// Same shape as [`ProjectDescription`]; deliberately not consolidated with
15/// it — see the plan's BACKLOG note. `language` stays `Option<String>`
16/// rather than a closed `Language` enum, even though D9 proves the server's
17/// tag set is closed at exactly `{de, en, fr, it, rm}`: mirroring the
18/// existing `ProjectDescription` precedent means an unexpected tag stays a
19/// value the CLI can still display, rather than becoming a hard parse error
20/// (`ServerError`). Reads should degrade, not refuse.
21///
22/// [`ProjectDescription`]: crate::model::ProjectDescription
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct LocalizedText {
25 /// The label/comment text.
26 pub value: String,
27 /// BCP-47-shaped language tag, if the server provides one (e.g. `"en"`).
28 pub language: Option<String>,
29}
30
31/// Identity + labels of a vocabulary or one of its nodes. No children, no
32/// counts — those live on [`Vocabulary`] / [`VocabularyNode`] / [`VocabularyTree`].
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct VocabularyHeader {
35 /// The vocabulary's or node's IRI (e.g. `http://rdfh.ch/lists/0838/…`).
36 pub iri: String,
37 /// Human-readable short name, if the server supplies one.
38 pub name: Option<String>,
39 /// Language-tagged labels (D4: all languages kept, no preference rule).
40 pub labels: Vec<LocalizedText>,
41 /// Language-tagged comments (D7: carried, out of the default column set).
42 pub comments: Vec<LocalizedText>,
43}
44
45/// A vocabulary as shown by `dsp vre vocabulary list` — the lean list-index
46/// projection.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct Vocabulary {
49 pub header: VocabularyHeader,
50 /// `Some` only when `--count` fetched this vocabulary's tree; `None`
51 /// when a per-tree fetch failed (disclosed to the caller, not silently
52 /// dropped). Counts nodes strictly BELOW the root — the root itself is
53 /// never a node.
54 pub node_count: Option<usize>,
55 /// `Some` only under `--count`. Deepest level; the root's direct
56 /// children sit at level 1.
57 pub depth: Option<usize>,
58}
59
60/// One node in a vocabulary's tree, as returned by the DSP-API
61/// (position-sorted by the server; the client re-sorts defensively).
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct VocabularyNode {
64 pub header: VocabularyHeader,
65 /// Raw, 0-based DSP-API `position` among siblings. NOT the 1-based
66 /// outline `number` the renderer derives (D10) — kept unchanged here so
67 /// `--columns position` still shows the untranslated wire value.
68 pub position: i32,
69 pub children: Vec<VocabularyNode>,
70}
71
72/// What the CLIENT returns from `describe_vocabulary`: a faithful,
73/// position-ordered tree plus the facts the wire response carried. Holds NO
74/// rendered-counts and no render decisions — structurally, since it has no
75/// such fields, the client cannot express them even by accident. [`VocabularyDetail`]
76/// is where those decisions live (Step 3's layer-ownership split).
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct VocabularyTree {
79 pub root: VocabularyHeader,
80 /// The WHOLE tree, always — never pruned. Absolute `number` (D10) and
81 /// `path` (D11) are derived from each node's ancestor chain, which
82 /// pruning would destroy.
83 pub children: Vec<VocabularyNode>,
84 /// From `listinfo.projectIri`, which a root response ALWAYS carries — so
85 /// this is never absent and the cross-project guard never has to fail
86 /// open.
87 pub project_iri: String,
88 /// Set when the address that was resolved turned out to be a NODE, not a
89 /// root: the client is the layer that saw the `Node` response shape
90 /// (D2), so it is the layer that records this.
91 pub requested_node: Option<String>,
92}
93
94/// What the ACTION hands the renderer for `describe`: the tree plus the
95/// render decisions only the action can make, because only it sees `--subtree`.
96///
97/// The split is deliberate and is what makes the layer ownership structural
98/// rather than a convention: `describe_vocabulary` (the client) returns a
99/// bare [`VocabularyTree`], so the client has no `node_count` field to fill
100/// in even by accident.
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct VocabularyDetail {
103 pub tree: VocabularyTree,
104 /// Set by the action from `--subtree` (D14): the node IRI to narrow
105 /// RENDERING to. `None` renders the whole vocabulary.
106 pub subtree_of: Option<String>,
107 /// Nodes RENDERED (honouring `subtree_of`). Equals the tabular data-row
108 /// count in both whole-vocabulary and `--subtree` mode (D15). Computed
109 /// by the action via [`VocabularyTree::count_and_depth`].
110 pub node_count: usize,
111 /// Deepest level of what is RENDERED (a root's direct children sit at
112 /// level 1). Under `--subtree` this is branch-relative — the addressed
113 /// node itself is level 1 of its own branch, so a leaf renders `1 node ·
114 /// 1 level`. The per-node `depth` COLUMN the renderer derives separately
115 /// stays absolute, so it never disagrees with `number`'s segment count.
116 pub depth: usize,
117}
118
119impl VocabularyTree {
120 /// Count nodes and measure depth at or below the node named by `from`
121 /// (the whole tree when `from` is `None`).
122 ///
123 /// Shared derivation used by BOTH `list --count` and `describe`, so one
124 /// walk has one implementation — the thing that makes the D15 invariant
125 /// hold (`node_count` equals the rendered data-row count in both modes).
126 ///
127 /// - `from: None` — whole-vocabulary mode. The root itself is never a node, so it is not
128 /// counted; `depth` treats the root's direct children as level 1.
129 /// - `from: Some(iri)` — branch mode (`--subtree`). The addressed node IS included, as the top
130 /// of its own branch (D14b): a leaf node yields `(1, 1)` — one node, one level, because the
131 /// node itself occupies level 1 of the branch, its children level 2, and so on. If `iri` does
132 /// not address any node in this tree, returns `(0, 0)` (the action layer validates that
133 /// `--subtree`'s address names a node present in the tree before calling this, so that case
134 /// should not arise from user input — this is a defensive default, not user-facing
135 /// behaviour).
136 ///
137 /// This is not on the untrusted-input parse path (that's
138 /// `src/client/http.rs`, which must walk iteratively) — it walks a tree
139 /// that already survived deserialisation, so plain recursion is fine;
140 /// real data tops out at 9 levels.
141 pub fn count_and_depth(&self, from: Option<&str>) -> (usize, usize) {
142 match from {
143 None => {
144 let mut count = 0;
145 let mut depth = 0;
146 for child in &self.children {
147 let (child_count, child_height) = subtree_stats(child);
148 count += child_count;
149 depth = depth.max(child_height);
150 }
151 (count, depth)
152 }
153 Some(iri) => match find_node(&self.children, iri) {
154 Some(node) => subtree_stats(node),
155 None => (0, 0),
156 },
157 }
158 }
159}
160
161/// Node count and height of the subtree rooted at `node`, INCLUSIVE of
162/// `node` itself: a leaf returns `(1, 1)`.
163fn subtree_stats(node: &VocabularyNode) -> (usize, usize) {
164 let mut count = 1;
165 let mut max_child_height = 0;
166 for child in &node.children {
167 let (child_count, child_height) = subtree_stats(child);
168 count += child_count;
169 max_child_height = max_child_height.max(child_height);
170 }
171 (count, 1 + max_child_height)
172}
173
174/// Depth-first search for the node whose header IRI equals `iri`, anywhere
175/// in `nodes` or their descendants.
176fn find_node<'a>(nodes: &'a [VocabularyNode], iri: &str) -> Option<&'a VocabularyNode> {
177 for node in nodes {
178 if node.header.iri == iri {
179 return Some(node);
180 }
181 if let Some(found) = find_node(&node.children, iri) {
182 return Some(found);
183 }
184 }
185 None
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191
192 fn header(iri: &str) -> VocabularyHeader {
193 VocabularyHeader {
194 iri: iri.to_string(),
195 name: Some(iri.to_string()),
196 labels: vec![LocalizedText { value: iri.to_string(), language: Some("en".into()) }],
197 comments: vec![],
198 }
199 }
200
201 fn leaf(iri: &str, position: i32) -> VocabularyNode {
202 VocabularyNode { header: header(iri), position, children: vec![] }
203 }
204
205 /// Builds:
206 /// ```text
207 /// root
208 /// 1 node1 (leaf)
209 /// 2 node2
210 /// 2.1 node2a (leaf)
211 /// 2.2 node2b
212 /// 2.2.1 node2b1 (leaf)
213 /// ```
214 /// 5 nodes total; deepest level is 3 (node2 -> node2b -> node2b1).
215 fn fixture_tree() -> VocabularyTree {
216 let node2b1 = leaf("node2b1", 0);
217 let node2b = VocabularyNode {
218 header: header("node2b"),
219 position: 1,
220 children: vec![node2b1],
221 };
222 let node2a = leaf("node2a", 0);
223 let node2 = VocabularyNode {
224 header: header("node2"),
225 position: 1,
226 children: vec![node2a, node2b],
227 };
228 let node1 = leaf("node1", 0);
229 VocabularyTree {
230 root: header("root"),
231 children: vec![node1, node2],
232 project_iri: "http://rdfh.ch/projects/0001".into(),
233 requested_node: None,
234 }
235 }
236
237 #[test]
238 fn count_and_depth_whole_tree() {
239 let tree = fixture_tree();
240 let (count, depth) = tree.count_and_depth(None);
241 // 5 real nodes; root itself is not counted.
242 assert_eq!(count, 5);
243 // node1 is level 1; node2/node2a level 1/2; node2b1 level 3.
244 assert_eq!(depth, 3);
245 }
246
247 #[test]
248 fn count_and_depth_subtree_of_non_root_branch() {
249 let tree = fixture_tree();
250 // node2's own branch: node2, node2a, node2b, node2b1 = 4 nodes.
251 let (count, depth) = tree.count_and_depth(Some("node2"));
252 assert_eq!(count, 4);
253 // node2 itself is level 1 of its branch, node2b1 is level 3.
254 assert_eq!(depth, 3);
255 }
256
257 #[test]
258 fn count_and_depth_subtree_of_leaf_yields_one_node_one_level() {
259 let tree = fixture_tree();
260 // D14b: the addressed node is included, as the top of its branch.
261 let (count, depth) = tree.count_and_depth(Some("node2a"));
262 assert_eq!(count, 1);
263 assert_eq!(depth, 1);
264 }
265
266 #[test]
267 fn count_and_depth_subtree_of_intermediate_branch() {
268 let tree = fixture_tree();
269 // node2b's branch: node2b, node2b1 = 2 nodes, 2 levels.
270 let (count, depth) = tree.count_and_depth(Some("node2b"));
271 assert_eq!(count, 2);
272 assert_eq!(depth, 2);
273 }
274
275 #[test]
276 fn count_and_depth_unknown_iri_returns_zero() {
277 let tree = fixture_tree();
278 let (count, depth) = tree.count_and_depth(Some("does-not-exist"));
279 assert_eq!(count, 0);
280 assert_eq!(depth, 0);
281 }
282
283 #[test]
284 fn position_ordering_is_preserved_as_given() {
285 // This model does no sorting itself (the client sorts defensively by
286 // `position` before building the tree); this test just confirms the
287 // field and `Vec` order carry through unchanged.
288 let children = vec![leaf("a", 0), leaf("b", 1), leaf("c", 2)];
289 let parent = VocabularyNode { header: header("parent"), position: 0, children };
290 assert_eq!(parent.children[0].header.iri, "a");
291 assert_eq!(parent.children[0].position, 0);
292 assert_eq!(parent.children[1].header.iri, "b");
293 assert_eq!(parent.children[1].position, 1);
294 assert_eq!(parent.children[2].header.iri, "c");
295 assert_eq!(parent.children[2].position, 2);
296 }
297
298 /// D15: `node_count` equals the rendered data-row count in BOTH
299 /// whole-vocabulary and `--subtree` mode. Here we hand-count the fixture
300 /// tree's nodes for each mode and assert `count_and_depth` agrees.
301 #[test]
302 fn d15_node_count_matches_manually_counted_rendered_rows() {
303 let tree = fixture_tree();
304
305 // Whole-vocabulary mode: every real node is a rendered row.
306 let whole_vocabulary_rows = ["node1", "node2", "node2a", "node2b", "node2b1"];
307 let (whole_count, _) = tree.count_and_depth(None);
308 assert_eq!(whole_count, whole_vocabulary_rows.len());
309
310 // `--subtree`-equivalent mode narrowed to node2: node2 and its
311 // descendants are the rendered rows.
312 let subtree_rows = ["node2", "node2a", "node2b", "node2b1"];
313 let (subtree_count, _) = tree.count_and_depth(Some("node2"));
314 assert_eq!(subtree_count, subtree_rows.len());
315
316 // `--subtree`-equivalent mode narrowed to a leaf: exactly one
317 // rendered row — the leaf itself.
318 let leaf_rows = ["node2a"];
319 let (leaf_count, _) = tree.count_and_depth(Some("node2a"));
320 assert_eq!(leaf_count, leaf_rows.len());
321 }
322
323 #[test]
324 fn localized_text_construction_and_equality() {
325 let a = LocalizedText { value: "Period".into(), language: Some("en".into()) };
326 let b = a.clone();
327 assert_eq!(a, b);
328 assert_eq!(a.value, "Period");
329 assert_eq!(a.language.as_deref(), Some("en"));
330 }
331
332 #[test]
333 fn localized_text_untagged() {
334 let a = LocalizedText { value: "untagged".into(), language: None };
335 assert_eq!(a.language, None);
336 }
337
338 #[test]
339 fn vocabulary_node_count_none_before_count_flag() {
340 let vocab = Vocabulary { header: header("vocab"), node_count: None, depth: None };
341 assert_eq!(vocab.node_count, None);
342 assert_eq!(vocab.depth, None);
343 }
344
345 #[test]
346 fn vocabulary_tree_requested_node_default_none() {
347 let tree = fixture_tree();
348 assert_eq!(tree.requested_node, None);
349 assert_eq!(tree.project_iri, "http://rdfh.ch/projects/0001");
350 }
351
352 #[test]
353 fn vocabulary_detail_construction_and_equality() {
354 let tree = fixture_tree();
355 let (node_count, depth) = tree.count_and_depth(None);
356 let detail = VocabularyDetail { tree: tree.clone(), subtree_of: None, node_count, depth };
357 let cloned = detail.clone();
358 assert_eq!(detail, cloned);
359 assert_eq!(detail.node_count, 5);
360 assert_eq!(detail.depth, 3);
361 assert_eq!(detail.subtree_of, None);
362 }
363}