1use std::collections::BTreeMap;
14use std::io::Write;
15use std::ops::Bound::{Included, Unbounded};
16
17use serde::{Deserialize, Serialize};
18use serde_json::{json, Value};
19
20use khive_storage::{BlobStore, ContentRef};
21
22use crate::{KhiveRuntime, RuntimeError};
23
24pub const TREE_SCHEMA: &str = "khive-tree/v1";
25
26pub const SCOPED_TREE_SCHEMA: &str = "khive-tree/scoped-v1";
28
29pub const MAX_SCOPE_PATHS: usize = 64;
31
32pub const MAX_MANIFEST_BYTES: u64 = 8 * 1024 * 1024;
34
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36pub struct TreeEntry {
37 pub path: String,
38 #[serde(rename = "ref")]
39 pub content_ref: String,
40 pub mode: u32,
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
44struct Manifest {
45 schema: String,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
48 scope: Option<Vec<String>>,
49 entries: Vec<TreeEntry>,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct Tree {
55 pub entries: Vec<TreeEntry>,
56 pub scope: Option<Vec<String>>,
58}
59
60pub fn validate_relative_path(path: &str, what: &str) -> Result<String, RuntimeError> {
63 if path.is_empty() {
64 return Err(RuntimeError::InvalidInput(format!("{what} path is empty")));
65 }
66 if path.starts_with('/') {
67 return Err(RuntimeError::InvalidInput(format!(
68 "{what} path {path:?} is absolute; paths are relative to the tree root"
69 )));
70 }
71 if path.contains('\0') || path.contains('\\') {
72 return Err(RuntimeError::InvalidInput(format!(
73 "{what} path {path:?} contains a forbidden character"
74 )));
75 }
76 for component in path.split('/') {
77 if component.is_empty() || component == "." || component == ".." {
78 return Err(RuntimeError::InvalidInput(format!(
79 "{what} path {path:?} is not normalized (empty, '.' or '..' component)"
80 )));
81 }
82 }
83 Ok(path.to_string())
84}
85
86pub fn canonical_scope(paths: &[String]) -> Result<Vec<String>, RuntimeError> {
89 if paths.is_empty() || paths.len() > MAX_SCOPE_PATHS {
90 return Err(RuntimeError::InvalidInput(format!(
91 "a tree scope names 1 to {MAX_SCOPE_PATHS} paths; this one names {}",
92 paths.len()
93 )));
94 }
95 let mut sorted = paths
96 .iter()
97 .map(|path| validate_relative_path(path, "scope"))
98 .collect::<Result<Vec<_>, _>>()?;
99 sorted.sort();
100 for (index, path) in sorted.iter().enumerate() {
101 for other in &sorted[index + 1..] {
102 if other == path {
103 return Err(RuntimeError::InvalidInput(format!(
104 "scope names {path:?} twice"
105 )));
106 }
107 if other.starts_with(path.as_str()) && other.as_bytes()[path.len()] == b'/' {
108 return Err(RuntimeError::InvalidInput(format!(
109 "scope path {other:?} is beneath scope path {path:?}"
110 )));
111 }
112 }
113 }
114 Ok(sorted)
115}
116
117pub fn parse_entries(value: &Value) -> Result<Vec<TreeEntry>, RuntimeError> {
120 let items = value.as_array().ok_or_else(|| {
121 RuntimeError::InvalidInput("entries must be an array of {path, ref, mode}".into())
122 })?;
123 let mut seen = EntryIndex::default();
124 for item in items {
125 let path = item
126 .get("path")
127 .and_then(Value::as_str)
128 .ok_or_else(|| RuntimeError::InvalidInput("entry.path must be a string".into()))?;
129 let path = validate_relative_path(path, "entry")?;
130 let content_ref = item
131 .get("ref")
132 .and_then(Value::as_str)
133 .ok_or_else(|| RuntimeError::InvalidInput("entry.ref must be a string".into()))?;
134 ContentRef::from_hex(content_ref)
135 .map_err(|e| RuntimeError::InvalidInput(format!("entry {path:?} ref: {e}")))?;
136 let mode = item.get("mode").and_then(Value::as_u64).ok_or_else(|| {
137 RuntimeError::InvalidInput("entry.mode must be 644, 755 or 120000".into())
138 })?;
139 if !matches!(mode, 644 | 755 | 120000) {
140 return Err(RuntimeError::InvalidInput(format!(
141 "entry {path:?} mode must be 644, 755 or 120000; got {mode}"
142 )));
143 }
144 insert_entry(
145 &mut seen,
146 TreeEntry {
147 path,
148 content_ref: content_ref.to_string(),
149 mode: mode as u32,
150 },
151 )?;
152 }
153 Ok(seen.into_sorted_entries())
154}
155
156fn validate_entries(entries: &[TreeEntry]) -> Result<Vec<TreeEntry>, RuntimeError> {
158 let mut seen = EntryIndex::default();
159 for entry in entries {
160 let path = validate_relative_path(&entry.path, "entry")?;
161 ContentRef::from_hex(&entry.content_ref)
162 .map_err(|e| RuntimeError::InvalidInput(format!("entry {path:?} ref: {e}")))?;
163 if !matches!(entry.mode, 644 | 755 | 120000) {
164 return Err(RuntimeError::InvalidInput(format!(
165 "entry {path:?} mode must be 644, 755 or 120000; got {}",
166 entry.mode
167 )));
168 }
169 insert_entry(&mut seen, entry.clone())?;
170 }
171 Ok(seen.into_sorted_entries())
172}
173
174#[derive(Default)]
175struct EntryIndex {
176 entries: BTreeMap<String, TreeEntry>,
177 prefixes: PrefixIndex,
178 work: PrefixWork,
179}
180
181impl EntryIndex {
182 fn into_sorted_entries(self) -> Vec<TreeEntry> {
183 self.entries.into_values().collect()
184 }
185}
186
187#[derive(Default)]
188struct PrefixWork {
189 #[cfg(any(test, feature = "test-internals"))]
190 compared_bytes: usize,
191 #[cfg(any(test, feature = "test-internals"))]
192 child_lookups: usize,
193 #[cfg(any(test, feature = "test-internals"))]
194 ordered_probes: usize,
195 #[cfg(any(test, feature = "test-internals"))]
196 copied_label_bytes: usize,
197}
198
199impl PrefixWork {
200 #[inline]
201 fn copied_label(&mut self, bytes: usize) {
202 #[cfg(any(test, feature = "test-internals"))]
203 {
204 self.copied_label_bytes += bytes;
205 }
206 #[cfg(not(any(test, feature = "test-internals")))]
207 let _ = (self, bytes);
208 }
209
210 #[inline]
211 fn comparison(&mut self, bytes: usize) {
212 #[cfg(any(test, feature = "test-internals"))]
213 {
214 self.compared_bytes += bytes;
215 }
216 #[cfg(not(any(test, feature = "test-internals")))]
217 let _ = (self, bytes);
218 }
219
220 #[inline]
221 fn lookup(&mut self) {
222 #[cfg(any(test, feature = "test-internals"))]
223 {
224 self.child_lookups += 1;
225 }
226 #[cfg(not(any(test, feature = "test-internals")))]
227 let _ = self;
228 }
229
230 #[inline]
231 fn ordered_probe(&mut self) {
232 #[cfg(any(test, feature = "test-internals"))]
233 {
234 self.ordered_probes += 1;
235 }
236 #[cfg(not(any(test, feature = "test-internals")))]
237 let _ = self;
238 }
239}
240
241struct PrefixEdge {
242 label: String,
243 child: usize,
244}
245
246#[derive(Default)]
247struct PrefixNode {
248 children: BTreeMap<char, PrefixEdge>,
249 entry: bool,
250}
251
252struct PrefixIndex {
255 nodes: Vec<PrefixNode>,
256}
257
258impl Default for PrefixIndex {
259 fn default() -> Self {
260 Self {
261 nodes: vec![PrefixNode::default()],
262 }
263 }
264}
265
266impl PrefixIndex {
267 fn first_parent<'a>(&self, path: &'a str, work: &mut PrefixWork) -> Option<&'a str> {
268 self.first_prefix(path, false, work)
269 }
270
271 fn first_prefix<'a>(
272 &self,
273 path: &'a str,
274 include_exact: bool,
275 work: &mut PrefixWork,
276 ) -> Option<&'a str> {
277 let mut node = 0;
278 let mut consumed = 0;
279 loop {
280 let remaining = &path[consumed..];
281 if self.nodes[node].entry
282 && (remaining.starts_with('/') || (include_exact && remaining.is_empty()))
283 {
284 return Some(&path[..consumed]);
285 }
286 let first = remaining.chars().next()?;
287 work.lookup();
288 let edge = self.nodes[node].children.get(&first)?;
289 let common = common_prefix_bytes(remaining, &edge.label, work);
290 if common != edge.label.len() {
291 return None;
292 }
293 consumed += common;
294 node = edge.child;
295 }
296 }
297
298 fn insert(&mut self, path: &str, work: &mut PrefixWork) {
299 let mut node = 0;
300 let mut consumed = 0;
301 loop {
302 let remaining = &path[consumed..];
303 let Some(first) = remaining.chars().next() else {
304 self.nodes[node].entry = true;
305 return;
306 };
307 work.lookup();
308 let Some(edge) = self.nodes[node].children.get(&first) else {
309 work.copied_label(remaining.len());
310 let child = self.nodes.len();
311 self.nodes.push(PrefixNode {
312 entry: true,
313 ..PrefixNode::default()
314 });
315 self.nodes[node].children.insert(
316 first,
317 PrefixEdge {
318 label: remaining.to_string(),
319 child,
320 },
321 );
322 return;
323 };
324 let common = common_prefix_bytes(remaining, &edge.label, work);
325 if common == edge.label.len() {
326 consumed += common;
327 node = edge.child;
328 continue;
329 }
330
331 let mut edge = self.nodes[node]
334 .children
335 .remove(&first)
336 .expect("edge exists");
337 work.copied_label(edge.label.len() - common);
338 let old_suffix = edge.label.split_off(common);
339 let middle = self.nodes.len();
340 let mut middle_node = PrefixNode::default();
341 middle_node.children.insert(
342 old_suffix.chars().next().expect("nonempty suffix"),
343 PrefixEdge {
344 label: old_suffix,
345 child: edge.child,
346 },
347 );
348 self.nodes.push(middle_node);
349 edge.child = middle;
350 self.nodes[node].children.insert(first, edge);
351 if common == remaining.len() {
352 self.nodes[middle].entry = true;
353 } else {
354 let suffix = &remaining[common..];
355 work.copied_label(suffix.len());
356 let child = self.nodes.len();
357 self.nodes.push(PrefixNode {
358 entry: true,
359 ..PrefixNode::default()
360 });
361 self.nodes[middle].children.insert(
362 suffix.chars().next().expect("nonempty suffix"),
363 PrefixEdge {
364 label: suffix.to_string(),
365 child,
366 },
367 );
368 }
369 return;
370 }
371 }
372}
373
374pub struct PathCoverage {
377 prefixes: PrefixIndex,
378 #[cfg(any(test, feature = "test-internals"))]
379 build_work: PrefixWorkSnapshot,
380}
381
382#[cfg(any(test, feature = "test-internals"))]
384#[doc(hidden)]
385#[derive(Clone, Copy, Debug, Default)]
386pub struct PrefixWorkSnapshot {
387 pub compared_bytes: usize,
388 pub child_lookups: usize,
389 pub copied_label_bytes: usize,
390}
391
392#[cfg(any(test, feature = "test-internals"))]
393impl PrefixWork {
394 fn snapshot(&self) -> PrefixWorkSnapshot {
395 PrefixWorkSnapshot {
396 compared_bytes: self.compared_bytes,
397 child_lookups: self.child_lookups,
398 copied_label_bytes: self.copied_label_bytes,
399 }
400 }
401}
402
403impl PathCoverage {
404 pub fn new(paths: &[String]) -> Self {
405 let mut ordered: Vec<&str> = paths.iter().map(String::as_str).collect();
406 ordered.sort_by_key(|path| path.len());
409 let mut prefixes = PrefixIndex::default();
410 let mut build = PrefixWork::default();
411 for path in ordered {
412 prefixes.insert(path, &mut build);
413 }
414 Self {
415 prefixes,
416 #[cfg(any(test, feature = "test-internals"))]
417 build_work: build.snapshot(),
418 }
419 }
420
421 pub fn covers(&self, path: &str) -> bool {
422 self.prefixes
423 .first_prefix(path, true, &mut PrefixWork::default())
424 .is_some()
425 }
426
427 #[cfg(any(test, feature = "test-internals"))]
428 #[doc(hidden)]
429 pub fn build_work(&self) -> PrefixWorkSnapshot {
430 self.build_work
431 }
432
433 #[cfg(any(test, feature = "test-internals"))]
434 #[doc(hidden)]
435 pub fn covers_with_work(&self, path: &str) -> (bool, PrefixWorkSnapshot) {
436 let mut query = PrefixWork::default();
437 let covered = self.prefixes.first_prefix(path, true, &mut query).is_some();
438 (covered, query.snapshot())
439 }
440}
441
442fn common_prefix_bytes(left: &str, right: &str, work: &mut PrefixWork) -> usize {
443 let mut common = 0;
444 for (a, b) in left.chars().zip(right.chars()) {
445 work.comparison(a.len_utf8().max(b.len_utf8()));
446 if a != b {
447 break;
448 }
449 common += a.len_utf8();
450 }
451 common
452}
453
454fn insert_entry(seen: &mut EntryIndex, entry: TreeEntry) -> Result<(), RuntimeError> {
457 let path = &entry.path;
458 seen.work.ordered_probe();
459 if seen.entries.contains_key(path) {
460 return Err(RuntimeError::InvalidInput(format!(
461 "duplicate entry path {path:?}"
462 )));
463 }
464 if let Some(existing) = seen.prefixes.first_parent(path, &mut seen.work) {
466 return Err(RuntimeError::InvalidInput(format!(
467 "entry {path:?} conflicts with entry {existing:?} (file and directory at one path)"
468 )));
469 }
470 let prefix = format!("{path}/");
471 seen.work.ordered_probe();
472 if let Some((existing, _)) = seen
473 .entries
474 .range::<str, _>((Included(prefix.as_str()), Unbounded))
475 .next()
476 {
477 if existing.starts_with(&prefix) {
478 return Err(RuntimeError::InvalidInput(format!(
479 "entry {path:?} conflicts with entry {existing:?} (file and directory at one path)"
480 )));
481 }
482 }
483 seen.prefixes.insert(path, &mut seen.work);
484 seen.work.ordered_probe();
485 seen.entries.insert(entry.path.clone(), entry);
486 Ok(())
487}
488
489#[cfg(test)]
490fn canonical_bytes(entries: &[TreeEntry]) -> Result<Vec<u8>, RuntimeError> {
491 manifest_bytes(entries, None)
492}
493
494fn manifest_bytes(
498 entries: &[TreeEntry],
499 scope: Option<&[String]>,
500) -> Result<Vec<u8>, RuntimeError> {
501 let mut sorted: Vec<TreeEntry> = entries.to_vec();
502 sorted.sort_by(|a, b| a.path.cmp(&b.path));
503 let manifest = Manifest {
504 schema: if scope.is_some() {
505 SCOPED_TREE_SCHEMA
506 } else {
507 TREE_SCHEMA
508 }
509 .to_string(),
510 scope: scope.map(<[String]>::to_vec),
511 entries: sorted,
512 };
513 struct BoundedWriter {
514 bytes: Vec<u8>,
515 exceeded: bool,
516 }
517 impl Write for BoundedWriter {
518 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
519 if self.bytes.len().saturating_add(buf.len()) > MAX_MANIFEST_BYTES as usize {
520 self.exceeded = true;
521 return Err(std::io::Error::new(
522 std::io::ErrorKind::InvalidData,
523 "tree manifest exceeds load limit",
524 ));
525 }
526 self.bytes.extend_from_slice(buf);
527 Ok(buf.len())
528 }
529
530 fn flush(&mut self) -> std::io::Result<()> {
531 Ok(())
532 }
533 }
534 let mut writer = BoundedWriter {
535 bytes: Vec::new(),
536 exceeded: false,
537 };
538 serde_json::to_writer(&mut writer, &manifest).map_err(|error| {
539 if writer.exceeded {
540 RuntimeError::InvalidInput(format!(
541 "tree manifest exceeds {MAX_MANIFEST_BYTES}-byte load limit"
542 ))
543 } else {
544 RuntimeError::InvalidInput(format!("tree manifest serialization failed: {error}"))
545 }
546 })?;
547 Ok(writer.bytes)
548}
549
550pub fn blob_store(rt: &KhiveRuntime) -> Result<std::sync::Arc<dyn BlobStore>, RuntimeError> {
551 rt.blob_store().ok_or_else(|| {
552 RuntimeError::Unconfigured("no blob store is configured for this runtime".into())
553 })
554}
555
556pub async fn store_from_value(rt: &KhiveRuntime, entries: &Value) -> Result<String, RuntimeError> {
558 let entries = parse_entries(entries)?;
559 store(rt, &entries).await
560}
561
562pub async fn store(rt: &KhiveRuntime, entries: &[TreeEntry]) -> Result<String, RuntimeError> {
564 store_tree(rt, entries, None).await
565}
566
567pub async fn store_tree(
570 rt: &KhiveRuntime,
571 entries: &[TreeEntry],
572 scope: Option<&[String]>,
573) -> Result<String, RuntimeError> {
574 let scope = scope.map(canonical_scope).transpose()?;
575 let entries = validate_entries(entries)?;
576 let bytes = manifest_bytes(&entries, scope.as_deref())?;
577 let store = blob_store(rt)?;
578 let content_ref = store.put(bytes).await?;
579 Ok(content_ref.as_str().to_string())
580}
581
582pub async fn load(rt: &KhiveRuntime, tree_ref: &str) -> Result<Vec<TreeEntry>, RuntimeError> {
587 let tree = load_tree(rt, tree_ref).await?;
588 match tree.scope {
589 None => Ok(tree.entries),
590 Some(scope) => Err(RuntimeError::InvalidInput(format!(
591 "tree {tree_ref} is scoped to {}; this operation reads only whole trees",
592 scope.join(", ")
593 ))),
594 }
595}
596
597pub async fn load_tree(rt: &KhiveRuntime, tree_ref: &str) -> Result<Tree, RuntimeError> {
600 let content_ref = ContentRef::from_hex(tree_ref)
601 .map_err(|e| RuntimeError::InvalidInput(format!("tree ref {tree_ref:?}: {e}")))?;
602 let store = blob_store(rt)?;
603 if !store.exists(&content_ref).await? {
604 return Err(RuntimeError::NotFound(format!(
605 "tree {tree_ref} is not in the blob store"
606 )));
607 }
608 let hydrator = rt
609 .blob_hydrator()
610 .ok_or_else(|| RuntimeError::Unconfigured("exec blob hydrator is not installed".into()))?;
611 let bytes = hydrator
612 .hydrate_verified(&content_ref, MAX_MANIFEST_BYTES)
613 .await?;
614 let manifest: Manifest = serde_json::from_slice(bytes.bytes()).map_err(|e| {
615 RuntimeError::InvalidInput(format!("tree {tree_ref} is not a khive-tree manifest: {e}"))
616 })?;
617 drop(bytes);
618 let scope = match (manifest.schema.as_str(), manifest.scope) {
619 (TREE_SCHEMA, None) => None,
620 (SCOPED_TREE_SCHEMA, Some(scope)) => {
621 let canonical = canonical_scope(&scope).map_err(|error| match error {
622 RuntimeError::InvalidInput(text) => {
623 RuntimeError::InvalidInput(format!("tree {tree_ref}: {text}"))
624 }
625 other => other,
626 })?;
627 if canonical != scope {
628 return Err(RuntimeError::InvalidInput(format!(
629 "tree {tree_ref} lists its scope out of canonical order"
630 )));
631 }
632 Some(canonical)
633 }
634 (TREE_SCHEMA, Some(_)) => {
635 return Err(RuntimeError::InvalidInput(format!(
636 "tree {tree_ref} has schema {TREE_SCHEMA:?} and a scope; a whole tree carries none"
637 )));
638 }
639 (SCOPED_TREE_SCHEMA, None) => {
640 return Err(RuntimeError::InvalidInput(format!(
641 "tree {tree_ref} has schema {SCOPED_TREE_SCHEMA:?} and no scope"
642 )));
643 }
644 (other, _) => {
645 return Err(RuntimeError::InvalidInput(format!(
646 "tree {tree_ref} has schema {other:?}; expected {TREE_SCHEMA:?} or {SCOPED_TREE_SCHEMA:?}"
647 )));
648 }
649 };
650 let entries = validate_entries(&manifest.entries)?;
651 Ok(Tree { entries, scope })
652}
653
654pub async fn verify_blobs(rt: &KhiveRuntime, entries: &[TreeEntry]) -> Result<(), RuntimeError> {
656 let store = blob_store(rt)?;
657 for entry in entries {
658 let content_ref = ContentRef::from_hex(&entry.content_ref)
659 .map_err(|e| RuntimeError::InvalidInput(format!("entry {:?} ref: {e}", entry.path)))?;
660 if !store.exists(&content_ref).await? {
661 return Err(RuntimeError::NotFound(format!(
662 "entry {:?} references blob {} which is not in the store",
663 entry.path, entry.content_ref
664 )));
665 }
666 }
667 Ok(())
668}
669
670pub fn entries_json(entries: &[TreeEntry]) -> Value {
671 Value::Array(
672 entries
673 .iter()
674 .map(|e| json!({"path": e.path, "ref": e.content_ref, "mode": e.mode}))
675 .collect(),
676 )
677}
678
679#[cfg(test)]
680#[path = "blob_tree/tests.rs"]
681mod tests;