Skip to main content

gix_error/concrete/
metadata.rs

1use std::{borrow::Cow, collections::BTreeMap, fmt, path::PathBuf};
2
3use crate::{Class, Error, ErrorExt, ResourceExhaustionKind};
4
5/// An ordered dictionary of named diagnostic values belonging to a single error context.
6///
7/// Functions returning metadata document the keys and their meaning. [`crate::Exn::metadata()`] and
8/// [`crate::Error::metadata()`] yield non-empty dictionaries separately; dictionaries from independent causes
9/// are never merged. Keys are iterated and formatted in lexicographic order.
10/// Debug formatting and [`Message`]'s display omit key quotes for non-empty names containing only ASCII
11/// letters, digits, `_`, `-`, or `.`. Other keys use quoted, escaped string formatting.
12///
13/// # Privacy
14///
15/// Metadata is not redacted. [`Message`] includes its values in both [`fmt::Display`] and [`fmt::Debug`], so
16/// printing an error carrying a message can expose these values without explicitly accessing its metadata.
17/// Paths, command arguments, environment values, and captured output may contain personally identifiable
18/// information (PII), such as user names and email addresses, or secrets such as passwords and access tokens.
19/// Omit or sanitize sensitive information before attaching it, and consider where errors will be logged or shared.
20///
21/// # Common schemas
22///
23/// These schemas define conventional keys, not required fields. Store only information already available at the
24/// failure site; do not collect additional information just to populate a schema. Omitted keys mean the information
25/// was not recorded, not that it was empty or absent. Functions returning metadata document which keys they provide.
26/// Metadata alone does not establish a semantic classification or whether recovery is safe.
27///
28/// ## Input validation
29///
30/// | Key | Value | Meaning |
31/// | --- | --- | --- |
32/// | `input` | Any [`MetadataValue`] | The offending input, preserving its original representation where possible. |
33///
34/// Use [`Message::with_input()`] to record already-known input. This convention also applies to malformed data
35/// classified as [`Class::Corruption`]; attaching `input` does not imply [`Class::Validation`]. Do not record secrets
36/// or other sensitive input that should not appear in diagnostics.
37///
38/// ## External program runtime failure
39///
40/// | Key | Value | Meaning |
41/// | --- | --- | --- |
42/// | `program` | [`MetadataValue::Path`] | The invoked program name or path, without resolving it. |
43/// | `command` | [`MetadataValue::String`] | The debug representation of the prepared command, or of the configured command when the prepared command is no longer available. |
44/// | `exit_status` | [`MetadataValue::String`] | The display representation of [`std::process::ExitStatus`], including termination without an exit code. |
45/// | `exit_code` | [`MetadataValue::I64`] | The exit code, when [`std::process::ExitStatus::code()`] returns one. |
46/// | `stdout` | [`MetadataValue::Bytes`] | Captured standard output, without text decoding. |
47/// | `stderr` | [`MetadataValue::Bytes`] | Captured standard error, without text decoding. |
48///
49/// Use [`Message::with_command_status()`] to record `program`, `exit_status`, and an available `exit_code` together,
50/// or [`Message::with_command_output()`] to include already-captured output. [`Message::with_program()`] and
51/// [`Message::with_exit_status()`] record the fields available at spawn failures or after program identity was lost.
52/// [`Message::with_command()`] records `program` and opts into command text, with its
53/// [privacy implications](Message::with_command). The text is diagnostic, not a stable or executable command line.
54/// If the prepared command is no longer available, use [`Message::with()`] to record the configured command's
55/// debug representation under `command` without inferring `program`.
56///
57/// A failed exit status does not by itself establish a recovery class. Preserve native errors from spawning or
58/// communicating with a program as causes; their contexts can also use `program`, without an exit status or output.
59#[derive(Clone, Default, PartialEq)]
60pub struct Metadata(BTreeMap<Cow<'static, str>, MetadataValue>);
61
62impl Metadata {
63    /// Create an empty dictionary.
64    pub fn new() -> Self {
65        Self::default()
66    }
67
68    /// Return the number of values in this dictionary.
69    pub fn len(&self) -> usize {
70        self.0.len()
71    }
72
73    /// Return whether this dictionary has no values.
74    pub fn is_empty(&self) -> bool {
75        self.0.is_empty()
76    }
77
78    /// Return whether a value is recorded under `key`.
79    pub fn contains_key(&self, key: &str) -> bool {
80        self.0.contains_key(key)
81    }
82
83    /// Return the value recorded under `key`, if present.
84    pub fn get(&self, key: &str) -> Option<&MetadataValue> {
85        self.0.get(key)
86    }
87
88    /// Return a mutable reference to the value recorded under `key`, if present.
89    pub fn get_mut(&mut self, key: &str) -> Option<&mut MetadataValue> {
90        self.0.get_mut(key)
91    }
92
93    /// Record `value` under `key`, returning any previous value.
94    pub fn insert(
95        &mut self,
96        key: impl Into<Cow<'static, str>>,
97        value: impl Into<MetadataValue>,
98    ) -> Option<MetadataValue> {
99        self.0.insert(key.into(), value.into())
100    }
101
102    /// Remove and return the value recorded under `key`, if present.
103    pub fn remove(&mut self, key: &str) -> Option<MetadataValue> {
104        self.0.remove(key)
105    }
106
107    /// Remove all recorded values.
108    pub fn clear(&mut self) {
109        self.0.clear();
110    }
111
112    /// Iterate over keys and values in lexicographic key order.
113    pub fn iter(
114        &self,
115    ) -> impl DoubleEndedIterator<Item = (&Cow<'static, str>, &MetadataValue)> + ExactSizeIterator + '_ {
116        self.0.iter()
117    }
118
119    /// Iterate over keys and mutable values in lexicographic key order.
120    pub fn iter_mut(
121        &mut self,
122    ) -> impl DoubleEndedIterator<Item = (&Cow<'static, str>, &mut MetadataValue)> + ExactSizeIterator + '_ {
123        self.0.iter_mut()
124    }
125}
126
127impl std::ops::Index<&str> for Metadata {
128    type Output = MetadataValue;
129
130    fn index(&self, key: &str) -> &Self::Output {
131        &self.0[key]
132    }
133}
134
135impl FromIterator<(Cow<'static, str>, MetadataValue)> for Metadata {
136    fn from_iter<T: IntoIterator<Item = (Cow<'static, str>, MetadataValue)>>(iter: T) -> Self {
137        Self(iter.into_iter().collect())
138    }
139}
140
141impl<const N: usize> From<[(Cow<'static, str>, MetadataValue); N]> for Metadata {
142    fn from(values: [(Cow<'static, str>, MetadataValue); N]) -> Self {
143        values.into_iter().collect()
144    }
145}
146
147impl Extend<(Cow<'static, str>, MetadataValue)> for Metadata {
148    fn extend<T: IntoIterator<Item = (Cow<'static, str>, MetadataValue)>>(&mut self, iter: T) {
149        self.0.extend(iter);
150    }
151}
152
153impl fmt::Debug for Metadata {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        let mut debug = f.debug_map();
156        for (key, value) in self.iter() {
157            debug.entry(&DebugKey(key), value);
158        }
159        debug.finish()
160    }
161}
162
163struct DebugKey<'a>(&'a str);
164
165impl fmt::Debug for DebugKey<'_> {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        if !self.0.is_empty()
168            && self
169                .0
170                .bytes()
171                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
172        {
173            f.write_str(self.0)
174        } else {
175            fmt::Debug::fmt(self.0, f)
176        }
177    }
178}
179
180/// A diagnostic message with an optional semantic class and named diagnostic values.
181///
182/// Use this instead of chaining message, classification, and scalar-context errors when they describe a single
183/// failure. [`Self::new()`] starts without a class or values; [`Self::with_class()`] and [`Self::with()`] add them.
184/// Class builders such as [`Self::corrupted()`], [`Self::validation()`], [`Self::not_found()`], [`Self::retryable()`],
185/// and [`Self::resource_exhaustion()`] are useful with formatted [`crate::message!`]s.
186/// [`Self::allocation_limit()`] and [`Self::allocation_failure()`] select common resource exhaustion kinds.
187/// Builders ending in `_error`, such as [`Self::corrupted_error()`] and [`Self::validation_error()`],
188/// also raise the classified message as an [`Error`].
189/// Class-based constructors such as [`crate::not_found()`] combine the message and class in one step.
190///
191/// Unlike [`ClassificationMarker`](crate::ClassificationMarker), this is a visible diagnostic: it participates in
192/// error iteration, downcasting, reports, and cause selection. A marker only adds a classification to an existing
193/// error without a diagnostic of its own, preserving that error's concrete type. Both are inspected by [`crate::classify()`].
194/// The class itself isn't displayed, and [`crate::types::Classification::error()`] refers to this error, not a synthetic source.
195///
196/// Preserve real callee errors with [`ResultExt::or_raise()`](crate::ResultExt::or_raise) or
197/// [`Exn::raise()`](crate::Exn::raise). Keep concrete error types when recovery requires a specific condition or payload;
198/// use classification predicates to recognize categories, and document diagnostic keys on the function returning them.
199/// [`Exn::metadata()`](crate::Exn::metadata) and [`crate::Error::metadata()`] yield each message's non-empty value dictionary.
200/// Use [`Exn::metadata_merged()`](crate::Exn::metadata_merged) or [`crate::Error::metadata_merged()`] to combine them,
201/// letting more specific causes override their enclosing contexts. To identify a specific failure, downcast to its
202/// operation's error enum and match a variant; see [matching a specific failure](crate#matching-a-specific-failure).
203///
204/// Debug formatting omits absent classes and empty values. Present classes omit their `Some` wrapper,
205/// and the class and values stay on single lines, even in pretty output.
206pub struct Message {
207    /// The operation or situation described by these values.
208    pub message: Cow<'static, str>,
209    /// The semantic class of this diagnostic, if known.
210    pub class: Option<Class>,
211    /// Diagnostic values, ordered by key. Functions returning metadata document their keys.
212    pub values: Metadata,
213}
214
215/// Lifecycle
216impl Message {
217    /// Create a diagnostic with `message`, no classification, and no values.
218    pub fn new(message: impl Into<Cow<'static, str>>) -> Self {
219        Self {
220            message: message.into(),
221            class: None,
222            values: Metadata::new(),
223        }
224    }
225
226    /// Set `class`, replacing any previous classification without adding a cause.
227    pub fn with_class(mut self, class: Class) -> Self {
228        self.class = Some(class);
229        self
230    }
231}
232
233/// Builders
234impl Message {
235    /// Classify malformed or internally inconsistent stored or streamed data as [`Class::Corruption`].
236    ///
237    /// Like [`Self::with_class()`], this replaces any previous class without changing the message or values or adding a cause.
238    pub fn corrupted(self) -> Self {
239        self.with_class(Class::Corruption)
240    }
241
242    /// Classify malformed or internally inconsistent stored or streamed data and raise it as an [`Error`].
243    ///
244    /// Like [`Self::corrupted()`], this preserves the message and values and replaces any previous class without adding a cause.
245    /// The error records the caller's location, just like [`ErrorExt::raise()`].
246    #[track_caller]
247    pub fn corrupted_error(self) -> Error {
248        self.corrupted().raise()
249    }
250
251    /// Classify invalid function or method input as [`Class::Validation`].
252    ///
253    /// Like [`Self::with_class()`], this replaces any previous class without changing the message or values or adding a cause.
254    pub fn validation(self) -> Self {
255        self.with_class(Class::Validation)
256    }
257
258    /// Classify invalid function or method input and raise it as an [`Error`].
259    ///
260    /// Like [`Self::validation()`], this preserves the message and values and replaces any previous class without adding a cause.
261    /// The error records the caller's location, just like [`ErrorExt::raise()`].
262    #[track_caller]
263    pub fn validation_error(self) -> Error {
264        self.validation().raise()
265    }
266
267    /// Classify a missing resource as [`Class::NotFound`].
268    ///
269    /// Like [`Self::with_class()`], this replaces any previous class without changing the message or values or adding a cause.
270    pub fn not_found(self) -> Self {
271        self.with_class(Class::NotFound)
272    }
273
274    /// Classify a missing resource and raise it as an [`Error`].
275    ///
276    /// Like [`Self::not_found()`], this preserves the message and values and replaces any previous class without adding a cause.
277    /// The error records the caller's location, just like [`ErrorExt::raise()`].
278    #[track_caller]
279    pub fn not_found_error(self) -> Error {
280        self.not_found().raise()
281    }
282
283    /// Classify an operation that may succeed when retried as [`Class::Retryable`].
284    ///
285    /// Like [`Self::with_class()`], this replaces any previous class without changing the message or values or adding a cause.
286    pub fn retryable(self) -> Self {
287        self.with_class(Class::Retryable)
288    }
289
290    /// Classify an operation that may succeed when retried and raise it as an [`Error`].
291    ///
292    /// Like [`Self::retryable()`], this preserves the message and values and replaces any previous class without adding a cause.
293    /// The error records the caller's location, just like [`ErrorExt::raise()`].
294    #[track_caller]
295    pub fn retryable_error(self) -> Error {
296        self.retryable().raise()
297    }
298
299    /// The caller requested cancellation; stop rather than retry.
300    ///
301    /// Replaces any previous class without changing the message or values or adding a cause.
302    pub fn cancelled(self) -> Self {
303        self.with_class(Class::Cancelled)
304    }
305
306    /// Apply [`Self::cancelled()`] and raise the message, recording the caller location.
307    #[track_caller]
308    pub fn cancelled_error(self) -> Error {
309        self.cancelled().raise()
310    }
311
312    /// Authorization or permissions are insufficient; obtain authorization or change permissions.
313    ///
314    /// Replaces any previous class without changing the message or values or adding a cause.
315    pub fn permission_denied(self) -> Self {
316        self.with_class(Class::PermissionDenied)
317    }
318
319    /// Apply [`Self::permission_denied()`] and raise the message, recording the caller location.
320    #[track_caller]
321    pub fn permission_denied_error(self) -> Error {
322        self.permission_denied().raise()
323    }
324
325    /// Credentials are missing or rejected; obtain or refresh credentials.
326    ///
327    /// Replaces any previous class without changing the message or values or adding a cause.
328    pub fn unauthenticated(self) -> Self {
329        self.with_class(Class::Unauthenticated)
330    }
331
332    /// Apply [`Self::unauthenticated()`] and raise the message, recording the caller location.
333    #[track_caller]
334    pub fn unauthenticated_error(self) -> Error {
335        self.unauthenticated().raise()
336    }
337
338    /// Current state conflicts with the operation; refresh or reconcile state before retrying.
339    ///
340    /// Replaces any previous class without changing the message or values or adding a cause.
341    pub fn conflict(self) -> Self {
342        self.with_class(Class::Conflict)
343    }
344
345    /// Apply [`Self::conflict()`] and raise the message, recording the caller location.
346    #[track_caller]
347    pub fn conflict_error(self) -> Error {
348        self.conflict().raise()
349    }
350
351    /// A required capability is unsupported; switch implementation, format, protocol, or strategy.
352    ///
353    /// Replaces any previous class without changing the message or values or adding a cause.
354    pub fn unsupported(self) -> Self {
355        self.with_class(Class::Unsupported)
356    }
357
358    /// Apply [`Self::unsupported()`] and raise the message, recording the caller location.
359    #[track_caller]
360    pub fn unsupported_error(self) -> Error {
361        self.unsupported().raise()
362    }
363
364    /// Classify an exhausted resource as [`Class::ResourceExhaustion`] of `kind`.
365    ///
366    /// Like [`Self::with_class()`], this replaces any previous class without changing the message or values or adding a cause.
367    pub fn resource_exhaustion(self, kind: ResourceExhaustionKind) -> Self {
368        self.with_class(Class::ResourceExhaustion(kind))
369    }
370
371    /// Classify an exhausted resource of `kind` and raise it as an [`Error`].
372    ///
373    /// Like [`Self::resource_exhaustion()`], this preserves the message and values and replaces any previous class without adding a cause.
374    /// The error records the caller's location, just like [`ErrorExt::raise()`].
375    #[track_caller]
376    pub fn resource_exhaustion_error(self, kind: ResourceExhaustionKind) -> Error {
377        self.resource_exhaustion(kind).raise()
378    }
379
380    /// Classify an exceeded application-configured allocation limit.
381    ///
382    /// Like [`Self::resource_exhaustion()`], this preserves the message and values and replaces any previous class without adding a cause.
383    pub fn allocation_limit(self) -> Self {
384        self.resource_exhaustion(ResourceExhaustionKind::AllocationLimit)
385    }
386
387    /// Classify an exceeded application-configured allocation limit and raise it as an [`Error`].
388    ///
389    /// Like [`Self::allocation_limit()`], this preserves the message and values and replaces any previous class without adding a cause.
390    /// The error records the caller's location, just like [`ErrorExt::raise()`].
391    #[track_caller]
392    pub fn allocation_limit_error(self) -> Error {
393        self.allocation_limit().raise()
394    }
395
396    /// Classify an unrepresentable allocation size or memory that could not be reserved.
397    ///
398    /// Like [`Self::resource_exhaustion()`], this preserves the message and values and replaces any previous class without adding a cause.
399    pub fn allocation_failure(self) -> Self {
400        self.resource_exhaustion(ResourceExhaustionKind::AllocationFailure)
401    }
402
403    /// Classify an unrepresentable allocation size or memory that could not be reserved and raise it as an [`Error`].
404    ///
405    /// Like [`Self::allocation_failure()`], this preserves the message and values and replaces any previous class without adding a cause.
406    /// The error records the caller's location, just like [`ErrorExt::raise()`].
407    #[track_caller]
408    pub fn allocation_failure_error(self) -> Error {
409        self.allocation_failure().raise()
410    }
411}
412
413/// Metadata builders
414impl Message {
415    /// Record the offending input using the [input validation schema](Metadata#input-validation).
416    ///
417    /// Replaces `input` in this context, preserving its representation through [`MetadataValue`]. Other values,
418    /// the message, and the classification are unchanged; input does not imply [`Class::Validation`].
419    /// Only record already-known input that is appropriate for diagnostics, never secrets or other sensitive data.
420    pub fn with_input(self, input: impl Into<MetadataValue>) -> Self {
421        self.with("input", input)
422    }
423
424    /// Record command details using the [external program runtime failure schema](Metadata#external-program-runtime-failure).
425    ///
426    /// Records `program` from [`std::process::Command::get_program()`] without resolving it, and `command` as
427    /// the command's [`fmt::Debug`] representation. The text is for diagnostics, not a stable or executable command line.
428    /// Does not execute the command, capture output, or record exit status; use [`Self::with_exit_status()`] for the latter.
429    /// Inspect values through [`crate::Error::metadata()`] or [`crate::Exn::metadata()`] on typed exceptions.
430    ///
431    /// # Privacy
432    ///
433    /// Command details may contain personally identifiable information (PII) or secrets in arguments, paths,
434    /// or explicitly configured environment values. They are stored without redaction and can be exposed when
435    /// the message or its enclosing error is printed with [`fmt::Display`] or [`fmt::Debug`]. Only record details
436    /// that are safe to include in diagnostics; omit or sanitize sensitive information before calling this method.
437    pub fn with_command(self, command: &std::process::Command) -> Self {
438        self.with_program(command.get_program())
439            .with("command", format!("{command:?}"))
440    }
441
442    /// Record a command's program and exit status using the [external program runtime failure schema](Metadata#external-program-runtime-failure).
443    ///
444    /// Replaces `program` with the native program name or path from [`std::process::Command::get_program()`], without
445    /// resolving it, and `exit_status` with the status's display representation. Sets `exit_code` when available,
446    /// otherwise removes any previous `exit_code`. Other values, the message, and the classification are unchanged.
447    /// This does not require a failed status or imply a recovery class, and does not capture output or command text.
448    /// Recording command text requires opting into [`Self::with_command()`] and its privacy implications.
449    pub fn with_command_status(self, command: &std::process::Command, status: std::process::ExitStatus) -> Self {
450        self.with_program(command.get_program()).with_exit_status(status)
451    }
452
453    /// Record an already-known program name or path as `program`, without resolving it or changing the classification.
454    ///
455    /// Use [`std::process::Command::get_program()`] when a prepared command is available.
456    pub fn with_program(self, program: impl AsRef<std::ffi::OsStr>) -> Self {
457        self.with("program", std::path::Path::new(program.as_ref()))
458    }
459
460    /// Record `exit_status` and an available `exit_code` using the
461    /// [external program runtime failure schema](Metadata#external-program-runtime-failure).
462    ///
463    /// Replaces any previous status and removes a previous `exit_code` if this status has none.
464    /// Does not require a failed status, change the classification, or collect program identity or output.
465    pub fn with_exit_status(mut self, status: std::process::ExitStatus) -> Self {
466        self = self.with("exit_status", status.to_string());
467        if let Some(code) = status.code() {
468            self = self.with("exit_code", code);
469        } else {
470            self.values.remove("exit_code");
471        }
472        self
473    }
474
475    /// Record a command's program, exit status, and already-captured output using the
476    /// [external program runtime failure schema](Metadata#external-program-runtime-failure).
477    ///
478    /// Like [`Self::with_command_status()`], replaces the program and status fields, then replaces `stdout` and
479    /// `stderr` with the captured bytes, including empty buffers. Does not execute a command or capture more output.
480    /// Only use this when both streams are appropriate for diagnostics; in particular, do not record credential output.
481    /// Recording command text requires opting into [`Self::with_command()`] and its privacy implications.
482    pub fn with_command_output(self, command: &std::process::Command, output: std::process::Output) -> Self {
483        self.with_command_status(command, output.status)
484            .with("stdout", output.stdout)
485            .with("stderr", output.stderr)
486    }
487
488    /// Add `value` under `key`, replacing any previous value in this context.
489    /// Inspect values through [`crate::Error::metadata()`], or [`crate::Exn::metadata()`] on typed exceptions.
490    pub fn with(mut self, key: impl Into<Cow<'static, str>>, value: impl Into<MetadataValue>) -> Self {
491        self.values.insert(key, value);
492        self
493    }
494}
495
496impl fmt::Debug for Message {
497    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
498        let mut debug = f.debug_struct("Message");
499        debug.field("message", &self.message);
500        if let Some(class) = self.class {
501            debug.field("class", &format_args!("{class:?}"));
502        }
503        if !self.values.is_empty() {
504            debug.field("values", &format_args!("{:?}", self.values));
505        }
506        debug.finish()
507    }
508}
509
510impl fmt::Display for Message {
511    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512        f.write_str(&self.message)?;
513        for (key, value) in self.values.iter() {
514            write!(f, ", {:?}={value}", DebugKey(key))?;
515        }
516        Ok(())
517    }
518}
519
520impl std::error::Error for Message {}
521
522impl From<Cow<'static, str>> for Message {
523    fn from(message: Cow<'static, str>) -> Self {
524        Self::new(message)
525    }
526}
527
528impl From<String> for Message {
529    fn from(message: String) -> Self {
530        Self::new(message)
531    }
532}
533
534impl From<&'static str> for Message {
535    fn from(message: &'static str) -> Self {
536        Self::new(message)
537    }
538}
539
540/// Create a diagnostic for invalid function or method input, classified as [`Class::Validation`].
541///
542/// If the offending input is recorded, use the `input` key from the [input validation schema](Metadata#input-validation).
543pub fn validation(message: impl Into<Cow<'static, str>>) -> Message {
544    Message::new(message).validation()
545}
546
547/// Create a diagnostic for malformed or internally inconsistent data, classified as [`Class::Corruption`].
548pub fn corruption(message: impl Into<Cow<'static, str>>) -> Message {
549    Message::new(message).corrupted()
550}
551
552/// Create a diagnostic for a missing resource, classified as [`Class::NotFound`].
553pub fn not_found(message: impl Into<Cow<'static, str>>) -> Message {
554    Message::new(message).not_found()
555}
556
557/// Create a diagnostic for an operation that may succeed when retried, classified as [`Class::Retryable`].
558pub fn retryable(message: impl Into<Cow<'static, str>>) -> Message {
559    Message::new(message).retryable()
560}
561
562/// The caller requested cancellation; stop rather than retry.
563pub fn cancelled(message: impl Into<Cow<'static, str>>) -> Message {
564    Message::new(message).cancelled()
565}
566
567/// Authorization or permissions are insufficient; obtain authorization or change permissions.
568pub fn permission_denied(message: impl Into<Cow<'static, str>>) -> Message {
569    Message::new(message).permission_denied()
570}
571
572/// Credentials are missing or rejected; obtain or refresh credentials.
573pub fn unauthenticated(message: impl Into<Cow<'static, str>>) -> Message {
574    Message::new(message).unauthenticated()
575}
576
577/// Current state conflicts with the operation; refresh or reconcile state before retrying.
578pub fn conflict(message: impl Into<Cow<'static, str>>) -> Message {
579    Message::new(message).conflict()
580}
581
582/// A required capability is unsupported; switch implementation, format, protocol, or strategy.
583pub fn unsupported(message: impl Into<Cow<'static, str>>) -> Message {
584    Message::new(message).unsupported()
585}
586
587/// Create a diagnostic for an exhausted resource, classified as [`Class::ResourceExhaustion`] of `kind`.
588pub fn resource_exhaustion(kind: ResourceExhaustionKind, message: impl Into<Cow<'static, str>>) -> Message {
589    Message::new(message).resource_exhaustion(kind)
590}
591
592/// Create a diagnostic for an exceeded application-configured allocation limit.
593pub fn allocation_limit(message: impl Into<Cow<'static, str>>) -> Message {
594    Message::new(message).allocation_limit()
595}
596
597/// Create a diagnostic for an unrepresentable allocation size or memory that could not be reserved.
598pub fn allocation_failure(message: impl Into<Cow<'static, str>>) -> Message {
599    Message::new(message).allocation_failure()
600}
601
602/// An owned scalar value in a [`Metadata`] dictionary. Bytes and native paths retain their original representation.
603///
604/// Debug formatting keeps the variant and its value on a single line, even in pretty output.
605/// Byte values always use `Vec<u8>`; the optional `bstr` feature adds conversions from `BString` and `&BStr`.
606#[derive(Clone, PartialEq)]
607#[non_exhaustive]
608pub enum MetadataValue {
609    /// A boolean.
610    Bool(bool),
611    /// A signed integer.
612    I64(i64),
613    /// An unsigned integer.
614    U64(u64),
615    /// A floating-point number.
616    F64(f64),
617    /// UTF-8 text.
618    String(String),
619    /// An arbitrary byte string, pretty-printed on debug or display.
620    Bytes(Vec<u8>),
621    /// A native filesystem path.
622    Path(PathBuf),
623}
624
625impl fmt::Debug for MetadataValue {
626    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627        match self {
628            MetadataValue::Bool(value) => write!(f, "Bool({value:?})"),
629            MetadataValue::I64(value) => write!(f, "I64({value:?})"),
630            MetadataValue::U64(value) => write!(f, "U64({value:?})"),
631            MetadataValue::F64(value) => write!(f, "F64({value:?})"),
632            MetadataValue::String(value) => write!(f, "String({value:?})"),
633            MetadataValue::Bytes(value) => {
634                f.write_str("Bytes(")?;
635                fmt::Debug::fmt(&DebugBytes(value), f)?;
636                f.write_str(")")
637            }
638            MetadataValue::Path(value) => write!(f, "Path({value:?})"),
639        }
640    }
641}
642
643impl fmt::Display for MetadataValue {
644    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
645        match self {
646            MetadataValue::Bool(value) => fmt::Display::fmt(value, f),
647            MetadataValue::I64(value) => fmt::Display::fmt(value, f),
648            MetadataValue::U64(value) => fmt::Display::fmt(value, f),
649            MetadataValue::F64(value) => fmt::Display::fmt(value, f),
650            MetadataValue::String(value) => fmt::Debug::fmt(value, f),
651            MetadataValue::Bytes(value) => fmt::Debug::fmt(&DebugBytes(value), f),
652            MetadataValue::Path(value) => fmt::Debug::fmt(value, f),
653        }
654    }
655}
656
657macro_rules! from {
658    ($variant:ident: $($ty:ty),+ $(,)?) => {
659        $(impl From<$ty> for MetadataValue {
660            fn from(value: $ty) -> Self {
661                Self::$variant(value.into())
662            }
663        })+
664    };
665}
666
667from!(Bool: bool);
668from!(I64: i8, i16, i32, i64);
669from!(U64: u8, u16, u32, u64);
670from!(F64: f32, f64);
671from!(String: String, &str);
672from!(Bytes: Vec<u8>, &[u8]);
673#[cfg(feature = "bstr")]
674from!(Bytes: bstr::BString);
675from!(Path: PathBuf, &std::path::Path);
676
677#[cfg(feature = "bstr")]
678impl From<&bstr::BStr> for MetadataValue {
679    fn from(value: &bstr::BStr) -> Self {
680        Self::Bytes(value.to_vec())
681    }
682}
683
684impl From<usize> for MetadataValue {
685    fn from(value: usize) -> Self {
686        Self::U64(value as u64)
687    }
688}
689
690impl From<isize> for MetadataValue {
691    fn from(value: isize) -> Self {
692        Self::I64(value as i64)
693    }
694}
695
696struct DebugBytes<'a>(&'a [u8]);
697
698impl fmt::Debug for DebugBytes<'_> {
699    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
700        f.write_str("\"")?;
701        let mut bytes = self.0;
702        while !bytes.is_empty() {
703            let (text, invalid) = match std::str::from_utf8(bytes) {
704                Ok(text) => (text, &[][..]),
705                Err(err) => {
706                    let (valid, rest) = bytes.split_at(err.valid_up_to());
707                    let text = std::str::from_utf8(valid).map_err(|_| fmt::Error)?;
708                    (text, &rest[..err.error_len().unwrap_or(rest.len())])
709                }
710            };
711            for ch in text.chars() {
712                match ch {
713                    '\0' => f.write_str("\\0")?,
714                    '\x01'..='\x7f' => write!(f, "{}", (ch as u8).escape_ascii())?,
715                    _ => write!(f, "{}", ch.escape_debug())?,
716                }
717            }
718            for byte in invalid {
719                write!(f, "\\x{byte:02x}")?;
720            }
721            bytes = &bytes[text.len() + invalid.len()..];
722        }
723        f.write_str("\"")
724    }
725}
726
727#[cfg(test)]
728mod tests {
729    #[cfg(feature = "bstr")]
730    #[test]
731    fn bstr_inputs_convert_to_byte_metadata() {
732        let input = b"ref\xff";
733        let owned = bstr::BString::from(input.as_slice());
734        let allocation = owned.as_ptr();
735        let value = super::Message::new("invalid input")
736            .with_input(owned)
737            .values
738            .remove("input");
739        let Some(super::MetadataValue::Bytes(bytes)) = value else {
740            panic!("owned byte strings must become byte metadata");
741        };
742        assert_eq!(bytes, input, "owned input retains every byte");
743        assert_eq!(bytes.as_ptr(), allocation, "owned conversion reuses the allocation");
744        assert_eq!(
745            super::Message::new("invalid input")
746                .with_input(bstr::BStr::new(input))
747                .values["input"],
748            super::MetadataValue::Bytes(bytes),
749            "borrowed byte strings convert directly without losing invalid UTF-8"
750        );
751    }
752
753    #[test]
754    fn byte_metadata_preserves_and_formats_input() {
755        let input = b"hello\0\n\"'\\\xff\xf0\x9f";
756        let value = super::MetadataValue::from(input.as_slice());
757        let super::MetadataValue::Bytes(bytes) = &value else {
758            panic!("byte input must remain byte metadata");
759        };
760        assert_eq!(bytes.as_slice(), input, "metadata retains the exact input bytes");
761        assert_eq!(
762            format!("{value}"),
763            r#""hello\0\n\"\'\\\xff\xf0\x9f""#,
764            "display escapes control characters and truncated UTF-8 without data loss"
765        );
766    }
767
768    #[cfg(feature = "bstr")]
769    #[test]
770    fn dependency_free_byte_formatting_matches_bstr() {
771        for bytes in [
772            Vec::new(),
773            (0..=u8::MAX).collect(),
774            "你好\u{fffd}\u{200d}\n\0\"'\\".as_bytes().to_vec(),
775            b"valid\xf0\x9f\x92\xa9\xff\xe2\x82text\xc0\xaf\xed\xa0\x80\xf0\x9f".to_vec(),
776        ] {
777            assert_eq!(
778                format!("{:?}", super::DebugBytes(&bytes)),
779                format!("{:?}", bstr::BStr::new(&bytes)),
780                "dependency-free formatting preserves UTF-8 and escapes invalid bytes like bstr"
781            );
782        }
783    }
784}