Onset: version control where nobody waits and nothing gets lost. The on command, its core and onset-server.
| 1 | //! vcs-core for the hosted service, through a C ABI. |
| 2 | //! |
| 3 | //! The Worker owns storage. It loads objects into this module's cache |
| 4 | //! (`cache_put`), then calls an operation. Each project gets its own cache |
| 5 | //! slot (`cache_use`), since one isolate can serve several projects. An operation that reaches an |
| 6 | //! object the cache doesn't have answers `{"need": [ids]}`; the Worker loads |
| 7 | //! them and calls again (operations are deterministic). Answers are JSON in |
| 8 | //! the result buffer (`result_ptr`/`result_len`); objects an operation made |
| 9 | //! come back as a bundle from `take_new`. |
| 10 |
| 11 | use std::cell::RefCell; |
| 12 | use std::collections::{HashMap, HashSet, VecDeque}; |
| 13 | use std::io::{Read, Write}; |
| 14 |
| 15 | use serde::Deserialize; |
| 16 | use serde_json::{Value, json}; |
| 17 | use sha1::{Digest, Sha1}; |
| 18 | use vcs_core::bundle::{self, Frame, RAW, ZSTD}; |
| 19 | use vcs_core::merge::{self, Mode}; |
| 20 | use vcs_core::object::{Kind, Object, decode_chunks}; |
| 21 | use vcs_core::tree::{self, EntryKind}; |
| 22 | use vcs_core::{Error, Id, MemSource, Source, filter}; |
| 23 |
| 24 | thread_local! { |
| 25 | static CACHES: RefCell<HashMap<u32, Slot>> = RefCell::new(HashMap::new()); |
| 26 | static SLOT: std::cell::Cell<u32> = const { std::cell::Cell::new(0) }; |
| 27 | static NEW: RefCell<MemSource> = RefCell::new(MemSource::default()); |
| 28 | static RESULT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) }; |
| 29 | } |
| 30 |
| 31 | #[unsafe(no_mangle)] |
| 32 | pub extern "C" fn alloc(len: usize) -> *mut u8 { |
| 33 | let mut buf = Vec::<u8>::with_capacity(len.max(1)); |
| 34 | let ptr = buf.as_mut_ptr(); |
| 35 | std::mem::forget(buf); |
| 36 | ptr |
| 37 | } |
| 38 |
| 39 | /// # Safety |
| 40 | /// `ptr` and `len` must come from `alloc`. |
| 41 | #[unsafe(no_mangle)] |
| 42 | pub unsafe extern "C" fn dealloc(ptr: *mut u8, len: usize) { |
| 43 | unsafe { drop(Vec::from_raw_parts(ptr, 0, len.max(1))) }; |
| 44 | } |
| 45 |
| 46 | #[unsafe(no_mangle)] |
| 47 | pub extern "C" fn result_ptr() -> *const u8 { |
| 48 | RESULT.with(|r| r.borrow().as_ptr()) |
| 49 | } |
| 50 |
| 51 | #[unsafe(no_mangle)] |
| 52 | pub extern "C" fn result_len() -> usize { |
| 53 | RESULT.with(|r| r.borrow().len()) |
| 54 | } |
| 55 |
| 56 | fn set_result(bytes: Vec<u8>) { |
| 57 | RESULT.with(|r| *r.borrow_mut() = bytes); |
| 58 | } |
| 59 |
| 60 | fn answer(value: Value) -> i32 { |
| 61 | set_result(serde_json::to_vec(&value).unwrap_or_default()); |
| 62 | 0 |
| 63 | } |
| 64 |
| 65 | fn fail(message: String) -> i32 { |
| 66 | set_result(serde_json::to_vec(&json!({ "error": message })).unwrap_or_default()); |
| 67 | -1 |
| 68 | } |
| 69 |
| 70 | fn input<'a>(ptr: *const u8, len: usize) -> &'a [u8] { |
| 71 | // SAFETY: the Worker passes a buffer it allocated with `alloc` and filled. |
| 72 | unsafe { std::slice::from_raw_parts(ptr, len) } |
| 73 | } |
| 74 |
| 75 | struct Cache; |
| 76 |
| 77 | impl Source for Cache { |
| 78 | fn get(&self, id: &Id) -> vcs_core::Result<Option<Object>> { |
| 79 | if let Some(o) = NEW.with(|n| n.borrow().objects.get(id).cloned()) { |
| 80 | return Ok(Some(o)); |
| 81 | } |
| 82 | Ok(CACHES.with(|c| c.borrow().get(&SLOT.get()).and_then(|s| s.objects.get(id).cloned()))) |
| 83 | } |
| 84 | } |
| 85 |
| 86 | fn decode(frame: &Frame) -> Result<Vec<u8>, String> { |
| 87 | match frame.codec { |
| 88 | RAW => Ok(frame.payload.clone()), |
| 89 | ZSTD => { |
| 90 | let mut out = Vec::with_capacity(frame.raw_len as usize); |
| 91 | ruzstd::decoding::StreamingDecoder::new(&frame.payload[..]) |
| 92 | .map_err(|e| format!("damaged object {}: {e}", frame.id.short()))? |
| 93 | .read_to_end(&mut out) |
| 94 | .map_err(|e| format!("damaged object {}: {e}", frame.id.short()))?; |
| 95 | Ok(out) |
| 96 | } |
| 97 | _ => Err("unknown codec".into()), |
| 98 | } |
| 99 | } |
| 100 |
| 101 | #[derive(Default)] |
| 102 | struct Slot { |
| 103 | objects: HashMap<Id, Object>, |
| 104 | bytes: usize, |
| 105 | } |
| 106 |
| 107 | fn insert(id: Id, object: Object) { |
| 108 | let size = object.data.len() + 64; |
| 109 | CACHES.with(|c| { |
| 110 | let mut caches = c.borrow_mut(); |
| 111 | let slot = caches.entry(SLOT.get()).or_default(); |
| 112 | if slot.objects.insert(id, object).is_none() { |
| 113 | slot.bytes += size; |
| 114 | } |
| 115 | }); |
| 116 | } |
| 117 |
| 118 | /// Checks every object in a bundle, caching them when `cache`. Answers each |
| 119 | /// frame's place in the bundle, for the Worker's index. |
| 120 | fn take_bundle(bytes: &[u8], cache: bool) -> Result<Vec<Value>, String> { |
| 121 | let frames = bundle::read(bytes).map_err(|e| e.to_string())?; |
| 122 | let mut out = Vec::with_capacity(frames.len()); |
| 123 | let mut at = bundle::MAGIC.len(); |
| 124 | for frame in frames { |
| 125 | let len = 50 + frame.payload.len(); |
| 126 | let data = decode(&frame)?; |
| 127 | bundle::verify(&frame, &data).map_err(|e| e.to_string())?; |
| 128 | out.push(json!({ "id": frame.id.hex(), "kind": frame.kind as u8, "off": at, "len": len, "raw": frame.raw_len })); |
| 129 | at += len; |
| 130 | if cache { |
| 131 | insert(frame.id, Object::new(frame.kind, data)); |
| 132 | } |
| 133 | } |
| 134 | Ok(out) |
| 135 | } |
| 136 |
| 137 | /// Verifies a bundle (an upload) and answers where each frame is. |
| 138 | #[unsafe(no_mangle)] |
| 139 | pub extern "C" fn verify(ptr: *const u8, len: usize) -> i32 { |
| 140 | match take_bundle(input(ptr, len), false) { |
| 141 | Ok(frames) => answer(json!({ "frames": frames })), |
| 142 | Err(e) => fail(e), |
| 143 | } |
| 144 | } |
| 145 |
| 146 | /// Caches every object in a bundle (frames loaded from storage). |
| 147 | #[unsafe(no_mangle)] |
| 148 | pub extern "C" fn cache_put(ptr: *const u8, len: usize) -> i32 { |
| 149 | match take_bundle(input(ptr, len), true) { |
| 150 | Ok(frames) => answer(json!({ "cached": frames.len() })), |
| 151 | Err(e) => fail(e), |
| 152 | } |
| 153 | } |
| 154 |
| 155 | /// Selects the cache slot (one per project) later calls use. |
| 156 | #[unsafe(no_mangle)] |
| 157 | pub extern "C" fn cache_use(slot: u32) { |
| 158 | SLOT.set(slot); |
| 159 | } |
| 160 |
| 161 | /// Empties one slot. |
| 162 | #[unsafe(no_mangle)] |
| 163 | pub extern "C" fn cache_drop(slot: u32) { |
| 164 | CACHES.with(|c| c.borrow_mut().remove(&slot)); |
| 165 | } |
| 166 |
| 167 | /// Cached bytes in every slot, in KiB. |
| 168 | #[unsafe(no_mangle)] |
| 169 | pub extern "C" fn cache_kib() -> u32 { |
| 170 | CACHES.with(|c| (c.borrow().values().map(|s| s.bytes).sum::<usize>() / 1024) as u32) |
| 171 | } |
| 172 |
| 173 | /// The objects the last operation made, as a bundle (and forgets them). |
| 174 | #[unsafe(no_mangle)] |
| 175 | pub extern "C" fn take_new() -> i32 { |
| 176 | let objects = NEW.with(|n| std::mem::take(&mut *n.borrow_mut())); |
| 177 | let mut out = Vec::new(); |
| 178 | bundle::write_header(&mut out); |
| 179 | for (id, o) in objects.objects { |
| 180 | insert(id, o.clone()); |
| 181 | bundle::write_frame(&mut out, &Frame::raw(&o)); |
| 182 | } |
| 183 | bundle::write_end(&mut out); |
| 184 | set_result(out); |
| 185 | 0 |
| 186 | } |
| 187 |
| 188 | fn parse<T: for<'de> Deserialize<'de>>(ptr: *const u8, len: usize) -> Result<T, String> { |
| 189 | serde_json::from_slice(input(ptr, len)).map_err(|e| format!("bad request: {e}")) |
| 190 | } |
| 191 |
| 192 | fn id(text: &str) -> Result<Id, String> { |
| 193 | Id::parse(text).ok_or_else(|| format!("not an object id: {text}")) |
| 194 | } |
| 195 |
| 196 | /// Runs an operation; a missing object becomes `{"need": [id]}`. |
| 197 | fn run(op: impl FnOnce() -> Result<Value, Error>) -> i32 { |
| 198 | match op() { |
| 199 | Ok(v) => answer(v), |
| 200 | Err(Error::Missing(missing)) => answer(json!({ "need": [missing.hex()] })), |
| 201 | Err(e) => fail(e.to_string()), |
| 202 | } |
| 203 | } |
| 204 |
| 205 | #[derive(Deserialize)] |
| 206 | struct Roots { |
| 207 | roots: Vec<String>, |
| 208 | } |
| 209 |
| 210 | /// Trees (and chunk lists) under `roots` that the cache doesn't have yet, |
| 211 | /// nearest first: the Worker loads these before an operation that walks |
| 212 | /// whole trees. |
| 213 | #[unsafe(no_mangle)] |
| 214 | pub extern "C" fn need_trees(ptr: *const u8, len: usize) -> i32 { |
| 215 | let req: Roots = match parse(ptr, len) { |
| 216 | Ok(r) => r, |
| 217 | Err(e) => return fail(e), |
| 218 | }; |
| 219 | let mut need = Vec::new(); |
| 220 | let mut seen = HashSet::new(); |
| 221 | let mut queue: VecDeque<Id> = VecDeque::new(); |
| 222 | for r in &req.roots { |
| 223 | match id(r) { |
| 224 | Ok(i) => queue.push_back(i), |
| 225 | Err(e) => return fail(e), |
| 226 | } |
| 227 | } |
| 228 | while let Some(t) = queue.pop_front() { |
| 229 | if !seen.insert(t) { |
| 230 | continue; |
| 231 | } |
| 232 | match Cache.get(&t) { |
| 233 | Ok(Some(o)) if o.kind == Kind::Tree => { |
| 234 | if let Ok(entries) = tree::decode(&o.data) { |
| 235 | for e in entries { |
| 236 | if e.kind == EntryKind::Tree { |
| 237 | queue.push_back(e.id); |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | Ok(Some(_)) => {} |
| 243 | _ => need.push(t.hex()), |
| 244 | } |
| 245 | if need.len() >= 2000 { |
| 246 | break; |
| 247 | } |
| 248 | } |
| 249 | answer(json!({ "need": need })) |
| 250 | } |
| 251 |
| 252 | #[derive(Deserialize)] |
| 253 | struct MergeReq { |
| 254 | base: String, |
| 255 | ours: String, |
| 256 | theirs: String, |
| 257 | #[serde(default)] |
| 258 | labels: Vec<String>, |
| 259 | } |
| 260 |
| 261 | /// A landing's merge: `{"tree", "conflicts"}`. |
| 262 | #[unsafe(no_mangle)] |
| 263 | pub extern "C" fn merge(ptr: *const u8, len: usize) -> i32 { |
| 264 | let req: MergeReq = match parse(ptr, len) { |
| 265 | Ok(r) => r, |
| 266 | Err(e) => return fail(e), |
| 267 | }; |
| 268 | let (base, ours, theirs) = match (id(&req.base), id(&req.ours), id(&req.theirs)) { |
| 269 | (Ok(a), Ok(b), Ok(c)) => (a, b, c), |
| 270 | _ => return fail("bad ids".into()), |
| 271 | }; |
| 272 | let labels = (req.labels.first().cloned().unwrap_or_else(|| "main".into()), req.labels.get(1).cloned().unwrap_or_else(|| "change".into())); |
| 273 | run(|| { |
| 274 | let m = merge::trees(&Cache, Some(&base), &ours, &theirs, Mode::Land, (&labels.0, &labels.1))?; |
| 275 | if m.clean() { |
| 276 | NEW.with(|n| *n.borrow_mut() = m.objects); |
| 277 | } |
| 278 | Ok(json!({ "tree": m.tree.hex(), "conflicts": m.conflicts })) |
| 279 | }) |
| 280 | } |
| 281 |
| 282 | #[derive(Deserialize)] |
| 283 | struct FilterReq { |
| 284 | tree: String, |
| 285 | hidden: Vec<String>, |
| 286 | } |
| 287 |
| 288 | #[unsafe(no_mangle)] |
| 289 | pub extern "C" fn filter_tree(ptr: *const u8, len: usize) -> i32 { |
| 290 | let req: FilterReq = match parse(ptr, len) { |
| 291 | Ok(r) => r, |
| 292 | Err(e) => return fail(e), |
| 293 | }; |
| 294 | let t = match id(&req.tree) { |
| 295 | Ok(t) => t, |
| 296 | Err(e) => return fail(e), |
| 297 | }; |
| 298 | run(|| { |
| 299 | let (out, objects) = filter::filter(&Cache, &t, &req.hidden)?; |
| 300 | NEW.with(|n| { |
| 301 | let mut n = n.borrow_mut(); |
| 302 | for o in objects { |
| 303 | n.put(o); |
| 304 | } |
| 305 | }); |
| 306 | Ok(json!({ "tree": out.hex() })) |
| 307 | }) |
| 308 | } |
| 309 |
| 310 | #[derive(Deserialize)] |
| 311 | struct GraftReq { |
| 312 | visible: String, |
| 313 | full: String, |
| 314 | hidden: Vec<String>, |
| 315 | } |
| 316 |
| 317 | #[unsafe(no_mangle)] |
| 318 | pub extern "C" fn graft_tree(ptr: *const u8, len: usize) -> i32 { |
| 319 | let req: GraftReq = match parse(ptr, len) { |
| 320 | Ok(r) => r, |
| 321 | Err(e) => return fail(e), |
| 322 | }; |
| 323 | let (v, f) = match (id(&req.visible), id(&req.full)) { |
| 324 | (Ok(a), Ok(b)) => (a, b), |
| 325 | _ => return fail("bad ids".into()), |
| 326 | }; |
| 327 | run(|| match filter::graft(&Cache, &v, &f, &req.hidden)? { |
| 328 | Ok((out, objects)) => { |
| 329 | NEW.with(|n| { |
| 330 | let mut n = n.borrow_mut(); |
| 331 | for o in objects { |
| 332 | n.put(o); |
| 333 | } |
| 334 | }); |
| 335 | Ok(json!({ "tree": out.hex() })) |
| 336 | } |
| 337 | Err(path) => Ok(json!({ "refused": path })), |
| 338 | }) |
| 339 | } |
| 340 |
| 341 | #[derive(Deserialize)] |
| 342 | struct EditReq { |
| 343 | tree: String, |
| 344 | /// `[path, kind (1 file, 2 executable), content in base64]`. |
| 345 | #[serde(default)] |
| 346 | put: Vec<(String, u8, String)>, |
| 347 | #[serde(default)] |
| 348 | delete: Vec<String>, |
| 349 | } |
| 350 |
| 351 | /// A tree with files written and deleted: `{"tree"}`, or `{"bad_path"}`. |
| 352 | #[unsafe(no_mangle)] |
| 353 | pub extern "C" fn edit_tree(ptr: *const u8, len: usize) -> i32 { |
| 354 | use base64::Engine; |
| 355 | let req: EditReq = match parse(ptr, len) { |
| 356 | Ok(r) => r, |
| 357 | Err(e) => return fail(e), |
| 358 | }; |
| 359 | let t = match id(&req.tree) { |
| 360 | Ok(t) => t, |
| 361 | Err(e) => return fail(e), |
| 362 | }; |
| 363 | let mut put = Vec::with_capacity(req.put.len()); |
| 364 | for (path, kind, b64) in &req.put { |
| 365 | let Ok(content) = base64::engine::general_purpose::STANDARD.decode(b64) else { return fail(format!("{path}: content isn't base64")) }; |
| 366 | put.push(tree::Put { path: path.clone(), kind: if *kind == 2 { EntryKind::Exec } else { EntryKind::File }, content }); |
| 367 | } |
| 368 | run(|| match tree::edit(&Cache, &t, &put, &req.delete)? { |
| 369 | Ok((root, objects)) => { |
| 370 | NEW.with(|n| { |
| 371 | let mut n = n.borrow_mut(); |
| 372 | for o in objects { |
| 373 | n.put(o); |
| 374 | } |
| 375 | }); |
| 376 | Ok(json!({ "tree": root.hex() })) |
| 377 | } |
| 378 | Err(path) => Ok(json!({ "bad_path": path })), |
| 379 | }) |
| 380 | } |
| 381 |
| 382 | #[derive(Deserialize)] |
| 383 | struct ScanReq { |
| 384 | old: String, |
| 385 | new: String, |
| 386 | } |
| 387 |
| 388 | /// Secrets in lines `new` adds over `old`: `{"hits": [{path, line, kind}]}`. |
| 389 | #[unsafe(no_mangle)] |
| 390 | pub extern "C" fn secrets(ptr: *const u8, len: usize) -> i32 { |
| 391 | let req: ScanReq = match parse(ptr, len) { |
| 392 | Ok(r) => r, |
| 393 | Err(e) => return fail(e), |
| 394 | }; |
| 395 | let (old, new) = match (id(&req.old), id(&req.new)) { |
| 396 | (Ok(a), Ok(b)) => (a, b), |
| 397 | _ => return fail("bad ids".into()), |
| 398 | }; |
| 399 | run(|| Ok(json!({ "hits": vcs_core::secrets::scan(&Cache, &old, &new)? }))) |
| 400 | } |
| 401 |
| 402 | #[derive(Deserialize)] |
| 403 | struct PathReq { |
| 404 | tree: String, |
| 405 | #[serde(default)] |
| 406 | path: String, |
| 407 | } |
| 408 |
| 409 | /// The entry at a path: `{"entry": {kind, id} | null}` (the root is a tree). |
| 410 | #[unsafe(no_mangle)] |
| 411 | pub extern "C" fn lookup(ptr: *const u8, len: usize) -> i32 { |
| 412 | let req: PathReq = match parse(ptr, len) { |
| 413 | Ok(r) => r, |
| 414 | Err(e) => return fail(e), |
| 415 | }; |
| 416 | let root = match id(&req.tree) { |
| 417 | Ok(t) => t, |
| 418 | Err(e) => return fail(e), |
| 419 | }; |
| 420 | run(|| { |
| 421 | let mut at = (EntryKind::Tree, root); |
| 422 | for part in req.path.split('/').filter(|p| !p.is_empty()) { |
| 423 | if at.0 != EntryKind::Tree { |
| 424 | return Ok(json!({ "entry": null })); |
| 425 | } |
| 426 | match tree::read(&Cache, &at.1)?.into_iter().find(|e| e.name == part) { |
| 427 | Some(e) => at = (e.kind, e.id), |
| 428 | None => return Ok(json!({ "entry": null })), |
| 429 | } |
| 430 | } |
| 431 | Ok(json!({ "entry": { "kind": at.0.name(), "id": at.1.hex() } })) |
| 432 | }) |
| 433 | } |
| 434 |
| 435 | /// A folder's entries: `{"entries": [[name, kind]]}`. |
| 436 | #[unsafe(no_mangle)] |
| 437 | pub extern "C" fn list_dir(ptr: *const u8, len: usize) -> i32 { |
| 438 | let req: PathReq = match parse(ptr, len) { |
| 439 | Ok(r) => r, |
| 440 | Err(e) => return fail(e), |
| 441 | }; |
| 442 | let t = match id(&req.tree) { |
| 443 | Ok(t) => t, |
| 444 | Err(e) => return fail(e), |
| 445 | }; |
| 446 | run(|| Ok(json!({ "entries": tree::read(&Cache, &t)?.iter().map(|e| json!([e.name, e.kind.name()])).collect::<Vec<_>>() }))) |
| 447 | } |
| 448 |
| 449 | #[derive(Deserialize)] |
| 450 | struct ReadReq { |
| 451 | id: String, |
| 452 | #[serde(default)] |
| 453 | max: Option<usize>, |
| 454 | } |
| 455 |
| 456 | /// A file's content: `{"base64", "size"}`, or `{"too_big": size}` over `max` bytes. |
| 457 | #[unsafe(no_mangle)] |
| 458 | pub extern "C" fn read_file(ptr: *const u8, len: usize) -> i32 { |
| 459 | use base64::Engine; |
| 460 | let req: ReadReq = match parse(ptr, len) { |
| 461 | Ok(r) => r, |
| 462 | Err(e) => return fail(e), |
| 463 | }; |
| 464 | let f = match id(&req.id) { |
| 465 | Ok(t) => t, |
| 466 | Err(e) => return fail(e), |
| 467 | }; |
| 468 | run(|| { |
| 469 | let size = vcs_core::chunk::file_size(&Cache, &f)?; |
| 470 | if req.max.is_some_and(|m| size as usize > m) { |
| 471 | return Ok(json!({ "too_big": size })); |
| 472 | } |
| 473 | let bytes = vcs_core::chunk::read_file(&Cache, &f)?; |
| 474 | Ok(json!({ "base64": base64::engine::general_purpose::STANDARD.encode(&bytes), "size": bytes.len() })) |
| 475 | }) |
| 476 | } |
| 477 |
| 478 | /// The first hidden path a tree holds: `{"found": path | null}`. |
| 479 | #[unsafe(no_mangle)] |
| 480 | pub extern "C" fn hidden_in(ptr: *const u8, len: usize) -> i32 { |
| 481 | let req: FilterReq = match parse(ptr, len) { |
| 482 | Ok(r) => r, |
| 483 | Err(e) => return fail(e), |
| 484 | }; |
| 485 | let t = match id(&req.tree) { |
| 486 | Ok(t) => t, |
| 487 | Err(e) => return fail(e), |
| 488 | }; |
| 489 | run(|| Ok(json!({ "found": filter::holds_hidden(&Cache, &t, &req.hidden)? }))) |
| 490 | } |
| 491 |
| 492 | #[derive(Deserialize)] |
| 493 | struct SinceReq { |
| 494 | tree: String, |
| 495 | #[serde(default)] |
| 496 | have: Option<String>, |
| 497 | } |
| 498 |
| 499 | /// Every object under `tree` that `have` doesn't share, chunks included. |
| 500 | #[unsafe(no_mangle)] |
| 501 | pub extern "C" fn new_since(ptr: *const u8, len: usize) -> i32 { |
| 502 | let req: SinceReq = match parse(ptr, len) { |
| 503 | Ok(r) => r, |
| 504 | Err(e) => return fail(e), |
| 505 | }; |
| 506 | let t = match id(&req.tree) { |
| 507 | Ok(t) => t, |
| 508 | Err(e) => return fail(e), |
| 509 | }; |
| 510 | let have = match req.have.as_deref().map(id) { |
| 511 | Some(Ok(h)) => Some(h), |
| 512 | Some(Err(e)) => return fail(e), |
| 513 | None => None, |
| 514 | }; |
| 515 | run(|| { |
| 516 | let mut ids = Vec::new(); |
| 517 | tree::new_since(&Cache, have.as_ref(), &t, &mut ids)?; |
| 518 | let mut out = Vec::with_capacity(ids.len()); |
| 519 | let mut need = Vec::new(); |
| 520 | for i in ids { |
| 521 | out.push(i.hex()); |
| 522 | // Chunk lists name chunks; the Worker knows a file's kind from |
| 523 | // its index, so it asks for those lists separately. |
| 524 | if let Some(o) = Cache.get(&i)? |
| 525 | && o.kind == Kind::Chunks |
| 526 | { |
| 527 | for (c, _) in decode_chunks(&o.data)? { |
| 528 | out.push(c.hex()); |
| 529 | } |
| 530 | } else if Cache.get(&i)?.is_none() { |
| 531 | need.push(i.hex()); |
| 532 | } |
| 533 | } |
| 534 | Ok(json!({ "ids": out, "files_not_loaded": need })) |
| 535 | }) |
| 536 | } |
| 537 |
| 538 | #[derive(Deserialize)] |
| 539 | struct FlattenReq { |
| 540 | tree: String, |
| 541 | } |
| 542 |
| 543 | /// Every file under a tree: `[[path, kind, id]]`. |
| 544 | #[unsafe(no_mangle)] |
| 545 | pub extern "C" fn flatten(ptr: *const u8, len: usize) -> i32 { |
| 546 | let req: FlattenReq = match parse(ptr, len) { |
| 547 | Ok(r) => r, |
| 548 | Err(e) => return fail(e), |
| 549 | }; |
| 550 | let t = match id(&req.tree) { |
| 551 | Ok(t) => t, |
| 552 | Err(e) => return fail(e), |
| 553 | }; |
| 554 | run(|| { |
| 555 | let files = tree::flatten(&Cache, &t)?; |
| 556 | Ok(json!({ "files": files.iter().map(|(p, e)| json!([p, e.kind as u8, e.id.hex()])).collect::<Vec<_>>() })) |
| 557 | }) |
| 558 | } |
| 559 |
| 560 | // The git view: versions written as git objects, streamed as one pack. |
| 561 | // |
| 562 | // The Worker plans a version (`git_plan`) and looks up git IDs it already |
| 563 | // knows. It starts a pack (`pack_begin`), hashes each new file (`blob_begin` |
| 564 | // with write 0, `blob_feed` one stored frame at a time, `blob_end`), writes |
| 565 | // the trees and the commit (`git_trees`), which names the commit it pushes, |
| 566 | // then writes each new file into the pack (`blob_begin` with write 1) and |
| 567 | // closes it (`pack_end`). Pack bytes collect in a buffer the Worker drains |
| 568 | // with `pack_take`. |
| 569 |
| 570 | struct GitPack { |
| 571 | sha: Sha1, |
| 572 | out: Vec<u8>, |
| 573 | blob: Option<GitBlob>, |
| 574 | } |
| 575 |
| 576 | struct GitBlob { |
| 577 | sha: Sha1, |
| 578 | /// None: only hashing (the git ID is needed before the pack is sent). |
| 579 | z: Option<flate2::write::ZlibEncoder<Vec<u8>>>, |
| 580 | size: u64, |
| 581 | fed: u64, |
| 582 | } |
| 583 |
| 584 | thread_local! { |
| 585 | static PACK: RefCell<Option<GitPack>> = const { RefCell::new(None) }; |
| 586 | } |
| 587 |
| 588 | fn emit(pack: &mut GitPack, bytes: &[u8]) { |
| 589 | pack.sha.update(bytes); |
| 590 | pack.out.extend_from_slice(bytes); |
| 591 | } |
| 592 |
| 593 | /// A pack entry's header: type and size. |
| 594 | fn entry_header(kind: u8, size: u64) -> Vec<u8> { |
| 595 | let mut out = Vec::with_capacity(10); |
| 596 | let mut byte = (kind << 4) | (size & 0x0f) as u8; |
| 597 | let mut rest = size >> 4; |
| 598 | while rest > 0 { |
| 599 | out.push(byte | 0x80); |
| 600 | byte = (rest & 0x7f) as u8; |
| 601 | rest >>= 7; |
| 602 | } |
| 603 | out.push(byte); |
| 604 | out |
| 605 | } |
| 606 |
| 607 | fn hex(bytes: &[u8]) -> String { |
| 608 | bytes.iter().map(|b| format!("{b:02x}")).collect() |
| 609 | } |
| 610 |
| 611 | fn git_header(kind: &str, size: u64) -> Vec<u8> { |
| 612 | format!("{kind} {size}\0").into_bytes() |
| 613 | } |
| 614 |
| 615 | /// Adds a whole object (trees, commits) to the pack; answers its git ID. |
| 616 | fn emit_object(pack: &mut GitPack, kind: &str, type_code: u8, data: &[u8]) -> String { |
| 617 | let mut h = Sha1::new(); |
| 618 | h.update(git_header(kind, data.len() as u64)); |
| 619 | h.update(data); |
| 620 | let id = hex(&h.finalize()); |
| 621 | let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); |
| 622 | let _ = z.write_all(data); |
| 623 | let deflated = z.finish().unwrap_or_default(); |
| 624 | emit(pack, &entry_header(type_code, data.len() as u64)); |
| 625 | emit(pack, &deflated); |
| 626 | id |
| 627 | } |
| 628 |
| 629 | fn with_pack(f: impl FnOnce(&mut GitPack) -> Result<Value, String>) -> i32 { |
| 630 | let result = PACK.with(|p| match p.borrow_mut().as_mut() { |
| 631 | Some(pack) => f(pack), |
| 632 | None => Err("no pack started".into()), |
| 633 | }); |
| 634 | match result { |
| 635 | Ok(v) => answer(v), |
| 636 | Err(e) => fail(e), |
| 637 | } |
| 638 | } |
| 639 |
| 640 | #[unsafe(no_mangle)] |
| 641 | pub extern "C" fn pack_begin(count: u32) -> i32 { |
| 642 | let mut pack = GitPack { sha: Sha1::new(), out: Vec::new(), blob: None }; |
| 643 | let mut head = b"PACK".to_vec(); |
| 644 | head.extend_from_slice(&2u32.to_be_bytes()); |
| 645 | head.extend_from_slice(&count.to_be_bytes()); |
| 646 | emit(&mut pack, &head); |
| 647 | PACK.with(|p| *p.borrow_mut() = Some(pack)); |
| 648 | answer(json!({})) |
| 649 | } |
| 650 |
| 651 | /// Pack bytes made so far (and forgets them). |
| 652 | #[unsafe(no_mangle)] |
| 653 | pub extern "C" fn pack_take() -> i32 { |
| 654 | let bytes = PACK.with(|p| p.borrow_mut().as_mut().map(|pack| std::mem::take(&mut pack.out)).unwrap_or_default()); |
| 655 | set_result(bytes); |
| 656 | 0 |
| 657 | } |
| 658 |
| 659 | /// Ends the pack: the last bytes, with the checksum. |
| 660 | #[unsafe(no_mangle)] |
| 661 | pub extern "C" fn pack_end() -> i32 { |
| 662 | let Some(mut pack) = PACK.with(|p| p.borrow_mut().take()) else { return fail("no pack started".into()) }; |
| 663 | if pack.blob.is_some() { |
| 664 | return fail("a file is still open".into()); |
| 665 | } |
| 666 | let sum = pack.sha.finalize(); |
| 667 | pack.out.extend_from_slice(&sum); |
| 668 | set_result(pack.out); |
| 669 | 0 |
| 670 | } |
| 671 |
| 672 | /// Starts a file of `size` bytes (a JS number: files under 2^53 bytes). |
| 673 | /// With `write` 0 the file is only hashed; with 1 it goes into the pack. |
| 674 | #[unsafe(no_mangle)] |
| 675 | pub extern "C" fn blob_begin(size: f64, write: u32) -> i32 { |
| 676 | let size = size as u64; |
| 677 | with_pack(|pack| { |
| 678 | if pack.blob.is_some() { |
| 679 | return Err("a file is already open".into()); |
| 680 | } |
| 681 | let mut sha = Sha1::new(); |
| 682 | sha.update(git_header("blob", size)); |
| 683 | let z = if write != 0 { |
| 684 | emit(pack, &entry_header(3, size)); |
| 685 | Some(flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast())) |
| 686 | } else { |
| 687 | None |
| 688 | }; |
| 689 | pack.blob = Some(GitBlob { sha, z, size, fed: 0 }); |
| 690 | Ok(json!({})) |
| 691 | }) |
| 692 | } |
| 693 |
| 694 | /// One stored frame of the open file: the whole blob, or its next chunk. |
| 695 | #[unsafe(no_mangle)] |
| 696 | pub extern "C" fn blob_feed(ptr: *const u8, len: usize) -> i32 { |
| 697 | let frame = match one_frame(input(ptr, len)) { |
| 698 | Ok(f) => f, |
| 699 | Err(e) => return fail(e), |
| 700 | }; |
| 701 | with_pack(|pack| { |
| 702 | let data = decode(&frame)?; |
| 703 | bundle::verify(&frame, &data).map_err(|e| e.to_string())?; |
| 704 | let blob = pack.blob.as_mut().ok_or("no file open")?; |
| 705 | blob.sha.update(&data); |
| 706 | blob.fed += data.len() as u64; |
| 707 | if let Some(z) = blob.z.as_mut() { |
| 708 | z.write_all(&data).map_err(|e| e.to_string())?; |
| 709 | let out = std::mem::take(z.get_mut()); |
| 710 | emit(pack, &out); |
| 711 | } |
| 712 | Ok(json!({})) |
| 713 | }) |
| 714 | } |
| 715 |
| 716 | #[unsafe(no_mangle)] |
| 717 | pub extern "C" fn blob_end() -> i32 { |
| 718 | with_pack(|pack| { |
| 719 | let blob = pack.blob.take().ok_or("no file open")?; |
| 720 | if blob.fed != blob.size { |
| 721 | return Err(format!("file was {} bytes, expected {}", blob.fed, blob.size)); |
| 722 | } |
| 723 | if let Some(z) = blob.z { |
| 724 | let rest = z.finish().map_err(|e| e.to_string())?; |
| 725 | emit(pack, &rest); |
| 726 | } |
| 727 | Ok(json!({ "git": hex(&blob.sha.finalize()) })) |
| 728 | }) |
| 729 | } |
| 730 |
| 731 | /// One frame as stored in a pack (no bundle header). |
| 732 | fn one_frame(bytes: &[u8]) -> Result<Frame, String> { |
| 733 | let mut b = Vec::with_capacity(bundle::MAGIC.len() + bytes.len() + 32); |
| 734 | bundle::write_header(&mut b); |
| 735 | b.extend_from_slice(bytes); |
| 736 | bundle::write_end(&mut b); |
| 737 | let mut frames = bundle::read(&b).map_err(|e| e.to_string())?; |
| 738 | if frames.len() != 1 { |
| 739 | return Err("expected one object".into()); |
| 740 | } |
| 741 | Ok(frames.remove(0)) |
| 742 | } |
| 743 |
| 744 | /// A big file's chunk list (one stored frame): `{"chunks": [[id, size]], "size"}`. |
| 745 | #[unsafe(no_mangle)] |
| 746 | pub extern "C" fn chunk_list(ptr: *const u8, len: usize) -> i32 { |
| 747 | let result = (|| { |
| 748 | let frame = one_frame(input(ptr, len))?; |
| 749 | let data = decode(&frame)?; |
| 750 | bundle::verify(&frame, &data).map_err(|e| e.to_string())?; |
| 751 | if frame.kind != Kind::Chunks { |
| 752 | return Err("not a chunk list".to_string()); |
| 753 | } |
| 754 | let chunks = decode_chunks(&data).map_err(|e| e.to_string())?; |
| 755 | let size: u64 = chunks.iter().map(|(_, n)| n).sum(); |
| 756 | Ok(json!({ "chunks": chunks.iter().map(|(c, n)| json!([c.hex(), n])).collect::<Vec<_>>(), "size": size })) |
| 757 | })(); |
| 758 | match result { |
| 759 | Ok(v) => answer(v), |
| 760 | Err(e) => fail(e), |
| 761 | } |
| 762 | } |
| 763 |
| 764 | #[derive(Deserialize)] |
| 765 | struct PlanReq { |
| 766 | tree: String, |
| 767 | #[serde(default)] |
| 768 | have: Option<String>, |
| 769 | /// IDs whose git form isn't known: treated as new. |
| 770 | #[serde(default)] |
| 771 | force: Vec<String>, |
| 772 | } |
| 773 |
| 774 | #[derive(Default)] |
| 775 | struct Plan { |
| 776 | trees: Vec<Id>, |
| 777 | files: Vec<Id>, |
| 778 | lookup: Vec<Id>, |
| 779 | seen: HashSet<Id>, |
| 780 | looked: HashSet<Id>, |
| 781 | } |
| 782 |
| 783 | fn plan_tree(t: &Id, have: Option<&Id>, force: &HashSet<Id>, plan: &mut Plan) -> Result<(), Error> { |
| 784 | if !plan.seen.insert(*t) { |
| 785 | return Ok(()); |
| 786 | } |
| 787 | plan.trees.push(*t); |
| 788 | let old: HashMap<String, tree::TreeEntry> = match have { |
| 789 | Some(h) => tree::read(&Cache, h)?.into_iter().map(|e| (e.name.clone(), e)).collect(), |
| 790 | None => HashMap::new(), |
| 791 | }; |
| 792 | for e in tree::read(&Cache, t)? { |
| 793 | if e.kind == EntryKind::Gitlink { |
| 794 | // A submodule's commit isn't an object the pack carries. |
| 795 | continue; |
| 796 | } |
| 797 | let before = old.get(&e.name); |
| 798 | if before.is_some_and(|b| b.id == e.id) && !force.contains(&e.id) { |
| 799 | if plan.looked.insert(e.id) { |
| 800 | plan.lookup.push(e.id); |
| 801 | } |
| 802 | continue; |
| 803 | } |
| 804 | if e.kind == EntryKind::Tree { |
| 805 | // A forced tree is rebuilt whole. |
| 806 | let old_sub = if force.contains(&e.id) { None } else { before.filter(|b| b.kind == EntryKind::Tree).map(|b| b.id) }; |
| 807 | plan_tree(&e.id, old_sub.as_ref(), force, plan)?; |
| 808 | } else if plan.seen.insert(e.id) { |
| 809 | plan.files.push(e.id); |
| 810 | } |
| 811 | } |
| 812 | Ok(()) |
| 813 | } |
| 814 |
| 815 | /// What a version adds over the one before it, for git: new trees, new |
| 816 | /// files, and unchanged entries whose git IDs the Worker looks up. |
| 817 | #[unsafe(no_mangle)] |
| 818 | pub extern "C" fn git_plan(ptr: *const u8, len: usize) -> i32 { |
| 819 | let req: PlanReq = match parse(ptr, len) { |
| 820 | Ok(r) => r, |
| 821 | Err(e) => return fail(e), |
| 822 | }; |
| 823 | let root = match id(&req.tree) { |
| 824 | Ok(t) => t, |
| 825 | Err(e) => return fail(e), |
| 826 | }; |
| 827 | let have = match req.have.as_deref().map(id) { |
| 828 | Some(Ok(h)) => Some(h), |
| 829 | Some(Err(e)) => return fail(e), |
| 830 | None => None, |
| 831 | }; |
| 832 | let force: HashSet<Id> = req.force.iter().filter_map(|f| Id::parse(f)).collect(); |
| 833 | run(|| { |
| 834 | let mut plan = Plan::default(); |
| 835 | if have == Some(root) && !force.contains(&root) { |
| 836 | plan.lookup.push(root); |
| 837 | } else { |
| 838 | let have = if force.contains(&root) { None } else { have }; |
| 839 | plan_tree(&root, have.as_ref(), &force, &mut plan)?; |
| 840 | } |
| 841 | let list = |ids: &[Id]| ids.iter().map(|i| i.hex()).collect::<Vec<_>>(); |
| 842 | Ok(json!({ "trees": list(&plan.trees), "files": list(&plan.files), "lookup": list(&plan.lookup) })) |
| 843 | }) |
| 844 | } |
| 845 |
| 846 | #[derive(Deserialize)] |
| 847 | struct TreesReq { |
| 848 | tree: String, |
| 849 | /// The plan's new trees: each is written to the pack once. |
| 850 | trees: Vec<String>, |
| 851 | /// Native ID → git ID for everything else the trees name. |
| 852 | known: HashMap<String, String>, |
| 853 | #[serde(default)] |
| 854 | parents: Vec<String>, |
| 855 | message: String, |
| 856 | author: String, |
| 857 | time: i64, |
| 858 | } |
| 859 |
| 860 | fn git_tree(t: &Id, fresh: &HashSet<Id>, known: &HashMap<String, String>, made: &mut HashMap<Id, String>, pack: &mut GitPack) -> Result<String, Error> { |
| 861 | if let Some(g) = made.get(t) { |
| 862 | return Ok(g.clone()); |
| 863 | } |
| 864 | if !fresh.contains(t) { |
| 865 | return known.get(&t.hex()).cloned().ok_or_else(|| Error::Corrupt(format!("git id of tree {} isn't known", t.short()))); |
| 866 | } |
| 867 | // Git sorts entries by name, with folders compared as if they end in '/'. |
| 868 | let mut rows: Vec<(Vec<u8>, Vec<u8>)> = Vec::new(); |
| 869 | for e in tree::read(&Cache, t)? { |
| 870 | let (mode, gid) = match e.kind { |
| 871 | EntryKind::Tree => ("40000", git_tree(&e.id, fresh, known, made, pack)?), |
| 872 | EntryKind::Gitlink => ("160000", gitlink(&e.id)?), |
| 873 | kind => { |
| 874 | let gid = known.get(&e.id.hex()).cloned().ok_or_else(|| Error::Corrupt(format!("git id of file {} isn't known", e.id.short())))?; |
| 875 | (match kind { |
| 876 | EntryKind::Exec => "100755", |
| 877 | EntryKind::Link => "120000", |
| 878 | _ => "100644", |
| 879 | }, gid) |
| 880 | } |
| 881 | }; |
| 882 | let mut key = e.name.as_bytes().to_vec(); |
| 883 | if mode == "40000" { |
| 884 | key.push(b'/'); |
| 885 | } |
| 886 | let mut row = format!("{mode} {}", e.name).into_bytes(); |
| 887 | row.push(0); |
| 888 | for i in (0..gid.len()).step_by(2) { |
| 889 | row.push(u8::from_str_radix(&gid[i..i + 2], 16).map_err(|_| Error::Corrupt("bad git id".into()))?); |
| 890 | } |
| 891 | rows.push((key, row)); |
| 892 | } |
| 893 | rows.sort_by(|a, b| a.0.cmp(&b.0)); |
| 894 | let data: Vec<u8> = rows.into_iter().flat_map(|(_, r)| r).collect(); |
| 895 | let g = emit_object(pack, "tree", 2, &data); |
| 896 | made.insert(*t, g.clone()); |
| 897 | Ok(g) |
| 898 | } |
| 899 |
| 900 | /// The commit a submodule entry points at (its content, 40 hex digits). |
| 901 | fn gitlink(id: &Id) -> Result<String, Error> { |
| 902 | let text = String::from_utf8(vcs_core::chunk::read_file(&Cache, id)?).map_err(|_| Error::Corrupt("bad submodule entry".into()))?; |
| 903 | let sha = text.trim().to_string(); |
| 904 | if sha.len() != 40 || !sha.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 905 | return Err(Error::Corrupt("bad submodule entry".into())); |
| 906 | } |
| 907 | Ok(sha) |
| 908 | } |
| 909 |
| 910 | /// Writes the version's new trees and its commit to the pack. |
| 911 | #[unsafe(no_mangle)] |
| 912 | pub extern "C" fn git_trees(ptr: *const u8, len: usize) -> i32 { |
| 913 | let req: TreesReq = match parse(ptr, len) { |
| 914 | Ok(r) => r, |
| 915 | Err(e) => return fail(e), |
| 916 | }; |
| 917 | let root = match id(&req.tree) { |
| 918 | Ok(t) => t, |
| 919 | Err(e) => return fail(e), |
| 920 | }; |
| 921 | let fresh: HashSet<Id> = req.trees.iter().filter_map(|t| Id::parse(t)).collect(); |
| 922 | // Every new tree is loaded first, so nothing reaches the pack twice, |
| 923 | // and so are the submodule entries in them. |
| 924 | let mut need: Vec<String> = fresh.iter().filter(|t| Cache.get(t).ok().flatten().is_none()).map(|t| t.hex()).collect(); |
| 925 | if need.is_empty() { |
| 926 | for t in &fresh { |
| 927 | if let Ok(entries) = tree::read(&Cache, t) { |
| 928 | need.extend(entries.iter().filter(|e| e.kind == EntryKind::Gitlink && Cache.get(&e.id).ok().flatten().is_none()).map(|e| e.id.hex())); |
| 929 | } |
| 930 | } |
| 931 | } |
| 932 | if !need.is_empty() { |
| 933 | return answer(json!({ "need": need })); |
| 934 | } |
| 935 | with_pack(|pack| { |
| 936 | let mut made = HashMap::new(); |
| 937 | let tree_id = git_tree(&root, &fresh, &req.known, &mut made, pack).map_err(|e| e.to_string())?; |
| 938 | if made.len() != fresh.len() { |
| 939 | return Err(format!("wrote {} trees, planned {}", made.len(), fresh.len())); |
| 940 | } |
| 941 | let (name, email) = match req.author.split_once(" <") { |
| 942 | Some((n, e)) => (n.to_string(), e.trim_end_matches('>').to_string()), |
| 943 | None => (req.author.clone(), "vcs@localhost".into()), |
| 944 | }; |
| 945 | let mut commit = format!("tree {tree_id}\n"); |
| 946 | for p in &req.parents { |
| 947 | if p.len() != 40 || !p.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 948 | return Err(format!("bad parent {p}")); |
| 949 | } |
| 950 | commit.push_str(&format!("parent {p}\n")); |
| 951 | } |
| 952 | commit.push_str(&format!("author {name} <{email}> {} +0000\ncommitter {name} <{email}> {} +0000\n\n{}", req.time, req.time, req.message)); |
| 953 | if !commit.ends_with('\n') { |
| 954 | commit.push('\n'); |
| 955 | } |
| 956 | let commit_id = emit_object(pack, "commit", 1, commit.as_bytes()); |
| 957 | let trees: HashMap<String, String> = made.into_iter().map(|(k, v)| (k.hex(), v)).collect(); |
| 958 | Ok(json!({ "commit": commit_id, "tree": tree_id, "trees": trees })) |
| 959 | }) |
| 960 | } |
| 961 |
| 962 |
| 963 | #[cfg(test)] |
| 964 | mod tests { |
| 965 | use super::*; |
| 966 | use vcs_core::tree::{Entry, Files}; |
| 967 |
| 968 | fn sha1_git(kind: &str, data: &[u8]) -> String { |
| 969 | let mut h = Sha1::new(); |
| 970 | h.update(git_header(kind, data.len() as u64)); |
| 971 | h.update(data); |
| 972 | hex(&h.finalize()) |
| 973 | } |
| 974 |
| 975 | #[test] |
| 976 | fn git_ids_match_git() { |
| 977 | // `printf 'hello\n' | git hash-object --stdin` |
| 978 | assert_eq!(sha1_git("blob", b"hello\n"), "ce013625030ba8dba906f756967f9e9ca394464a"); |
| 979 | } |
| 980 |
| 981 | fn feed(o: &Object) { |
| 982 | let mut b = Vec::new(); |
| 983 | bundle::write_frame(&mut b, &Frame::raw(o)); |
| 984 | assert_eq!(blob_feed(b.as_ptr(), b.len()), 0); |
| 985 | } |
| 986 |
| 987 | fn result() -> Vec<u8> { |
| 988 | RESULT.with(|r| r.borrow().clone()) |
| 989 | } |
| 990 |
| 991 | fn call_json(f: extern "C" fn(*const u8, usize) -> i32, v: Value) -> Value { |
| 992 | let b = serde_json::to_vec(&v).unwrap(); |
| 993 | assert_eq!(f(b.as_ptr(), b.len()), 0, "{}", String::from_utf8_lossy(&result())); |
| 994 | serde_json::from_slice(&result()).unwrap() |
| 995 | } |
| 996 |
| 997 | /// A version's pack is one git accepts, with the IDs git computes. |
| 998 | #[test] |
| 999 | fn git_pack_is_git() { |
| 1000 | let small = Object::blob(b"fn main() {}\n".to_vec()); |
| 1001 | let big: Vec<u8> = (0..3_000_000u32).map(|i| (i.wrapping_mul(2654435761) >> 13) as u8).collect(); |
| 1002 | let big_parts = vcs_core::chunk::file_objects(&big); |
| 1003 | let big_id = big_parts[0].id(); |
| 1004 | let mut files = Files::new(); |
| 1005 | files.insert("src/main.rs".into(), Entry { kind: EntryKind::File, id: small.id() }); |
| 1006 | files.insert("run.sh".into(), Entry { kind: EntryKind::Exec, id: small.id() }); |
| 1007 | files.insert("data/big.bin".into(), Entry { kind: EntryKind::File, id: big_id }); |
| 1008 | let (root, trees) = tree::build(&files); |
| 1009 | cache_drop(0); |
| 1010 | for t in &trees { |
| 1011 | insert(t.id(), t.clone()); |
| 1012 | } |
| 1013 | let plan = call_json(git_plan, json!({ "tree": root.hex() })); |
| 1014 | let new_trees: Vec<String> = serde_json::from_value(plan["trees"].clone()).unwrap(); |
| 1015 | let new_files: Vec<String> = serde_json::from_value(plan["files"].clone()).unwrap(); |
| 1016 | assert_eq!(new_trees.len(), 3); |
| 1017 | assert_eq!(new_files.len(), 2); |
| 1018 |
| 1019 | assert_eq!(pack_begin((new_trees.len() + new_files.len() + 1) as u32), 0); |
| 1020 | let mut known = HashMap::new(); |
| 1021 | let list = big_parts.iter().find(|o| o.kind == Kind::Chunks).unwrap(); |
| 1022 | let chunks: HashMap<Id, &Object> = big_parts.iter().map(|o| (o.id(), o)).collect(); |
| 1023 | let mut files_pass = |write: u32, pack: &mut Vec<u8>| -> Vec<String> { |
| 1024 | let mut ids = Vec::new(); |
| 1025 | assert_eq!(blob_begin(small.data.len() as f64, write), 0); |
| 1026 | feed(&small); |
| 1027 | assert_eq!(blob_end(), 0); |
| 1028 | let v: Value = serde_json::from_slice(&result()).unwrap(); |
| 1029 | ids.push(v["git"].as_str().unwrap().to_string()); |
| 1030 | assert_eq!(blob_begin(big.len() as f64, write), 0); |
| 1031 | for (c, _) in decode_chunks(&list.data).unwrap() { |
| 1032 | feed(chunks[&c]); |
| 1033 | pack_take(); |
| 1034 | pack.extend(result()); |
| 1035 | } |
| 1036 | assert_eq!(blob_end(), 0); |
| 1037 | let v: Value = serde_json::from_slice(&result()).unwrap(); |
| 1038 | ids.push(v["git"].as_str().unwrap().to_string()); |
| 1039 | ids |
| 1040 | }; |
| 1041 | let mut pack = Vec::new(); |
| 1042 | let hashed = files_pass(0, &mut pack); |
| 1043 | known.insert(small.id().hex(), hashed[0].clone()); |
| 1044 | known.insert(big_id.hex(), hashed[1].clone()); |
| 1045 | let done = call_json( |
| 1046 | git_trees, |
| 1047 | json!({ "tree": root.hex(), "trees": new_trees, "known": known, "parents": [], "message": "First\n", "author": "Ada <ada@example.com>", "time": 1700000000 }), |
| 1048 | ); |
| 1049 | let written = files_pass(1, &mut pack); |
| 1050 | assert_eq!(hashed, written); |
| 1051 | pack_take(); |
| 1052 | pack.extend(result()); |
| 1053 | assert_eq!(pack_end(), 0); |
| 1054 | pack.extend(result()); |
| 1055 | let dir = std::env::temp_dir().join(format!("vcs-wasm-git-{}", std::process::id())); |
| 1056 | let _ = std::fs::remove_dir_all(&dir); |
| 1057 | std::fs::create_dir_all(&dir).unwrap(); |
| 1058 | let git = |args: &[&str], input: Option<&[u8]>| -> String { |
| 1059 | let mut c = std::process::Command::new("git"); |
| 1060 | c.args(args).current_dir(&dir).stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()); |
| 1061 | let mut child = c.spawn().unwrap(); |
| 1062 | if let Some(i) = input { |
| 1063 | child.stdin.take().unwrap().write_all(i).unwrap(); |
| 1064 | } else { |
| 1065 | drop(child.stdin.take()); |
| 1066 | } |
| 1067 | let out = child.wait_with_output().unwrap(); |
| 1068 | assert!(out.status.success(), "git {args:?} failed"); |
| 1069 | String::from_utf8(out.stdout).unwrap() |
| 1070 | }; |
| 1071 | git(&["init", "-q", "--bare", "."], None); |
| 1072 | git(&["index-pack", "--stdin", "--strict"], Some(&pack)); |
| 1073 | let commit = done["commit"].as_str().unwrap(); |
| 1074 | git(&["update-ref", "refs/heads/main", commit], None); |
| 1075 | git(&["fsck", "--strict", "--no-dangling"], None); |
| 1076 | let listing = git(&["ls-tree", "-r", "main"], None); |
| 1077 | assert!(listing.contains("100755 blob") && listing.contains("run.sh"), "{listing}"); |
| 1078 | assert_eq!(git(&["cat-file", "-p", "main:src/main.rs"], None), "fn main() {}\n"); |
| 1079 | assert_eq!(git(&["cat-file", "-s", "main:data/big.bin"], None).trim(), big.len().to_string()); |
| 1080 | let _ = std::fs::remove_dir_all(&dir); |
| 1081 | } |
| 1082 | } |
| 1083 |