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