Skip to main content

agent_first_data/document/
error.rs

1//! Error types with context and helpful hints.
2
3use std::fmt;
4use std::io;
5
6pub type DocumentResult<T> = Result<T, DocumentError>;
7
8#[derive(Debug, Clone)]
9pub enum DocumentError {
10    EmptyPath,
11    EmptyValues,
12    UnknownSegment {
13        path: String,
14        segment: String,
15    },
16    /// A non-numeric segment addressed an array that nothing claims: no
17    /// [`KeyedList`](crate::document::KeyedList) registration covers it and its
18    /// format states no rule of its own.
19    ///
20    /// The message names the two ways out rather than the internal type that
21    /// happens to be missing — a caller can supply a rule or use an index, and
22    /// neither is discoverable from the name of a Rust struct.
23    UnregisteredArray {
24        path: String,
25    },
26    SlugNotFound {
27        prefix: String,
28        slug: String,
29    },
30    /// A non-numeric segment matched several elements of the array at `prefix`.
31    ///
32    /// Substring matching can produce this, as can an explicit keyed-list field
33    /// when an externally authored document contains duplicate identities.
34    /// Naming several things at once is not an address, and picking the first
35    /// would silently answer a different question than the one asked, so it is
36    /// refused with structural candidate indices.
37    ///
38    /// Candidate text is deliberately absent: an error must not become a route
39    /// for document content to bypass normal output redaction.
40    AmbiguousMatch {
41        prefix: String,
42        segment: String,
43        indices: Vec<usize>,
44    },
45    SlugAlreadyExists {
46        prefix: String,
47        slug: String,
48    },
49    NotTraversable {
50        path: String,
51        got: String,
52    },
53    TypeMismatch {
54        path: String,
55        expected: String,
56        got: String,
57        hint: Option<String>,
58    },
59    PathNotFound {
60        path: String,
61    },
62    IndexOutOfBounds {
63        path: String,
64        index: usize,
65        len: usize,
66    },
67    /// A parser rejected the source. `detail` is the parser's own text, which
68    /// quotes the offending line — see [`Self::redacted_message`].
69    ParseError {
70        format: String,
71        detail: String,
72    },
73    /// A dot-path is malformed: a bad escape, a trailing `\`, a bare `*`, an
74    /// index past the platform's range.
75    ///
76    /// Distinct from [`Self::ParseError`] because nothing here came from the
77    /// document — the caller's own address is what failed to parse, and
78    /// `detail` is afdata's own words about it. Sharing a code with a rejected
79    /// *file* sent readers to inspect the wrong thing.
80    PathSyntax {
81        detail: String,
82    },
83    /// afdata declines to read a source its parser would accept, because it
84    /// cannot answer honestly about it.
85    ///
86    /// `detail` is authored here and names the way out; it holds no document
87    /// text, so [`Self::redacted_message`] keeps it. Distinct from
88    /// [`Self::ParseError`] because the file is not malformed — reporting it as
89    /// a parse failure sends the reader hunting for a syntax error that is not
90    /// there.
91    SourceRefused {
92        format: String,
93        detail: String,
94    },
95    /// A caller argument contradicts itself or the document. `detail` is
96    /// afdata's own words about the argument, never document content.
97    InvalidArgument {
98        detail: String,
99    },
100    /// A staged edit rendered source this format's own parser rejects, caught
101    /// by the read-back in `save_atomic` before any bytes reached disk.
102    ///
103    /// `detail` is already redacted: it comes from
104    /// [`Self::redacted_message`] of the rejection, not from its `Display`.
105    WriteWouldCorrupt {
106        format: String,
107        detail: String,
108    },
109    /// No format could be inferred for `path`, so nothing was parsed at all.
110    ///
111    /// Distinct from [`Self::ParseError`] because it is about the file's name,
112    /// never its contents: it carries no document text, and dropping its detail
113    /// as a precaution would throw away the only actionable thing it says.
114    FormatUnknown {
115        path: String,
116    },
117    /// A create-only commit found an existing target. Kept separate from
118    /// [`Self::IoError`] so callers can safely implement idempotent create
119    /// workflows without parsing platform-specific I/O messages.
120    AlreadyExists {
121        path: String,
122    },
123    /// A capped read found more bytes than the caller allowed. Kept separate
124    /// from [`Self::IoError`] for the same reason as [`Self::AlreadyExists`]: a
125    /// caller enforcing a size budget has to tell "too big" from "missing" or
126    /// "unreadable", and should not have to match on a message to do it.
127    TooLarge {
128        path: String,
129        max_bytes: u64,
130    },
131    /// The source held zero bytes and its format has no empty document (an
132    /// empty JSON text is not JSON). `source` names where the bytes came from
133    /// (`stdin` or a path) so the reader looks at the producer, not at syntax.
134    EmptyInput {
135        source: String,
136    },
137    IoError {
138        detail: String,
139    },
140    UnsupportedOperation {
141        format: String,
142        operation: String,
143        detail: String,
144    },
145}
146
147impl fmt::Display for DocumentError {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        match self {
150            DocumentError::EmptyPath => {
151                write!(f, "empty path provided")
152            }
153            DocumentError::EmptyValues => {
154                write!(f, "at least one value required")
155            }
156            DocumentError::UnknownSegment { path, segment } => {
157                write!(f, "path `{path}` segment `{segment}` not found")
158            }
159            DocumentError::UnregisteredArray { path } => {
160                write!(
161                    f,
162                    "array at `{path}` has no rule for naming an element by its content; \
163                     address an element by index, or name the field that identifies one"
164                )
165            }
166            DocumentError::SlugNotFound { prefix, slug } => {
167                write!(f, "no element with slug `{slug}` found in `{prefix}`")
168            }
169            DocumentError::SlugAlreadyExists { prefix, slug } => {
170                write!(f, "slug `{slug}` already exists in `{prefix}`")
171            }
172            DocumentError::AmbiguousMatch {
173                prefix,
174                segment,
175                indices,
176            } => {
177                let candidates = indices
178                    .iter()
179                    .map(usize::to_string)
180                    .collect::<Vec<_>>()
181                    .join(", ");
182                write!(
183                    f,
184                    "segment `{}` matches {} elements of `{}` at indices {}",
185                    segment,
186                    indices.len(),
187                    prefix,
188                    candidates
189                )
190            }
191            // An empty prefix is the document itself: name it, and say what an empty
192            // document parses to, rather than print an empty pair of backticks.
193            DocumentError::NotTraversable { path, got } if path.is_empty() => {
194                if got == "null" {
195                    write!(
196                        f,
197                        "the document is empty (its root is null), cannot traverse into it"
198                    )
199                } else {
200                    write!(f, "the document root is {got}, cannot traverse into it")
201                }
202            }
203            DocumentError::NotTraversable { path, got } => {
204                write!(f, "path `{path}` is {got}, cannot traverse further")
205            }
206            DocumentError::TypeMismatch {
207                path,
208                expected,
209                got,
210                hint,
211            } => {
212                write!(f, "field `{path}` expects {expected}, got `{got}`")?;
213                if let Some(h) = hint {
214                    write!(f, "\n  hint: {h}")?;
215                }
216                Ok(())
217            }
218            DocumentError::PathNotFound { path } => {
219                write!(f, "path `{path}` not found in document")
220            }
221            DocumentError::IndexOutOfBounds { path, index, len } => {
222                write!(f, "index {index} out of bounds at `{path}` (len {len})")
223            }
224            DocumentError::ParseError { format, detail } => {
225                write!(f, "failed to parse {format}: {detail}")
226            }
227            DocumentError::PathSyntax { detail } => {
228                write!(f, "invalid path: {detail}")
229            }
230            DocumentError::SourceRefused { format, detail } => {
231                write!(f, "refusing to read this {format}: {detail}")
232            }
233            DocumentError::InvalidArgument { detail } => {
234                write!(f, "invalid argument: {detail}")
235            }
236            DocumentError::WriteWouldCorrupt { format, detail } => {
237                write!(
238                    f,
239                    "refusing to write: the edit produced {format} this parser rejects ({detail}); the file is unchanged"
240                )
241            }
242            DocumentError::FormatUnknown { path } => {
243                write!(
244                    f,
245                    "cannot detect the format of `{path}` from its extension; pass an explicit format"
246                )
247            }
248            DocumentError::AlreadyExists { path } => {
249                write!(f, "document target `{path}` already exists")
250            }
251            DocumentError::TooLarge { path, max_bytes } => {
252                write!(f, "`{path}` exceeds the {max_bytes}-byte read limit")
253            }
254            DocumentError::EmptyInput { source } => {
255                write!(
256                    f,
257                    "{source} is empty (zero bytes); there is no document to read"
258                )
259            }
260            DocumentError::IoError { detail } => {
261                write!(f, "io error: {detail}")
262            }
263            DocumentError::UnsupportedOperation {
264                format,
265                operation,
266                detail,
267            } => write!(f, "{format} does not support {operation}: {detail}"),
268        }
269    }
270}
271
272impl std::error::Error for DocumentError {}
273
274impl DocumentError {
275    /// Stable, program-decidable error code for this failure category.
276    ///
277    /// Multiple variants share a code only when callers should handle them in
278    /// the same way. An ordinary missing path is `document_path_not_found`;
279    /// named array lookup distinguishes a missing slug from an ambiguous one.
280    #[must_use]
281    pub const fn code(&self) -> &'static str {
282        match self {
283            Self::ParseError { .. } => "document_parse_failed",
284            Self::PathSyntax { .. } => "document_invalid_path",
285            Self::SourceRefused { .. } => "document_source_refused",
286            Self::FormatUnknown { .. } => "document_format_unknown",
287            Self::AlreadyExists { .. } => "document_target_exists",
288            Self::TooLarge { .. } => "document_too_large",
289            Self::WriteWouldCorrupt { .. } => "document_write_would_corrupt",
290            Self::PathNotFound { .. }
291            | Self::UnknownSegment { .. }
292            | Self::IndexOutOfBounds { .. }
293            | Self::UnregisteredArray { .. } => "document_path_not_found",
294            Self::NotTraversable { .. } | Self::TypeMismatch { .. } => "document_type_mismatch",
295            Self::SlugNotFound { .. } => "document_slug_not_found",
296            Self::AmbiguousMatch { .. } => "document_ambiguous_match",
297            Self::SlugAlreadyExists { .. } => "document_slug_exists",
298            Self::EmptyInput { .. } => "document_empty",
299            Self::IoError { .. } => "document_io_failed",
300            Self::UnsupportedOperation { .. } => "document_unsupported_operation",
301            Self::EmptyPath | Self::EmptyValues | Self::InvalidArgument { .. } => {
302                "document_invalid_argument"
303            }
304        }
305    }
306
307    /// Best-effort, content-free source location for a parse failure.
308    ///
309    /// Returns e.g. `"line 5 column 12"` (or `"line 5"`) for a
310    /// [`DocumentError::ParseError`], and `None` for every other variant or
311    /// when the underlying parser reported no position. The returned string is
312    /// derived from the parser's position only and never contains document
313    /// content, so it is safe to surface even when the parsed file may hold
314    /// secrets.
315    #[must_use]
316    pub fn location(&self) -> Option<String> {
317        let Self::ParseError { detail, .. } = self else {
318            return None;
319        };
320        // A parser diagnostic opens with its own position and echoes the
321        // offending source on the lines below it:
322        //
323        //     TOML parse error at line 2, column 5
324        //       |
325        //     2 | note = "see at line 999 for details" bad
326        //
327        // So the position is on the first line and document content never is.
328        // Searching the whole detail — from either end — can read the echo:
329        // from the end it finds `at line 999`, which is the file's own text.
330        let head = detail.split('\n').next().unwrap_or(detail);
331        let rest = match head.split_once(" at line ") {
332            Some((_, rest)) => rest,
333            None => head.strip_prefix("line ")?,
334        };
335        let line = leading_ascii_digits(rest)?;
336        let column = rest
337            .split_once("column ")
338            .and_then(|(_, tail)| leading_ascii_digits(tail));
339        Some(match column {
340            Some(column) => format!("line {line} column {column}"),
341            None => format!("line {line}"),
342        })
343    }
344
345    /// A display message with any potentially content-bearing detail removed —
346    /// safe to surface when the document may hold secrets.
347    ///
348    /// Two variants can quote material that originates in the document and are
349    /// rewritten here:
350    ///
351    /// - [`DocumentError::ParseError`] renders as `failed to parse {format}`
352    ///   (with the [`location`](Self::location) appended when known), dropping
353    ///   the parser detail, which echoes a snippet of the source.
354    ///
355    /// [`DocumentError::PathSyntax`], [`DocumentError::SourceRefused`] and
356    /// [`DocumentError::InvalidArgument`] keep their detail in full. It is the
357    /// reason they exist as separate variants: their text is written here, about
358    /// the caller's address, argument, or file *encoding* — never lifted from
359    /// document content — and it is the only part that says what to do next.
360    /// Dropping it as a precaution against a leak that cannot happen turned an
361    /// actionable refusal into `failed to parse Markdown`.
362    /// - [`DocumentError::TypeMismatch`] drops `got` and `hint`. When built by
363    ///   [`Self::from_serde`] those carry serde's rendering of the offending
364    ///   value, which is document content.
365    ///
366    /// Every other variant renders the same as its [`std::fmt::Display`], carrying only
367    /// structural context: paths, requested slugs, indices, and type or format
368    /// names. In particular, [`Self::AmbiguousMatch`] carries candidate indices
369    /// rather than matched field values.
370    /// [`DocumentError::NotTraversable`] belongs to that group because `got` is
371    /// a [`Value::kind_name`](crate::document::Value::kind_name), not a value.
372    #[must_use]
373    pub fn redacted_message(&self) -> String {
374        match self {
375            // afdata's own sentence about a binary property list read as the
376            // wrong format: it names the flag and quotes nothing from the file.
377            #[cfg(feature = "plist")]
378            Self::ParseError { detail, .. }
379                if detail == crate::document::format::plist::WRONG_FORMAT_DETAIL
380                    || detail == crate::document::format::plist::WRONG_FORMAT_XML_DETAIL =>
381            {
382                self.to_string()
383            }
384            Self::ParseError { format, .. } => match self.location() {
385                Some(location) => format!("failed to parse {format} at {location}"),
386                None => format!("failed to parse {format}"),
387            },
388            Self::TypeMismatch { path, expected, .. } => {
389                if expected.is_empty() {
390                    format!("field `{path}` has the wrong type")
391                } else {
392                    format!("field `{path}` expects {expected}")
393                }
394            }
395            other => other.to_string(),
396        }
397    }
398
399    /// Wrap a serde deserialization failure as a `TypeMismatch` so callers that
400    /// do a read-modify-write cycle (set_path → serde round-trip) surface a
401    /// consistent error style rather than a raw serde message.
402    pub fn from_serde(path: impl Into<String>, err: impl std::fmt::Display) -> Self {
403        let msg = err.to_string();
404        // serde messages look like "invalid type: string \"x\", expected u16 at …"
405        // Strip the trailing " at line N column M" to keep the hint concise.
406        let hint = msg
407            .split(" at line ")
408            .next()
409            .unwrap_or(&msg)
410            .trim()
411            .to_string();
412        DocumentError::TypeMismatch {
413            path: path.into(),
414            expected: String::new(),
415            got: hint,
416            hint: None,
417        }
418    }
419}
420
421impl From<io::Error> for DocumentError {
422    fn from(err: io::Error) -> Self {
423        DocumentError::IoError {
424            detail: err.to_string(),
425        }
426    }
427}
428
429fn leading_ascii_digits(text: &str) -> Option<&str> {
430    let end = text.bytes().take_while(u8::is_ascii_digit).count();
431    (end > 0).then_some(&text[..end])
432}
433
434#[cfg(test)]
435mod tests {
436    use super::DocumentError;
437
438    #[test]
439    fn document_error_codes_are_stable() {
440        let cases = [
441            (DocumentError::EmptyPath, "document_invalid_argument"),
442            (DocumentError::EmptyValues, "document_invalid_argument"),
443            (
444                DocumentError::UnknownSegment {
445                    path: "root.key".to_string(),
446                    segment: "key".to_string(),
447                },
448                "document_path_not_found",
449            ),
450            (
451                DocumentError::UnregisteredArray {
452                    path: "items".to_string(),
453                },
454                "document_path_not_found",
455            ),
456            (
457                DocumentError::SlugNotFound {
458                    prefix: "items".to_string(),
459                    slug: "missing".to_string(),
460                },
461                "document_slug_not_found",
462            ),
463            (
464                DocumentError::SlugAlreadyExists {
465                    prefix: "items".to_string(),
466                    slug: "existing".to_string(),
467                },
468                "document_slug_exists",
469            ),
470            (
471                DocumentError::AmbiguousMatch {
472                    prefix: "items".to_string(),
473                    segment: "look".to_string(),
474                    indices: vec![0, 2],
475                },
476                "document_ambiguous_match",
477            ),
478            (
479                DocumentError::NotTraversable {
480                    path: "root".to_string(),
481                    got: "string".to_string(),
482                },
483                "document_type_mismatch",
484            ),
485            (
486                DocumentError::TypeMismatch {
487                    path: "root.key".to_string(),
488                    expected: "integer".to_string(),
489                    got: "string".to_string(),
490                    hint: None,
491                },
492                "document_type_mismatch",
493            ),
494            (
495                DocumentError::PathNotFound {
496                    path: "root.key".to_string(),
497                },
498                "document_path_not_found",
499            ),
500            (
501                DocumentError::EmptyInput {
502                    source: "stdin".to_string(),
503                },
504                "document_empty",
505            ),
506            (
507                DocumentError::IndexOutOfBounds {
508                    path: "items".to_string(),
509                    index: 2,
510                    len: 1,
511                },
512                "document_path_not_found",
513            ),
514            (
515                DocumentError::ParseError {
516                    format: "JSON".to_string(),
517                    detail: "invalid input".to_string(),
518                },
519                "document_parse_failed",
520            ),
521            (
522                DocumentError::IoError {
523                    detail: "unreadable".to_string(),
524                },
525                "document_io_failed",
526            ),
527            (
528                DocumentError::AlreadyExists {
529                    path: "config.toml".to_string(),
530                },
531                "document_target_exists",
532            ),
533            (
534                DocumentError::TooLarge {
535                    path: "config.toml".to_string(),
536                    max_bytes: 1024,
537                },
538                "document_too_large",
539            ),
540            (
541                DocumentError::UnsupportedOperation {
542                    format: "INI".to_string(),
543                    operation: "set".to_string(),
544                    detail: "unsupported".to_string(),
545                },
546                "document_unsupported_operation",
547            ),
548        ];
549
550        for (error, expected) in cases {
551            assert_eq!(error.code(), expected);
552        }
553    }
554
555    #[test]
556    fn location_extracts_position_without_content() {
557        // The real layout a parser produces: its own position first, then the
558        // offending source echoed below. The echo here carries `at line 999`
559        // out of the document, and a search from the end reads exactly that —
560        // reporting a wrong line and leaking a document-derived number through
561        // `redacted_message`, which promises never to surface file content.
562        let err = DocumentError::ParseError {
563            format: "TOML".to_string(),
564            detail: "TOML parse error at line 5, column 12\n  |\n\
565                     5 | note = \"see at line 999 for TOPSECRET\" bad\n  |     ^"
566                .to_string(),
567        };
568        assert_eq!(err.location().as_deref(), Some("line 5 column 12"));
569        assert!(!err.redacted_message().contains("999"));
570        assert!(!err.redacted_message().contains("TOPSECRET"));
571
572        let no_column = DocumentError::ParseError {
573            format: "JSON".to_string(),
574            detail: "boom at line 3".to_string(),
575        };
576        assert_eq!(no_column.location().as_deref(), Some("line 3"));
577
578        // No position, and non-parse variants, carry no location.
579        assert!(
580            DocumentError::ParseError {
581                format: "INI".to_string(),
582                detail: "sensitive value".to_string(),
583            }
584            .location()
585            .is_none()
586        );
587        assert!(
588            DocumentError::PathNotFound {
589                path: "a.b".to_string(),
590            }
591            .location()
592            .is_none()
593        );
594    }
595
596    #[test]
597    fn redacted_message_drops_parser_detail() {
598        let err = DocumentError::ParseError {
599            format: "YAML".to_string(),
600            detail: "unexpected TOPSECRET at line 5 column 12".to_string(),
601        };
602        let redacted = err.redacted_message();
603        assert_eq!(redacted, "failed to parse YAML at line 5 column 12");
604        assert!(!redacted.contains("TOPSECRET"));
605
606        // Structural variants pass through unchanged.
607        let path_err = DocumentError::PathNotFound {
608            path: "database.url".to_string(),
609        };
610        assert_eq!(path_err.redacted_message(), path_err.to_string());
611    }
612
613    #[test]
614    fn redacted_message_drops_the_offending_value() {
615        // `from_serde` keeps serde's rendering, which quotes the value that
616        // failed the type check — document content, and a secret as often as not.
617        let err = DocumentError::from_serde(
618            "credentials.token",
619            "invalid type: string \"sk-live-TOPSECRET\", expected u16",
620        );
621        assert!(err.to_string().contains("sk-live-TOPSECRET"));
622        let redacted = err.redacted_message();
623        assert!(!redacted.contains("sk-live-TOPSECRET"), "{redacted}");
624        assert!(redacted.contains("credentials.token"), "{redacted}");
625    }
626
627    #[test]
628    fn ambiguous_match_reports_indices_without_document_content() {
629        let err = DocumentError::AmbiguousMatch {
630            prefix: "h1.0.h2".to_string(),
631            segment: "look".to_string(),
632            indices: vec![0, 2],
633        };
634        assert_eq!(
635            err.redacted_message(),
636            "segment `look` matches 2 elements of `h1.0.h2` at indices 0, 2"
637        );
638        assert!(!err.redacted_message().contains("Quick look"));
639    }
640
641    #[test]
642    fn not_traversable_names_the_type_not_the_value() {
643        // This one is safe by construction rather than by redaction: `got` is a
644        // kind name, so even `Display` cannot echo the leaf.
645        let err = DocumentError::NotTraversable {
646            path: "token_secret.inner".to_string(),
647            got: crate::document::Value::String("sk-live-TOPSECRET".to_string())
648                .kind_name()
649                .to_string(),
650        };
651        assert_eq!(
652            err.to_string(),
653            "path `token_secret.inner` is string, cannot traverse further"
654        );
655        assert_eq!(err.redacted_message(), err.to_string());
656    }
657
658    #[test]
659    fn not_traversable_at_the_root_names_the_document() {
660        let empty = DocumentError::NotTraversable {
661            path: String::new(),
662            got: "null".to_string(),
663        };
664        assert_eq!(
665            empty.to_string(),
666            "the document is empty (its root is null), cannot traverse into it"
667        );
668        let scalar = DocumentError::NotTraversable {
669            path: String::new(),
670            got: "string".to_string(),
671        };
672        assert_eq!(
673            scalar.to_string(),
674            "the document root is string, cannot traverse into it"
675        );
676    }
677}