| 1 |
// Copyright 2023 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 |
use std::collections::HashMap; |
| 16 |
use std::fmt::Debug; |
| 17 |
use std::fmt::Error; |
| 18 |
use std::fmt::Formatter; |
| 19 |
use std::path::Path; |
| 20 |
use std::path::PathBuf; |
| 21 |
use std::pin::Pin; |
| 22 |
use std::sync::Arc; |
| 23 |
use std::sync::Mutex; |
| 24 |
use std::sync::MutexGuard; |
| 25 |
use std::time::SystemTime; |
| 26 |
|
| 27 |
use async_trait::async_trait; |
| 28 |
use futures::AsyncRead; |
| 29 |
use futures::AsyncReadExt as _; |
| 30 |
use futures::StreamExt as _; |
| 31 |
use futures::io::Cursor; |
| 32 |
use futures::stream; |
| 33 |
use futures::stream::BoxStream; |
| 34 |
use itertools::Itertools as _; |
| 35 |
use jj_lib::backend::Backend; |
| 36 |
use jj_lib::backend::BackendError; |
| 37 |
use jj_lib::backend::BackendResult; |
| 38 |
use jj_lib::backend::ChangeId; |
| 39 |
use jj_lib::backend::Commit; |
| 40 |
use jj_lib::backend::CommitId; |
| 41 |
use jj_lib::backend::CopyHistory; |
| 42 |
use jj_lib::backend::CopyId; |
| 43 |
use jj_lib::backend::CopyRecord; |
| 44 |
use jj_lib::backend::FileId; |
| 45 |
use jj_lib::backend::RelatedCopy; |
| 46 |
use jj_lib::backend::SecureSig; |
| 47 |
use jj_lib::backend::SigningFn; |
| 48 |
use jj_lib::backend::SymlinkId; |
| 49 |
use jj_lib::backend::Tree; |
| 50 |
use jj_lib::backend::TreeId; |
| 51 |
use jj_lib::backend::make_root_commit; |
| 52 |
use jj_lib::dag_walk::topo_order_reverse; |
| 53 |
use jj_lib::index::Index; |
| 54 |
use jj_lib::object_id::ObjectId as _; |
| 55 |
use jj_lib::repo_path::RepoPath; |
| 56 |
use jj_lib::repo_path::RepoPathBuf; |
| 57 |
use tokio::runtime::Runtime; |
| 58 |
|
| 59 |
const HASH_LENGTH: usize = 10; |
| 60 |
const CHANGE_ID_LENGTH: usize = 16; |
| 61 |
|
| 62 |
// Keyed by canonical store path. Since we just use the path as a key, we can't |
| 63 |
// rely on on the file system to resolve two different uncanonicalized paths to |
| 64 |
// the same real path (as we would if we just used the path with `std::fs` |
| 65 |
// functions). |
| 66 |
type TestBackendDataMap = HashMap<PathBuf, Arc<Mutex<TestBackendData>>>; |
| 67 |
|
| 68 |
#[derive(Default)] |
| 69 |
pub struct TestBackendData { |
| 70 |
commits: HashMap<CommitId, Commit>, |
| 71 |
trees: HashMap<RepoPathBuf, HashMap<TreeId, Tree>>, |
| 72 |
files: HashMap<RepoPathBuf, HashMap<FileId, Vec<u8>>>, |
| 73 |
symlinks: HashMap<RepoPathBuf, HashMap<SymlinkId, String>>, |
| 74 |
copies: HashMap<CopyId, CopyHistory>, |
| 75 |
} |
| 76 |
|
| 77 |
#[derive(Clone, Default)] |
| 78 |
pub struct TestBackendFactory { |
| 79 |
backend_data: Arc<Mutex<TestBackendDataMap>>, |
| 80 |
} |
| 81 |
|
| 82 |
impl TestBackendFactory { |
| 83 |
pub fn init(&self, store_path: &Path) -> TestBackend { |
| 84 |
let data = Arc::new(Mutex::new(TestBackendData::default())); |
| 85 |
self.backend_data |
| 86 |
.lock() |
| 87 |
.unwrap() |
| 88 |
.insert(store_path.canonicalize().unwrap(), data.clone()); |
| 89 |
TestBackend::with_data(data) |
| 90 |
} |
| 91 |
|
| 92 |
pub fn load(&self, store_path: &Path) -> TestBackend { |
| 93 |
let data = self |
| 94 |
.backend_data |
| 95 |
.lock() |
| 96 |
.unwrap() |
| 97 |
.get(&store_path.canonicalize().unwrap()) |
| 98 |
.unwrap() |
| 99 |
.clone(); |
| 100 |
TestBackend::with_data(data) |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
impl Debug for TestBackendFactory { |
| 105 |
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { |
| 106 |
f.debug_struct("TestBackendFactory").finish_non_exhaustive() |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
fn get_hash(content: &(impl jj_lib::content_hash::ContentHash + ?Sized)) -> Vec<u8> { |
| 111 |
jj_lib::content_hash::blake2b_hash(content).as_slice()[..HASH_LENGTH].to_vec() |
| 112 |
} |
| 113 |
|
| 114 |
/// A commit backend for use in tests. |
| 115 |
/// |
| 116 |
/// It's meant to be strict, in order to catch bugs where we make the |
| 117 |
/// wrong assumptions. For example, unlike both `GitBackend` and |
| 118 |
/// `SimpleBackend`, this backend doesn't share objects written to |
| 119 |
/// different paths (writing a file with contents X to path A will not |
| 120 |
/// make it possible to read that contents from path B given the same |
| 121 |
/// `FileId`). |
| 122 |
pub struct TestBackend { |
| 123 |
root_commit_id: CommitId, |
| 124 |
root_change_id: ChangeId, |
| 125 |
empty_tree_id: TreeId, |
| 126 |
data: Arc<Mutex<TestBackendData>>, |
| 127 |
runtime: Runtime, |
| 128 |
} |
| 129 |
|
| 130 |
impl TestBackend { |
| 131 |
pub fn with_data(data: Arc<Mutex<TestBackendData>>) -> Self { |
| 132 |
let root_commit_id = CommitId::from_bytes(&[0; HASH_LENGTH]); |
| 133 |
let root_change_id = ChangeId::from_bytes(&[0; CHANGE_ID_LENGTH]); |
| 134 |
let empty_tree_id = TreeId::new(get_hash(&Tree::default())); |
| 135 |
let runtime = Runtime::new().unwrap(); |
| 136 |
|
| 137 |
Self { |
| 138 |
root_commit_id, |
| 139 |
root_change_id, |
| 140 |
empty_tree_id, |
| 141 |
data, |
| 142 |
runtime, |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
fn locked_data(&self) -> MutexGuard<'_, TestBackendData> { |
| 147 |
self.data.lock().unwrap() |
| 148 |
} |
| 149 |
|
| 150 |
pub fn remove_commit_unchecked(&self, id: &CommitId) { |
| 151 |
self.locked_data().commits.remove(id); |
| 152 |
} |
| 153 |
|
| 154 |
async fn run_async<R: Send + 'static>( |
| 155 |
&self, |
| 156 |
process: impl FnOnce(MutexGuard<TestBackendData>) -> R + Send + 'static, |
| 157 |
) -> R { |
| 158 |
let data = self.data.clone(); |
| 159 |
self.runtime |
| 160 |
.spawn(async move { process(data.lock().unwrap()) }) |
| 161 |
.await |
| 162 |
.unwrap() |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
impl Debug for TestBackend { |
| 167 |
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { |
| 168 |
f.debug_struct("TestBackend").finish_non_exhaustive() |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
#[async_trait] |
| 173 |
impl Backend for TestBackend { |
| 174 |
fn name(&self) -> &'static str { |
| 175 |
"test" |
| 176 |
} |
| 177 |
|
| 178 |
fn commit_id_length(&self) -> usize { |
| 179 |
HASH_LENGTH |
| 180 |
} |
| 181 |
|
| 182 |
fn change_id_length(&self) -> usize { |
| 183 |
CHANGE_ID_LENGTH |
| 184 |
} |
| 185 |
|
| 186 |
fn root_commit_id(&self) -> &CommitId { |
| 187 |
&self.root_commit_id |
| 188 |
} |
| 189 |
|
| 190 |
fn root_change_id(&self) -> &ChangeId { |
| 191 |
&self.root_change_id |
| 192 |
} |
| 193 |
|
| 194 |
fn empty_tree_id(&self) -> &TreeId { |
| 195 |
&self.empty_tree_id |
| 196 |
} |
| 197 |
|
| 198 |
fn concurrency(&self) -> usize { |
| 199 |
// Not optimal, just for testing the async code more |
| 200 |
10 |
| 201 |
} |
| 202 |
|
| 203 |
async fn read_file( |
| 204 |
&self, |
| 205 |
path: &RepoPath, |
| 206 |
id: &FileId, |
| 207 |
) -> BackendResult<Pin<Box<dyn AsyncRead + Send>>> { |
| 208 |
let path = path.to_owned(); |
| 209 |
let id = id.clone(); |
| 210 |
self.run_async(move |data| { |
| 211 |
match data |
| 212 |
.files |
| 213 |
.get(&path) |
| 214 |
.and_then(|items| items.get(&id)) |
| 215 |
.cloned() |
| 216 |
{ |
| 217 |
None => Err(BackendError::ObjectNotFound { |
| 218 |
object_type: "file".to_string(), |
| 219 |
hash: id.hex(), |
| 220 |
source: format!("at path {path:?}").into(), |
| 221 |
}), |
| 222 |
Some(contents) => { |
| 223 |
let reader: Pin<Box<dyn AsyncRead + Send>> = Box::pin(Cursor::new(contents)); |
| 224 |
Ok(reader) |
| 225 |
} |
| 226 |
} |
| 227 |
}) |
| 228 |
.await |
| 229 |
} |
| 230 |
|
| 231 |
async fn write_file( |
| 232 |
&self, |
| 233 |
path: &RepoPath, |
| 234 |
contents: &mut (dyn AsyncRead + Send + Unpin), |
| 235 |
) -> BackendResult<FileId> { |
| 236 |
let path = path.to_owned(); |
| 237 |
let mut bytes = Vec::new(); |
| 238 |
contents.read_to_end(&mut bytes).await.unwrap(); |
| 239 |
self.run_async(move |mut data| { |
| 240 |
let id = FileId::new(get_hash(&bytes)); |
| 241 |
data.files |
| 242 |
.entry(path.clone()) |
| 243 |
.or_default() |
| 244 |
.insert(id.clone(), bytes); |
| 245 |
Ok(id) |
| 246 |
}) |
| 247 |
.await |
| 248 |
} |
| 249 |
|
| 250 |
async fn read_symlink(&self, path: &RepoPath, id: &SymlinkId) -> BackendResult<String> { |
| 251 |
let path = path.to_owned(); |
| 252 |
let id = id.clone(); |
| 253 |
self.run_async(move |data| { |
| 254 |
match data |
| 255 |
.symlinks |
| 256 |
.get(&path) |
| 257 |
.and_then(|items| items.get(&id)) |
| 258 |
.cloned() |
| 259 |
{ |
| 260 |
None => Err(BackendError::ObjectNotFound { |
| 261 |
object_type: "symlink".to_string(), |
| 262 |
hash: id.hex(), |
| 263 |
source: format!("at path {path:?}").into(), |
| 264 |
}), |
| 265 |
Some(target) => Ok(target), |
| 266 |
} |
| 267 |
}) |
| 268 |
.await |
| 269 |
} |
| 270 |
|
| 271 |
async fn write_symlink(&self, path: &RepoPath, target: &str) -> BackendResult<SymlinkId> { |
| 272 |
let id = SymlinkId::new(get_hash(target.as_bytes())); |
| 273 |
let path = path.to_owned(); |
| 274 |
let target = target.to_owned(); |
| 275 |
self.run_async(move |mut data| { |
| 276 |
data.symlinks |
| 277 |
.entry(path) |
| 278 |
.or_default() |
| 279 |
.insert(id.clone(), target); |
| 280 |
Ok(id) |
| 281 |
}) |
| 282 |
.await |
| 283 |
} |
| 284 |
|
| 285 |
async fn read_copy(&self, id: &CopyId) -> BackendResult<CopyHistory> { |
| 286 |
let id = id.clone(); |
| 287 |
self.run_async(move |data| { |
| 288 |
let copy = |
| 289 |
data.copies |
| 290 |
.get(&id) |
| 291 |
.cloned() |
| 292 |
.ok_or_else(|| BackendError::ObjectNotFound { |
| 293 |
object_type: "copy".to_string(), |
| 294 |
hash: id.hex(), |
| 295 |
source: "".into(), |
| 296 |
})?; |
| 297 |
Ok(copy) |
| 298 |
}) |
| 299 |
.await |
| 300 |
} |
| 301 |
|
| 302 |
async fn write_copy(&self, contents: &CopyHistory) -> BackendResult<CopyId> { |
| 303 |
let contents = contents.clone(); |
| 304 |
self.run_async(move |mut data| { |
| 305 |
let id = CopyId::new(get_hash(&contents)); |
| 306 |
data.copies.insert(id.clone(), contents); |
| 307 |
Ok(id) |
| 308 |
}) |
| 309 |
.await |
| 310 |
} |
| 311 |
|
| 312 |
async fn get_related_copies(&self, copy_id: &CopyId) -> BackendResult<Vec<RelatedCopy>> { |
| 313 |
let copy_id = copy_id.clone(); |
| 314 |
self.run_async(move |data| { |
| 315 |
let copies = &data.copies; |
| 316 |
if !copies.contains_key(©_id) { |
| 317 |
return Err(BackendError::ObjectNotFound { |
| 318 |
object_type: "copy history".to_string(), |
| 319 |
hash: copy_id.hex(), |
| 320 |
source: "".into(), |
| 321 |
}); |
| 322 |
} |
| 323 |
// Return all copy histories to test that the caller correctly ignores histories |
| 324 |
// that are not relevant to the trees they're working with. |
| 325 |
let mut histories = vec![]; |
| 326 |
for id in topo_order_reverse( |
| 327 |
copies.keys().sorted(), |
| 328 |
|id| *id, |
| 329 |
|id| copies.get(*id).unwrap().parents.iter(), |
| 330 |
|_| panic!("graph has cycle"), |
| 331 |
) |
| 332 |
.unwrap() |
| 333 |
{ |
| 334 |
histories.push(RelatedCopy { |
| 335 |
id: id.clone(), |
| 336 |
history: copies.get(id).unwrap().clone(), |
| 337 |
}); |
| 338 |
} |
| 339 |
Ok(histories) |
| 340 |
}) |
| 341 |
.await |
| 342 |
} |
| 343 |
|
| 344 |
async fn read_tree(&self, path: &RepoPath, id: &TreeId) -> BackendResult<Tree> { |
| 345 |
if id == &self.empty_tree_id { |
| 346 |
return Ok(Tree::default()); |
| 347 |
} |
| 348 |
let path = path.to_owned(); |
| 349 |
let id = id.clone(); |
| 350 |
self.run_async(move |data| { |
| 351 |
match data |
| 352 |
.trees |
| 353 |
.get(&path) |
| 354 |
.and_then(|items| items.get(&id)) |
| 355 |
.cloned() |
| 356 |
{ |
| 357 |
None => Err(BackendError::ObjectNotFound { |
| 358 |
object_type: "tree".to_string(), |
| 359 |
hash: id.hex(), |
| 360 |
source: format!("at path {path:?}").into(), |
| 361 |
}), |
| 362 |
Some(tree) => Ok(tree), |
| 363 |
} |
| 364 |
}) |
| 365 |
.await |
| 366 |
} |
| 367 |
|
| 368 |
async fn write_tree(&self, path: &RepoPath, contents: &Tree) -> BackendResult<TreeId> { |
| 369 |
let path = path.to_owned(); |
| 370 |
let contents = contents.clone(); |
| 371 |
self.run_async(move |mut data| { |
| 372 |
let id = TreeId::new(get_hash(&contents)); |
| 373 |
data.trees |
| 374 |
.entry(path.clone()) |
| 375 |
.or_default() |
| 376 |
.insert(id.clone(), contents.clone()); |
| 377 |
Ok(id) |
| 378 |
}) |
| 379 |
.await |
| 380 |
} |
| 381 |
|
| 382 |
async fn read_commit(&self, id: &CommitId) -> BackendResult<Commit> { |
| 383 |
if id == &self.root_commit_id { |
| 384 |
return Ok(make_root_commit( |
| 385 |
self.root_change_id.clone(), |
| 386 |
self.empty_tree_id.clone(), |
| 387 |
)); |
| 388 |
} |
| 389 |
let id = id.clone(); |
| 390 |
self.run_async(move |data| match data.commits.get(&id).cloned() { |
| 391 |
None => Err(BackendError::ObjectNotFound { |
| 392 |
object_type: "commit".to_string(), |
| 393 |
hash: id.hex(), |
| 394 |
source: "".into(), |
| 395 |
}), |
| 396 |
Some(commit) => Ok(commit), |
| 397 |
}) |
| 398 |
.await |
| 399 |
} |
| 400 |
|
| 401 |
async fn write_commit( |
| 402 |
&self, |
| 403 |
mut contents: Commit, |
| 404 |
mut sign_with: Option<&mut SigningFn>, |
| 405 |
) -> BackendResult<(CommitId, Commit)> { |
| 406 |
assert!(contents.secure_sig.is_none(), "commit.secure_sig was set"); |
| 407 |
|
| 408 |
if let Some(sign) = &mut sign_with { |
| 409 |
let data = format!("{contents:?}").into_bytes(); |
| 410 |
let sig = sign(&data).map_err(|err| BackendError::Other(Box::new(err)))?; |
| 411 |
contents.secure_sig = Some(SecureSig { data, sig }); |
| 412 |
} |
| 413 |
|
| 414 |
self.run_async(move |mut data| { |
| 415 |
let id = CommitId::new(get_hash(&contents)); |
| 416 |
data.commits.insert(id.clone(), contents.clone()); |
| 417 |
Ok((id, contents)) |
| 418 |
}) |
| 419 |
.await |
| 420 |
} |
| 421 |
|
| 422 |
fn get_copy_records( |
| 423 |
&self, |
| 424 |
_paths: Option<&[RepoPathBuf]>, |
| 425 |
_root: &CommitId, |
| 426 |
_head: &CommitId, |
| 427 |
) -> BackendResult<BoxStream<'_, BackendResult<CopyRecord>>> { |
| 428 |
Ok(stream::empty().boxed()) |
| 429 |
} |
| 430 |
|
| 431 |
fn gc(&self, _index: &dyn Index, _keep_newer: SystemTime) -> BackendResult<()> { |
| 432 |
Ok(()) |
| 433 |
} |
| 434 |
} |
| 435 |
|
| 436 |
#[cfg(test)] |
| 437 |
mod tests { |
| 438 |
|
| 439 |
use pollster::FutureExt as _; |
| 440 |
|
| 441 |
use super::*; |
| 442 |
use crate::TestResult; |
| 443 |
use crate::repo_path_buf; |
| 444 |
|
| 445 |
fn copy_history(path: &str, parents: &[CopyId]) -> CopyHistory { |
| 446 |
CopyHistory { |
| 447 |
current_path: repo_path_buf(path), |
| 448 |
parents: parents.to_vec(), |
| 449 |
salt: vec![], |
| 450 |
} |
| 451 |
} |
| 452 |
|
| 453 |
#[test] |
| 454 |
fn get_related_copies() -> TestResult { |
| 455 |
let backend = TestBackend::with_data(Arc::new(Mutex::new(TestBackendData::default()))); |
| 456 |
|
| 457 |
// Test with a single chain so the resulting order is deterministic |
| 458 |
let copy1 = copy_history("foo1", &[]); |
| 459 |
let copy1_id = backend.write_copy(©1).block_on()?; |
| 460 |
let copy2 = copy_history("foo2", std::slice::from_ref(©1_id)); |
| 461 |
let copy2_id = backend.write_copy(©2).block_on()?; |
| 462 |
let copy3 = copy_history("foo3", std::slice::from_ref(©2_id)); |
| 463 |
let copy3_id = backend.write_copy(©3).block_on()?; |
| 464 |
|
| 465 |
// Error when looking up by non-existent id |
| 466 |
assert!( |
| 467 |
backend |
| 468 |
.get_related_copies(&CopyId::from_hex("abcd")) |
| 469 |
.block_on() |
| 470 |
.is_err() |
| 471 |
); |
| 472 |
|
| 473 |
// Looking up by any id returns the related copies in the same order (children |
| 474 |
// before parents) |
| 475 |
let related = backend.get_related_copies(©1_id).block_on()?; |
| 476 |
assert_eq!( |
| 477 |
related, |
| 478 |
vec![ |
| 479 |
RelatedCopy { |
| 480 |
id: copy3_id.clone(), |
| 481 |
history: copy3.clone() |
| 482 |
}, |
| 483 |
RelatedCopy { |
| 484 |
id: copy2_id.clone(), |
| 485 |
history: copy2.clone() |
| 486 |
}, |
| 487 |
RelatedCopy { |
| 488 |
id: copy1_id.clone(), |
| 489 |
history: copy1.clone() |
| 490 |
}, |
| 491 |
] |
| 492 |
); |
| 493 |
let related = backend.get_related_copies(©3_id).block_on()?; |
| 494 |
assert_eq!( |
| 495 |
related, |
| 496 |
vec![ |
| 497 |
RelatedCopy { |
| 498 |
id: copy3_id.clone(), |
| 499 |
history: copy3.clone() |
| 500 |
}, |
| 501 |
RelatedCopy { |
| 502 |
id: copy2_id.clone(), |
| 503 |
history: copy2.clone() |
| 504 |
}, |
| 505 |
RelatedCopy { |
| 506 |
id: copy1_id.clone(), |
| 507 |
history: copy1.clone() |
| 508 |
}, |
| 509 |
] |
| 510 |
); |
| 511 |
Ok(()) |
| 512 |
} |
| 513 |
} |