grit_lib/refs/store/mod.rs
1//! Pluggable reference storage: typed transactions and backends.
2//!
3//! The [`RefStore`] trait models Git's ref backend vtable (prepare/commit with
4//! locking, raw reads, iteration, and reflog helpers). [`MemoryRefStore`] is an
5//! embeddable in-memory implementation used by tests and callers that keep refs
6//! outside a repository directory.
7//!
8//! To write your own backend, build `prepare` and `commit` on the [`backend`] helpers,
9//! implement [`RefStore::rewrite_reflog`] with the same writer exclusion as `prepare`/`commit`,
10//! and check it with the `grit_test_support::refstore_conformance` suite.
11
12mod apply;
13pub mod backend;
14mod checked;
15mod error;
16mod files;
17mod linked_worktree;
18mod memory;
19mod open;
20pub mod paths;
21pub(crate) mod reference_transaction;
22mod reftable;
23mod routing;
24mod semantics;
25mod transaction;
26mod types;
27mod validation;
28
29pub(crate) use checked::{open_checked_ref_store, ObjectCheckedRefStore};
30pub use error::{BackendError, RefStoreError};
31pub use files::{FilesRefStore, FilesRefStoreConfig};
32pub(crate) use linked_worktree::LinkedWorktreeRefStore;
33pub use memory::MemoryRefStore;
34pub use open::open_ref_store;
35pub(crate) use open::{initialize_head, open_files_ref_store, open_ref_store_uncached};
36pub use reftable::ReftableRefStore;
37pub(crate) use semantics::format_reflog_identity;
38pub use transaction::RefTransaction;
39pub use types::{
40 Expected, RawRef, RefCaseOnlyRename, RefEntry, RefName, RefReflogRename, RefStorageFormat,
41 RefUpdate, RefUpdateFlags, ReflogUpdate,
42};
43pub(crate) use validation::{
44 validate_reflog_identity_string, validate_reflog_message, validate_reflog_update,
45};
46
47use std::fmt::Debug;
48use std::ops::ControlFlow;
49
50use crate::error::Result;
51use crate::lockfile::LockWait;
52use crate::objects::ObjectId;
53use crate::reflog::ReflogEntry;
54use crate::refs::SYMREF_MAXDEPTH;
55
56type StoreResult<T> = std::result::Result<T, RefStoreError>;
57
58/// Committable ref update batch returned from [`RefStore::prepare`].
59///
60/// The value owns the locks `prepare` took. Exactly one of three things releases them:
61/// [`Self::commit`], [`Self::abort`], or dropping the value. Implementations must release
62/// their locks in `Drop` when neither method ran (callers bail out with `?` between prepare
63/// and commit), leaving stored refs unchanged, so the next `prepare` does not fail with
64/// [`RefStoreError::LockHeld`].
65pub trait PreparedRefTransaction: Send {
66 /// Apply queued updates and release locks.
67 ///
68 /// Every update becomes visible to readers, or (on error) none does where the backend
69 /// can guarantee it.
70 ///
71 /// # Errors
72 ///
73 /// Returns [`RefStoreError`] when the batch can no longer be applied.
74 fn commit(self: Box<Self>) -> StoreResult<()>;
75
76 /// Updates [`RefTransaction::allowing_failures`] skipped during [`Self::commit`]'s prepare.
77 ///
78 /// Empty when the transaction was not prepared with [`RefTransaction::allowing_failures`].
79 fn rejected_updates(&self) -> &[(String, RefStoreError)] {
80 &[]
81 }
82
83 /// Release locks without changing stored refs.
84 ///
85 /// # Errors
86 ///
87 /// Propagates backend errors while releasing resources.
88 fn abort(self: Box<Self>) -> StoreResult<()>;
89}
90
91/// Reference storage backend (loose/packed files, reftable, or in-memory).
92///
93/// # Re-entrant callbacks
94///
95/// The callbacks passed to [`Self::for_each_ref`], [`Self::for_each_reflog_entry`] and
96/// [`Self::for_each_reflog_ref`] may call back into the same store, both to read (resolve a
97/// symref, read each listed ref's reflog) and to write. The set of names to visit is fixed when
98/// the walk starts, so a write made from the callback may not be seen by the walk in progress.
99/// Implementations must not hold internal locks while a callback runs.
100///
101/// # Implementing a backend
102///
103/// Refs are full names (`HEAD`, `refs/heads/main`, …) mapped to a [`RawRef`]. Reads never
104/// resolve symbolic refs except in [`Self::resolve`] and [`RefEntry::peeled`]. Writes only go
105/// through [`Self::prepare`]; see its documentation for the checks it must make. The
106/// [`backend`] module implements those checks and the commit semantics, and the
107/// `grit_test_support::refstore_conformance` suite verifies a store agrees with the built-in
108/// backends. You must implement [`Self::rewrite_reflog`] with the same writer exclusion as
109/// `prepare`/`commit` for that ref; the suite includes a case that fails unsafe read-transform-write
110/// paths. Report failures of your own storage as [`RefStoreError::Backend`] (or
111/// [`crate::error::Error::RefStore`] wrapping it from the `Result` methods).
112pub trait RefStore: Send + Sync + Debug {
113 /// Which on-disk or logical format this store uses.
114 ///
115 /// Custom backends return [`RefStorageFormat::Custom`].
116 fn format(&self) -> RefStorageFormat;
117
118 /// Read the stored value for `name` without resolving symbolic targets.
119 ///
120 /// A missing ref returns `Ok(None)` without allocating a new name string.
121 fn read_raw(&self, name: &str) -> Result<Option<RawRef>>;
122
123 /// Resolve `name` to an object id, following symbolic refs.
124 ///
125 /// Default implementation uses [`Self::read_raw`] and stops after
126 /// [`SYMREF_MAXDEPTH`] hops.
127 ///
128 /// # Errors
129 ///
130 /// Returns [`RefStoreError::SymrefLoop`] when the chain is too deep and
131 /// [`RefStoreError::NotFound`] when `name` or a symbolic target is missing.
132 fn resolve(&self, name: &str) -> Result<ObjectId> {
133 resolve_store(self, name)
134 }
135
136 /// Invoke `f` for each ref whose name starts with `prefix`, in sorted name order.
137 ///
138 /// A non-empty `prefix` is a literal name prefix, so `"H"` or `"HEAD"` lists `HEAD` and
139 /// `"ORIG"` lists `ORIG_HEAD`. An empty `prefix` lists only the refs under `refs/`, like
140 /// `git for-each-ref` with no pattern: root refs such as `HEAD` and `ORIG_HEAD` are left
141 /// out and stay reachable through [`Self::read_raw`] or a non-empty prefix they match.
142 ///
143 /// `f` may call back into the store; see [re-entrant callbacks](Self#re-entrant-callbacks).
144 fn for_each_ref(
145 &self,
146 prefix: &str,
147 f: &mut dyn FnMut(&RefEntry) -> ControlFlow<()>,
148 ) -> Result<()>;
149
150 /// Walk refs stored in this handle's physical reftable stack (`reftable/` under the
151 /// store git directory). On the files backend this matches [`Self::for_each_ref`].
152 fn for_each_physical_stack_ref(
153 &self,
154 prefix: &str,
155 f: &mut dyn FnMut(&RefEntry) -> ControlFlow<()>,
156 ) -> Result<()> {
157 self.for_each_ref(prefix, f)
158 }
159
160 /// Validate `txn`, take locks, and return a committable batch.
161 ///
162 /// Every check runs here, before anything is written, and a failure leaves the store
163 /// unchanged and unlocked. A store must:
164 ///
165 /// 1. Before taking locks, reject names Git refuses to store (an update name or either
166 /// side of a reflog or case-only rename) with [`RefStoreError::InvalidRefName`], a
167 /// symbolic value Git refuses with [`RefStoreError::InvalidSymrefTarget`], an update
168 /// other than a reflog-only one that would store the null object id with
169 /// [`RefStoreError::NullOid`], and malformed reflog identity or message fields with
170 /// [`RefStoreError::InvalidReflog`].
171 /// 2. While another writer holds a lock this transaction needs, fail promptly with
172 /// [`RefStoreError::LockHeld`] naming this transaction's first ref. Do not spin or
173 /// queue: grit-lib's ref writes go through [`crate::refs::prepare_with_lock_wait`],
174 /// which retries with backoff for `core.filesRefLockTimeout`. The files backend takes
175 /// one lock per ref (plus packed-refs when needed), so only the same ref contends.
176 /// A store with one writer slot for everything may report every overlap this way, so
177 /// disjoint refs serialize but still all succeed.
178 /// 3. Reject a created ref whose name is a directory prefix of a stored ref or of
179 /// another ref in the batch, or the other way round (`a` vs `a/b`), with
180 /// [`RefStoreError::NameUnavailable`]. Deletes in the same batch do not free a name.
181 /// 4. Check each [`RefUpdate::expected`] against the state left by the earlier updates
182 /// in the batch ([`RefStoreError::ExpectedMismatch`]). For a direct-value update
183 /// through a symbolic ref, an [`Expected::Oid`] is compared with the resolved id.
184 /// 5. Reject two updates that write the same stored ref, including through symbolic
185 /// refs, with [`RefStoreError::DuplicateUpdate`].
186 ///
187 /// [`backend::check_transaction`] performs steps 1 and 3–5 and
188 /// [`backend::apply_transaction`] defines what [`PreparedRefTransaction::commit`] stores,
189 /// including reflog lines.
190 ///
191 /// A backend does not look at objects. The store
192 /// [`Repository::refs`](crate::repo::Repository::refs) returns (whatever backend it
193 /// wraps, including one injected with
194 /// [`RepositoryBuilder::ref_store`](crate::repo::RepositoryBuilder::ref_store)) adds one
195 /// more check before calling the backend. Each direct value must name an object the
196 /// repository stores ([`RefStoreError::MissingObject`]). A branch (`refs/heads/…`) or
197 /// `HEAD` must name a commit ([`RefStoreError::NotACommit`]). An object that cannot be
198 /// read fails with [`RefStoreError::ObjectLookup`]. Deletes and symbolic values are not
199 /// looked up. Reflog-only updates and explicit reflog object ids are checked like direct
200 /// values. Updates flagged [`RefUpdateFlags::skip_oid_verification`] are not looked up.
201 fn prepare(
202 &self,
203 txn: RefTransaction,
204 ) -> StoreResult<Box<dyn PreparedRefTransaction + Send + '_>>;
205
206 /// Check the objects `updates` would point refs at, without taking any lock or writing.
207 ///
208 /// This is the object check [`Self::prepare`] makes on the store
209 /// [`Repository::refs`](crate::repo::Repository::refs) returns. Writers that update a ref
210 /// without a transaction (the files-backend fast path behind
211 /// [`update_branch_for_commit_on_store`](crate::refs::update_branch_for_commit_on_store))
212 /// call it before locking. Backends do not look at objects, so the default accepts
213 /// everything; there is no need to override it.
214 ///
215 /// # Errors
216 ///
217 /// On the repository's store: [`RefStoreError::MissingObject`],
218 /// [`RefStoreError::NotACommit`] or [`RefStoreError::ObjectLookup`] for the first
219 /// offending update.
220 fn verify_update_targets(&self, updates: &[RefUpdate]) -> StoreResult<()> {
221 let _ = updates;
222 Ok(())
223 }
224
225 /// Hook context when this store runs `reference-transaction` hooks.
226 #[doc(hidden)]
227 fn ref_hook_context(&self) -> Option<&crate::hooks::RefHookContext> {
228 let _ = self;
229 None
230 }
231
232 /// Null object id width for `reference-transaction` stdin on this store.
233 #[doc(hidden)]
234 fn reference_transaction_null_oid(&self) -> ObjectId {
235 crate::diff::zero_oid()
236 }
237
238 /// Whether a reflog is present for `name`.
239 fn reflog_exists(&self, name: &str) -> Result<bool>;
240
241 /// Iterate reflog entries for `name` (oldest first unless `reverse`).
242 ///
243 /// `f` may call back into the store; see [re-entrant callbacks](Self#re-entrant-callbacks).
244 fn for_each_reflog_entry(
245 &self,
246 name: &str,
247 reverse: bool,
248 f: &mut dyn FnMut(&ReflogEntry) -> ControlFlow<()>,
249 ) -> Result<()>;
250
251 /// Create an empty reflog file/record for `name`.
252 fn create_reflog(&self, name: &str) -> Result<()>;
253
254 /// Remove the reflog for `name`.
255 fn delete_reflog(&self, name: &str) -> Result<()>;
256
257 /// Replace the entire reflog (used by expire/delete-entries).
258 fn replace_reflog(&self, name: &str, entries: Vec<ReflogEntry>) -> Result<()>;
259
260 /// Read a reflog under the backend writer lock, transform it, and write it back atomically.
261 ///
262 /// Custom backends must implement this method; there is no default. Hold the same writer
263 /// exclusion as [`Self::prepare`] / [`PreparedRefTransaction::commit`] for the whole
264 /// read-transform-write on `name`, pass the locked re-read of entries into `transform`, and
265 /// do not call back into this store from `transform` (that deadlocks backends that hold a
266 /// mutex across the call).
267 ///
268 /// # Errors
269 ///
270 /// Propagates lock, I/O, and transform failures. [`RefStoreError::ReflogRewriteStale`] is
271 /// returned when a caller compares against a snapshot and the locked re-read no longer
272 /// matches (retry the outer operation).
273 fn rewrite_reflog(
274 &self,
275 name: &str,
276 transform: &mut dyn FnMut(Vec<ReflogEntry>) -> Result<Vec<ReflogEntry>>,
277 ) -> Result<()>;
278
279 /// Invoke `f` for each ref name that has a reflog, in sorted order.
280 ///
281 /// `f` may call back into the store; see [re-entrant callbacks](Self#re-entrant-callbacks).
282 fn for_each_reflog_ref(&self, f: &mut dyn FnMut(&str) -> ControlFlow<()>) -> Result<()>;
283
284 /// The files backend behind this store, when it is one.
285 ///
286 /// Lets callers reuse state the files backend keeps between calls (such as its
287 /// `packed-refs` snapshot) instead of reading the same files again. Other backends,
288 /// including injected ones, return `None`.
289 fn as_files(&self) -> Option<&FilesRefStore> {
290 None
291 }
292
293 /// How long grit-lib retries [`RefStoreError::LockHeld`] from [`Self::prepare`].
294 ///
295 /// The files backend reads `core.filesRefLockTimeout` from its git directory. Injected
296 /// backends return Git's 100 ms default unless a wrapper (such as the store returned by
297 /// [`crate::repo::Repository::refs`]) overrides this from the repository git directory.
298 fn ref_lock_wait(&self) -> LockWait {
299 self.as_files()
300 .map(|files| LockWait::files_ref_lock_for_git_dir(files.git_dir()))
301 .unwrap_or_else(|| LockWait::files_ref_lock(None))
302 }
303}
304
305/// Resolve `name` through `store`, following symbolic refs.
306pub fn resolve_store<S: RefStore + ?Sized>(store: &S, name: &str) -> Result<ObjectId> {
307 resolve_via_raw(store, name, 0).map_err(Into::into)
308}
309
310fn resolve_via_raw<S: RefStore + ?Sized>(
311 store: &S,
312 name: &str,
313 depth: usize,
314) -> StoreResult<ObjectId> {
315 if depth >= SYMREF_MAXDEPTH {
316 return Err(RefStoreError::SymrefLoop);
317 }
318 match store.read_raw(name).map_err(|err| match err {
319 crate::error::Error::RefStore(err) => err,
320 other => RefStoreError::Corrupt(other.to_string()),
321 })? {
322 None => Err(RefStoreError::not_found(name)),
323 Some(RawRef::Direct(oid)) => Ok(oid),
324 Some(RawRef::Symbolic(target)) => resolve_via_raw(store, &target, depth + 1),
325 }
326}