Skip to main content

grit_lib/error/
object.rs

1//! [`ObjectError`]: object database, pack, and promisor failures.
2
3use thiserror::Error;
4
5use super::{ErrorSummary, MidxError, ObjectReadFailure};
6
7/// Object database failure: loose objects, packs, indexes, commit-graph, multi-pack-index,
8/// and promisor (partial clone) objects.
9///
10/// Surfaced on the umbrella as [`Error::Object`](crate::error::Error::Object).
11#[derive(Debug, Error)]
12#[non_exhaustive]
13pub enum ObjectError {
14    /// A supplied object ID string was not valid hex or the wrong length.
15    #[error("invalid object id '{input}'")]
16    InvalidId {
17        /// The text that was parsed as an object id.
18        input: String,
19    },
20
21    /// SHA-1 object hashing detected a chosen-prefix collision (sha1dc).
22    #[error("SHA-1 hash collision detected for object {oid}")]
23    HashCollision {
24        /// Plain SHA-1 digest for the colliding input (not safe to use as an object id).
25        oid: crate::objects::ObjectId,
26    },
27
28    /// The requested object does not exist in the object store.
29    #[error("object not found: {name}")]
30    NotFound {
31        /// Object id (hex) or the name that was looked up.
32        name: String,
33    },
34
35    /// A partial-clone promisor object is not present locally and no fetcher ran.
36    #[error("promised object not available locally: {oid}")]
37    PromisedMissing {
38        /// The missing object.
39        oid: crate::objects::ObjectId,
40    },
41
42    /// Promised objects could not be fetched: every promisor remote was asked, and some
43    /// failed. [`Self::PromisedMissing`] is used instead when every remote answered
44    /// but none had the object.
45    #[error("{}", promisor_fetch_failed_message(missing, failures))]
46    PromisorFetchFailed {
47        /// The first object still missing after every remote was tried.
48        missing: crate::objects::ObjectId,
49        /// One entry per remote that failed, in the order they were tried.
50        failures: Vec<PromisorFetchFailure>,
51    },
52
53    /// A promisor fetch triggered further promisor fetches more than `limit` levels deep.
54    #[error("too many nested promisor lazy fetches (limit {limit})")]
55    PromisorFetchTooDeep {
56        /// Maximum nesting of lazy fetches.
57        limit: u32,
58    },
59
60    /// An object's stored data is corrupt or malformed.
61    #[error("corrupt object: {detail}")]
62    Corrupt {
63        /// What is wrong with the object bytes.
64        detail: String,
65    },
66
67    /// A pack index (`.idx`) file's trailing checksum does not match its contents.
68    ///
69    /// Only reported by reads that verify the index trailer, such as
70    /// [`crate::pack::read_pack_index`]; the checksum of the `.pack` the index
71    /// describes is checked separately.
72    #[error("corrupt object: index checksum mismatch for {}: {mismatch}", crate::git_path::user_display_path(.path))]
73    PackIndexChecksumMismatch {
74        /// The `.idx` file that failed verification.
75        path: std::path::PathBuf,
76        /// Expected and stored trailer digests.
77        mismatch: crate::hash::TrailerMismatch,
78    },
79
80    /// Indexing or unpacking a pack left deltas whose bases are neither in the pack nor
81    /// in the object database: a thin pack without its bases, or a ref-delta cycle.
82    #[error("corrupt object: {count} delta(s) could not be resolved")]
83    UnresolvedDeltas {
84        /// Number of deltas left unresolved.
85        count: u64,
86    },
87
88    /// A pack being written that is not thin reached a delta before its base: the base
89    /// is missing from the pack, or the planned deltas form a cycle. The receiver could
90    /// not resolve that delta, so the pack was abandoned.
91    #[error("pack delta for {target} comes before its base {base}")]
92    PackDeltaBaseNotWritten {
93        /// The object that would have been stored as a delta.
94        target: crate::objects::ObjectId,
95        /// Its delta base, not written ahead of it.
96        base: crate::objects::ObjectId,
97    },
98
99    /// [`crate::objects::Objects::write`] refused a payload that `git fsck` would reject;
100    /// nothing was written.
101    #[error("refusing to write invalid {kind} object: {}", .check.report_line())]
102    Invalid {
103        /// Kind the payload was meant to be stored as.
104        kind: crate::objects::ObjectKind,
105        /// The first fsck rule the payload breaks (`check.id` is Git's fsck message id).
106        check: crate::fsck_standalone::FsckError,
107    },
108
109    /// [`crate::objects::Objects::write_tree`] refused an entry.
110    #[error(transparent)]
111    InvalidTreeEntry(#[from] crate::objects::TreeEntryError),
112
113    /// A [`crate::ident::Signature`] cannot be written as an author, committer or tagger line.
114    #[error(transparent)]
115    InvalidSignature(#[from] crate::ident::SignatureError),
116
117    /// An object exists but has a different kind than the operation requires, such as a
118    /// tree or blob where a commit was expected.
119    #[error("object {oid} is a {actual}, not a {expected}")]
120    UnexpectedKind {
121        /// The object that was read.
122        oid: crate::objects::ObjectId,
123        /// The kind the operation required.
124        expected: crate::objects::ObjectKind,
125        /// The kind the object actually has.
126        actual: crate::objects::ObjectKind,
127    },
128
129    /// A commit-graph write was given a commit whose parent is neither among the commits
130    /// being written nor in the base graph layers, so its parent edge cannot be encoded.
131    #[error("commit-graph cannot encode parent {parent} of commit {commit}: parent not in graph")]
132    CommitGraphParentMissing {
133        /// Commit whose parent list was being encoded.
134        commit: crate::objects::ObjectId,
135        /// Parent that is missing from the graph.
136        parent: crate::objects::ObjectId,
137    },
138
139    /// In-pack delta resolution exceeded the read-side chain depth limit (guards
140    /// against cyclic ref-delta chains and unbounded recursion; Git has no read limit).
141    #[error("delta chain too deep (limit {limit})")]
142    DeltaChainTooDeep {
143        /// Maximum delta chain depth allowed while reading packed objects.
144        limit: usize,
145    },
146
147    /// An unsupported or unknown object type was encountered.
148    #[error("unknown object type '{name}'")]
149    UnknownType {
150        /// The type token as read.
151        name: String,
152    },
153
154    /// Loose object header type field exceeds Git's 32-byte limit.
155    #[error("header for {oid} too long, exceeds 32 bytes")]
156    HeaderTooLong {
157        /// Object id (hex) of the loose object with an oversized header.
158        oid: String,
159    },
160
161    /// A zlib compression or decompression failure.
162    #[error("zlib error: {detail}")]
163    Zlib {
164        /// The zlib library's description of the failure.
165        detail: String,
166    },
167
168    /// A loose object file is present but its stored bytes could not be decoded.
169    #[error("loose object {oid} at {} is unreadable: {source}", crate::git_path::user_display_path(.path))]
170    #[non_exhaustive]
171    CorruptLoose {
172        /// Object id implied by the loose object path.
173        oid: crate::objects::ObjectId,
174        /// Path to the loose object file (often under `.git/objects/`).
175        path: std::path::PathBuf,
176        /// Underlying zlib, header, or I/O failure.
177        #[source]
178        source: Box<ObjectReadFailure>,
179    },
180
181    /// A pack entry names the object but its stored bytes could not be decoded.
182    #[error(
183        "packed object {oid} in {} (offset {offset}) is unreadable: {source}",
184        pack.display()
185    )]
186    #[non_exhaustive]
187    CorruptPacked {
188        /// Object id from the pack index.
189        oid: crate::objects::ObjectId,
190        /// Path to the `.pack` file.
191        pack: std::path::PathBuf,
192        /// Byte offset of the object record in the pack.
193        offset: u64,
194        /// Underlying zlib, header, or I/O failure.
195        #[source]
196        source: Box<ObjectReadFailure>,
197    },
198
199    /// Loose object bytes hash to a different OID than the file path implies (`git fsck` / `read_loose_object`).
200    #[error("{real_oid}: hash-path mismatch, found at: {path}")]
201    LooseHashMismatch {
202        /// Repository-relative or filesystem path to the loose object file.
203        path: String,
204        /// Hex object id of the unpacked contents.
205        real_oid: String,
206    },
207
208    /// A prepared loose object could not be written during parallel index staging.
209    #[error("could not store {path}: {source}")]
210    LooseObjectWrite {
211        /// Index-relative path of the blob being stored.
212        path: String,
213        /// Underlying filesystem error from the object store.
214        source: std::io::Error,
215    },
216
217    /// A streamed object write or hash ended before the declared size was read.
218    #[error("object stream ended after {actual} of {expected} bytes")]
219    StreamTruncated {
220        /// Payload size the caller declared.
221        expected: u64,
222        /// Bytes the stream delivered before end of file.
223        actual: u64,
224    },
225
226    /// A bitmap reachability walk could not run or could not read the bitmap.
227    #[error(transparent)]
228    BitmapWalk(#[from] crate::bitmap_walk::BitmapWalkError),
229
230    /// Multi-pack-index load or write failure.
231    #[error(transparent)]
232    Midx(#[from] MidxError),
233
234    /// Offloading blobs to a large-object promisor was refused
235    /// ([`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs)).
236    #[error(transparent)]
237    Offload(#[from] crate::offload::OffloadError),
238
239    /// The operation fetches objects back from a promisor remote, and the repository
240    /// has none: no `remote.<name>.promisor = true` and no `extensions.partialClone`.
241    /// Nothing was changed.
242    #[error("{operation} needs a promisor remote to fetch objects back from")]
243    NoPromisorRemote {
244        /// Operation that was refused (for example `"drop-large-blobs"`).
245        operation: &'static str,
246    },
247}
248
249/// One promisor remote's failure inside [`ObjectError::PromisorFetchFailed`].
250#[derive(Debug, Clone, PartialEq, Eq)]
251#[non_exhaustive]
252pub struct PromisorFetchFailure {
253    /// Name of the promisor remote that was asked.
254    pub remote: String,
255    /// Why fetching from that remote failed.
256    pub error: ErrorSummary,
257}
258
259impl PromisorFetchFailure {
260    /// Record that fetching from `remote` failed with `error`.
261    #[must_use]
262    pub fn new(remote: impl Into<String>, error: &super::Error) -> Self {
263        Self {
264            remote: remote.into(),
265            error: ErrorSummary::from(error),
266        }
267    }
268}
269
270fn promisor_fetch_failed_message(
271    missing: &crate::objects::ObjectId,
272    failures: &[PromisorFetchFailure],
273) -> String {
274    let causes = failures
275        .iter()
276        .map(|f| format!("{}: {}", f.remote, f.error))
277        .collect::<Vec<_>>()
278        .join("; ");
279    format!("could not fetch promised object {missing} ({causes})")
280}
281
282impl ObjectError {
283    /// Stable snake_case slug for this failure (the former umbrella variant names, so
284    /// scripts that branch on [`Error::kind_name`](crate::error::Error::kind_name) keep working).
285    #[must_use]
286    pub fn kind_name(&self) -> &'static str {
287        match self {
288            Self::InvalidId { .. } => "invalid_object_id",
289            Self::HashCollision { .. } => "hash_collision",
290            Self::NotFound { .. } => "object_not_found",
291            Self::PromisedMissing { .. } => "promised_object_missing",
292            Self::PromisorFetchFailed { .. } => "promisor_fetch_failed",
293            Self::PromisorFetchTooDeep { .. } => "promisor_fetch_too_deep",
294            Self::Corrupt { .. } => "corrupt_object",
295            Self::PackIndexChecksumMismatch { .. } => "pack_index_checksum_mismatch",
296            Self::UnresolvedDeltas { .. } => "unresolved_deltas",
297            Self::PackDeltaBaseNotWritten { .. } => "pack_delta_base_not_written",
298            Self::Invalid { .. } => "invalid_object",
299            Self::InvalidTreeEntry(..) => "invalid_tree_entry",
300            Self::InvalidSignature(..) => "invalid_signature",
301            Self::UnexpectedKind { .. } => "unexpected_object_kind",
302            Self::CommitGraphParentMissing { .. } => "commit_graph_parent_missing",
303            Self::DeltaChainTooDeep { .. } => "delta_chain_too_deep",
304            Self::UnknownType { .. } => "unknown_object_type",
305            Self::HeaderTooLong { .. } => "object_header_too_long",
306            Self::Zlib { .. } => "zlib",
307            Self::CorruptLoose { .. } => "corrupt_loose_object",
308            Self::CorruptPacked { .. } => "corrupt_packed_object",
309            Self::LooseHashMismatch { .. } => "loose_hash_mismatch",
310            Self::LooseObjectWrite { .. } => "loose_object_write",
311            Self::StreamTruncated { .. } => "object_stream_truncated",
312            Self::Midx(..) => "midx",
313            Self::BitmapWalk(..) => "bitmap_walk",
314            Self::Offload(..) => "offload",
315            Self::NoPromisorRemote { .. } => "no_promisor_remote",
316        }
317    }
318}