Skip to main content

jj_lib/
simple_op_heads_store.rs

1// Copyright 2021-2022 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
17use std::fmt::Debug;
18use std::fmt::Formatter;
19use std::fs;
20use std::io;
21use std::path::Path;
22use std::path::PathBuf;
23
24use async_trait::async_trait;
25use thiserror::Error;
26
27use crate::backend::BackendInitError;
28use crate::file_util::IoResultExt as _;
29use crate::file_util::PathError;
30use crate::hex_util;
31use crate::lock::FileLock;
32use crate::object_id::ObjectId as _;
33use crate::op_heads_store::OpHeadsStore;
34use crate::op_heads_store::OpHeadsStoreError;
35use crate::op_heads_store::OpHeadsStoreLock;
36use crate::op_store::OperationId;
37
38/// Error that may occur during [`SimpleOpHeadsStore`] initialization.
39#[derive(Debug, Error)]
40#[error("Failed to initialize simple operation heads store")]
41pub struct SimpleOpHeadsStoreInitError(#[from] pub PathError);
42
43impl From<SimpleOpHeadsStoreInitError> for BackendInitError {
44    fn from(err: SimpleOpHeadsStoreInitError) -> Self {
45        Self(err.into())
46    }
47}
48
49pub struct SimpleOpHeadsStore {
50    dir: PathBuf,
51}
52
53impl Debug for SimpleOpHeadsStore {
54    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
55        f.debug_struct("SimpleOpHeadsStore")
56            .field("dir", &self.dir)
57            .finish()
58    }
59}
60
61impl SimpleOpHeadsStore {
62    pub const NAME: &str = "simple_op_heads_store";
63
64    pub fn init(dir: &Path, root_op_id: &OperationId) -> Result<Self, SimpleOpHeadsStoreInitError> {
65        let op_heads_dir = dir.join("heads");
66        fs::create_dir(&op_heads_dir).context(&op_heads_dir)?;
67        let store = Self { dir: op_heads_dir };
68        store.add_op_head(root_op_id)?;
69        Ok(store)
70    }
71
72    pub fn load(dir: &Path) -> Self {
73        let op_heads_dir = dir.join("heads");
74        Self { dir: op_heads_dir }
75    }
76
77    fn add_op_head(&self, id: &OperationId) -> Result<(), PathError> {
78        let path = self.dir.join(id.hex());
79        std::fs::write(&path, "").context(path)
80    }
81
82    fn remove_op_head(&self, id: &OperationId) -> Result<(), PathError> {
83        let path = self.dir.join(id.hex());
84        std::fs::remove_file(&path)
85            .or_else(|err| {
86                if err.kind() == io::ErrorKind::NotFound {
87                    // It's fine if the old head was not found. It probably means
88                    // that we're on a distributed file system where the locking
89                    // doesn't work. We'll probably end up with two current
90                    // heads. We'll detect that next time we load the view.
91                    Ok(())
92                } else {
93                    Err(err)
94                }
95            })
96            .context(path)
97    }
98}
99
100struct SimpleOpHeadsStoreLock {
101    _lock: FileLock,
102}
103
104impl OpHeadsStoreLock for SimpleOpHeadsStoreLock {}
105
106#[async_trait]
107impl OpHeadsStore for SimpleOpHeadsStore {
108    fn name(&self) -> &str {
109        Self::NAME
110    }
111
112    async fn update_op_heads(
113        &self,
114        old_ids: &[OperationId],
115        new_id: &OperationId,
116    ) -> Result<(), OpHeadsStoreError> {
117        self.add_op_head(new_id)
118            .map_err(|err| OpHeadsStoreError::Write {
119                new_op_id: new_id.clone(),
120                source: err.into(),
121            })?;
122        for old_id in old_ids {
123            if old_id == new_id {
124                continue;
125            }
126            self.remove_op_head(old_id)
127                .map_err(|err| OpHeadsStoreError::Write {
128                    new_op_id: new_id.clone(),
129                    source: err.into(),
130                })?;
131        }
132        Ok(())
133    }
134
135    async fn get_op_heads(&self) -> Result<Vec<OperationId>, OpHeadsStoreError> {
136        let mut op_heads = vec![];
137        for op_head_entry in
138            std::fs::read_dir(&self.dir).map_err(|err| OpHeadsStoreError::Read(err.into()))?
139        {
140            let op_head_file_name = op_head_entry
141                .map_err(|err| OpHeadsStoreError::Read(err.into()))?
142                .file_name();
143            let op_head_file_name = op_head_file_name.to_str().ok_or_else(|| {
144                OpHeadsStoreError::Read(
145                    format!("Non-utf8 in op head file name: {op_head_file_name:?}").into(),
146                )
147            })?;
148            if let Some(op_head) = hex_util::decode_hex(op_head_file_name) {
149                op_heads.push(OperationId::new(op_head));
150            }
151        }
152        op_heads.sort();
153        if op_heads.is_empty() {
154            Err(OpHeadsStoreError::Read(
155                "Corrupt repository: no head operation".into(),
156            ))
157        } else {
158            Ok(op_heads)
159        }
160    }
161
162    async fn lock(&self) -> Result<Box<dyn OpHeadsStoreLock + '_>, OpHeadsStoreError> {
163        let lock = FileLock::lock(self.dir.join("lock"))
164            .map_err(|err| OpHeadsStoreError::Lock(err.into()))?;
165        Ok(Box::new(SimpleOpHeadsStoreLock { _lock: lock }))
166    }
167}
168
169#[cfg(test)]
170mod tests {
171
172    use std::slice;
173
174    use pollster::FutureExt as _;
175
176    use super::*;
177    use crate::tests::TestResult;
178
179    #[test]
180    fn test_op_heads() -> TestResult {
181        let dir = tempfile::tempdir()?;
182
183        let op1 = OperationId::from_hex("1111");
184        let op2 = OperationId::from_hex("2222");
185        let op3 = OperationId::from_hex("3333");
186        let op4 = OperationId::from_hex("4444");
187
188        // Initial op head is respected
189        let op_heads_store = SimpleOpHeadsStore::init(dir.path(), &op1)?;
190        let op_heads = op_heads_store.get_op_heads().block_on()?;
191        assert_eq!(op_heads, vec![op1.clone()]);
192
193        // Simple replacement
194        op_heads_store
195            .update_op_heads(slice::from_ref(&op1), &op2)
196            .block_on()?;
197        let op_heads = op_heads_store.get_op_heads().block_on()?;
198        assert_eq!(op_heads, vec![op2.clone()]);
199
200        // Duplicating is a no-op
201        op_heads_store.update_op_heads(&[], &op2).block_on()?;
202        let op_heads = op_heads_store.get_op_heads().block_on()?;
203        assert_eq!(op_heads, vec![op2.clone()]);
204
205        // Deleting non-head is a no-op
206        op_heads_store
207            .update_op_heads(slice::from_ref(&op1), &op2)
208            .block_on()?;
209        let op_heads = op_heads_store.get_op_heads().block_on()?;
210        assert_eq!(op_heads, vec![op2.clone()]);
211
212        // Can create multiple heads
213        op_heads_store.update_op_heads(&[], &op3).block_on()?;
214        let op_heads = op_heads_store.get_op_heads().block_on()?;
215        assert_eq!(op_heads, vec![op2.clone(), op3.clone()]);
216
217        // Can replace multiple heads
218        op_heads_store
219            .update_op_heads(&[op2.clone(), op3.clone()], &op4)
220            .block_on()?;
221        let op_heads = op_heads_store.get_op_heads().block_on()?;
222        assert_eq!(op_heads, vec![op4.clone()]);
223
224        // Can replace multiple heads by one of the old heads
225        op_heads_store.update_op_heads(&[], &op3).block_on()?;
226        op_heads_store
227            .update_op_heads(&[op3.clone(), op4.clone()], &op4)
228            .block_on()?;
229        let op_heads = op_heads_store.get_op_heads().block_on()?;
230        assert_eq!(op_heads, vec![op4.clone()]);
231
232        Ok(())
233    }
234}