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