docsrs_cli/error/vocab.rs
1//! Vocabulary the error catalogue is written in.
2//!
3//! These enums name *what* an error is about ([`Subject`]), *which* operation
4//! failed ([`IoOp`], [`InternalOp`]), and *where* a value came from
5//! ([`ValueSource`], [`AllowlistStage`]). They change rarely; the catalogue in
6//! [`super::detail`] grows with every new failure, so the two live apart.
7
8/// The thing an error is about, when the failure shape is generic.
9///
10/// Separating subject from shape is what collapses "crate name is empty",
11/// "search query is empty" and "item path is empty" into one variant.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Subject {
14 /// A crate name (`serde`).
15 CrateName,
16 /// A crate reference (`serde@1.0.0`).
17 CrateRef,
18 /// A search query string.
19 SearchQuery,
20 /// A rustdoc item path (`runtime::Runtime::new`).
21 ItemPath,
22 /// One `::`-separated segment of an item path.
23 ItemPathSegment,
24 /// A semver version argument.
25 Version,
26 /// The `--page-token` opaque pagination cursor.
27 PageToken,
28 /// The HTTP `User-Agent` header value.
29 UserAgent,
30 /// The contact URL or address embedded in the User-Agent.
31 Contact,
32 /// An allowlisted origin URL.
33 Origin,
34 /// The wall-clock request timeout.
35 Timeout,
36 /// The TCP connect timeout.
37 ConnectTimeout,
38 /// The downloaded-body byte budget.
39 MaxBodyBytes,
40 /// The emitted-stdout byte budget.
41 MaxOutputBytes,
42 /// The optional XDG `config.toml`.
43 ConfigFile,
44 /// The `log_directive` tracing filter from `config.toml`.
45 LogDirective,
46}
47
48/// Grammatical gender of a [`Subject`] noun in Portuguese.
49///
50/// Adjectives agree with their noun in pt-BR, so "consulta … vazia" but "nome …
51/// vazio". Without this the renderer produced "consulta de busca está vazio",
52/// which reads as broken Portuguese — the kind of defect a translation table
53/// keyed on English prose can never surface, because English has no agreement.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum GenderPtBr {
56 /// Masculine noun (`nome`, `caminho`, `contato`).
57 Masculine,
58 /// Feminine noun (`consulta`, `versão`, `referência`).
59 Feminine,
60}
61
62impl Subject {
63 /// Gender of this subject's Portuguese noun, for adjective agreement.
64 pub(crate) fn gender_pt_br(self) -> GenderPtBr {
65 match self {
66 // "referência", "consulta", "versão", "URL"
67 Self::CrateRef | Self::SearchQuery | Self::Version | Self::Origin => {
68 GenderPtBr::Feminine
69 }
70 // "nome", "caminho", "segmento", "contato", plus knob identifiers
71 // that stay verbatim and read as masculine tokens.
72 Self::CrateName
73 | Self::ItemPath
74 | Self::ItemPathSegment
75 | Self::PageToken
76 | Self::UserAgent
77 | Self::Contact
78 | Self::Timeout
79 | Self::ConnectTimeout
80 | Self::MaxBodyBytes
81 | Self::MaxOutputBytes
82 | Self::ConfigFile
83 | Self::LogDirective => GenderPtBr::Masculine,
84 }
85 }
86
87 /// Whether this subject is operator configuration rather than command input.
88 ///
89 /// Drives the [`ErrorKind`] split: a bad crate name is `invalid_input`
90 /// (exit 65) because the caller typed it this run, while a bad origin is
91 /// `config` (exit 78) because it lives in `config.toml`. Same failure
92 /// *shape*, different remedy — and agents branch on the exit code.
93 pub(super) fn is_operator_config(self) -> bool {
94 matches!(
95 self,
96 Self::Origin | Self::UserAgent | Self::Contact | Self::ConfigFile | Self::LogDirective
97 )
98 }
99}
100
101/// Which layer supplied a value that failed validation.
102///
103/// The same limit is reachable from a flag and from `config.toml`, and the two
104/// carry different exit codes (65 vs 78) because they need different fixes.
105/// Recording the layer keeps one variant serving both without guessing.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum ValueSource {
108 /// Passed as a CLI flag in this invocation.
109 CommandLine,
110 /// Read from the XDG `config.toml`.
111 ConfigFile,
112}
113
114/// A filesystem or process operation that failed, for [`crate::error::ErrorDetail::Io`].
115///
116/// Named rather than free text so both languages describe the same act and the
117/// underlying `std::io::Error` stays on the source chain where it belongs.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum IoOp {
120 /// Reading a file.
121 Read,
122 /// Writing a file.
123 Write,
124 /// Creating a directory.
125 CreateDir,
126 /// Creating a temporary file.
127 CreateTemp,
128 /// Renaming a path into place.
129 Rename,
130 /// Flushing data to durable storage.
131 Sync,
132 /// Installing a generated file at its destination.
133 Install,
134 /// Opening a lock file.
135 OpenLock,
136 /// Taking an exclusive lock.
137 Lock,
138 /// Listing a directory.
139 ReadDir,
140 /// Removing an entry.
141 Remove,
142}
143
144/// An internal invariant or infrastructure failure, for [`crate::error::ErrorDetail::Internal`].
145///
146/// These are bugs or host problems, never user input. They are still localized:
147/// the operator reading stderr deserves their own language even when the cause
148/// on the source chain is upstream English.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub enum InternalOp {
151 /// Serializing a value to JSON.
152 JsonSerialize,
153 /// Pretty-printing JSON.
154 JsonPrettyPrint,
155 /// Writing to stdout.
156 StdoutWrite,
157 /// An embedded schema document is not valid JSON.
158 EmbeddedSchemaInvalid,
159 /// A built URL was rejected by the parser.
160 UrlBuild,
161 /// The concurrency semaphore was closed.
162 SemaphoreClosed,
163 /// A CPU worker task failed to join.
164 WorkerJoin,
165 /// A CPU worker panicked mid-parse.
166 WorkerPanic,
167 /// The system clock is before the UNIX epoch.
168 ClockBeforeEpoch,
169 /// A cache key did not satisfy its own format invariant.
170 CacheKeyMalformed,
171 /// An associated-item path reached the builder with too few segments.
172 AssocPathTooShort,
173 /// A probe table named a member kind as a parent page host.
174 AssocParentOwnsNoPage,
175 /// An already-validated origin failed to re-parse.
176 AllowedOriginUnparseable,
177 /// Injected failure used by tests to exercise the CPU-bound error path.
178 SyntheticParseFailure,
179}
180
181/// Where an allowlist rejection happened.
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub enum AllowlistStage {
184 /// The URL the caller asked for.
185 Request,
186 /// A hop inside the redirect chain.
187 Redirect,
188 /// The URL the chain finally landed on.
189 FinalUrl,
190}
191
192/// Which payload flavour a response was expected to carry.
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub enum ContentKind {
195 /// `text/html`
196 Html,
197 /// `application/json`
198 Json,
199}
200
201/// What a destructive verb would have done to the target it was refused.
202///
203/// The refusal message has to name the harm, and "would delete" is false for a
204/// verb that overwrites. Carrying the effect as an enum rather than a phrase
205/// keeps both locales honest: a third kind of harm cannot ship until the
206/// exhaustive match in each renderer is taught the word for it.
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub enum DestructiveEffect {
209 /// The target and its contents would be removed (`cache clear`).
210 Delete,
211 /// The target would be replaced in place (`config init --force`).
212 Overwrite,
213}
214
215/// Why an I/O failure is or is not worth another attempt.
216///
217/// Retryability is a property of the operating-system cause, never of the call
218/// site: `ENOSPC` on the cache directory clears when the operator frees space,
219/// and `EACCES` on the same path does not. Classifying once, where the
220/// [`std::io::Error`] is still in hand, is what stops the envelope from
221/// promising an agent a retry that can only ever fail.
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223pub enum IoCause {
224 /// The condition can clear without the caller changing anything.
225 Transient,
226 /// The condition needs operator action; retrying repeats the failure.
227 Permanent,
228}
229
230impl IoCause {
231 /// Classify an OS error by whether waiting could plausibly help.
232 ///
233 /// Unknown kinds classify as [`Self::Permanent`]. An agent that stops early
234 /// on a transient fault wastes one run; an agent that retries a permanent
235 /// one spins until its budget is gone, so the safe default is to stop.
236 pub fn of(err: &std::io::Error) -> Self {
237 use std::io::ErrorKind as K;
238 match err.kind() {
239 K::StorageFull
240 | K::Interrupted
241 | K::WouldBlock
242 | K::TimedOut
243 | K::ResourceBusy
244 | K::QuotaExceeded => Self::Transient,
245 _ => Self::Permanent,
246 }
247 }
248
249 /// True when another attempt is worth making.
250 pub fn retryable(self) -> bool {
251 matches!(self, Self::Transient)
252 }
253}