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