1use std::collections::{BTreeMap, HashMap};
8
9use omgbase_format::hash::hex;
10use omgbase_store::{Store, is_id_ref};
11use rusqlite::{Connection, OptionalExtension, params};
12use serde_json::{Map, Value as Json, json};
13
14use crate::context::glob_to_like;
15use crate::cursor::{decode_path_cursor, encode_cursor};
16use crate::error::Result;
17use crate::paths::{reference_path, storage_path};
18
19pub const MANY_CAP: usize = 100;
21pub const LIST_DEFAULT_LIMIT: usize = 200;
23
24#[must_use]
26pub fn token_cost(v: &Json) -> usize {
27 v.to_string().chars().count().div_ceil(4)
28}
29
30#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct DocInfo {
35 pub doc_id: String,
36 pub repo_id: String,
37 pub path: String,
40 pub format: String,
41 pub current_rev: Option<String>,
42}
43
44fn doc_row(conn: &Connection, sql: &str, p: &[&dyn rusqlite::ToSql]) -> Result<Option<DocInfo>> {
45 Ok(conn
46 .query_row(sql, p, |r| {
47 Ok(DocInfo {
48 doc_id: r.get(0)?,
49 repo_id: r.get(1)?,
50 path: r.get(2)?,
51 format: r
52 .get::<_, Option<String>>(3)?
53 .unwrap_or_else(|| "markdown".to_owned()),
54 current_rev: r.get(4)?,
55 })
56 })
57 .optional()?)
58}
59
60pub fn find_doc_by_id(conn: &Connection, doc_id: &str) -> Result<Option<DocInfo>> {
62 doc_row(
63 conn,
64 "SELECT doc_id, repo_id, path, format, current_rev FROM docs WHERE doc_id = ?1 AND deleted_commit IS NULL",
65 &[&doc_id],
66 )
67}
68
69pub fn find_doc_by_path(conn: &Connection, repo_id: &str, path: &str) -> Result<Option<DocInfo>> {
71 doc_row(
72 conn,
73 "SELECT doc_id, repo_id, path, format, current_rev FROM docs WHERE repo_id = ?1 AND path = ?2 AND deleted_commit IS NULL",
74 &[&repo_id, &storage_path(path)],
75 )
76}
77
78pub fn find_doc_by_ref(conn: &Connection, repo_id: &str, r: &str) -> Result<Option<DocInfo>> {
81 if is_id_ref(r, "d") {
82 return find_doc_by_id(conn, r);
83 }
84 find_doc_by_path(conn, repo_id, r)
85}
86
87fn id_prefix(r: &str) -> Option<&str> {
91 let (p, _) = r.split_once('_')?;
92 is_id_ref(r, p).then_some(p)
93}
94
95#[derive(Clone, Debug, PartialEq, Eq)]
97pub enum ResolvedRef {
98 Block { doc_id: String, block_id: String },
99 Document { doc_id: String },
100}
101
102impl ResolvedRef {
103 #[must_use]
104 pub fn doc_id(&self) -> &str {
105 match self {
106 ResolvedRef::Block { doc_id, .. } | ResolvedRef::Document { doc_id } => doc_id,
107 }
108 }
109}
110
111fn is_node_id(s: &str) -> bool {
112 s.len() == 14
113 && s.starts_with("n_")
114 && s[2..]
115 .bytes()
116 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
117}
118
119pub fn resolve_ref(conn: &Connection, repo_id: &str, r: &str) -> Result<Option<ResolvedRef>> {
123 if is_node_id(r) {
124 let node: Option<(String, Option<String>)> = conn
125 .query_row(
126 "SELECT doc_id, block_id FROM nodes WHERE node_id = ?1",
127 params![r],
128 |row| Ok((row.get(0)?, row.get(1)?)),
129 )
130 .optional()?;
131 let Some((doc_id, block_id)) = node else {
132 return Ok(None);
133 };
134 if let Some(b) = block_id {
135 let live: bool = conn
136 .prepare_cached(
137 "SELECT 1 FROM blocks WHERE block_id = ?1 AND deleted_commit IS NULL",
138 )?
139 .exists(params![b])?;
140 if live {
141 return Ok(Some(ResolvedRef::Block {
142 doc_id,
143 block_id: b,
144 }));
145 }
146 }
147 return Ok(Some(ResolvedRef::Document { doc_id }));
148 }
149 match id_prefix(r) {
150 Some("b") => {
151 let doc: Option<String> = conn
152 .query_row(
153 "SELECT doc_id FROM blocks WHERE block_id = ?1 AND deleted_commit IS NULL",
154 params![r],
155 |row| row.get(0),
156 )
157 .optional()?;
158 Ok(doc.map(|doc_id| ResolvedRef::Block {
159 doc_id,
160 block_id: r.to_owned(),
161 }))
162 }
163 Some("d") => {
164 Ok(find_doc_by_id(conn, r)?.map(|i| ResolvedRef::Document { doc_id: i.doc_id }))
165 }
166 _ => {
167 Ok(find_doc_by_path(conn, repo_id, r)?
168 .map(|i| ResolvedRef::Document { doc_id: i.doc_id }))
169 }
170 }
171}
172
173#[derive(Clone, Debug, PartialEq)]
177pub struct BlockNode {
178 pub block_id: String,
179 pub doc_id: String,
180 pub parent_block: Option<String>,
181 pub ordinal: i64,
182 pub depth: i64,
183 pub kind: String,
184 pub attrs: Json,
185 pub text: String,
186 pub raw_hash_hex: String,
187 pub children: Vec<BlockNode>,
188}
189
190pub fn load_doc_blocks(conn: &Connection, doc_id: &str) -> Result<Vec<BlockNode>> {
193 struct Row {
194 block_id: String,
195 parent_block: Option<String>,
196 ordinal: i64,
197 depth: i64,
198 kind: String,
199 attrs: String,
200 text: String,
201 raw_hash: Vec<u8>,
202 }
203 let rows: Vec<Row> = {
204 let mut stmt = conn.prepare_cached(
205 "SELECT block_id, parent_block, ordinal, depth, type, attrs, text, raw_hash
206 FROM blocks WHERE doc_id = ?1 AND deleted_commit IS NULL
207 ORDER BY parent_block, order_key",
208 )?;
209 let it = stmt.query_map(params![doc_id], |r| {
210 Ok(Row {
211 block_id: r.get(0)?,
212 parent_block: r.get(1)?,
213 ordinal: r.get(2)?,
214 depth: r.get(3)?,
215 kind: r.get(4)?,
216 attrs: r.get(5)?,
217 text: r.get(6)?,
218 raw_hash: r.get(7)?,
219 })
220 })?;
221 it.collect::<std::result::Result<Vec<_>, _>>()?
222 };
223 let ids: Vec<String> = rows.iter().map(|r| r.block_id.clone()).collect();
224 let index: HashMap<&str, usize> = ids
225 .iter()
226 .enumerate()
227 .map(|(i, id)| (id.as_str(), i))
228 .collect();
229 let mut nodes: Vec<Option<BlockNode>> = rows
230 .iter()
231 .map(|r| {
232 Some(BlockNode {
233 block_id: r.block_id.clone(),
234 doc_id: doc_id.to_owned(),
235 parent_block: r.parent_block.clone(),
236 ordinal: r.ordinal,
237 depth: r.depth,
238 kind: r.kind.clone(),
239 attrs: serde_json::from_str(&r.attrs).unwrap_or(Json::Object(Map::new())),
240 text: r.text.clone(),
241 raw_hash_hex: hex(&r.raw_hash),
242 children: Vec::new(),
243 })
244 })
245 .collect();
246 let mut children_of: Vec<Vec<usize>> = vec![Vec::new(); rows.len()];
248 let mut roots: Vec<usize> = Vec::new();
249 for (i, r) in rows.iter().enumerate() {
250 match r.parent_block.as_deref().and_then(|p| index.get(p)) {
251 Some(&p) => children_of[p].push(i),
252 None => roots.push(i),
253 }
254 }
255 fn build(i: usize, nodes: &mut [Option<BlockNode>], children_of: &[Vec<usize>]) -> BlockNode {
256 let kids: Vec<BlockNode> = children_of[i]
257 .iter()
258 .map(|&c| build(c, nodes, children_of))
259 .collect();
260 let mut n = nodes[i].take().expect("each node is built once");
261 n.children = kids;
262 n
263 }
264 Ok(roots
265 .into_iter()
266 .map(|i| build(i, &mut nodes, &children_of))
267 .collect())
268}
269
270fn find_block<'n>(roots: &'n [BlockNode], block_id: &str) -> Option<&'n BlockNode> {
271 for n in roots {
272 if n.block_id == block_id {
273 return Some(n);
274 }
275 if let Some(f) = find_block(&n.children, block_id) {
276 return Some(f);
277 }
278 }
279 None
280}
281
282pub fn block_raw(conn: &Connection, raw_hash_hex: &str) -> Result<String> {
284 let bytes: Vec<u8> = (0..raw_hash_hex.len() / 2)
285 .filter_map(|i| u8::from_str_radix(&raw_hash_hex[2 * i..2 * i + 2], 16).ok())
286 .collect();
287 Ok(omgbase_store::read::blob_text(conn, &bytes)?)
288}
289
290pub fn docs_read(store: &Store, doc_id: &str, include_ids: bool) -> Result<Option<Json>> {
295 let conn = store.conn();
296 let Some(info) = find_doc_by_id(conn, doc_id)? else {
297 return Ok(None);
298 };
299 let Some(content) = store.reconstruct(doc_id)? else {
300 return Ok(None);
301 };
302 let mut m = Map::new();
303 m.insert("path".to_owned(), json!(reference_path(&info.path)));
304 m.insert("docId".to_owned(), json!(info.doc_id));
305 m.insert("rev".to_owned(), json!(info.current_rev));
306 m.insert("properties".to_owned(), store.properties_grouped(doc_id)?);
307 m.insert("content".to_owned(), json!(content));
308 if include_ids {
309 let mut ids = Vec::new();
310 let mut hashes = Map::new();
311 let mut parents = Map::new();
312 fn collect(
313 nodes: &[BlockNode],
314 ids: &mut Vec<Json>,
315 hashes: &mut Map<String, Json>,
316 parents: &mut Map<String, Json>,
317 ) {
318 for n in nodes {
319 ids.push(json!(n.block_id));
320 hashes.insert(n.block_id.clone(), json!(n.raw_hash_hex));
321 parents.insert(n.block_id.clone(), json!(n.parent_block));
322 collect(&n.children, ids, hashes, parents);
323 }
324 }
325 collect(
326 &load_doc_blocks(conn, doc_id)?,
327 &mut ids,
328 &mut hashes,
329 &mut parents,
330 );
331 m.insert("ids".to_owned(), Json::Array(ids));
332 m.insert("hashes".to_owned(), Json::Object(hashes));
333 m.insert("parents".to_owned(), Json::Object(parents));
334 }
335 Ok(Some(Json::Object(m)))
336}
337
338pub fn docs_read_many(
340 store: &Store,
341 repo_id: &str,
342 refs: &[String],
343 include_ids: bool,
344 budget_tokens: Option<usize>,
345) -> Result<Json> {
346 let capped = &refs[..refs.len().min(MANY_CAP)];
347 let mut truncated = refs.len() > MANY_CAP;
348 let mut items = Vec::new();
349 let mut errors = Vec::new();
350 let mut seen: Vec<&str> = Vec::new();
351 let mut tokens = 0usize;
352 for r in capped {
353 if seen.contains(&r.as_str()) {
354 continue;
355 }
356 seen.push(r);
357 let info = find_doc_by_ref(store.conn(), repo_id, r)?;
358 let read = match info {
359 Some(i) => docs_read(store, &i.doc_id, include_ids)?,
360 None => None,
361 };
362 let Some(read) = read else {
363 errors.push(json!({ "ref": r, "error": "doc_not_found" }));
364 continue;
365 };
366 let cost = token_cost(&read);
370 if !items.is_empty() && budget_tokens.is_some_and(|b| tokens + cost > b) {
371 truncated = true;
372 break;
373 }
374 tokens += cost;
375 items.push(read);
376 }
377 Ok(json!({ "items": items, "errors": errors, "truncated": truncated }))
378}
379
380pub fn docs_read_at(store: &Store, doc_id: &str, rev: &str) -> Result<Option<Json>> {
382 let Some(r) = store.read_at_revision(doc_id, rev)? else {
383 return Ok(None);
384 };
385 Ok(Some(json!({
386 "path": reference_path(&r.path),
387 "docId": doc_id,
388 "rev": rev,
389 "content": r.content,
390 "renderedHashMatch": r.rendered_hash_match,
391 "properties": store.properties_grouped(doc_id)?,
392 "propertiesAreCurrent": true,
393 })))
394}
395
396#[derive(Clone, Copy, Debug, PartialEq, Eq)]
400pub enum Resolution {
401 Skeleton,
402 Outline,
403 Text,
404 Raw,
405 Full,
406}
407
408impl Resolution {
409 #[must_use]
411 pub fn parse(s: &str) -> Option<Self> {
412 Some(match s {
413 "skeleton" => Resolution::Skeleton,
414 "outline" => Resolution::Outline,
415 "text" => Resolution::Text,
416 "raw" => Resolution::Raw,
417 "full" => Resolution::Full,
418 _ => return None,
419 })
420 }
421}
422
423#[must_use]
425pub fn first_words(text: &str, n: usize) -> String {
426 let words: Vec<&str> = text.split_whitespace().collect();
427 if words.len() <= n {
428 words.join(" ")
429 } else {
430 format!("{}…", words[..n].join(" "))
431 }
432}
433
434fn project(
435 conn: &Connection,
436 node: &BlockNode,
437 resolution: Resolution,
438 include_children: bool,
439) -> Result<Json> {
440 let mut m = Map::new();
441 m.insert("id".to_owned(), json!(node.block_id));
442 m.insert("type".to_owned(), json!(node.kind));
443 match resolution {
444 Resolution::Skeleton => {
445 let label = if node.kind == "heading" {
446 node.text.clone()
447 } else {
448 node.kind.clone()
449 };
450 m.insert("label".to_owned(), json!(label));
451 }
452 Resolution::Outline => {
453 m.insert("label".to_owned(), json!(first_words(&node.text, 10)));
454 }
455 Resolution::Text => {
456 m.insert("text".to_owned(), json!(node.text));
457 }
458 Resolution::Raw => {
459 m.insert(
460 "raw".to_owned(),
461 json!(block_raw(conn, &node.raw_hash_hex)?),
462 );
463 m.insert("content_hash".to_owned(), json!(node.raw_hash_hex));
464 }
465 Resolution::Full => {
466 m.insert(
467 "raw".to_owned(),
468 json!(block_raw(conn, &node.raw_hash_hex)?),
469 );
470 m.insert("content_hash".to_owned(), json!(node.raw_hash_hex));
471 m.insert("text".to_owned(), json!(node.text));
472 m.insert("attrs".to_owned(), node.attrs.clone());
473 m.insert(
474 "placement".to_owned(),
475 json!({ "parent": node.parent_block, "ordinal": node.ordinal, "depth": node.depth }),
476 );
477 }
478 }
479 if include_children && !node.children.is_empty() {
480 let kids: Result<Vec<Json>> = node
481 .children
482 .iter()
483 .map(|c| project(conn, c, resolution, true))
484 .collect();
485 m.insert("children".to_owned(), Json::Array(kids?));
486 }
487 Ok(Json::Object(m))
488}
489
490pub fn nodes_get(
493 store: &Store,
494 doc_id: &str,
495 block_id: &str,
496 resolution: Resolution,
497) -> Result<Option<Json>> {
498 let roots = load_doc_blocks(store.conn(), doc_id)?;
499 match find_block(&roots, block_id) {
500 Some(n) => Ok(Some(project(store.conn(), n, resolution, true)?)),
501 None => Ok(None),
502 }
503}
504
505pub fn nodes_get_many(
507 store: &Store,
508 doc_id: Option<&str>,
509 block_ids: &[String],
510 resolution: Resolution,
511 budget_tokens: Option<usize>,
512) -> Result<Json> {
513 let conn = store.conn();
514 let capped = &block_ids[..block_ids.len().min(MANY_CAP)];
515 let mut owner: HashMap<String, String> = HashMap::new();
516 if !capped.is_empty() {
517 let placeholders: Vec<String> = (1..=capped.len()).map(|i| format!("?{i}")).collect();
518 let sql = format!(
519 "SELECT block_id, doc_id FROM blocks WHERE deleted_commit IS NULL AND block_id IN ({})",
520 placeholders.join(",")
521 );
522 let mut stmt = conn.prepare(&sql)?;
523 let rows = stmt.query_map(rusqlite::params_from_iter(capped.iter()), |r| {
524 Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
525 })?;
526 for row in rows {
527 let (b, d) = row?;
528 if doc_id.is_none_or(|want| want == d) {
529 owner.insert(b, d);
530 }
531 }
532 }
533 let mut forests: BTreeMap<String, Vec<BlockNode>> = BTreeMap::new();
534 for d in owner.values() {
535 if !forests.contains_key(d) {
536 forests.insert(d.clone(), load_doc_blocks(conn, d)?);
537 }
538 }
539 let mut nodes = Vec::new();
540 let mut unresolved = Vec::new();
541 let mut tokens = 0usize;
542 let mut truncated = block_ids.len() > MANY_CAP;
543 for id in capped {
544 let node = owner
545 .get(id)
546 .and_then(|d| forests.get(d))
547 .and_then(|f| find_block(f, id));
548 let Some(node) = node else {
549 unresolved.push(json!(id));
550 continue;
551 };
552 let projected = project(conn, node, resolution, false)?;
553 let cost = token_cost(&projected);
555 if !nodes.is_empty() && budget_tokens.is_some_and(|b| tokens + cost > b) {
556 truncated = true;
557 break;
558 }
559 tokens += cost;
560 nodes.push(projected);
561 }
562 Ok(json!({ "nodes": nodes, "truncated": truncated, "unresolved": unresolved }))
563}
564
565fn type_label(node: &BlockNode) -> String {
568 match node.kind.as_str() {
569 "heading" => format!(
570 "h{}",
571 node.attrs
572 .get("level")
573 .map(|l| match l {
574 Json::String(s) => s.clone(),
575 Json::Null => String::new(),
576 other => other.to_string(),
577 })
578 .unwrap_or_default()
579 ),
580 "paragraph" => "p".to_owned(),
581 "list" => "ul".to_owned(),
582 "list_item" | "task" => "li".to_owned(),
583 "blockquote" => "bq".to_owned(),
584 "code_fence" => "code".to_owned(),
585 "table" => "tbl".to_owned(),
586 "table_row" => "tr".to_owned(),
587 "thematic_break" => "hr".to_owned(),
588 "html_block" => "html".to_owned(),
589 "opaque" => "raw".to_owned(),
590 other => other.to_owned(),
591 }
592}
593
594fn label_for(node: &BlockNode) -> String {
595 match node.kind.as_str() {
596 "list" | "blockquote" | "table" => String::new(),
597 "task" => {
598 let checked = node.attrs.get("checked").is_some_and(|c| {
599 !matches!(c, Json::Null | Json::Bool(false)) && c != &json!(0) && c != &json!("")
600 });
601 let glyph = if checked { "☑" } else { "☐" };
602 format!("{glyph} {}", first_words(&node.text, 10))
603 }
604 _ => first_words(&node.text, 10),
605 }
606}
607
608pub fn docs_outline(
610 store: &Store,
611 doc_id: &str,
612 skeleton: bool,
613 depth: Option<i64>,
614 budget_tokens: Option<usize>,
615) -> Result<Json> {
616 let roots = load_doc_blocks(store.conn(), doc_id)?;
617 struct Walk {
618 skeleton: bool,
619 max_depth: Option<i64>,
620 budget: Option<usize>,
621 lines: Vec<String>,
622 tokens: usize,
623 truncated: bool,
624 }
625 impl Walk {
626 fn walk(&mut self, nodes: &[BlockNode], indent: i64) {
627 for node in nodes {
628 if self.truncated {
629 return;
630 }
631 if self.max_depth.is_some_and(|d| indent > d) {
632 continue;
633 }
634 let pad = " ".repeat(usize::try_from(indent).unwrap_or(0));
635 let section_mark = if node.kind == "heading" { " §" } else { "" };
636 let label = if self.skeleton {
637 String::new()
638 } else {
639 label_for(node)
640 };
641 let line = format!(
642 "{pad}{} {:<4} {label}{section_mark}",
643 node.block_id,
644 type_label(node)
645 );
646 let line = line.trim_end().to_owned();
647 let line_tokens = line.chars().count().div_ceil(4);
648 if self.budget.is_some_and(|b| self.tokens + line_tokens > b) {
649 self.truncated = true;
650 return;
651 }
652 self.tokens += line_tokens;
653 self.lines.push(line);
654 if !node.children.is_empty() {
655 self.walk(&node.children, indent + 1);
656 }
657 }
658 }
659 }
660 let mut w = Walk {
661 skeleton,
662 max_depth: depth,
663 budget: budget_tokens,
664 lines: Vec::new(),
665 tokens: 0,
666 truncated: false,
667 };
668 w.walk(&roots, 0);
669 let (lines, truncated) = (w.lines, w.truncated);
670 Ok(json!({ "text": lines.join("\n"), "truncated": truncated }))
671}
672
673#[derive(Clone, Debug, PartialEq, Eq)]
677pub struct DocListRow {
678 pub path: String,
679 pub blocks: i64,
680 pub ts: Option<String>,
681}
682
683impl DocListRow {
684 fn to_json(&self) -> Json {
686 json!({ "path": reference_path(&self.path), "blocks": self.blocks, "ts": self.ts })
687 }
688}
689
690fn live_doc_rows(
693 conn: &Connection,
694 repo_id: &str,
695 like: &str,
696 after: Option<&str>,
697 limit: Option<usize>,
698) -> Result<Vec<DocListRow>> {
699 let mut sql = String::from(
700 "SELECT d.path,
701 (SELECT count(*) FROM blocks b WHERE b.doc_id = d.doc_id AND b.deleted_commit IS NULL),
702 (SELECT c.ts FROM revisions r JOIN commits c ON c.commit_id = r.commit_id WHERE r.rev_id = d.current_rev)
703 FROM docs d
704 WHERE d.repo_id = ?1 AND d.deleted_commit IS NULL AND d.path LIKE ?2 ESCAPE '\\'",
705 );
706 let mut p: Vec<rusqlite::types::Value> = vec![
707 rusqlite::types::Value::Text(repo_id.to_owned()),
708 rusqlite::types::Value::Text(like.to_owned()),
709 ];
710 if let Some(a) = after {
711 sql.push_str(" AND d.path > ?3");
712 p.push(rusqlite::types::Value::Text(a.to_owned()));
713 }
714 sql.push_str(" ORDER BY d.path");
715 if let Some(l) = limit {
716 sql.push_str(&format!(" LIMIT ?{}", p.len() + 1));
717 p.push(rusqlite::types::Value::Integer(
718 i64::try_from(l).unwrap_or(i64::MAX),
719 ));
720 }
721 let mut stmt = conn.prepare_cached(&sql)?;
724 let rows = stmt.query_map(rusqlite::params_from_iter(p.iter()), |r| {
725 Ok(DocListRow {
726 path: r.get(0)?,
727 blocks: r.get(1)?,
728 ts: r.get(2)?,
729 })
730 })?;
731 Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
732}
733
734fn page_path_ordered(
738 rows: Vec<(String, Json)>,
739 limit: usize,
740 budget_tokens: Option<usize>,
741 more_beyond: bool,
742) -> (Vec<Json>, bool, Option<String>) {
743 let mut items: Vec<Json> = Vec::new();
744 let mut last_path: Option<String> = None;
745 let mut tokens = 0usize;
746 let mut truncated = more_beyond;
747 for (path, row) in rows {
748 if items.len() >= limit {
749 truncated = true;
750 break;
751 }
752 let cost = token_cost(&row);
753 if !items.is_empty() && budget_tokens.is_some_and(|b| tokens + cost > b) {
754 truncated = true;
755 break;
756 }
757 tokens += cost;
758 items.push(row);
759 last_path = Some(path);
760 }
761 let cursor = match (&truncated, last_path) {
762 (true, Some(p)) => Some(encode_cursor(&[&p])),
763 _ => None,
764 };
765 (items, truncated, cursor)
766}
767
768pub fn docs_list(
770 store: &Store,
771 repo_id: &str,
772 path_glob: Option<&str>,
773 limit: Option<i64>,
774 cursor: Option<&str>,
775 budget_tokens: Option<usize>,
776) -> Result<Json> {
777 let like = path_glob.map_or_else(|| "%".to_owned(), |g| glob_to_like(storage_path(g), true));
779 let limit = usize::try_from(limit.unwrap_or(LIST_DEFAULT_LIMIT as i64).max(1)).unwrap_or(1);
780 let after = match cursor.filter(|c| !c.is_empty()) {
783 Some(c) => Some(
784 storage_path(&decode_path_cursor(c, "docs_list/docs_tree", 1)?.remove(0)).to_owned(),
785 ),
786 None => None,
787 };
788 let mut rows = live_doc_rows(
789 store.conn(),
790 repo_id,
791 &like,
792 after.as_deref(),
793 Some(limit + 1),
794 )?;
795 let more_beyond = rows.len() > limit;
796 rows.truncate(limit);
797 let (items, truncated, cursor) = page_path_ordered(
798 rows.into_iter()
799 .map(|r| (reference_path(&r.path), r.to_json()))
800 .collect(),
801 limit,
802 budget_tokens,
803 more_beyond,
804 );
805 Ok(json!({ "items": items, "truncated": truncated, "cursor": cursor }))
806}
807
808#[must_use]
811pub fn normalize_tree_prefix(path: Option<&str>) -> String {
812 let trimmed = storage_path(path.unwrap_or("")).trim_end_matches('/');
813 if trimmed.is_empty() {
814 String::new()
815 } else {
816 format!("{trimmed}/")
817 }
818}
819
820pub fn docs_tree(
825 store: &Store,
826 repo_id: &str,
827 path: Option<&str>,
828 depth: Option<i64>,
829 limit: Option<i64>,
830 cursor: Option<&str>,
831 budget_tokens: Option<usize>,
832) -> Result<Json> {
833 let prefix = normalize_tree_prefix(path);
834 let depth = usize::try_from(depth.unwrap_or(1).max(1)).unwrap_or(1);
835 let limit = usize::try_from(limit.unwrap_or(LIST_DEFAULT_LIMIT as i64).max(1)).unwrap_or(1);
836 let like = if prefix.is_empty() {
837 "%".to_owned()
838 } else {
839 format!("{}%", glob_to_like(&prefix, true))
840 };
841 let rows = live_doc_rows(store.conn(), repo_id, &like, None, None)?;
842
843 struct Entry {
844 path: String,
845 dir: bool,
846 docs: i64,
847 blocks: i64,
848 ts: Option<String>,
849 }
850 let mut by_path: Vec<Entry> = Vec::new();
851 let (mut total_docs, mut total_blocks) = (0i64, 0i64);
852 for row in &rows {
853 total_docs += 1;
854 total_blocks += row.blocks;
855 let rel = &row.path[prefix.len().min(row.path.len())..];
856 let segs: Vec<&str> = rel.split('/').collect();
857 if segs.len() <= depth {
858 by_path.push(Entry {
859 path: row.path.clone(),
860 dir: false,
861 docs: 1,
862 blocks: row.blocks,
863 ts: row.ts.clone(),
864 });
865 continue;
866 }
867 let dir = format!("{prefix}{}/", segs[..depth].join("/"));
868 match by_path.iter_mut().find(|e| e.path == dir) {
869 Some(cur) => {
870 cur.docs += 1;
871 cur.blocks += row.blocks;
872 if let Some(ts) = &row.ts {
873 if cur.ts.as_ref().is_none_or(|c| ts > c) {
874 cur.ts = Some(ts.clone());
875 }
876 }
877 }
878 None => by_path.push(Entry {
879 path: dir,
880 dir: true,
881 docs: 1,
882 blocks: row.blocks,
883 ts: row.ts.clone(),
884 }),
885 }
886 }
887 by_path.sort_by(|a, b| a.path.cmp(&b.path));
888 if let Some(c) = cursor.filter(|c| !c.is_empty()) {
889 let after = decode_path_cursor(c, "docs_list/docs_tree", 1)?.remove(0);
890 by_path.retain(|e| reference_path(&e.path) > after);
891 }
892 let entries: Vec<(String, Json)> = by_path
893 .into_iter()
894 .map(|e| {
895 let path = reference_path(&e.path);
896 (
897 path.clone(),
898 json!({
899 "path": path,
900 "kind": if e.dir { "dir" } else { "doc" },
901 "docs": e.docs,
902 "blocks": e.blocks,
903 "ts": e.ts,
904 }),
905 )
906 })
907 .collect();
908 let (items, truncated, cursor) = page_path_ordered(entries, limit, budget_tokens, false);
909 Ok(json!({
910 "prefix": reference_path(&prefix),
911 "depth": depth,
912 "total": { "docs": total_docs, "blocks": total_blocks },
913 "entries": items,
914 "truncated": truncated,
915 "cursor": cursor,
916 }))
917}
918
919#[cfg(test)]
920mod tests {
921 use super::*;
922
923 #[test]
924 fn words_and_prefixes() {
925 assert_eq!(first_words("a b\tc", 10), "a b c");
926 assert_eq!(first_words("a b c", 2), "a b…");
927 assert_eq!(normalize_tree_prefix(None), "");
928 assert_eq!(normalize_tree_prefix(Some("/projects//")), "projects/");
929 assert_eq!(normalize_tree_prefix(Some("a/b")), "a/b/");
930 assert!(is_node_id("n_0123456789ab"));
931 assert!(!is_node_id("n_0123456789AB"));
932 assert!(!is_node_id("b_0123456789ab"));
933 }
934
935 #[test]
936 fn token_cost_is_ceil_quarter_of_json_length() {
937 assert_eq!(token_cost(&json!("ab")), 1); assert_eq!(token_cost(&json!("abc")), 2); }
940}