Debian Codegraph @

lib/src/op_heads_store.rs

raw
1 // Copyright 2021 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 #![expect(missing_docs)]
16
17 use std::any::Any;
18 use std::collections::HashSet;
19 use std::fmt::Debug;
20 use std::sync::Arc;
21
22 use async_trait::async_trait;
23 use futures::future::try_join_all;
24 use itertools::Itertools as _;
25 use thiserror::Error;
26
27 use crate::dag_walk_async;
28 use crate::op_store::OpStore;
29 use crate::op_store::OpStoreError;
30 use crate::op_store::OperationId;
31 use crate::operation::Operation;
32
33 #[derive(Debug, Error)]
34 pub enum OpHeadsStoreError {
35 #[error("Failed to read operation heads")]
36 Read(#[source] Box<dyn std::error::Error + Send + Sync>),
37 #[error("Failed to record operation head {new_op_id}")]
38 Write {
39 new_op_id: OperationId,
40 source: Box<dyn std::error::Error + Send + Sync>,
41 },
42 #[error("Failed to lock operation heads store")]
43 Lock(#[source] Box<dyn std::error::Error + Send + Sync>),
44 }
45
46 pub trait OpHeadsStoreLock {}
47
48 /// Manages the set of current heads of the operation log.
49 #[async_trait]
50 pub trait OpHeadsStore: Any + Send + Sync + Debug {
51 fn name(&self) -> &str;
52
53 /// Remove the old op heads and add the new one.
54 ///
55 /// If the old op heads contains the new one, then the update effectively
56 /// removes all specified old operations except for the new one.
57 async fn update_op_heads(
58 &self,
59 old_ids: &[OperationId],
60 new_id: &OperationId,
61 ) -> Result<(), OpHeadsStoreError>;
62
63 /// Return the current op heads. The returned list must not be empty; it
64 /// must contain the root operation if there are no later op heads.
65 async fn get_op_heads(&self) -> Result<Vec<OperationId>, OpHeadsStoreError>;
66
67 /// Optionally takes a lock on the op heads store. The purpose of the lock
68 /// is to prevent concurrent processes from resolving the same divergent
69 /// operations. It is not needed for correctness; implementations are free
70 /// to return a type that doesn't hold a lock.
71 async fn lock(&self) -> Result<Box<dyn OpHeadsStoreLock + '_>, OpHeadsStoreError>;
72 }
73
74 impl dyn OpHeadsStore {
75 /// Returns reference of the implementation type.
76 pub fn downcast_ref<T: OpHeadsStore>(&self) -> Option<&T> {
77 (self as &dyn Any).downcast_ref()
78 }
79 }
80
81 // Given an OpHeadsStore, fetch and resolve its op heads down to one under a
82 // lock.
83 //
84 // This routine is defined outside the trait because it must support generics.
85 pub async fn resolve_op_heads<E>(
86 op_heads_store: &dyn OpHeadsStore,
87 op_store: &Arc<dyn OpStore>,
88 resolver: impl AsyncFnOnce(Vec<Operation>) -> Result<Operation, E>,
89 ) -> Result<Operation, E>
90 where
91 E: From<OpHeadsStoreError> + From<OpStoreError>,
92 {
93 // This can be empty if the OpHeadsStore doesn't support atomic updates.
94 // For example, all entries ahead of a readdir() pointer could be deleted by
95 // another concurrent process.
96 let mut op_heads = op_heads_store.get_op_heads().await?;
97
98 if op_heads.len() == 1 {
99 let operation_id = op_heads.pop().unwrap();
100 let operation = op_store.read_operation(&operation_id).await?;
101 return Ok(Operation::new(op_store.clone(), operation_id, operation));
102 }
103
104 // There are no/multiple heads. We take a lock, then check if there are
105 // still no/multiple heads (it's likely that another process was in the
106 // process of deleting on of them). If there are still multiple heads, we
107 // attempt to merge all the views into one. We then write that view and a
108 // corresponding operation to the op-store.
109 // Note that the locking isn't necessary for correctness of merge; we take
110 // the lock only to prevent other concurrent processes from doing the same
111 // work (and producing another set of divergent heads).
112 let _lock = op_heads_store.lock().await?;
113 let op_head_ids = op_heads_store.get_op_heads().await?;
114 assert!(!op_head_ids.is_empty());
115
116 if op_head_ids.len() == 1 {
117 let op_head_id = op_head_ids[0].clone();
118 let op_head = op_store.read_operation(&op_head_id).await?;
119 return Ok(Operation::new(op_store.clone(), op_head_id, op_head));
120 }
121
122 let op_heads: Vec<_> = try_join_all(op_head_ids.iter().map(
123 async |op_id: &OperationId| -> Result<Operation, OpStoreError> {
124 let data = op_store.read_operation(op_id).await?;
125 Ok(Operation::new(op_store.clone(), op_id.clone(), data))
126 },
127 ))
128 .await?;
129 // Remove ancestors so we don't create merge operation with an operation and its
130 // ancestor
131 let op_head_ids_before: HashSet<_> = op_heads.iter().map(|op| op.id().clone()).collect();
132 let filtered_op_heads = dag_walk_async::heads(
133 op_heads,
134 |op: &Operation| op.id().clone(),
135 async |op: &Operation| op.parents().await,
136 )
137 .await?;
138 let op_head_ids_after: HashSet<_> =
139 filtered_op_heads.iter().map(|op| op.id().clone()).collect();
140 let ancestor_op_heads = op_head_ids_before
141 .difference(&op_head_ids_after)
142 .cloned()
143 .collect_vec();
144 let mut op_heads = filtered_op_heads.into_iter().collect_vec();
145
146 // Return without creating a merge operation
147 if let [op_head] = &*op_heads {
148 op_heads_store
149 .update_op_heads(&ancestor_op_heads, op_head.id())
150 .await?;
151 return Ok(op_head.clone());
152 }
153
154 op_heads.sort_by_key(|op| op.metadata().time.end.timestamp);
155 let new_op = resolver(op_heads).await?;
156 let mut old_op_heads = ancestor_op_heads;
157 old_op_heads.extend_from_slice(new_op.parent_ids());
158 op_heads_store
159 .update_op_heads(&old_op_heads, new_op.id())
160 .await?;
161 Ok(new_op)
162 }