| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
|
| 17 | |
|
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | |
|
| 22 | |
|
| 23 | |
|
| 24 | |
|
| 25 | |
|
| 26 | |
|
| 27 | |
|
| 28 | | use super::{fail, Repo, RepoError, Result}; |
| 29 | | use crate::hash::{ChangeHash, ObjectRef, ObjectType}; |
| 30 | | use crate::objects::StateObject; |
| 31 | | use crate::protocol::{ |
| 32 | | wire, Bundle, RefResult, RefUpdate, RefsResponse, Remote, RemoteOptions, SignedPolicy, TagRef, |
| 33 | | UNBOUND_ID, |
| 34 | | }; |
| 35 | | use crate::strata::{Error as StoreError, Store, Version}; |
| 36 | | use std::cell::RefCell; |
| 37 | | use std::collections::BTreeSet; |
| 38 | | use std::fs; |
| 39 | | use std::path::{Path, PathBuf}; |
| 40 | |
|
| 41 | | const MARKER_KEY: &str = "oxygen.toml"; |
| 42 | | const REFS_KEY: &str = "refs"; |
| 43 | | const BUNDLES_PREFIX: &str = "bundles/"; |
| 44 | | const FORMAT: u32 = 1; |
| 45 | |
|
| 46 | | impl From<StoreError> for RepoError { |
| 47 | 1× | fn from(e: StoreError) -> RepoError { |
| 48 | 1× | RepoError::Msg(e.to_string()) |
| 49 | 1× | } |
| 50 | | } |
| 51 | |
|
| 52 | |
|
| 53 | 11× | fn marker(id: [u8; 16]) -> Vec<u8> { |
| 54 | 11× | format!("format = {FORMAT}\nrepo = \"{}\"\n", hex::encode(id)).into_bytes() |
| 55 | 11× | } |
| 56 | |
|
| 57 | 115× | fn parse_marker(bytes: &[u8], what: &str) -> Result<[u8; 16]> { |
| 58 | 115× | let text = String::from_utf8_lossy(bytes); |
| 59 | 115× | let mut format = None; |
| 60 | 115× | let mut repo = None; |
| 61 | 229× | for line in text.lines() { |
| 62 | 229× | let Some((k, v)) = line.split_once('=') else { |
| 63 | 1× | continue; |
| 64 | | }; |
| 65 | 228× | let v = v.trim().trim_matches('"'); |
| 66 | 228× | match k.trim() { |
| 67 | 228× | "format" => format = v.parse::<u32>().ok(), |
| 68 | 114× | "repo" => { |
| 69 | 114× | repo = hex::decode(v) |
| 70 | 114× | .ok() |
| 71 | 114× | .and_then(|b| <[u8; 16]>::try_from(b).ok()) |
| 72 | | } |
| 73 | 0× | _ => {} |
| 74 | | } |
| 75 | | } |
| 76 | 115× | match (format, repo) { |
| 77 | 114× | (Some(f), _) if f > FORMAT => fail(format!( |
| 78 | | "{what} holds a repository in Strata format {f}, newer than this oxy understands (format {FORMAT}): upgrade oxy" |
| 79 | | )), |
| 80 | 113× | (Some(_), Some(id)) => Ok(id), |
| 81 | 1× | _ => fail(format!("{what}: its oxygen.toml is not a Strata marker")), |
| 82 | | } |
| 83 | 115× | } |
| 84 | |
|
| 85 | |
|
| 86 | | pub struct BucketRemote { |
| 87 | | store: Box<dyn Store>, |
| 88 | | |
| 89 | | |
| 90 | | |
| 91 | | dir: PathBuf, |
| 92 | | temporary: bool, |
| 93 | | claimed_id: Option<[u8; 16]>, |
| 94 | | mirror: RefCell<Option<Repo>>, |
| 95 | | } |
| 96 | |
|
| 97 | | impl Drop for BucketRemote { |
| 98 | 59× | fn drop(&mut self) { |
| 99 | 59× | if self.temporary { |
| 100 | 9× | let _ = fs::remove_dir_all(&self.dir); |
| 101 | 50× | } |
| 102 | 59× | } |
| 103 | | } |
| 104 | |
|
| 105 | |
|
| 106 | |
|
| 107 | | struct Synced { |
| 108 | | version: Option<Version>, |
| 109 | | id: Option<[u8; 16]>, |
| 110 | | } |
| 111 | |
|
| 112 | | impl BucketRemote { |
| 113 | 59× | pub fn open(store: Box<dyn Store>, options: &RemoteOptions) -> Result<BucketRemote> { |
| 114 | 59× | let (dir, temporary) = match &options.cache_dir { |
| 115 | 50× | Some(d) => (d.clone(), false), |
| 116 | | None => { |
| 117 | 9× | let mut nonce = [0u8; 6]; |
| 118 | 9× | rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut nonce); |
| 119 | 9× | ( |
| 120 | 9× | std::env::temp_dir().join(format!( |
| 121 | 9× | "oxy-strata-{}-{}", |
| 122 | 9× | std::process::id(), |
| 123 | 9× | hex::encode(nonce) |
| 124 | 9× | )), |
| 125 | 9× | true, |
| 126 | 9× | ) |
| 127 | | } |
| 128 | | }; |
| 129 | 59× | Ok(BucketRemote { |
| 130 | 59× | store, |
| 131 | 59× | dir, |
| 132 | 59× | temporary, |
| 133 | 59× | claimed_id: options.repo_id, |
| 134 | 59× | mirror: RefCell::new(None), |
| 135 | 59× | }) |
| 136 | 59× | } |
| 137 | |
|
| 138 | 113× | fn what(&self) -> String { |
| 139 | 113× | self.store.describe() |
| 140 | 113× | } |
| 141 | |
|
| 142 | | |
| 143 | 137× | fn stored_id(&self) -> Result<Option<[u8; 16]>> { |
| 144 | 137× | match self.store.get(MARKER_KEY) { |
| 145 | 111× | Ok(b) => Ok(Some(parse_marker(&b, &self.what())?)), |
| 146 | 26× | Err(StoreError::NotFound(_)) => Ok(None), |
| 147 | 0× | Err(e) => Err(e.into()), |
| 148 | | } |
| 149 | 137× | } |
| 150 | |
|
| 151 | 48× | fn mirror_dir(&self) -> PathBuf { |
| 152 | 48× | self.dir.join("mirror") |
| 153 | 48× | } |
| 154 | |
|
| 155 | 179× | fn seen_path(&self) -> PathBuf { |
| 156 | 179× | self.dir.join("seen") |
| 157 | 179× | } |
| 158 | |
|
| 159 | | |
| 160 | 128× | fn seen(&self) -> BTreeSet<String> { |
| 161 | 128× | fs::read_to_string(self.seen_path()) |
| 162 | 128× | .map(|s| s.lines().map(str::to_string).collect()) |
| 163 | 128× | .unwrap_or_default() |
| 164 | 128× | } |
| 165 | |
|
| 166 | 51× | fn mark_seen(&self, key: &str) -> Result<()> { |
| 167 | 51× | let mut seen = self.seen(); |
| 168 | 51× | if seen.insert(key.to_string()) { |
| 169 | 114× | let text: String = seen.iter().map(|k| format!("{k}\n")).collect(); |
| 170 | 51× | crate::durable::write_atomic(&self.seen_path(), text.as_bytes())?; |
| 171 | 0× | } |
| 172 | 51× | Ok(()) |
| 173 | 51× | } |
| 174 | |
|
| 175 | | |
| 176 | 77× | fn open_mirror(&self, id: [u8; 16]) -> Result<()> { |
| 177 | 77× | if self.mirror.borrow().is_some() { |
| 178 | 29× | return Ok(()); |
| 179 | 48× | } |
| 180 | 48× | let dir = self.mirror_dir(); |
| 181 | 48× | let repo = if dir.join(super::OXY_DIR).is_dir() { |
| 182 | 27× | let repo = Repo::open(&dir)?; |
| 183 | 27× | if repo.id()? != id { |
| 184 | | |
| 185 | | |
| 186 | 0× | drop(repo); |
| 187 | 0× | fs::remove_dir_all(&self.dir)?; |
| 188 | 0× | fs::create_dir_all(&self.dir)?; |
| 189 | 0× | Repo::init_bare_with_id(&dir, id)? |
| 190 | | } else { |
| 191 | 27× | repo |
| 192 | | } |
| 193 | | } else { |
| 194 | 21× | fs::create_dir_all(&self.dir)?; |
| 195 | 21× | Repo::init_bare_with_id(&dir, id)? |
| 196 | | }; |
| 197 | 48× | *self.mirror.borrow_mut() = Some(repo); |
| 198 | 48× | Ok(()) |
| 199 | 77× | } |
| 200 | |
|
| 201 | 230× | fn with_mirror<T>(&self, f: impl FnOnce(&Repo) -> Result<T>) -> Result<T> { |
| 202 | 230× | let m = self.mirror.borrow(); |
| 203 | 230× | match m.as_ref() { |
| 204 | 230× | Some(repo) => f(repo), |
| 205 | 0× | None => fail(format!( |
| 206 | | "{} holds no repository yet: push one to it first", |
| 207 | 0× | self.what() |
| 208 | | )), |
| 209 | | } |
| 210 | 230× | } |
| 211 | |
|
| 212 | | |
| 213 | 96× | fn sync(&self) -> Result<Synced> { |
| 214 | 96× | let Some(id) = self.stored_id()? else { |
| 215 | 19× | return Ok(Synced { |
| 216 | 19× | version: None, |
| 217 | 19× | id: None, |
| 218 | 19× | }); |
| 219 | | }; |
| 220 | 77× | self.open_mirror(id)?; |
| 221 | 77× | let record = self.store.read_ref(REFS_KEY)?; |
| 222 | 77× | let (resp, version) = match record { |
| 223 | 67× | Some((bytes, version)) => { |
| 224 | 67× | let (rid, resp) = wire::decode_refs(&bytes)?; |
| 225 | 67× | if rid != id { |
| 226 | 0× | return fail(format!( |
| 227 | | "{}: its refs record names a different repository than its oxygen.toml; the store is damaged", |
| 228 | 0× | self.what() |
| 229 | | )); |
| 230 | 67× | } |
| 231 | 67× | (resp, Some(version)) |
| 232 | | } |
| 233 | 10× | None => (RefsResponse::default(), None), |
| 234 | | }; |
| 235 | 77× | self.with_mirror(|mirror| { |
| 236 | | |
| 237 | | |
| 238 | 77× | mirror.refresh()?; |
| 239 | | |
| 240 | 77× | if let Some(sp) = &resp.policy { |
| 241 | 0× | let have = mirror.current_policy()?.map(|(_, p)| p.policy.serial); |
| 242 | 0× | if have.is_none_or(|s| s < sp.policy.serial) { |
| 243 | 0× | mirror |
| 244 | 0× | .adopt_policy_chain(&resp.history, sp, "strata sync") |
| 245 | 0× | .map_err(|e| RepoError::Msg(format!("policy from {}: {e}", self.what())))?; |
| 246 | 0× | } |
| 247 | 77× | } |
| 248 | 77× | self.import_new_bundles(mirror)?; |
| 249 | 76× | self.set_view(mirror, &resp)?; |
| 250 | 75× | Ok(()) |
| 251 | 77× | })?; |
| 252 | 75× | Ok(Synced { |
| 253 | 75× | version, |
| 254 | 75× | id: Some(id), |
| 255 | 75× | }) |
| 256 | 96× | } |
| 257 | |
|
| 258 | | |
| 259 | | |
| 260 | | |
| 261 | | |
| 262 | 77× | fn import_new_bundles(&self, mirror: &Repo) -> Result<()> { |
| 263 | 77× | let seen = self.seen(); |
| 264 | 77× | let mut pending: Vec<String> = self |
| 265 | 77× | .store |
| 266 | 77× | .list(BUNDLES_PREFIX)? |
| 267 | 77× | .into_iter() |
| 268 | 77× | .map(|e| e.key) |
| 269 | 116× | .filter(|k| !seen.contains(k)) |
| 270 | 77× | .collect(); |
| 271 | 77× | let strict = mirror.current_policy()?.is_some(); |
| 272 | 96× | while !pending.is_empty() { |
| 273 | 20× | let mut deferred = Vec::new(); |
| 274 | 20× | let mut last_error = None; |
| 275 | 20× | let before = pending.len(); |
| 276 | 28× | for key in pending.drain(..) { |
| 277 | 28× | let bytes = match self.store.get(&key) { |
| 278 | 27× | Ok(b) => b, |
| 279 | | |
| 280 | | |
| 281 | 1× | Err(StoreError::NotFound(_)) => continue, |
| 282 | 0× | Err(e) => return Err(e.into()), |
| 283 | | }; |
| 284 | 27× | let bundle = wire::decode_bundle(&bytes) |
| 285 | 27× | .map_err(|e| RepoError::Msg(format!("{}: {key}: {e}", self.what())))?; |
| 286 | 27× | match mirror.import_bundle(&bundle, strict) { |
| 287 | 24× | Ok(_) => self.mark_seen(&key)?, |
| 288 | 3× | Err(RepoError::Msg(m)) if m.contains("neither stored nor in the bundle") => { |
| 289 | 3× | last_error = Some(m); |
| 290 | 3× | deferred.push(key); |
| 291 | 3× | } |
| 292 | 0× | Err(e) => return Err(RepoError::Msg(format!("{}: {key}: {e}", self.what()))), |
| 293 | | } |
| 294 | | } |
| 295 | 20× | if deferred.len() == before { |
| 296 | | |
| 297 | | |
| 298 | 1× | return fail(format!( |
| 299 | | "{}: {} cannot be imported ({}); a push may be in progress, so try again, else the store is missing changes", |
| 300 | 1× | self.what(), |
| 301 | 1× | deferred.join(", "), |
| 302 | 1× | last_error.unwrap_or_default() |
| 303 | | )); |
| 304 | 19× | } |
| 305 | 19× | pending = deferred; |
| 306 | | } |
| 307 | 76× | Ok(()) |
| 308 | 77× | } |
| 309 | |
|
| 310 | | |
| 311 | 76× | fn set_view(&self, mirror: &Repo, resp: &RefsResponse) -> Result<()> { |
| 312 | 76× | let (op_ref, op) = mirror.head_op()?; |
| 313 | 76× | let mut view = op.view.clone(); |
| 314 | 76× | view.bookmarks.clear(); |
| 315 | 76× | for r in &resp.refs { |
| 316 | 71× | for h in &r.heads { |
| 317 | 71× | if !mirror.store.has(h) { |
| 318 | 1× | return fail(format!( |
| 319 | | "{}: bookmark {:?} names change {}, which no bundle there holds; a push may be in progress, so try again", |
| 320 | 1× | self.what(), |
| 321 | | r.name, |
| 322 | 1× | h.short(12) |
| 323 | | )); |
| 324 | 70× | } |
| 325 | | } |
| 326 | 67× | let state = mirror.store.put_state(&StateObject::new(r.heads.clone()))?; |
| 327 | 67× | if state != r.state { |
| 328 | 0× | return fail(format!( |
| 329 | | "{}: bookmark {:?} names a state that does not match its heads; the store is damaged", |
| 330 | 0× | self.what(), |
| 331 | | r.name |
| 332 | | )); |
| 333 | 67× | } |
| 334 | 67× | if let Some(sa) = &r.attestation { |
| 335 | 8× | let current = mirror.latest_ref_attest(&r.name)?.map(|(_, a)| a); |
| 336 | 8× | if current.as_ref() != Some(sa) { |
| 337 | 3× | let a = mirror.store.put_attest(&sa.attest)?; |
| 338 | 3× | for sig in &sa.sigs { |
| 339 | 3× | mirror.store.put_signature(&a, sig)?; |
| 340 | | } |
| 341 | 3× | mirror.set_ref_attest(&r.name, &a)?; |
| 342 | 5× | } |
| 343 | 59× | } |
| 344 | 67× | view.bookmarks.insert(r.name.clone(), state); |
| 345 | | } |
| 346 | 75× | let policy = mirror.current_policy()?.map(|(_, sp)| sp.policy); |
| 347 | 75× | for t in &resp.tags { |
| 348 | 21× | mirror.store.put_state(&StateObject::new(t.heads.clone()))?; |
| 349 | 21× | mirror |
| 350 | 21× | .adopt_tag( |
| 351 | 21× | &mut view, |
| 352 | 21× | t, |
| 353 | 21× | policy.as_ref(), |
| 354 | 21× | &mut super::tags::TagCheck::Mirrored, |
| 355 | | ) |
| 356 | 21× | .map_err(|e| RepoError::Msg(format!("{}: {}", self.what(), e.reason)))?; |
| 357 | | } |
| 358 | 75× | if view != op.view { |
| 359 | 26× | mirror.record_op(&[op_ref], "strata sync", view)?; |
| 360 | 49× | } |
| 361 | 75× | Ok(()) |
| 362 | 76× | } |
| 363 | |
|
| 364 | | |
| 365 | 26× | fn record(&self, id: [u8; 16]) -> Result<Vec<u8>> { |
| 366 | 26× | self.with_mirror(|mirror| { |
| 367 | 26× | let mut resp = mirror.remote_refs()?; |
| 368 | | |
| 369 | | |
| 370 | 26× | resp.default_bookmark = None; |
| 371 | 26× | Ok(wire::encode_refs(id, &resp)) |
| 372 | 26× | }) |
| 373 | 26× | } |
| 374 | |
|
| 375 | | |
| 376 | 28× | fn upload(&self, bundle: &Bundle) -> Result<String> { |
| 377 | 28× | let bytes = wire::encode_bundle(bundle); |
| 378 | 28× | let hash = blake3::hash(&bytes).to_hex(); |
| 379 | 28× | let seq = self.store.list(BUNDLES_PREFIX)?.len() + 1; |
| 380 | 28× | let key = format!("{BUNDLES_PREFIX}{seq:08}-{}.bundle", &hash[..16]); |
| 381 | 28× | match self.store.put_new(&key, &bytes) { |
| 382 | 27× | Ok(()) | Err(StoreError::Exists(_)) => {} |
| 383 | 1× | Err(e) => return Err(e.into()), |
| 384 | | } |
| 385 | 27× | self.mark_seen(&key)?; |
| 386 | 27× | Ok(key) |
| 387 | 28× | } |
| 388 | | } |
| 389 | |
|
| 390 | | impl Remote for BucketRemote { |
| 391 | 41× | fn repo_id(&self) -> Result<[u8; 16]> { |
| 392 | 41× | Ok(self.stored_id()?.unwrap_or(UNBOUND_ID)) |
| 393 | 41× | } |
| 394 | |
|
| 395 | 55× | fn refs(&self) -> Result<RefsResponse> { |
| 396 | 55× | let synced = self.sync()?; |
| 397 | 53× | if synced.id.is_none() { |
| 398 | 9× | return Ok(RefsResponse::default()); |
| 399 | 44× | } |
| 400 | 44× | self.with_mirror(|mirror| { |
| 401 | 44× | let mut resp = mirror.remote_refs()?; |
| 402 | 44× | resp.default_bookmark = None; |
| 403 | 44× | Ok(resp) |
| 404 | 44× | }) |
| 405 | 55× | } |
| 406 | |
|
| 407 | 12× | fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> { |
| 408 | 12× | self.with_mirror(|m| m.negotiate(have, want)) |
| 409 | 12× | } |
| 410 | |
|
| 411 | 12× | fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> { |
| 412 | 12× | self.with_mirror(|m| m.bundle_raw_for(changes, max_blob)) |
| 413 | 12× | } |
| 414 | |
|
| 415 | 0× | fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> { |
| 416 | 0× | self.with_mirror(|m| m.objects_for(refs)) |
| 417 | 0× | } |
| 418 | |
|
| 419 | 0× | fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> { |
| 420 | 0× | self.with_mirror(|m| m.checkpoint_bundle_for(heads)) |
| 421 | 0× | } |
| 422 | |
|
| 423 | 0× | fn checkpoint_index(&self, heads: &[ChangeHash]) -> Result<Bundle> { |
| 424 | 0× | self.with_mirror(|m| m.checkpoint_index_for(heads)) |
| 425 | 0× | } |
| 426 | |
|
| 427 | 0× | fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> { |
| 428 | 0× | self.with_mirror(|m| m.shallow_changes(heads, depth)) |
| 429 | 0× | } |
| 430 | |
|
| 431 | 25× | fn push( |
| 432 | 25× | &self, |
| 433 | 25× | bundle: Bundle, |
| 434 | 25× | updates: Vec<RefUpdate>, |
| 435 | 25× | policy: Option<SignedPolicy>, |
| 436 | 25× | tags: Vec<TagRef>, |
| 437 | 25× | ) -> Result<Vec<RefResult>> { |
| 438 | 25× | let mut synced = self.sync()?; |
| 439 | 25× | let id = match synced.id { |
| 440 | 15× | Some(id) => id, |
| 441 | | None => { |
| 442 | | |
| 443 | | |
| 444 | | |
| 445 | 10× | let Some(id) = self.claimed_id else { |
| 446 | 0× | return fail(format!( |
| 447 | | "{} is empty, and this client did not say which repository it is", |
| 448 | 0× | self.what() |
| 449 | | )); |
| 450 | | }; |
| 451 | 10× | match self.store.put_new(MARKER_KEY, &marker(id)) { |
| 452 | 10× | Ok(()) => {} |
| 453 | 0× | Err(StoreError::Exists(_)) => {} |
| 454 | 0× | Err(e) => return Err(e.into()), |
| 455 | | } |
| 456 | 10× | synced = self.sync()?; |
| 457 | 10× | match synced.id { |
| 458 | 10× | Some(stored) if stored == id => id, |
| 459 | | _ => { |
| 460 | 0× | return fail(format!( |
| 461 | | "{} was just bound to another repository by a concurrent push", |
| 462 | 0× | self.what() |
| 463 | | )) |
| 464 | | } |
| 465 | | } |
| 466 | | } |
| 467 | | }; |
| 468 | 25× | if let Some(claimed) = self.claimed_id { |
| 469 | 25× | if claimed != id { |
| 470 | 0× | return fail(format!( |
| 471 | | "{} holds a different repository (id {}) than this one ({}): a store holds one repository; use another prefix or bucket", |
| 472 | 0× | self.what(), |
| 473 | 0× | hex::encode(id), |
| 474 | 0× | hex::encode(claimed) |
| 475 | | )); |
| 476 | 25× | } |
| 477 | 0× | } |
| 478 | | |
| 479 | | |
| 480 | | |
| 481 | | |
| 482 | | |
| 483 | | |
| 484 | 25× | let mut uploaded = false; |
| 485 | 27× | for attempt in 0..PUSH_ATTEMPTS { |
| 486 | 27× | let (before_ref, before) = self.with_mirror(|m| m.head_op())?; |
| 487 | 27× | let results = self.with_mirror(|m| { |
| 488 | 27× | m.receive_push( |
| 489 | 27× | bundle.clone(), |
| 490 | 27× | updates.clone(), |
| 491 | 27× | policy.clone(), |
| 492 | 27× | tags.clone(), |
| 493 | | ) |
| 494 | 27× | })?; |
| 495 | 27× | if !results.iter().any(|r| r.ok) { |
| 496 | 0× | return Ok(results); |
| 497 | 27× | } |
| 498 | 27× | if !bundle.is_empty() && !uploaded { |
| 499 | 25× | self.upload(&bundle)?; |
| 500 | 24× | uploaded = true; |
| 501 | 2× | } |
| 502 | 26× | let record = self.record(id)?; |
| 503 | 26× | match self |
| 504 | 26× | .store |
| 505 | 26× | .write_ref(REFS_KEY, &record, synced.version.as_ref()) |
| 506 | | { |
| 507 | 24× | Ok(_) => return Ok(results), |
| 508 | | Err(StoreError::Conflict(_)) => { |
| 509 | 2× | self.with_mirror(|m| { |
| 510 | 2× | let (now, _) = m.head_op()?; |
| 511 | 2× | if now != before_ref { |
| 512 | 2× | m.record_op( |
| 513 | 2× | &[now], |
| 514 | 2× | "strata push undone: the remote moved", |
| 515 | 2× | before.view.clone(), |
| 516 | 0× | )?; |
| 517 | 0× | } |
| 518 | 2× | Ok(()) |
| 519 | 2× | })?; |
| 520 | 2× | synced = self.sync()?; |
| 521 | 2× | if attempt + 1 == PUSH_ATTEMPTS { |
| 522 | 0× | return Ok(results |
| 523 | 0× | .into_iter() |
| 524 | 0× | .map(|r| RefResult { |
| 525 | 0× | name: r.name, |
| 526 | | ok: false, |
| 527 | 0× | reason: "the remote kept moving while pushing (other pushes landed first); pull, then push again".into(), |
| 528 | 0× | }) |
| 529 | 0× | .collect()); |
| 530 | 2× | } |
| 531 | | } |
| 532 | 0× | Err(e) => return Err(e.into()), |
| 533 | | } |
| 534 | | } |
| 535 | 0× | unreachable!("the loop returns") |
| 536 | 25× | } |
| 537 | | } |
| 538 | |
|
| 539 | |
|
| 540 | | const PUSH_ATTEMPTS: usize = 4; |
| 541 | |
|
| 542 | |
|
| 543 | |
|
| 544 | | pub const REMOTE_GC_GRACE: std::time::Duration = std::time::Duration::from_secs(7 * 86_400); |
| 545 | |
|
| 546 | |
|
| 547 | | const TRASH_KEY: &str = "gc"; |
| 548 | |
|
| 549 | |
|
| 550 | | type Trash = Vec<(String, u64)>; |
| 551 | |
|
| 552 | |
|
| 553 | | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 554 | | pub struct RemoteGc { |
| 555 | | |
| 556 | | pub merged: usize, |
| 557 | | |
| 558 | | pub bundle_bytes: usize, |
| 559 | | |
| 560 | | pub changes: usize, |
| 561 | | |
| 562 | | pub deleted: usize, |
| 563 | | |
| 564 | | pub deferred: usize, |
| 565 | | } |
| 566 | |
|
| 567 | 7× | fn now_ms() -> u64 { |
| 568 | 7× | std::time::SystemTime::now() |
| 569 | 7× | .duration_since(std::time::UNIX_EPOCH) |
| 570 | 7× | .map(|d| d.as_millis() as u64) |
| 571 | 7× | .unwrap_or(0) |
| 572 | 7× | } |
| 573 | |
|
| 574 | | impl BucketRemote { |
| 575 | | |
| 576 | 4× | fn trash(&self) -> Result<(Trash, Option<Version>)> { |
| 577 | 4× | match self.store.read_ref(TRASH_KEY)? { |
| 578 | 2× | Some((bytes, v)) => { |
| 579 | 2× | let text = String::from_utf8_lossy(&bytes); |
| 580 | 2× | let list = text |
| 581 | 2× | .lines() |
| 582 | 4× | .filter_map(|l| { |
| 583 | 4× | let (k, t) = l.split_once('\t')?; |
| 584 | 4× | Some((k.to_string(), t.parse().ok()?)) |
| 585 | 4× | }) |
| 586 | 2× | .collect(); |
| 587 | 2× | Ok((list, Some(v))) |
| 588 | | } |
| 589 | 2× | None => Ok((Vec::new(), None)), |
| 590 | | } |
| 591 | 4× | } |
| 592 | |
|
| 593 | 6× | fn write_trash(&self, list: &[(String, u64)], expected: Option<&Version>) -> Result<Version> { |
| 594 | 8× | let text: String = list.iter().map(|(k, t)| format!("{k}\t{t}\n")).collect(); |
| 595 | 6× | Ok(self.store.write_ref(TRASH_KEY, text.as_bytes(), expected)?) |
| 596 | 6× | } |
| 597 | |
|
| 598 | | |
| 599 | | |
| 600 | | |
| 601 | 4× | pub fn gc(&self, grace: std::time::Duration) -> Result<RemoteGc> { |
| 602 | 4× | let synced = self.sync()?; |
| 603 | 4× | let Some(id) = synced.id else { |
| 604 | 0× | return fail(format!("{} holds no repository yet", self.what())); |
| 605 | | }; |
| 606 | 4× | let mut report = RemoteGc::default(); |
| 607 | 4× | let existing: Vec<String> = self |
| 608 | 4× | .store |
| 609 | 4× | .list(BUNDLES_PREFIX)? |
| 610 | 4× | .into_iter() |
| 611 | 4× | .map(|e| e.key) |
| 612 | 4× | .collect(); |
| 613 | 4× | let (mut trash, mut trash_version) = self.trash()?; |
| 614 | 4× | let live: Vec<&String> = existing |
| 615 | 4× | .iter() |
| 616 | 14× | .filter(|k| !trash.iter().any(|(t, _)| t == *k)) |
| 617 | 4× | .collect(); |
| 618 | 4× | if live.len() > 1 { |
| 619 | | |
| 620 | | |
| 621 | 3× | let (bundle, changes) = self.with_mirror(|m| { |
| 622 | 3× | let resp = m.remote_refs()?; |
| 623 | 3× | let mut heads: Vec<ChangeHash> = Vec::new(); |
| 624 | 3× | for r in &resp.refs { |
| 625 | 3× | heads.extend(r.heads.iter().copied()); |
| 626 | 3× | } |
| 627 | 3× | for t in &resp.tags { |
| 628 | 2× | heads.extend(t.heads.iter().copied()); |
| 629 | 2× | } |
| 630 | 3× | heads.sort(); |
| 631 | 3× | heads.dedup(); |
| 632 | 3× | let changes = m.negotiate(&[], &heads)?; |
| 633 | 3× | let mut bundle = m.bundle_for(&changes)?; |
| 634 | 3× | for r in &resp.refs { |
| 635 | 3× | bundle.objects.push(( |
| 636 | 3× | ObjectType::State, |
| 637 | 3× | StateObject::new(r.heads.clone()).encode(), |
| 638 | 3× | )); |
| 639 | 3× | } |
| 640 | 3× | for t in &resp.tags { |
| 641 | 2× | bundle.objects.push(( |
| 642 | 2× | ObjectType::State, |
| 643 | 2× | StateObject::new(t.heads.clone()).encode(), |
| 644 | 2× | )); |
| 645 | 2× | } |
| 646 | 3× | Ok((bundle, changes.len())) |
| 647 | 3× | })?; |
| 648 | 3× | report.changes = changes; |
| 649 | 3× | report.bundle_bytes = wire::encode_bundle(&bundle).len(); |
| 650 | 3× | let merged_key = self.upload(&bundle)?; |
| 651 | 3× | let now = now_ms(); |
| 652 | 8× | for k in live { |
| 653 | 8× | if *k != merged_key { |
| 654 | 8× | trash.push((k.clone(), now)); |
| 655 | 8× | report.merged += 1; |
| 656 | 8× | } |
| 657 | | } |
| 658 | 3× | trash_version = Some(self.write_trash(&trash, trash_version.as_ref())?); |
| 659 | 1× | } |
| 660 | | |
| 661 | 4× | let now = now_ms(); |
| 662 | 4× | let mut kept = Vec::new(); |
| 663 | 12× | for (k, when) in trash { |
| 664 | 12× | if now.saturating_sub(when) >= grace.as_millis() as u64 { |
| 665 | 8× | self.store.delete(&k)?; |
| 666 | 8× | report.deleted += 1; |
| 667 | 4× | } else { |
| 668 | 4× | kept.push((k, when)); |
| 669 | 4× | report.deferred += 1; |
| 670 | 4× | } |
| 671 | | } |
| 672 | 4× | if report.deleted > 0 { |
| 673 | 3× | self.write_trash(&kept, trash_version.as_ref())?; |
| 674 | 1× | } |
| 675 | 4× | let _ = id; |
| 676 | 4× | Ok(report) |
| 677 | 4× | } |
| 678 | | } |
| 679 | |
|
| 680 | | impl Repo { |
| 681 | | |
| 682 | 6× | pub fn gc_remote(&self, name: &str, now: bool) -> Result<RemoteGc> { |
| 683 | 6× | let Some(url) = self.config.remotes.get(name).cloned() else { |
| 684 | 2× | return fail(format!("no remote {name:?}")); |
| 685 | | }; |
| 686 | 4× | let options = self.remote_options(name); |
| 687 | 4× | let Some(store) = crate::protocol::open_store(&url, &options) else { |
| 688 | 0× | return fail(format!( |
| 689 | | "gc --remote works on a remote kept on a store (s3://, gs://, az://, dir://); {name} is {url}" |
| 690 | | )); |
| 691 | | }; |
| 692 | 4× | let remote = BucketRemote::open(store?, &options)?; |
| 693 | 4× | let grace = if now { |
| 694 | 3× | std::time::Duration::ZERO |
| 695 | | } else { |
| 696 | 1× | REMOTE_GC_GRACE |
| 697 | | }; |
| 698 | 4× | remote.gc(grace) |
| 699 | 6× | } |
| 700 | | } |
| 701 | |
|
| 702 | |
|
| 703 | 48× | pub fn open_store_remote( |
| 704 | 48× | store: Box<dyn Store>, |
| 705 | 48× | options: &RemoteOptions, |
| 706 | 48× | ) -> Result<Box<dyn Remote>> { |
| 707 | 48× | Ok(Box::new(BucketRemote::open(store, options)?)) |
| 708 | 48× | } |
| 709 | |
|
| 710 | |
|
| 711 | 0× | pub fn is_store_dir(path: &Path) -> bool { |
| 712 | 0× | path.join(MARKER_KEY).is_file() || path.join(REFS_KEY).is_file() |
| 713 | 0× | } |
| 714 | |
|
| 715 | | #[cfg(test)] |
| 716 | | mod tests { |
| 717 | | use super::*; |
| 718 | | use crate::repo::IdentityScope; |
| 719 | | use crate::strata::{Entry, LocalStore, MemoryStore}; |
| 720 | | use std::ops::Range; |
| 721 | | use std::sync::Mutex; |
| 722 | |
|
| 723 | 9× | fn hermetic() { |
| 724 | | static ONCE: std::sync::Once = std::sync::Once::new(); |
| 725 | | static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new(); |
| 726 | 9× | ONCE.call_once(|| { |
| 727 | 9× | let d = tempfile::tempdir().unwrap(); |
| 728 | 9× | std::env::set_var("OXY_HOME", d.path()); |
| 729 | 9× | DIR.set(d).ok(); |
| 730 | 9× | }); |
| 731 | 9× | } |
| 732 | |
|
| 733 | 22× | fn write(root: &Path, rel: &str, content: &[u8]) { |
| 734 | 22× | let p = root.join(rel); |
| 735 | 22× | fs::create_dir_all(p.parent().unwrap()).unwrap(); |
| 736 | 22× | fs::write(p, content).unwrap(); |
| 737 | 22× | } |
| 738 | |
|
| 739 | 6× | fn add_remote(repo: &mut Repo, name: &str, url: &str) { |
| 740 | 6× | repo.config.set(&format!("remote.{name}.url"), url).unwrap(); |
| 741 | 6× | repo.save_config().unwrap(); |
| 742 | 6× | } |
| 743 | |
|
| 744 | 11× | fn keys(store: &dyn Store, prefix: &str) -> Vec<String> { |
| 745 | 11× | store |
| 746 | 11× | .list(prefix) |
| 747 | 11× | .unwrap() |
| 748 | 11× | .into_iter() |
| 749 | 11× | .map(|e| e.key) |
| 750 | 11× | .collect() |
| 751 | 11× | } |
| 752 | |
|
| 753 | | #[test] |
| 754 | 1× | fn push_clone_and_pull_through_a_directory_store() { |
| 755 | 1× | hermetic(); |
| 756 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 757 | 1× | let root = dir.path(); |
| 758 | 1× | let url = format!("dir://{}", root.join("bucket").display()); |
| 759 | 1× | let store = LocalStore::open(root.join("bucket")).unwrap(); |
| 760 | |
|
| 761 | | |
| 762 | | |
| 763 | 1× | let mut a = Repo::init(&root.join("a")) |
| 764 | 1× | .unwrap() |
| 765 | 1× | .with_home(root.join("home-a")); |
| 766 | 1× | a.create_identity("Ada", "[email protected]", IdentityScope::Repo) |
| 767 | 1× | .unwrap(); |
| 768 | 1× | add_remote(&mut a, "bucket", &url); |
| 769 | 1× | write(&root.join("a"), "f.txt", b"a\n"); |
| 770 | 1× | let h1 = a.commit("first", &[]).unwrap(); |
| 771 | 1× | a.tag_create("v1", &[h1], "one").unwrap(); |
| 772 | 1× | let results = a.push("bucket", false).unwrap(); |
| 773 | 1× | assert!(results.iter().all(|r| r.ok), "{results:?}"); |
| 774 | 1× | assert_eq!( |
| 775 | 1× | keys(&store, ""), |
| 776 | 1× | [ |
| 777 | 1× | "bundles/00000001-".to_string() + &keys(&store, "bundles/")[0][17..], |
| 778 | 1× | "oxygen.toml".into(), |
| 779 | 1× | "refs".into() |
| 780 | 1× | ] |
| 781 | | ); |
| 782 | 1× | assert_eq!( |
| 783 | 1× | parse_marker(&store.get("oxygen.toml").unwrap(), "t").unwrap(), |
| 784 | 1× | a.id().unwrap() |
| 785 | | ); |
| 786 | 1× | let again = a.push("bucket", false).unwrap(); |
| 787 | 1× | assert!( |
| 788 | 1× | again[0].ok && again[0].reason.contains("up to date"), |
| 789 | | "{again:?}" |
| 790 | | ); |
| 791 | 1× | assert_eq!( |
| 792 | 1× | keys(&store, "bundles/").len(), |
| 793 | | 1, |
| 794 | | "a no-op push uploads nothing" |
| 795 | | ); |
| 796 | |
|
| 797 | | |
| 798 | | |
| 799 | 1× | let b = Repo::clone(&url, &root.join("b")).unwrap(); |
| 800 | 1× | assert_eq!(b.id().unwrap(), a.id().unwrap()); |
| 801 | 1× | assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n"); |
| 802 | 1× | assert_eq!(b.bookmark_heads().unwrap(), vec![h1]); |
| 803 | 1× | assert_eq!( |
| 804 | 1× | b.tags() |
| 805 | 1× | .unwrap() |
| 806 | 1× | .iter() |
| 807 | 1× | .map(|t| t.name.clone()) |
| 808 | 1× | .collect::<Vec<_>>(), |
| 809 | | ["v1"] |
| 810 | | ); |
| 811 | 1× | assert!(matches!( |
| 812 | 1× | b.authenticate_change(&h1).unwrap(), |
| 813 | | crate::repo::SignatureStatus::Valid { sealed: true, .. } |
| 814 | | )); |
| 815 | 1× | assert!( |
| 816 | 1× | root.join("b/.oxy/remotes/origin/strata/mirror/.oxy") |
| 817 | 1× | .is_dir(), |
| 818 | | "the mirror lives with the remote's state" |
| 819 | | ); |
| 820 | 1× | assert!( |
| 821 | 1× | !std::env::temp_dir() |
| 822 | 1× | .read_dir() |
| 823 | 1× | .unwrap() |
| 824 | 1× | .flatten() |
| 825 | 28× | .any(|e| e.file_name().to_string_lossy().starts_with("oxy-strata-")), |
| 826 | | "a clone's temporary mirror is removed" |
| 827 | | ); |
| 828 | |
|
| 829 | | |
| 830 | 1× | write(&root.join("b"), "f.txt", b"a\nb\n"); |
| 831 | 1× | let h2 = b.commit("second", &[]).unwrap(); |
| 832 | 1× | assert!(b.push("origin", false).unwrap()[0].ok); |
| 833 | 1× | assert_eq!(keys(&store, "bundles/").len(), 2); |
| 834 | 1× | let pr = a.pull("bucket").unwrap(); |
| 835 | 1× | assert!(pr.changed && pr.checked_out); |
| 836 | 1× | assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n"); |
| 837 | 1× | write(&root.join("a"), "g.txt", b"g\n"); |
| 838 | 1× | let h3 = a.commit("third", &[]).unwrap(); |
| 839 | 1× | assert!(a.push("bucket", false).unwrap()[0].ok); |
| 840 | 1× | let pr = b.pull("origin").unwrap(); |
| 841 | 1× | assert!(pr.changed); |
| 842 | | |
| 843 | 1× | let mut want = vec![h2, h3]; |
| 844 | 1× | want.sort(); |
| 845 | 1× | assert_eq!(b.bookmark_heads().unwrap(), want); |
| 846 | 1× | assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n"); |
| 847 | |
|
| 848 | | |
| 849 | 1× | let c = Repo::clone(&url, &root.join("c")).unwrap(); |
| 850 | 1× | assert_eq!(c.bookmark_heads().unwrap(), want); |
| 851 | 1× | assert_eq!(fs::read(root.join("c/f.txt")).unwrap(), b"a\nb\n"); |
| 852 | 1× | } |
| 853 | |
|
| 854 | | #[test] |
| 855 | 1× | fn a_push_behind_the_remote_is_refused_before_anything_is_uploaded() { |
| 856 | 1× | hermetic(); |
| 857 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 858 | 1× | let root = dir.path(); |
| 859 | 1× | let url = format!("dir://{}", root.join("bucket").display()); |
| 860 | 1× | let store = LocalStore::open(root.join("bucket")).unwrap(); |
| 861 | 1× | let mut a = Repo::init(&root.join("a")).unwrap(); |
| 862 | 1× | add_remote(&mut a, "bucket", &url); |
| 863 | 1× | write(&root.join("a"), "f.txt", b"a\n"); |
| 864 | 1× | a.commit("first", &[]).unwrap(); |
| 865 | 1× | assert!(a.push("bucket", false).unwrap()[0].ok); |
| 866 | 1× | let b = Repo::clone(&url, &root.join("b")).unwrap(); |
| 867 | 1× | write(&root.join("b"), "f.txt", b"b\n"); |
| 868 | 1× | b.commit("from b", &[]).unwrap(); |
| 869 | 1× | assert!(b.push("origin", false).unwrap()[0].ok); |
| 870 | 1× | write(&root.join("a"), "g.txt", b"g\n"); |
| 871 | 1× | a.commit("from a", &[]).unwrap(); |
| 872 | 1× | let e = a.push("bucket", false).unwrap_err().to_string(); |
| 873 | 1× | assert!(e.contains("pull first"), "{e}"); |
| 874 | 1× | assert_eq!(keys(&store, "bundles/").len(), 2); |
| 875 | 1× | assert!(a.pull("bucket").unwrap().changed); |
| 876 | 1× | assert!(a.push("bucket", false).unwrap()[0].ok); |
| 877 | 1× | assert_eq!(keys(&store, "bundles/").len(), 3); |
| 878 | 1× | } |
| 879 | |
|
| 880 | | |
| 881 | | |
| 882 | | |
| 883 | | struct Racing { |
| 884 | | inner: MemoryStore, |
| 885 | | raced: Mutex<bool>, |
| 886 | | } |
| 887 | |
|
| 888 | | impl Store for Racing { |
| 889 | 4× | fn describe(&self) -> String { |
| 890 | 4× | "racing".into() |
| 891 | 4× | } |
| 892 | 0× | fn has(&self, key: &str) -> crate::strata::Result<bool> { |
| 893 | 0× | self.inner.has(key) |
| 894 | 0× | } |
| 895 | 5× | fn get(&self, key: &str) -> crate::strata::Result<Vec<u8>> { |
| 896 | 5× | self.inner.get(key) |
| 897 | 5× | } |
| 898 | 0× | fn get_range(&self, key: &str, range: Range<u64>) -> crate::strata::Result<Vec<u8>> { |
| 899 | 0× | self.inner.get_range(key, range) |
| 900 | 0× | } |
| 901 | 3× | fn put_new(&self, key: &str, bytes: &[u8]) -> crate::strata::Result<()> { |
| 902 | 3× | self.inner.put_new(key, bytes) |
| 903 | 3× | } |
| 904 | 6× | fn list(&self, prefix: &str) -> crate::strata::Result<Vec<Entry>> { |
| 905 | 6× | self.inner.list(prefix) |
| 906 | 6× | } |
| 907 | 0× | fn delete(&self, key: &str) -> crate::strata::Result<()> { |
| 908 | 0× | self.inner.delete(key) |
| 909 | 0× | } |
| 910 | 4× | fn read_ref(&self, key: &str) -> crate::strata::Result<Option<(Vec<u8>, Version)>> { |
| 911 | 4× | self.inner.read_ref(key) |
| 912 | 4× | } |
| 913 | 3× | fn write_ref( |
| 914 | 3× | &self, |
| 915 | 3× | key: &str, |
| 916 | 3× | bytes: &[u8], |
| 917 | 3× | expected: Option<&Version>, |
| 918 | 3× | ) -> crate::strata::Result<Version> { |
| 919 | 3× | let mut raced = self.raced.lock().unwrap(); |
| 920 | 3× | if !*raced && expected.is_some() { |
| 921 | 1× | *raced = true; |
| 922 | | |
| 923 | | |
| 924 | 1× | let (current, v) = self.inner.read_ref(key)?.unwrap(); |
| 925 | 1× | let (id, mut resp) = |
| 926 | 1× | wire::decode_refs(¤t).map_err(|e| StoreError::Backend(e.to_string()))?; |
| 927 | 1× | resp.default_bookmark = Some("raced".into()); |
| 928 | 1× | self.inner |
| 929 | 1× | .write_ref(key, &wire::encode_refs(id, &resp), Some(&v))?; |
| 930 | 2× | } |
| 931 | 3× | self.inner.write_ref(key, bytes, expected) |
| 932 | 3× | } |
| 933 | | } |
| 934 | |
|
| 935 | | #[test] |
| 936 | 1× | fn a_record_moved_during_a_push_is_applied_over_what_landed() { |
| 937 | 1× | hermetic(); |
| 938 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 939 | 1× | let root = dir.path(); |
| 940 | 1× | let a = Repo::init(&root.join("a")).unwrap(); |
| 941 | 1× | write(&root.join("a"), "f.txt", b"a\n"); |
| 942 | 1× | let h1 = a.commit("first", &[]).unwrap(); |
| 943 | 1× | let store = Box::new(Racing { |
| 944 | 1× | inner: MemoryStore::new(), |
| 945 | 1× | raced: Mutex::new(false), |
| 946 | 1× | }); |
| 947 | 1× | let options = RemoteOptions { |
| 948 | 1× | repo_id: Some(a.id().unwrap()), |
| 949 | 1× | cache_dir: Some(root.join("cache")), |
| 950 | 1× | ..Default::default() |
| 951 | 1× | }; |
| 952 | 1× | let remote = BucketRemote::open(store, &options).unwrap(); |
| 953 | | |
| 954 | 1× | let state = a.store.put_state(&StateObject::new(vec![h1])).unwrap(); |
| 955 | 1× | let empty = a.store.put_state(&StateObject::new(vec![])).unwrap(); |
| 956 | 1× | let mut bundle = a.bundle_for(&[h1]).unwrap(); |
| 957 | 1× | bundle |
| 958 | 1× | .objects |
| 959 | 1× | .push((ObjectType::State, StateObject::new(vec![h1]).encode())); |
| 960 | 1× | let update = |old, new| RefUpdate { |
| 961 | 2× | name: "main".into(), |
| 962 | 2× | old_state: old, |
| 963 | 2× | new_state: new, |
| 964 | | force: false, |
| 965 | 2× | attestation: None, |
| 966 | 2× | }; |
| 967 | 1× | let r = remote |
| 968 | 1× | .push(bundle, vec![update(empty, state)], None, vec![]) |
| 969 | 1× | .unwrap(); |
| 970 | 1× | assert!(r[0].ok, "{r:?}"); |
| 971 | | |
| 972 | 1× | write(&root.join("a"), "f.txt", b"ab\n"); |
| 973 | 1× | let h2 = a.commit("second", &[]).unwrap(); |
| 974 | 1× | let state2 = a.store.put_state(&StateObject::new(vec![h2])).unwrap(); |
| 975 | 1× | let mut bundle = a.bundle_for(&[h2]).unwrap(); |
| 976 | 1× | bundle |
| 977 | 1× | .objects |
| 978 | 1× | .push((ObjectType::State, StateObject::new(vec![h2]).encode())); |
| 979 | 1× | let r = remote |
| 980 | 1× | .push(bundle, vec![update(state, state2)], None, vec![]) |
| 981 | 1× | .unwrap(); |
| 982 | 1× | assert!(r[0].ok, "applied over what landed meanwhile: {r:?}"); |
| 983 | 1× | let refs = remote.refs().unwrap(); |
| 984 | 1× | assert_eq!( |
| 985 | 1× | refs.refs[0].heads, |
| 986 | 1× | vec![h2], |
| 987 | | "the store and the mirror both moved" |
| 988 | | ); |
| 989 | 1× | } |
| 990 | |
|
| 991 | | #[test] |
| 992 | 1× | fn a_store_holds_one_repository() { |
| 993 | 1× | hermetic(); |
| 994 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 995 | 1× | let root = dir.path(); |
| 996 | 1× | let url = format!("dir://{}", root.join("bucket").display()); |
| 997 | 1× | let mut a = Repo::init(&root.join("a")).unwrap(); |
| 998 | 1× | add_remote(&mut a, "bucket", &url); |
| 999 | 1× | write(&root.join("a"), "f.txt", b"a\n"); |
| 1000 | 1× | a.commit("first", &[]).unwrap(); |
| 1001 | 1× | assert!(a.push("bucket", false).unwrap()[0].ok); |
| 1002 | 1× | let mut other = Repo::init(&root.join("other")).unwrap(); |
| 1003 | 1× | add_remote(&mut other, "bucket", &url); |
| 1004 | 1× | write(&root.join("other"), "f.txt", b"o\n"); |
| 1005 | 1× | other.commit("mine", &[]).unwrap(); |
| 1006 | 1× | let e = other.push("bucket", false).unwrap_err().to_string(); |
| 1007 | 1× | assert!( |
| 1008 | 1× | e.contains("different repository") || e.contains("another repository"), |
| 1009 | | "{e}" |
| 1010 | | ); |
| 1011 | 1× | assert_eq!( |
| 1012 | 1× | keys(&LocalStore::open(root.join("bucket")).unwrap(), "bundles/").len(), |
| 1013 | | 1 |
| 1014 | | ); |
| 1015 | 1× | } |
| 1016 | |
|
| 1017 | | #[test] |
| 1018 | 1× | fn a_damaged_bundle_is_caught_and_an_empty_store_cannot_be_cloned() { |
| 1019 | 1× | hermetic(); |
| 1020 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1021 | 1× | let root = dir.path(); |
| 1022 | 1× | let url = format!("dir://{}", root.join("bucket").display()); |
| 1023 | 1× | let e = Repo::clone(&url, &root.join("nothing")) |
| 1024 | 1× | .err() |
| 1025 | 1× | .expect("refused") |
| 1026 | 1× | .to_string(); |
| 1027 | 1× | assert!(e.contains("empty and unbound"), "{e}"); |
| 1028 | 1× | let mut a = Repo::init(&root.join("a")).unwrap(); |
| 1029 | 1× | add_remote(&mut a, "bucket", &url); |
| 1030 | 1× | write(&root.join("a"), "f.txt", b"a\n"); |
| 1031 | 1× | a.commit("first", &[]).unwrap(); |
| 1032 | 1× | assert!(a.push("bucket", false).unwrap()[0].ok); |
| 1033 | 1× | let store = LocalStore::open(root.join("bucket")).unwrap(); |
| 1034 | 1× | let key = keys(&store, "bundles/").remove(0); |
| 1035 | 1× | let mut bytes = store.get(&key).unwrap(); |
| 1036 | 1× | let mid = bytes.len() / 2; |
| 1037 | 1× | bytes[mid] ^= 0xff; |
| 1038 | 1× | store.delete(&key).unwrap(); |
| 1039 | 1× | store.put_new(&key, &bytes).unwrap(); |
| 1040 | 1× | let e = Repo::clone(&url, &root.join("b")) |
| 1041 | 1× | .err() |
| 1042 | 1× | .expect("refused") |
| 1043 | 1× | .to_string(); |
| 1044 | 1× | assert!( |
| 1045 | 1× | e.contains(&key) || e.contains("bundle") || e.contains("hash"), |
| 1046 | | "{e}" |
| 1047 | | ); |
| 1048 | 1× | assert!(!root.join("b/f.txt").exists()); |
| 1049 | 1× | } |
| 1050 | |
|
| 1051 | | |
| 1052 | | |
| 1053 | | |
| 1054 | | struct Shared { |
| 1055 | | inner: std::sync::Arc<MemoryStore>, |
| 1056 | | fail_uploads: std::sync::atomic::AtomicBool, |
| 1057 | | vanish: Mutex<Option<String>>, |
| 1058 | | } |
| 1059 | |
|
| 1060 | | thread_local! { |
| 1061 | | static HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) }; |
| 1062 | | } |
| 1063 | |
|
| 1064 | | impl Shared { |
| 1065 | 6× | fn new(inner: std::sync::Arc<MemoryStore>) -> Box<Shared> { |
| 1066 | 6× | Box::new(Shared { |
| 1067 | 6× | inner, |
| 1068 | 6× | fail_uploads: Default::default(), |
| 1069 | 6× | vanish: Mutex::new(None), |
| 1070 | 6× | }) |
| 1071 | 6× | } |
| 1072 | | } |
| 1073 | |
|
| 1074 | | impl Store for Shared { |
| 1075 | 24× | fn describe(&self) -> String { |
| 1076 | 24× | "shared".into() |
| 1077 | 24× | } |
| 1078 | 0× | fn has(&self, key: &str) -> crate::strata::Result<bool> { |
| 1079 | 0× | self.inner.has(key) |
| 1080 | 0× | } |
| 1081 | 38× | fn get(&self, key: &str) -> crate::strata::Result<Vec<u8>> { |
| 1082 | 38× | let mut vanish = self.vanish.lock().unwrap(); |
| 1083 | 38× | if vanish.as_deref() == Some(key) { |
| 1084 | 1× | *vanish = None; |
| 1085 | 1× | return Err(StoreError::NotFound(key.to_string())); |
| 1086 | 37× | } |
| 1087 | 37× | self.inner.get(key) |
| 1088 | 38× | } |
| 1089 | 0× | fn get_range(&self, key: &str, range: Range<u64>) -> crate::strata::Result<Vec<u8>> { |
| 1090 | 0× | self.inner.get_range(key, range) |
| 1091 | 0× | } |
| 1092 | 11× | fn put_new(&self, key: &str, bytes: &[u8]) -> crate::strata::Result<()> { |
| 1093 | 11× | if key.starts_with("bundles/") |
| 1094 | 8× | && self.fail_uploads.load(std::sync::atomic::Ordering::SeqCst) |
| 1095 | | { |
| 1096 | 1× | return Err(StoreError::Backend("shared: the disk is full".into())); |
| 1097 | 10× | } |
| 1098 | 10× | self.inner.put_new(key, bytes) |
| 1099 | 11× | } |
| 1100 | 31× | fn list(&self, prefix: &str) -> crate::strata::Result<Vec<Entry>> { |
| 1101 | 31× | self.inner.list(prefix) |
| 1102 | 31× | } |
| 1103 | 0× | fn delete(&self, key: &str) -> crate::strata::Result<()> { |
| 1104 | 0× | self.inner.delete(key) |
| 1105 | 0× | } |
| 1106 | 23× | fn read_ref(&self, key: &str) -> crate::strata::Result<Option<(Vec<u8>, Version)>> { |
| 1107 | 23× | self.inner.read_ref(key) |
| 1108 | 23× | } |
| 1109 | 8× | fn write_ref( |
| 1110 | 8× | &self, |
| 1111 | 8× | key: &str, |
| 1112 | 8× | bytes: &[u8], |
| 1113 | 8× | expected: Option<&Version>, |
| 1114 | 8× | ) -> crate::strata::Result<Version> { |
| 1115 | 8× | if key == "refs" && expected.is_some() { |
| 1116 | 5× | if let Some(hook) = HOOK.with(|h| h.borrow_mut().take()) { |
| 1117 | 1× | hook(); |
| 1118 | 4× | } |
| 1119 | 3× | } |
| 1120 | 8× | self.inner.write_ref(key, bytes, expected) |
| 1121 | 8× | } |
| 1122 | | } |
| 1123 | |
|
| 1124 | 3× | fn repo_with_commit(root: &Path, name: &str, file: &str, text: &[u8], msg: &str) -> Repo { |
| 1125 | 3× | let repo = Repo::init(&root.join(name)).unwrap(); |
| 1126 | 3× | write(&root.join(name), file, text); |
| 1127 | 3× | repo.commit(msg, &[]).unwrap(); |
| 1128 | 3× | repo |
| 1129 | 3× | } |
| 1130 | |
|
| 1131 | 6× | fn remote_for(repo: &Repo, store: Box<dyn Store>, root: &Path, name: &str) -> BucketRemote { |
| 1132 | 6× | let options = RemoteOptions { |
| 1133 | 6× | repo_id: Some(repo.id().unwrap()), |
| 1134 | 6× | cache_dir: Some(root.join(format!("cache-{name}"))), |
| 1135 | 6× | ..Default::default() |
| 1136 | 6× | }; |
| 1137 | 6× | BucketRemote::open(store, &options).unwrap() |
| 1138 | 6× | } |
| 1139 | |
|
| 1140 | 8× | fn push_bookmark( |
| 1141 | 8× | repo: &Repo, |
| 1142 | 8× | remote: &BucketRemote, |
| 1143 | 8× | bookmark: &str, |
| 1144 | 8× | old: Option<ObjectRef>, |
| 1145 | 8× | ) -> Vec<RefResult> { |
| 1146 | 8× | let heads = repo.heads_of(&repo.view().unwrap(), bookmark).unwrap(); |
| 1147 | 8× | let state = repo |
| 1148 | 8× | .store |
| 1149 | 8× | .put_state(&StateObject::new(heads.clone())) |
| 1150 | 8× | .unwrap(); |
| 1151 | 8× | let empty = repo.store.put_state(&StateObject::new(vec![])).unwrap(); |
| 1152 | | |
| 1153 | 8× | let have: Vec<ChangeHash> = remote |
| 1154 | 8× | .refs() |
| 1155 | 8× | .unwrap() |
| 1156 | 8× | .refs |
| 1157 | 8× | .iter() |
| 1158 | 8× | .flat_map(|r| r.heads.clone()) |
| 1159 | 8× | .collect(); |
| 1160 | 8× | let changes = repo.negotiate(&have, &heads).unwrap(); |
| 1161 | 8× | let mut bundle = repo.bundle_for(&changes).unwrap(); |
| 1162 | 8× | bundle |
| 1163 | 8× | .objects |
| 1164 | 8× | .push((ObjectType::State, StateObject::new(heads).encode())); |
| 1165 | 8× | let update = RefUpdate { |
| 1166 | 8× | name: bookmark.into(), |
| 1167 | 8× | old_state: old.unwrap_or(empty), |
| 1168 | 8× | new_state: state, |
| 1169 | 8× | force: false, |
| 1170 | 8× | attestation: None, |
| 1171 | 8× | }; |
| 1172 | 8× | remote.push(bundle, vec![update], None, vec![]).unwrap() |
| 1173 | 8× | } |
| 1174 | |
|
| 1175 | | #[test] |
| 1176 | 1× | fn two_pushes_to_different_bookmarks_both_land() { |
| 1177 | 1× | hermetic(); |
| 1178 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1179 | 1× | let root = dir.path(); |
| 1180 | 1× | let inner = std::sync::Arc::new(MemoryStore::new()); |
| 1181 | | |
| 1182 | | |
| 1183 | 1× | let a = repo_with_commit(root, "a", "f.txt", b"a\n", "first"); |
| 1184 | 1× | let ra = remote_for(&a, Shared::new(inner.clone()), root, "a"); |
| 1185 | 1× | let r = push_bookmark(&a, &ra, "main", None); |
| 1186 | 1× | assert!(r[0].ok, "{r:?}"); |
| 1187 | 1× | let b = Repo::init_with_id(&root.join("b"), a.id().unwrap()).unwrap(); |
| 1188 | 1× | let rb = remote_for(&b, Shared::new(inner.clone()), root, "b"); |
| 1189 | 1× | rb.refs().unwrap(); |
| 1190 | 1× | write(&root.join("b"), "g.txt", b"g\n"); |
| 1191 | 1× | b.commit("on b", &[]).unwrap(); |
| 1192 | 1× | let (_, op) = b.head_op().unwrap(); |
| 1193 | 1× | let mut view = op.view.clone(); |
| 1194 | 1× | let feature_heads = b.heads_of(&view, "main").unwrap(); |
| 1195 | 1× | view.bookmarks.insert( |
| 1196 | 1× | "feature".into(), |
| 1197 | 1× | b.store.put_state(&StateObject::new(feature_heads)).unwrap(), |
| 1198 | | ); |
| 1199 | 1× | b.record_op(&[b.head_op().unwrap().0], "bookmark create feature", view) |
| 1200 | 1× | .unwrap(); |
| 1201 | | |
| 1202 | 1× | write(&root.join("a"), "f.txt", b"aa\n"); |
| 1203 | 1× | a.commit("second", &[]).unwrap(); |
| 1204 | 1× | let a_old = ra |
| 1205 | 1× | .refs() |
| 1206 | 1× | .unwrap() |
| 1207 | 1× | .refs |
| 1208 | 1× | .iter() |
| 1209 | 1× | .find(|r| r.name == "main") |
| 1210 | 1× | .unwrap() |
| 1211 | | .state; |
| 1212 | 1× | let b_remote = std::sync::Arc::new(std::sync::Mutex::new(Some(rb))); |
| 1213 | 1× | let b_handle = b_remote.clone(); |
| 1214 | 1× | HOOK.with(|h| { |
| 1215 | 1× | *h.borrow_mut() = Some(Box::new(move || { |
| 1216 | 1× | let rb = b_handle.lock().unwrap().take().unwrap(); |
| 1217 | 1× | let r = push_bookmark(&b, &rb, "feature", None); |
| 1218 | 1× | assert!(r[0].ok, "{r:?}"); |
| 1219 | 1× | })) |
| 1220 | 1× | }); |
| 1221 | 1× | let r = push_bookmark(&a, &ra, "main", Some(a_old)); |
| 1222 | 1× | assert!(r[0].ok, "a's push is applied over b's: {r:?}"); |
| 1223 | 1× | let refs = ra.refs().unwrap(); |
| 1224 | 2× | let names: Vec<&str> = refs.refs.iter().map(|r| r.name.as_str()).collect(); |
| 1225 | 1× | assert_eq!(names, ["feature", "main"], "both landed"); |
| 1226 | 1× | assert_eq!(inner.list("bundles/").unwrap().len(), 3); |
| 1227 | 1× | let _ = b_remote; |
| 1228 | 1× | } |
| 1229 | |
|
| 1230 | | #[test] |
| 1231 | 1× | fn an_interrupted_push_leaves_the_store_usable() { |
| 1232 | 1× | hermetic(); |
| 1233 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1234 | 1× | let root = dir.path(); |
| 1235 | 1× | let inner = std::sync::Arc::new(MemoryStore::new()); |
| 1236 | 1× | let a = repo_with_commit(root, "a", "f.txt", b"a\n", "first"); |
| 1237 | 1× | let shared = Shared::new(inner.clone()); |
| 1238 | 1× | let fail = &shared.fail_uploads as *const std::sync::atomic::AtomicBool; |
| 1239 | 1× | let ra = remote_for(&a, shared, root, "a"); |
| 1240 | 1× | assert!(push_bookmark(&a, &ra, "main", None)[0].ok); |
| 1241 | 1× | let old = ra.refs().unwrap().refs[0].state; |
| 1242 | | |
| 1243 | | |
| 1244 | 1× | write(&root.join("a"), "f.txt", b"aa\n"); |
| 1245 | 1× | let h2 = a.commit("second", &[]).unwrap(); |
| 1246 | 1× | unsafe { (*fail).store(true, std::sync::atomic::Ordering::SeqCst) }; |
| 1247 | 1× | let e = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 1248 | 1× | push_bookmark(&a, &ra, "main", Some(old)) |
| 1249 | 1× | })); |
| 1250 | 1× | assert!(e.is_err(), "the push reports the failed upload"); |
| 1251 | 1× | assert_eq!(inner.list("bundles/").unwrap().len(), 1); |
| 1252 | 1× | let refs = ra.refs().unwrap(); |
| 1253 | 1× | assert_eq!(refs.refs[0].state, old, "the record did not move"); |
| 1254 | 1× | unsafe { (*fail).store(false, std::sync::atomic::Ordering::SeqCst) }; |
| 1255 | 1× | let r = push_bookmark(&a, &ra, "main", Some(old)); |
| 1256 | 1× | assert!(r[0].ok, "{r:?}"); |
| 1257 | 1× | assert_eq!(ra.refs().unwrap().refs[0].heads, vec![h2]); |
| 1258 | 1× | } |
| 1259 | |
|
| 1260 | | #[test] |
| 1261 | 1× | fn bundles_out_of_order_or_gone_are_handled() { |
| 1262 | 1× | hermetic(); |
| 1263 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1264 | 1× | let root = dir.path(); |
| 1265 | 1× | let inner = std::sync::Arc::new(MemoryStore::new()); |
| 1266 | 1× | let a = repo_with_commit(root, "a", "f.txt", b"a\n", "first"); |
| 1267 | 1× | let ra = remote_for(&a, Shared::new(inner.clone()), root, "a"); |
| 1268 | 1× | assert!(push_bookmark(&a, &ra, "main", None)[0].ok); |
| 1269 | 1× | let old = ra.refs().unwrap().refs[0].state; |
| 1270 | 1× | write(&root.join("a"), "f.txt", b"aa\n"); |
| 1271 | 1× | let h2 = a.commit("second", &[]).unwrap(); |
| 1272 | 1× | assert!(push_bookmark(&a, &ra, "main", Some(old))[0].ok); |
| 1273 | | |
| 1274 | 1× | let keys: Vec<String> = inner |
| 1275 | 1× | .list("bundles/") |
| 1276 | 1× | .unwrap() |
| 1277 | 1× | .into_iter() |
| 1278 | 1× | .map(|e| e.key) |
| 1279 | 1× | .collect(); |
| 1280 | 1× | assert_eq!(keys.len(), 2); |
| 1281 | 1× | let bytes = inner.get(&keys[1]).unwrap(); |
| 1282 | 1× | inner.delete(&keys[1]).unwrap(); |
| 1283 | 1× | inner |
| 1284 | 1× | .put_new("bundles/00000000-first.bundle", &bytes) |
| 1285 | 1× | .unwrap(); |
| 1286 | 1× | let shared = Shared::new(inner.clone()); |
| 1287 | 1× | let c = Repo::init_with_id(&root.join("c"), a.id().unwrap()).unwrap(); |
| 1288 | 1× | let rc = remote_for(&c, shared, root, "c"); |
| 1289 | 1× | assert_eq!( |
| 1290 | 1× | rc.refs().unwrap().refs[0].heads, |
| 1291 | 1× | vec![h2], |
| 1292 | | "the dependent bundle waited for its dependency" |
| 1293 | | ); |
| 1294 | | |
| 1295 | 1× | let shared = Shared::new(inner.clone()); |
| 1296 | 1× | *shared.vanish.lock().unwrap() = Some(keys[0].clone()); |
| 1297 | 1× | let d = Repo::init_with_id(&root.join("d"), a.id().unwrap()).unwrap(); |
| 1298 | 1× | let rd = remote_for(&d, shared, root, "d"); |
| 1299 | | |
| 1300 | | |
| 1301 | 1× | let e = rd.refs().expect_err("missing changes").to_string(); |
| 1302 | 1× | assert!(e.contains("cannot be imported"), "{e}"); |
| 1303 | 1× | } |
| 1304 | |
|
| 1305 | | #[test] |
| 1306 | 1× | fn gc_merges_bundles_and_prunes_after_the_grace_period() { |
| 1307 | 1× | hermetic(); |
| 1308 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 1309 | 1× | let root = dir.path(); |
| 1310 | 1× | let url = format!("dir://{}", root.join("bucket").display()); |
| 1311 | 1× | let store = LocalStore::open(root.join("bucket")).unwrap(); |
| 1312 | 1× | let mut a = Repo::init(&root.join("a")).unwrap(); |
| 1313 | 1× | add_remote(&mut a, "bucket", &url); |
| 1314 | 3× | for i in 1..=3 { |
| 1315 | 3× | write(&root.join("a"), "f.txt", format!("{i}\n").as_bytes()); |
| 1316 | 3× | a.commit(&format!("change {i}"), &[]).unwrap(); |
| 1317 | 3× | assert!(a.push("bucket", false).unwrap()[0].ok); |
| 1318 | | } |
| 1319 | 1× | a.tag_create("v3", &a.bookmark_heads().unwrap(), "three") |
| 1320 | 1× | .unwrap(); |
| 1321 | 1× | assert!(a.push("bucket", false).unwrap().iter().all(|r| r.ok)); |
| 1322 | 1× | assert_eq!( |
| 1323 | 1× | keys(&store, "bundles/").len(), |
| 1324 | | 4, |
| 1325 | | "three pushes and the tag's" |
| 1326 | | ); |
| 1327 | | |
| 1328 | 1× | let r = a.gc_remote("bucket", false).unwrap(); |
| 1329 | 1× | assert_eq!( |
| 1330 | 1× | (r.merged, r.changes, r.deleted, r.deferred), |
| 1331 | | (4, 3, 0, 4), |
| 1332 | | "{r:?}" |
| 1333 | | ); |
| 1334 | 1× | assert!(r.bundle_bytes > 0); |
| 1335 | 1× | assert_eq!(keys(&store, "bundles/").len(), 5); |
| 1336 | 1× | let b = Repo::clone(&url, &root.join("b")).unwrap(); |
| 1337 | 1× | assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"3\n"); |
| 1338 | 1× | assert_eq!(b.tags().unwrap().len(), 1); |
| 1339 | | |
| 1340 | 1× | let r = a.gc_remote("bucket", true).unwrap(); |
| 1341 | 1× | assert_eq!((r.merged, r.deleted, r.deferred), (0, 4, 0), "{r:?}"); |
| 1342 | 1× | assert_eq!(keys(&store, "bundles/").len(), 1); |
| 1343 | 1× | let c = Repo::clone(&url, &root.join("c")).unwrap(); |
| 1344 | 1× | assert_eq!(c.bookmark_heads().unwrap(), a.bookmark_heads().unwrap()); |
| 1345 | | |
| 1346 | 1× | write(&root.join("b"), "f.txt", b"4\n"); |
| 1347 | 1× | b.commit("four", &[]).unwrap(); |
| 1348 | 1× | assert!(b.push("origin", false).unwrap()[0].ok); |
| 1349 | 1× | assert!(a.pull("bucket").unwrap().changed); |
| 1350 | 1× | assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"4\n"); |
| 1351 | | |
| 1352 | 1× | let r = a.gc_remote("bucket", true).unwrap(); |
| 1353 | 1× | assert_eq!((r.merged, r.deleted), (2, 2)); |
| 1354 | 1× | assert!(a.gc_remote("nope", true).is_err()); |
| 1355 | 1× | } |
| 1356 | |
|
| 1357 | | #[test] |
| 1358 | 1× | fn markers_parse_and_refuse_newer_formats() { |
| 1359 | 1× | let id = [7u8; 16]; |
| 1360 | 1× | assert_eq!(parse_marker(&marker(id), "s").unwrap(), id); |
| 1361 | 1× | let e = parse_marker( |
| 1362 | 1× | b"format = 9\nrepo = \"07070707070707070707070707070707\"\n", |
| 1363 | 1× | "s", |
| 1364 | 1× | ) |
| 1365 | 1× | .unwrap_err() |
| 1366 | 1× | .to_string(); |
| 1367 | 1× | assert!(e.contains("format 9"), "{e}"); |
| 1368 | 1× | assert!(parse_marker(b"hello", "s").is_err()); |
| 1369 | 1× | } |
| 1370 | | } |