| 1 |
// Copyright 2020 The Jujutsu Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
//! Interfaces for indexes of the commits in a repository. |
| 16 |
|
| 17 |
use std::any::Any; |
| 18 |
use std::fmt::Debug; |
| 19 |
use std::sync::Arc; |
| 20 |
|
| 21 |
use async_trait::async_trait; |
| 22 |
use itertools::Itertools as _; |
| 23 |
use thiserror::Error; |
| 24 |
|
| 25 |
use crate::backend::ChangeId; |
| 26 |
use crate::backend::CommitId; |
| 27 |
use crate::commit::Commit; |
| 28 |
use crate::object_id::HexPrefix; |
| 29 |
use crate::object_id::PrefixResolution; |
| 30 |
use crate::operation::Operation; |
| 31 |
use crate::repo_path::RepoPathBuf; |
| 32 |
use crate::revset::ResolvedExpression; |
| 33 |
use crate::revset::Revset; |
| 34 |
use crate::revset::RevsetEvaluationError; |
| 35 |
use crate::store::Store; |
| 36 |
|
| 37 |
/// Returned by [`IndexStore`] in the event of an error. |
| 38 |
#[derive(Debug, Error)] |
| 39 |
pub enum IndexStoreError { |
| 40 |
/// Error reading a [`ReadonlyIndex`] from the [`IndexStore`]. |
| 41 |
#[error("Failed to read index")] |
| 42 |
Read(#[source] Box<dyn std::error::Error + Send + Sync>), |
| 43 |
/// Error writing a [`MutableIndex`] to the [`IndexStore`]. |
| 44 |
#[error("Failed to write index")] |
| 45 |
Write(#[source] Box<dyn std::error::Error + Send + Sync>), |
| 46 |
} |
| 47 |
|
| 48 |
/// Result of [`IndexStore`] operations. |
| 49 |
pub type IndexStoreResult<T> = Result<T, IndexStoreError>; |
| 50 |
|
| 51 |
/// Returned by [`Index`] backend in the event of an error. |
| 52 |
#[derive(Debug, Error)] |
| 53 |
pub enum IndexError { |
| 54 |
/// Error returned if [`Index::all_heads_for_gc()`] is not supported by the |
| 55 |
/// [`Index`] backend. |
| 56 |
#[error("Cannot collect all heads by index of this type")] |
| 57 |
AllHeadsForGcUnsupported, |
| 58 |
/// Some other index error. |
| 59 |
#[error(transparent)] |
| 60 |
Other(Box<dyn std::error::Error + Send + Sync>), |
| 61 |
} |
| 62 |
|
| 63 |
/// Result of [`Index`] operations. |
| 64 |
pub type IndexResult<T> = Result<T, IndexError>; |
| 65 |
|
| 66 |
/// Defines the interface for types that provide persistent storage for an |
| 67 |
/// index. |
| 68 |
#[async_trait(?Send)] |
| 69 |
pub trait IndexStore: Any + Send + Sync + Debug { |
| 70 |
/// Returns a name representing the type of index that the `IndexStore` is |
| 71 |
/// compatible with. For example, the `IndexStore` for the default index |
| 72 |
/// returns "default". |
| 73 |
fn name(&self) -> &str; |
| 74 |
|
| 75 |
/// Returns the index at the specified operation. |
| 76 |
async fn get_index_at_op( |
| 77 |
&self, |
| 78 |
op: &Operation, |
| 79 |
store: &Arc<Store>, |
| 80 |
) -> IndexStoreResult<Box<dyn ReadonlyIndex>>; |
| 81 |
|
| 82 |
/// Writes `index` to the index store and returns a read-only version of the |
| 83 |
/// index. |
| 84 |
fn write_index( |
| 85 |
&self, |
| 86 |
index: Box<dyn MutableIndex>, |
| 87 |
op: &Operation, |
| 88 |
) -> IndexStoreResult<Box<dyn ReadonlyIndex>>; |
| 89 |
} |
| 90 |
|
| 91 |
impl dyn IndexStore { |
| 92 |
/// Returns reference of the implementation type. |
| 93 |
pub fn downcast_ref<T: IndexStore>(&self) -> Option<&T> { |
| 94 |
(self as &dyn Any).downcast_ref() |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
/// Defines the interface for types that provide an index of the commits in a |
| 99 |
/// repository by [`CommitId`]. |
| 100 |
#[async_trait] |
| 101 |
pub trait Index: Send + Sync { |
| 102 |
/// Returns the minimum prefix length to disambiguate `commit_id` from other |
| 103 |
/// commits in the index. The length returned is the number of hexadecimal |
| 104 |
/// digits in the minimum prefix. |
| 105 |
/// |
| 106 |
/// If the given `commit_id` doesn't exist, returns the minimum prefix |
| 107 |
/// length which matches none of the commits in the index. |
| 108 |
async fn shortest_unique_commit_id_prefix_len( |
| 109 |
&self, |
| 110 |
commit_id: &CommitId, |
| 111 |
) -> IndexResult<usize>; |
| 112 |
|
| 113 |
/// Searches the index for commit IDs matching `prefix`. Returns a |
| 114 |
/// [`PrefixResolution`] with a [`CommitId`] if the prefix matches a single |
| 115 |
/// commit. |
| 116 |
async fn resolve_commit_id_prefix( |
| 117 |
&self, |
| 118 |
prefix: &HexPrefix, |
| 119 |
) -> IndexResult<PrefixResolution<CommitId>>; |
| 120 |
|
| 121 |
/// Returns true if `commit_id` is present in the index. |
| 122 |
async fn has_id(&self, commit_id: &CommitId) -> IndexResult<bool>; |
| 123 |
|
| 124 |
/// Returns true if `ancestor_id` commit is an ancestor of the |
| 125 |
/// `descendant_id` commit, or if `ancestor_id` equals `descendant_id`. |
| 126 |
async fn is_ancestor( |
| 127 |
&self, |
| 128 |
ancestor_id: &CommitId, |
| 129 |
descendant_id: &CommitId, |
| 130 |
) -> IndexResult<bool>; |
| 131 |
|
| 132 |
/// Returns the best common ancestor or ancestors of the commits in `set1` |
| 133 |
/// and `set2`. A "best common ancestor" has no descendants that are also |
| 134 |
/// common ancestors. |
| 135 |
async fn common_ancestors( |
| 136 |
&self, |
| 137 |
set1: &[CommitId], |
| 138 |
set2: &[CommitId], |
| 139 |
) -> IndexResult<Vec<CommitId>>; |
| 140 |
|
| 141 |
/// Heads among all indexed commits at the associated operation. |
| 142 |
/// |
| 143 |
/// Suppose the index contains all the historical heads and their ancestors |
| 144 |
/// reachable from the associated operation, this function returns the heads |
| 145 |
/// that should be preserved on garbage collection. |
| 146 |
/// |
| 147 |
/// The iteration order is unspecified. |
| 148 |
fn all_heads_for_gc(&self) -> IndexResult<Box<dyn Iterator<Item = CommitId> + '_>>; |
| 149 |
|
| 150 |
/// Returns the subset of commit IDs in `candidates` which are not ancestors |
| 151 |
/// of other commits in `candidates`. If a commit id is duplicated in the |
| 152 |
/// `candidates` list it will appear at most once in the output. |
| 153 |
async fn heads( |
| 154 |
&self, |
| 155 |
candidates: &mut (dyn Iterator<Item = &CommitId> + Send), |
| 156 |
) -> IndexResult<Vec<CommitId>>; |
| 157 |
|
| 158 |
/// Returns iterator over paths changed at the specified commit. The paths |
| 159 |
/// are sorted. Returns `None` if the commit wasn't indexed. |
| 160 |
async fn changed_paths_in_commit( |
| 161 |
&self, |
| 162 |
commit_id: &CommitId, |
| 163 |
) -> IndexResult<Option<Box<dyn Iterator<Item = RepoPathBuf> + '_>>>; |
| 164 |
|
| 165 |
/// Resolves the revset `expression` against the index and corresponding |
| 166 |
/// `store`. |
| 167 |
fn evaluate_revset( |
| 168 |
&self, |
| 169 |
expression: &ResolvedExpression, |
| 170 |
store: &Arc<Store>, |
| 171 |
) -> Result<Box<dyn Revset + '_>, RevsetEvaluationError>; |
| 172 |
} |
| 173 |
|
| 174 |
#[expect(missing_docs)] |
| 175 |
pub trait ReadonlyIndex: Any + Send + Sync { |
| 176 |
fn as_index(&self) -> &dyn Index; |
| 177 |
|
| 178 |
fn change_id_index(&self, heads: &mut dyn Iterator<Item = &CommitId>) |
| 179 |
-> Box<dyn ChangeIdIndex>; |
| 180 |
|
| 181 |
fn start_modification(&self) -> Box<dyn MutableIndex>; |
| 182 |
} |
| 183 |
|
| 184 |
impl dyn ReadonlyIndex { |
| 185 |
/// Returns reference of the implementation type. |
| 186 |
pub fn downcast_ref<T: ReadonlyIndex>(&self) -> Option<&T> { |
| 187 |
(self as &dyn Any).downcast_ref() |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
#[expect(missing_docs)] |
| 192 |
#[async_trait] |
| 193 |
pub trait MutableIndex: Any { |
| 194 |
fn as_index(&self) -> &dyn Index; |
| 195 |
|
| 196 |
fn change_id_index( |
| 197 |
&self, |
| 198 |
heads: &mut dyn Iterator<Item = &CommitId>, |
| 199 |
) -> Box<dyn ChangeIdIndex + '_>; |
| 200 |
|
| 201 |
async fn add_commit(&mut self, commit: &Commit) -> IndexResult<()>; |
| 202 |
|
| 203 |
fn merge_in(&mut self, other: &dyn ReadonlyIndex) -> IndexResult<()>; |
| 204 |
} |
| 205 |
|
| 206 |
impl dyn MutableIndex { |
| 207 |
/// Downcasts to the implementation type. |
| 208 |
pub fn downcast<T: MutableIndex>(self: Box<Self>) -> Option<Box<T>> { |
| 209 |
(self as Box<dyn Any>).downcast().ok() |
| 210 |
} |
| 211 |
|
| 212 |
/// Returns reference of the implementation type. |
| 213 |
pub fn downcast_ref<T: MutableIndex>(&self) -> Option<&T> { |
| 214 |
(self as &dyn Any).downcast_ref() |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
/// The state of a commit with a given change ID. |
| 219 |
#[derive(Copy, Clone, Eq, PartialEq, Debug)] |
| 220 |
pub enum ResolvedChangeState { |
| 221 |
/// The commit is visible (reachable from the visible heads). |
| 222 |
Visible, |
| 223 |
/// The commit is hidden (not reachable from the visible heads). |
| 224 |
Hidden, |
| 225 |
} |
| 226 |
|
| 227 |
/// Represents the possible target commits of a resolved change ID. If the |
| 228 |
/// change is divergent, there may be multiple visible commits. Hidden commits |
| 229 |
/// can also be returned to allow showing a change offset number in the evolog. |
| 230 |
#[derive(Clone, Eq, PartialEq, Debug)] |
| 231 |
pub struct ResolvedChangeTargets { |
| 232 |
/// All indexed commits with this change ID. The sort order of the commits |
| 233 |
/// is determined by the index implementation, but it is preferred that more |
| 234 |
/// recent commits should be sorted before later commits when possible. All |
| 235 |
/// visible commits must be included, but some hidden commits may be omitted |
| 236 |
/// if it would be inefficient for the index to support them. |
| 237 |
pub targets: Vec<(CommitId, ResolvedChangeState)>, |
| 238 |
} |
| 239 |
|
| 240 |
impl ResolvedChangeTargets { |
| 241 |
/// Returns an iterator over all visible commits for this change ID, as well |
| 242 |
/// as their offsets. |
| 243 |
pub fn visible_with_offsets(&self) -> impl Iterator<Item = (usize, &CommitId)> { |
| 244 |
self.targets |
| 245 |
.iter() |
| 246 |
.enumerate() |
| 247 |
.filter_map(|(i, (target, state))| { |
| 248 |
(*state == ResolvedChangeState::Visible).then_some((i, target)) |
| 249 |
}) |
| 250 |
} |
| 251 |
|
| 252 |
/// Returns true if the commit ID is one of the visible targets of this |
| 253 |
/// change ID. |
| 254 |
pub fn has_visible(&self, commit: &CommitId) -> bool { |
| 255 |
self.visible_with_offsets() |
| 256 |
.any(|(_, target)| target == commit) |
| 257 |
} |
| 258 |
|
| 259 |
/// Returns true if there are multiple visible targets for this change ID. |
| 260 |
pub fn is_divergent(&self) -> bool { |
| 261 |
self.visible_with_offsets().take(2).count() > 1 |
| 262 |
} |
| 263 |
|
| 264 |
/// Returns the commit ID at a given offset. The change offset of a commit |
| 265 |
/// can be found using [`ResolvedChangeTargets::find_offset`]. |
| 266 |
pub fn at_offset(&self, offset: usize) -> Option<&CommitId> { |
| 267 |
self.targets.get(offset).map(|(target, _state)| target) |
| 268 |
} |
| 269 |
|
| 270 |
/// Finds the change offset corresponding to a commit. Newer commits should |
| 271 |
/// generally have a lower offset than older commits, but this is not |
| 272 |
/// guaranteed. Hidden commits may not have an offset at all. |
| 273 |
pub fn find_offset(&self, commit_id: &CommitId) -> Option<usize> { |
| 274 |
self.targets |
| 275 |
.iter() |
| 276 |
.position(|(target, _state)| target == commit_id) |
| 277 |
} |
| 278 |
|
| 279 |
/// Extracts the visible commits for this change ID. Returns `None` if there |
| 280 |
/// are no visible commits with this change ID. |
| 281 |
pub fn into_visible(self) -> Option<Vec<CommitId>> { |
| 282 |
let visible = self |
| 283 |
.targets |
| 284 |
.into_iter() |
| 285 |
.filter_map(|(target, state)| (state == ResolvedChangeState::Visible).then_some(target)) |
| 286 |
.collect_vec(); |
| 287 |
(!visible.is_empty()).then_some(visible) |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
/// Defines the interface for types that provide an index of the commits in a |
| 292 |
/// repository by [`ChangeId`]. |
| 293 |
#[async_trait] |
| 294 |
pub trait ChangeIdIndex: Send + Sync { |
| 295 |
/// Resolve an unambiguous change ID prefix to the commit IDs in the index. |
| 296 |
async fn resolve_prefix( |
| 297 |
&self, |
| 298 |
prefix: &HexPrefix, |
| 299 |
) -> IndexResult<PrefixResolution<ResolvedChangeTargets>>; |
| 300 |
|
| 301 |
/// This function returns the shortest length of a prefix of `key` that |
| 302 |
/// disambiguates it from every other key in the index. |
| 303 |
/// |
| 304 |
/// The length returned is a number of hexadecimal digits. |
| 305 |
/// |
| 306 |
/// This has some properties that we do not currently make much use of: |
| 307 |
/// |
| 308 |
/// - The algorithm works even if `key` itself is not in the index. |
| 309 |
/// |
| 310 |
/// - In the special case when there are keys in the trie for which our |
| 311 |
/// `key` is an exact prefix, returns `key.len() + 1`. Conceptually, in |
| 312 |
/// order to disambiguate, you need every letter of the key *and* the |
| 313 |
/// additional fact that it's the entire key). This case is extremely |
| 314 |
/// unlikely for hashes with 12+ hexadecimal characters. |
| 315 |
async fn shortest_unique_prefix_len(&self, change_id: &ChangeId) -> IndexResult<usize>; |
| 316 |
} |