Onset: version control where nobody waits and nothing gets lost. The on command, its core and onset-server.
| 1 | //! onset-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 onset_core::bundle::{self, Frame, RAW, ZSTD}; |
| 19 | use onset_core::merge::{self, Mode}; |
| 20 | use onset_core::object::{Kind, Object, decode_chunks}; |
| 21 | use onset_core::tree::{self, EntryKind}; |
| 22 | use onset_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) -> onset_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 | // Its ID is the map's key: hashing the object again costs as much as making it. |
| 201 | bundle::write_frame(&mut out, &Frame { id, kind: o.kind, codec: RAW, raw_len: o.data.len() as u64, payload: o.data.clone() }); |
| 202 | insert(id, o); |
| 203 | } |
| 204 | bundle::write_end(&mut out); |
| 205 | set_result(out); |
| 206 | 0 |
| 207 | } |
| 208 |
| 209 | fn parse<T: for<'de> Deserialize<'de>>(ptr: *const u8, len: usize) -> Result<T, String> { |
| 210 | serde_json::from_slice(input(ptr, len)).map_err(|e| format!("bad request: {e}")) |
| 211 | } |
| 212 |
| 213 | fn id(text: &str) -> Result<Id, String> { |
| 214 | Id::parse(text).ok_or_else(|| format!("not an object id: {text}")) |
| 215 | } |
| 216 |
| 217 | /// Runs an operation; a missing object becomes `{"need": [id]}`. |
| 218 | fn run(op: impl FnOnce() -> Result<Value, Error>) -> i32 { |
| 219 | match op() { |
| 220 | Ok(v) => answer(v), |
| 221 | Err(Error::Missing(missing)) => answer(json!({ "need": [missing.hex()] })), |
| 222 | Err(e) => fail(e.to_string()), |
| 223 | } |
| 224 | } |
| 225 |
| 226 | #[derive(Deserialize)] |
| 227 | struct Roots { |
| 228 | roots: Vec<String>, |
| 229 | } |
| 230 |
| 231 | /// Trees (and chunk lists) under `roots` that the cache doesn't have yet, |
| 232 | /// nearest first: the Worker loads these before an operation that walks |
| 233 | /// whole trees. |
| 234 | #[unsafe(no_mangle)] |
| 235 | pub extern "C" fn need_trees(ptr: *const u8, len: usize) -> i32 { |
| 236 | let req: Roots = match parse(ptr, len) { |
| 237 | Ok(r) => r, |
| 238 | Err(e) => return fail(e), |
| 239 | }; |
| 240 | let mut need = Vec::new(); |
| 241 | let mut seen = HashSet::new(); |
| 242 | let mut queue: VecDeque<Id> = VecDeque::new(); |
| 243 | for r in &req.roots { |
| 244 | match id(r) { |
| 245 | Ok(i) => queue.push_back(i), |
| 246 | Err(e) => return fail(e), |
| 247 | } |
| 248 | } |
| 249 | while let Some(t) = queue.pop_front() { |
| 250 | if !seen.insert(t) { |
| 251 | continue; |
| 252 | } |
| 253 | match Cache.get(&t) { |
| 254 | Ok(Some(o)) if o.kind == Kind::Tree => { |
| 255 | if let Ok(entries) = tree::decode(&o.data) { |
| 256 | for e in entries { |
| 257 | if e.kind == EntryKind::Tree { |
| 258 | queue.push_back(e.id); |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | Ok(Some(_)) => {} |
| 264 | _ => need.push(t.hex()), |
| 265 | } |
| 266 | if need.len() >= 2000 { |
| 267 | break; |
| 268 | } |
| 269 | } |
| 270 | answer(json!({ "need": need })) |
| 271 | } |
| 272 |
| 273 | #[derive(Deserialize)] |
| 274 | struct MergeReq { |
| 275 | base: String, |
| 276 | ours: String, |
| 277 | theirs: String, |
| 278 | #[serde(default)] |
| 279 | labels: Vec<String>, |
| 280 | } |
| 281 |
| 282 | /// A landing's merge: `{"tree", "conflicts"}`. |
| 283 | #[unsafe(no_mangle)] |
| 284 | pub extern "C" fn merge(ptr: *const u8, len: usize) -> i32 { |
| 285 | let req: MergeReq = match parse(ptr, len) { |
| 286 | Ok(r) => r, |
| 287 | Err(e) => return fail(e), |
| 288 | }; |
| 289 | let (base, ours, theirs) = match (id(&req.base), id(&req.ours), id(&req.theirs)) { |
| 290 | (Ok(a), Ok(b), Ok(c)) => (a, b, c), |
| 291 | _ => return fail("bad ids".into()), |
| 292 | }; |
| 293 | let labels = (req.labels.first().cloned().unwrap_or_else(|| "main".into()), req.labels.get(1).cloned().unwrap_or_else(|| "change".into())); |
| 294 | run(|| { |
| 295 | let m = merge::trees(&Cache, Some(&base), &ours, &theirs, Mode::Land, (&labels.0, &labels.1))?; |
| 296 | if m.clean() { |
| 297 | NEW.with(|n| *n.borrow_mut() = m.objects); |
| 298 | } |
| 299 | Ok(json!({ "tree": m.tree.hex(), "conflicts": m.conflicts })) |
| 300 | }) |
| 301 | } |
| 302 |
| 303 | #[derive(Deserialize)] |
| 304 | struct FilterReq { |
| 305 | tree: String, |
| 306 | hidden: Vec<String>, |
| 307 | } |
| 308 |
| 309 | #[unsafe(no_mangle)] |
| 310 | pub extern "C" fn filter_tree(ptr: *const u8, len: usize) -> i32 { |
| 311 | let req: FilterReq = match parse(ptr, len) { |
| 312 | Ok(r) => r, |
| 313 | Err(e) => return fail(e), |
| 314 | }; |
| 315 | let t = match id(&req.tree) { |
| 316 | Ok(t) => t, |
| 317 | Err(e) => return fail(e), |
| 318 | }; |
| 319 | run(|| { |
| 320 | let (out, objects) = filter::filter(&Cache, &t, &req.hidden)?; |
| 321 | NEW.with(|n| { |
| 322 | let mut n = n.borrow_mut(); |
| 323 | for o in objects { |
| 324 | n.put(o); |
| 325 | } |
| 326 | }); |
| 327 | Ok(json!({ "tree": out.hex() })) |
| 328 | }) |
| 329 | } |
| 330 |
| 331 | #[derive(Deserialize)] |
| 332 | struct GraftReq { |
| 333 | visible: String, |
| 334 | full: String, |
| 335 | hidden: Vec<String>, |
| 336 | } |
| 337 |
| 338 | #[unsafe(no_mangle)] |
| 339 | pub extern "C" fn graft_tree(ptr: *const u8, len: usize) -> i32 { |
| 340 | let req: GraftReq = match parse(ptr, len) { |
| 341 | Ok(r) => r, |
| 342 | Err(e) => return fail(e), |
| 343 | }; |
| 344 | let (v, f) = match (id(&req.visible), id(&req.full)) { |
| 345 | (Ok(a), Ok(b)) => (a, b), |
| 346 | _ => return fail("bad ids".into()), |
| 347 | }; |
| 348 | run(|| match filter::graft(&Cache, &v, &f, &req.hidden)? { |
| 349 | Ok((out, objects)) => { |
| 350 | NEW.with(|n| { |
| 351 | let mut n = n.borrow_mut(); |
| 352 | for o in objects { |
| 353 | n.put(o); |
| 354 | } |
| 355 | }); |
| 356 | Ok(json!({ "tree": out.hex() })) |
| 357 | } |
| 358 | Err(path) => Ok(json!({ "refused": path })), |
| 359 | }) |
| 360 | } |
| 361 |
| 362 | #[derive(Deserialize)] |
| 363 | struct EditReq { |
| 364 | tree: String, |
| 365 | /// `[path, kind (1 file, 2 executable), content in base64]`. |
| 366 | #[serde(default)] |
| 367 | put: Vec<(String, u8, String)>, |
| 368 | #[serde(default)] |
| 369 | delete: Vec<String>, |
| 370 | } |
| 371 |
| 372 | /// A tree with files written and deleted: `{"tree"}`, or `{"bad_path"}`. |
| 373 | #[unsafe(no_mangle)] |
| 374 | pub extern "C" fn edit_tree(ptr: *const u8, len: usize) -> i32 { |
| 375 | use base64::Engine; |
| 376 | let req: EditReq = match parse(ptr, len) { |
| 377 | Ok(r) => r, |
| 378 | Err(e) => return fail(e), |
| 379 | }; |
| 380 | let t = match id(&req.tree) { |
| 381 | Ok(t) => t, |
| 382 | Err(e) => return fail(e), |
| 383 | }; |
| 384 | let mut put = Vec::with_capacity(req.put.len()); |
| 385 | for (path, kind, b64) in &req.put { |
| 386 | let Ok(content) = base64::engine::general_purpose::STANDARD.decode(b64) else { return fail(format!("{path}: content isn't base64")) }; |
| 387 | put.push(tree::Put { path: path.clone(), kind: if *kind == 2 { EntryKind::Exec } else { EntryKind::File }, content }); |
| 388 | } |
| 389 | run(|| match tree::edit(&Cache, &t, &put, &req.delete)? { |
| 390 | Ok((root, objects)) => { |
| 391 | NEW.with(|n| { |
| 392 | let mut n = n.borrow_mut(); |
| 393 | for o in objects { |
| 394 | n.put(o); |
| 395 | } |
| 396 | }); |
| 397 | Ok(json!({ "tree": root.hex() })) |
| 398 | } |
| 399 | Err(path) => Ok(json!({ "bad_path": path })), |
| 400 | }) |
| 401 | } |
| 402 |
| 403 | #[derive(Deserialize)] |
| 404 | struct ScanReq { |
| 405 | old: String, |
| 406 | new: String, |
| 407 | } |
| 408 |
| 409 | /// The first path `new` adds over `old` that no project may hold (Onset's or |
| 410 | /// git's own folder, a backslash): `{"bad": path | null}`. |
| 411 | #[unsafe(no_mangle)] |
| 412 | pub extern "C" fn unsafe_path(ptr: *const u8, len: usize) -> i32 { |
| 413 | let req: ScanReq = match parse(ptr, len) { |
| 414 | Ok(r) => r, |
| 415 | Err(e) => return fail(e), |
| 416 | }; |
| 417 | let (old, new) = match (id(&req.old), id(&req.new)) { |
| 418 | (Ok(a), Ok(b)) => (a, b), |
| 419 | _ => return fail("bad ids".into()), |
| 420 | }; |
| 421 | run(|| Ok(json!({ "bad": tree::unsafe_path(&Cache, &old, &new)? }))) |
| 422 | } |
| 423 |
| 424 | /// Secrets in lines `new` adds over `old`: `{"hits": [{path, line, kind}]}`. |
| 425 | #[unsafe(no_mangle)] |
| 426 | pub extern "C" fn secrets(ptr: *const u8, len: usize) -> i32 { |
| 427 | let req: ScanReq = match parse(ptr, len) { |
| 428 | Ok(r) => r, |
| 429 | Err(e) => return fail(e), |
| 430 | }; |
| 431 | let (old, new) = match (id(&req.old), id(&req.new)) { |
| 432 | (Ok(a), Ok(b)) => (a, b), |
| 433 | _ => return fail("bad ids".into()), |
| 434 | }; |
| 435 | run(|| Ok(json!({ "hits": onset_core::secrets::scan(&Cache, &old, &new)? }))) |
| 436 | } |
| 437 |
| 438 | #[derive(Deserialize)] |
| 439 | struct PathReq { |
| 440 | tree: String, |
| 441 | #[serde(default)] |
| 442 | path: String, |
| 443 | } |
| 444 |
| 445 | /// The entry at a path: `{"entry": {kind, id} | null}` (the root is a tree). |
| 446 | #[unsafe(no_mangle)] |
| 447 | pub extern "C" fn lookup(ptr: *const u8, len: usize) -> i32 { |
| 448 | let req: PathReq = match parse(ptr, len) { |
| 449 | Ok(r) => r, |
| 450 | Err(e) => return fail(e), |
| 451 | }; |
| 452 | let root = match id(&req.tree) { |
| 453 | Ok(t) => t, |
| 454 | Err(e) => return fail(e), |
| 455 | }; |
| 456 | run(|| { |
| 457 | let mut at = (EntryKind::Tree, root); |
| 458 | for part in req.path.split('/').filter(|p| !p.is_empty()) { |
| 459 | if at.0 != EntryKind::Tree { |
| 460 | return Ok(json!({ "entry": null })); |
| 461 | } |
| 462 | match tree::read(&Cache, &at.1)?.into_iter().find(|e| e.name == part) { |
| 463 | Some(e) => at = (e.kind, e.id), |
| 464 | None => return Ok(json!({ "entry": null })), |
| 465 | } |
| 466 | } |
| 467 | Ok(json!({ "entry": { "kind": at.0.name(), "id": at.1.hex() } })) |
| 468 | }) |
| 469 | } |
| 470 |
| 471 | #[derive(Deserialize)] |
| 472 | struct RenamedFromReq { |
| 473 | old: String, |
| 474 | new: String, |
| 475 | path: String, |
| 476 | } |
| 477 |
| 478 | /// Where `path` in tree `new` moved from in tree `old`: `{"from": path or null}`. |
| 479 | #[unsafe(no_mangle)] |
| 480 | pub extern "C" fn renamed_from(ptr: *const u8, len: usize) -> i32 { |
| 481 | let req: RenamedFromReq = match parse(ptr, len) { |
| 482 | Ok(r) => r, |
| 483 | Err(e) => return fail(e), |
| 484 | }; |
| 485 | let (old, new) = match (id(&req.old), id(&req.new)) { |
| 486 | (Ok(o), Ok(n)) => (o, n), |
| 487 | (Err(e), _) | (_, Err(e)) => return fail(e), |
| 488 | }; |
| 489 | run(|| Ok(json!({ "from": onset_core::rename::renamed_from(&Cache, &old, &new, &req.path)? }))) |
| 490 | } |
| 491 |
| 492 | #[derive(Deserialize)] |
| 493 | struct PurgeReq { |
| 494 | trees: Vec<String>, |
| 495 | paths: Vec<String>, |
| 496 | } |
| 497 |
| 498 | /// Trees without `paths` (on purge): `{"map": {old: new}, "gone": [ids |
| 499 | /// that were at them]}` for trees that had any, or `{"need": [ids]}`: every |
| 500 | /// folder on the way that the cache doesn't have yet, for all of them at once. |
| 501 | #[unsafe(no_mangle)] |
| 502 | pub extern "C" fn purge_trees(ptr: *const u8, len: usize) -> i32 { |
| 503 | use std::collections::BTreeSet; |
| 504 | use onset_core::purge; |
| 505 | let req: PurgeReq = match parse(ptr, len) { |
| 506 | Ok(r) => r, |
| 507 | Err(e) => return fail(e), |
| 508 | }; |
| 509 | let mut trees = Vec::with_capacity(req.trees.len()); |
| 510 | for t in &req.trees { |
| 511 | match id(t) { |
| 512 | Ok(t) => trees.push(t), |
| 513 | Err(e) => return fail(e), |
| 514 | } |
| 515 | } |
| 516 | let mut need = BTreeSet::new(); |
| 517 | for t in &trees { |
| 518 | if let Err(e) = purge::needs(&Cache, t, &req.paths, &mut need) { |
| 519 | return fail(e.to_string()); |
| 520 | } |
| 521 | if need.len() >= 2000 { |
| 522 | break; |
| 523 | } |
| 524 | } |
| 525 | if !need.is_empty() { |
| 526 | return answer(json!({ "need": need.iter().map(|i| i.hex()).collect::<Vec<_>>() })); |
| 527 | } |
| 528 | run(|| { |
| 529 | let mut gone = BTreeSet::new(); |
| 530 | let mut map = serde_json::Map::new(); |
| 531 | for t in &trees { |
| 532 | let (after, objects) = purge::without(&Cache, t, &req.paths, &mut gone)?; |
| 533 | if after != *t { |
| 534 | NEW.with(|n| { |
| 535 | let mut n = n.borrow_mut(); |
| 536 | for o in objects { |
| 537 | n.put(o); |
| 538 | } |
| 539 | }); |
| 540 | map.insert(t.hex(), Value::String(after.hex())); |
| 541 | } |
| 542 | } |
| 543 | Ok(json!({ "map": map, "gone": gone.iter().map(|i| i.hex()).collect::<Vec<_>>() })) |
| 544 | }) |
| 545 | } |
| 546 |
| 547 | #[derive(Deserialize)] |
| 548 | struct LiveReq { |
| 549 | trees: Vec<String>, |
| 550 | gone: Vec<String>, |
| 551 | } |
| 552 |
| 553 | /// One level of a walk over what's kept (after on purge): the folders in |
| 554 | /// `trees` (loaded first) and which of `gone` they hold: |
| 555 | /// `{"trees": [ids], "hits": [ids]}`, or `{"need": [ids]}`. |
| 556 | #[unsafe(no_mangle)] |
| 557 | pub extern "C" fn live_level(ptr: *const u8, len: usize) -> i32 { |
| 558 | let req: LiveReq = match parse(ptr, len) { |
| 559 | Ok(r) => r, |
| 560 | Err(e) => return fail(e), |
| 561 | }; |
| 562 | let gone: HashSet<&str> = req.gone.iter().map(String::as_str).collect(); |
| 563 | let (mut next, mut hits, mut need) = (Vec::new(), HashSet::new(), Vec::new()); |
| 564 | for t in &req.trees { |
| 565 | let t = match id(t) { |
| 566 | Ok(t) => t, |
| 567 | Err(e) => return fail(e), |
| 568 | }; |
| 569 | match Cache.get(&t) { |
| 570 | Ok(Some(o)) if o.kind == Kind::Tree => { |
| 571 | let Ok(entries) = tree::decode(&o.data) else { return fail(format!("damaged tree {}", t.short())) }; |
| 572 | for e in entries { |
| 573 | let hex = e.id.hex(); |
| 574 | if gone.contains(hex.as_str()) { |
| 575 | hits.insert(hex.clone()); |
| 576 | } |
| 577 | if e.kind == EntryKind::Tree { |
| 578 | next.push(hex); |
| 579 | } |
| 580 | } |
| 581 | } |
| 582 | Ok(Some(_)) => {} |
| 583 | _ => need.push(t.hex()), |
| 584 | } |
| 585 | } |
| 586 | if !need.is_empty() { |
| 587 | return answer(json!({ "need": need })); |
| 588 | } |
| 589 | answer(json!({ "trees": next, "hits": hits.into_iter().collect::<Vec<_>>() })) |
| 590 | } |
| 591 |
| 592 | #[derive(Deserialize)] |
| 593 | struct HistoryReq { |
| 594 | /// Versions of main, newest first: [n, tree]. |
| 595 | versions: Vec<(u64, String)>, |
| 596 | path: String, |
| 597 | /// The oldest of `versions` is version 1. |
| 598 | from_start: bool, |
| 599 | } |
| 600 |
| 601 | /// The versions that changed a path, newest first: |
| 602 | /// `{"changes": [[n, "added" | "modified" | "removed", id | null]]}`, or |
| 603 | /// `{"need": [ids]}`: every folder one level needs. |
| 604 | #[unsafe(no_mangle)] |
| 605 | pub extern "C" fn path_history(ptr: *const u8, len: usize) -> i32 { |
| 606 | use onset_core::history::{self, Found, Kind as Change}; |
| 607 | let req: HistoryReq = match parse(ptr, len) { |
| 608 | Ok(r) => r, |
| 609 | Err(e) => return fail(e), |
| 610 | }; |
| 611 | let mut ns = Vec::with_capacity(req.versions.len()); |
| 612 | let mut trees = Vec::with_capacity(req.versions.len()); |
| 613 | for (n, t) in &req.versions { |
| 614 | match id(t) { |
| 615 | Ok(t) => { |
| 616 | ns.push(*n); |
| 617 | trees.push(t); |
| 618 | } |
| 619 | Err(e) => return fail(e), |
| 620 | } |
| 621 | } |
| 622 | run(|| { |
| 623 | Ok(match history::entries(&Cache, &trees, &req.path)? { |
| 624 | Found::Need(need) => json!({ "need": need.iter().map(|i| i.hex()).collect::<Vec<_>>() }), |
| 625 | Found::All(found) => { |
| 626 | let changes: Vec<Value> = history::changes(&ns, &found, req.from_start) |
| 627 | .into_iter() |
| 628 | .map(|(n, kind, after)| { |
| 629 | let kind = match kind { |
| 630 | Change::Added => "added", |
| 631 | Change::Modified => "modified", |
| 632 | Change::Removed => "removed", |
| 633 | }; |
| 634 | json!([n, kind, after.map(|e| e.id.hex())]) |
| 635 | }) |
| 636 | .collect(); |
| 637 | json!({ "changes": changes }) |
| 638 | } |
| 639 | }) |
| 640 | }) |
| 641 | } |
| 642 |
| 643 | #[derive(Deserialize)] |
| 644 | struct TouchedReq { |
| 645 | /// [before (null: nothing), after] trees. |
| 646 | pairs: Vec<(Option<String>, String)>, |
| 647 | most: usize, |
| 648 | } |
| 649 |
| 650 | /// The paths each pair of trees changes (folders added or removed whole as |
| 651 | /// the folder): `{"touched": [[paths] | null]}` (null: more than `most`), or |
| 652 | /// `{"need": [ids]}`. |
| 653 | #[unsafe(no_mangle)] |
| 654 | pub extern "C" fn touched(ptr: *const u8, len: usize) -> i32 { |
| 655 | use onset_core::history::{self, Touched}; |
| 656 | let req: TouchedReq = match parse(ptr, len) { |
| 657 | Ok(r) => r, |
| 658 | Err(e) => return fail(e), |
| 659 | }; |
| 660 | let mut pairs = Vec::with_capacity(req.pairs.len()); |
| 661 | for (a, b) in &req.pairs { |
| 662 | let a = match a.as_deref().map(id).transpose() { |
| 663 | Ok(a) => a, |
| 664 | Err(e) => return fail(e), |
| 665 | }; |
| 666 | match id(b) { |
| 667 | Ok(b) => pairs.push((a, b)), |
| 668 | Err(e) => return fail(e), |
| 669 | } |
| 670 | } |
| 671 | run(|| { |
| 672 | Ok(match history::touched(&Cache, &pairs, req.most)? { |
| 673 | Touched::Need(need) => json!({ "need": need.iter().map(|i| i.hex()).collect::<Vec<_>>() }), |
| 674 | Touched::All(found) => json!({ "touched": found }), |
| 675 | }) |
| 676 | }) |
| 677 | } |
| 678 |
| 679 | #[derive(Deserialize)] |
| 680 | struct BlameReq { |
| 681 | /// The versions that changed the file, newest first: [n, file id or null]. |
| 682 | points: Vec<(u64, Option<String>)>, |
| 683 | } |
| 684 |
| 685 | /// Which version last changed each line of the newest content: |
| 686 | /// `{"owners": [[n, lines]...], "base64": content}` (runs of lines), or |
| 687 | /// `{"need": [ids]}`. |
| 688 | #[unsafe(no_mangle)] |
| 689 | pub extern "C" fn blame(ptr: *const u8, len: usize) -> i32 { |
| 690 | use base64::Engine; |
| 691 | let req: BlameReq = match parse(ptr, len) { |
| 692 | Ok(r) => r, |
| 693 | Err(e) => return fail(e), |
| 694 | }; |
| 695 | let mut ids = Vec::with_capacity(req.points.len()); |
| 696 | for (_, f) in &req.points { |
| 697 | match f.as_deref().map(id) { |
| 698 | Some(Ok(i)) => ids.push(Some(i)), |
| 699 | Some(Err(e)) => return fail(e), |
| 700 | None => ids.push(None), |
| 701 | } |
| 702 | } |
| 703 | run(|| { |
| 704 | // Every file, then every big file's parts, asked for at once. |
| 705 | let mut need: Vec<String> = ids.iter().flatten().filter(|i| Cache.get(i).ok().flatten().is_none()).map(|i| i.hex()).collect(); |
| 706 | if need.is_empty() { |
| 707 | for i in ids.iter().flatten() { |
| 708 | if let Some(o) = Cache.get(i)? |
| 709 | && o.kind == Kind::Chunks |
| 710 | { |
| 711 | need.extend(decode_chunks(&o.data)?.into_iter().filter(|(c, _)| Cache.get(c).ok().flatten().is_none()).map(|(c, _)| c.hex())); |
| 712 | } |
| 713 | } |
| 714 | } |
| 715 | if !need.is_empty() { |
| 716 | need.sort(); |
| 717 | need.dedup(); |
| 718 | return Ok(json!({ "need": need })); |
| 719 | } |
| 720 | let mut contents = Vec::with_capacity(ids.len()); |
| 721 | for i in &ids { |
| 722 | contents.push(match i { |
| 723 | Some(i) => onset_core::chunk::read_file(&Cache, i)?, |
| 724 | None => Vec::new(), |
| 725 | }); |
| 726 | } |
| 727 | let points: Vec<(u64, &[u8])> = req.points.iter().zip(&contents).map(|((n, _), c)| (*n, c.as_slice())).collect(); |
| 728 | let mut runs: Vec<(u64, u32)> = Vec::new(); |
| 729 | for n in onset_core::history::blame(&points) { |
| 730 | match runs.last_mut() { |
| 731 | Some((last, count)) if *last == n => *count += 1, |
| 732 | _ => runs.push((n, 1)), |
| 733 | } |
| 734 | } |
| 735 | let newest = contents.first().map(|c| base64::engine::general_purpose::STANDARD.encode(c)).unwrap_or_default(); |
| 736 | Ok(json!({ "owners": runs, "base64": newest })) |
| 737 | }) |
| 738 | } |
| 739 |
| 740 | /// A folder's entries: `{"entries": [[name, kind]]}`. |
| 741 | #[unsafe(no_mangle)] |
| 742 | pub extern "C" fn list_dir(ptr: *const u8, len: usize) -> i32 { |
| 743 | let req: PathReq = match parse(ptr, len) { |
| 744 | Ok(r) => r, |
| 745 | Err(e) => return fail(e), |
| 746 | }; |
| 747 | let t = match id(&req.tree) { |
| 748 | Ok(t) => t, |
| 749 | Err(e) => return fail(e), |
| 750 | }; |
| 751 | run(|| Ok(json!({ "entries": tree::read(&Cache, &t)?.iter().map(|e| json!([e.name, e.kind.name()])).collect::<Vec<_>>() }))) |
| 752 | } |
| 753 |
| 754 | #[derive(Deserialize)] |
| 755 | struct ReadReq { |
| 756 | id: String, |
| 757 | #[serde(default)] |
| 758 | max: Option<usize>, |
| 759 | } |
| 760 |
| 761 | /// A file's content: `{"base64", "size"}`, or `{"too_big": size}` over `max` bytes. |
| 762 | #[unsafe(no_mangle)] |
| 763 | pub extern "C" fn read_file(ptr: *const u8, len: usize) -> i32 { |
| 764 | use base64::Engine; |
| 765 | let req: ReadReq = match parse(ptr, len) { |
| 766 | Ok(r) => r, |
| 767 | Err(e) => return fail(e), |
| 768 | }; |
| 769 | let f = match id(&req.id) { |
| 770 | Ok(t) => t, |
| 771 | Err(e) => return fail(e), |
| 772 | }; |
| 773 | run(|| { |
| 774 | let size = onset_core::chunk::file_size(&Cache, &f)?; |
| 775 | if req.max.is_some_and(|m| size as usize > m) { |
| 776 | return Ok(json!({ "too_big": size })); |
| 777 | } |
| 778 | let bytes = onset_core::chunk::read_file(&Cache, &f)?; |
| 779 | Ok(json!({ "base64": base64::engine::general_purpose::STANDARD.encode(&bytes), "size": bytes.len() })) |
| 780 | }) |
| 781 | } |
| 782 |
| 783 | /// The first hidden path a tree holds: `{"found": path | null}`. |
| 784 | #[unsafe(no_mangle)] |
| 785 | pub extern "C" fn hidden_in(ptr: *const u8, len: usize) -> i32 { |
| 786 | let req: FilterReq = match parse(ptr, len) { |
| 787 | Ok(r) => r, |
| 788 | Err(e) => return fail(e), |
| 789 | }; |
| 790 | let t = match id(&req.tree) { |
| 791 | Ok(t) => t, |
| 792 | Err(e) => return fail(e), |
| 793 | }; |
| 794 | run(|| Ok(json!({ "found": filter::holds_hidden(&Cache, &t, &req.hidden)? }))) |
| 795 | } |
| 796 |
| 797 | #[derive(Deserialize)] |
| 798 | struct SinceReq { |
| 799 | tree: String, |
| 800 | #[serde(default)] |
| 801 | have: Option<String>, |
| 802 | } |
| 803 |
| 804 | /// Every object under `tree` that `have` doesn't share, chunks included. |
| 805 | #[unsafe(no_mangle)] |
| 806 | pub extern "C" fn new_since(ptr: *const u8, len: usize) -> i32 { |
| 807 | let req: SinceReq = match parse(ptr, len) { |
| 808 | Ok(r) => r, |
| 809 | Err(e) => return fail(e), |
| 810 | }; |
| 811 | let t = match id(&req.tree) { |
| 812 | Ok(t) => t, |
| 813 | Err(e) => return fail(e), |
| 814 | }; |
| 815 | let have = match req.have.as_deref().map(id) { |
| 816 | Some(Ok(h)) => Some(h), |
| 817 | Some(Err(e)) => return fail(e), |
| 818 | None => None, |
| 819 | }; |
| 820 | run(|| { |
| 821 | let mut ids = Vec::new(); |
| 822 | tree::new_since(&Cache, have.as_ref(), &t, &mut ids)?; |
| 823 | let mut out = Vec::with_capacity(ids.len()); |
| 824 | let mut need = Vec::new(); |
| 825 | for i in ids { |
| 826 | out.push(i.hex()); |
| 827 | // Chunk lists name chunks; the Worker knows a file's kind from |
| 828 | // its index, so it asks for those lists separately. |
| 829 | if let Some(o) = Cache.get(&i)? |
| 830 | && o.kind == Kind::Chunks |
| 831 | { |
| 832 | for (c, _) in decode_chunks(&o.data)? { |
| 833 | out.push(c.hex()); |
| 834 | } |
| 835 | } else if Cache.get(&i)?.is_none() { |
| 836 | need.push(i.hex()); |
| 837 | } |
| 838 | } |
| 839 | Ok(json!({ "ids": out, "files_not_loaded": need })) |
| 840 | }) |
| 841 | } |
| 842 |
| 843 | #[derive(Deserialize)] |
| 844 | struct FlattenReq { |
| 845 | tree: String, |
| 846 | } |
| 847 |
| 848 | /// Every file under a tree: `[[path, kind, id]]`. |
| 849 | #[unsafe(no_mangle)] |
| 850 | pub extern "C" fn flatten(ptr: *const u8, len: usize) -> i32 { |
| 851 | let req: FlattenReq = match parse(ptr, len) { |
| 852 | Ok(r) => r, |
| 853 | Err(e) => return fail(e), |
| 854 | }; |
| 855 | let t = match id(&req.tree) { |
| 856 | Ok(t) => t, |
| 857 | Err(e) => return fail(e), |
| 858 | }; |
| 859 | run(|| { |
| 860 | let files = tree::flatten(&Cache, &t)?; |
| 861 | Ok(json!({ "files": files.iter().map(|(p, e)| json!([p, e.kind as u8, e.id.hex()])).collect::<Vec<_>>() })) |
| 862 | }) |
| 863 | } |
| 864 |
| 865 | // The git view: versions written as git objects, streamed as one pack. |
| 866 | // |
| 867 | // The Worker plans a version (`git_plan`) and looks up git IDs it already |
| 868 | // knows. It starts a pack (`pack_begin`), hashes each new file (`blob_begin` |
| 869 | // with write 0, `blob_feed` one stored frame at a time, `blob_end`), writes |
| 870 | // the trees and the commit (`git_trees`), which names the commit it pushes, |
| 871 | // then writes each new file into the pack (`blob_begin` with write 1) and |
| 872 | // closes it (`pack_end`). Pack bytes collect in a buffer the Worker drains |
| 873 | // with `pack_take`. |
| 874 |
| 875 | struct GitPack { |
| 876 | sha: Sha1, |
| 877 | out: Vec<u8>, |
| 878 | blob: Option<GitBlob>, |
| 879 | /// Native ID → git ID of everything this pack's trees name: the Worker |
| 880 | /// sends each once per pack, not with every version. |
| 881 | known: HashMap<Id, [u8; 20]>, |
| 882 | /// With deltas on: each folder's tree as last written to this pack (git |
| 883 | /// ID, bytes, and how many deltas deep it is), so the next version's |
| 884 | /// tree there can be a delta on it. |
| 885 | bases: Option<HashMap<String, ([u8; 20], Vec<u8>, u8)>>, |
| 886 | } |
| 887 |
| 888 | /// Deltas made on deltas go this deep at most (git's own default is 50). |
| 889 | const MAX_DELTA_DEPTH: u8 = 50; |
| 890 | /// Trees smaller than this are written whole. |
| 891 | const DELTA_MIN: usize = 1024; |
| 892 |
| 893 | struct GitBlob { |
| 894 | sha: Sha1, |
| 895 | /// False: only hashing (the git ID is needed before the pack is sent). |
| 896 | write: bool, |
| 897 | size: u64, |
| 898 | fed: u64, |
| 899 | } |
| 900 |
| 901 | thread_local! { |
| 902 | static PACK: RefCell<Option<GitPack>> = const { RefCell::new(None) }; |
| 903 | /// One zlib stream, reused for every object: making one costs more |
| 904 | /// than deflating a small object. |
| 905 | static ZLIB: RefCell<flate2::Compress> = RefCell::new(flate2::Compress::new(flate2::Compression::fast(), true)); |
| 906 | } |
| 907 |
| 908 | /// Deflates `data` onto the zlib stream (started with `zlib_start`); `end` |
| 909 | /// finishes the stream. |
| 910 | fn deflate(data: &[u8], end: bool) -> Vec<u8> { |
| 911 | ZLIB.with(|z| { |
| 912 | let mut z = z.borrow_mut(); |
| 913 | let flush = if end { flate2::FlushCompress::Finish } else { flate2::FlushCompress::None }; |
| 914 | let start = z.total_in(); |
| 915 | let mut out = Vec::with_capacity(data.len() / 2 + 64); |
| 916 | loop { |
| 917 | let used = (z.total_in() - start) as usize; |
| 918 | let status = z.compress_vec(&data[used..], &mut out, flush).expect("zlib"); |
| 919 | let used = (z.total_in() - start) as usize; |
| 920 | if (end && status == flate2::Status::StreamEnd) || (!end && used == data.len() && out.len() < out.capacity()) { |
| 921 | return out; |
| 922 | } |
| 923 | out.reserve(out.capacity().max(64)); |
| 924 | } |
| 925 | }) |
| 926 | } |
| 927 |
| 928 | fn zlib_start() { |
| 929 | ZLIB.with(|z| z.borrow_mut().reset()); |
| 930 | } |
| 931 |
| 932 | fn emit(pack: &mut GitPack, bytes: &[u8]) { |
| 933 | pack.sha.update(bytes); |
| 934 | pack.out.extend_from_slice(bytes); |
| 935 | } |
| 936 |
| 937 | /// A pack entry's header: type and size. |
| 938 | fn entry_header(kind: u8, size: u64) -> Vec<u8> { |
| 939 | let mut out = Vec::with_capacity(10); |
| 940 | let mut byte = (kind << 4) | (size & 0x0f) as u8; |
| 941 | let mut rest = size >> 4; |
| 942 | while rest > 0 { |
| 943 | out.push(byte | 0x80); |
| 944 | byte = (rest & 0x7f) as u8; |
| 945 | rest >>= 7; |
| 946 | } |
| 947 | out.push(byte); |
| 948 | out |
| 949 | } |
| 950 |
| 951 | fn hex(bytes: &[u8]) -> String { |
| 952 | bytes.iter().map(|b| format!("{b:02x}")).collect() |
| 953 | } |
| 954 |
| 955 | fn git_header(kind: &str, size: u64) -> Vec<u8> { |
| 956 | format!("{kind} {size}\0").into_bytes() |
| 957 | } |
| 958 |
| 959 | /// Adds a whole object (trees, commits) to the pack; answers its git ID. |
| 960 | fn emit_object(pack: &mut GitPack, kind: &str, type_code: u8, data: &[u8]) -> String { |
| 961 | hex(&emit_raw(pack, kind, type_code, data)) |
| 962 | } |
| 963 |
| 964 | fn git_id(kind: &str, data: &[u8]) -> [u8; 20] { |
| 965 | let mut h = Sha1::new(); |
| 966 | h.update(git_header(kind, data.len() as u64)); |
| 967 | h.update(data); |
| 968 | h.finalize().into() |
| 969 | } |
| 970 |
| 971 | fn emit_raw(pack: &mut GitPack, kind: &str, type_code: u8, data: &[u8]) -> [u8; 20] { |
| 972 | let id = git_id(kind, data); |
| 973 | zlib_start(); |
| 974 | let deflated = deflate(data, true); |
| 975 | emit(pack, &entry_header(type_code, data.len() as u64)); |
| 976 | emit(pack, &deflated); |
| 977 | id |
| 978 | } |
| 979 |
| 980 | /// Adds the tree for folder `path` to the pack: as a delta on the folder's |
| 981 | /// tree written earlier in this pack when deltas are on and that's much |
| 982 | /// smaller (a version usually changes one entry of a big folder), else whole. |
| 983 | fn emit_tree(pack: &mut GitPack, path: &str, data: Vec<u8>) -> [u8; 20] { |
| 984 | let Some(bases) = pack.bases.as_mut() else { return emit_raw(pack, "tree", 2, &data) }; |
| 985 | if data.len() < DELTA_MIN { |
| 986 | return emit_raw_tree(pack, path, data, 0); |
| 987 | } |
| 988 | let made = bases.get(path).filter(|(_, _, depth)| *depth < MAX_DELTA_DEPTH).and_then(|(base_id, base, depth)| { |
| 989 | onset_core::git::make_delta(base, &data).map(|delta| (*base_id, delta, depth + 1)) |
| 990 | }); |
| 991 | let Some((base_id, delta, depth)) = made else { return emit_raw_tree(pack, path, data, 0) }; |
| 992 | let id = git_id("tree", &data); |
| 993 | zlib_start(); |
| 994 | let deflated = deflate(&delta, true); |
| 995 | // REF_DELTA (7): the base's git ID, then the deflated delta. |
| 996 | emit(pack, &entry_header(7, delta.len() as u64)); |
| 997 | emit(pack, &base_id); |
| 998 | emit(pack, &deflated); |
| 999 | pack.bases.as_mut().unwrap().insert(path.to_string(), (id, data, depth)); |
| 1000 | id |
| 1001 | } |
| 1002 |
| 1003 | fn emit_raw_tree(pack: &mut GitPack, path: &str, data: Vec<u8>, depth: u8) -> [u8; 20] { |
| 1004 | let id = emit_raw(pack, "tree", 2, &data); |
| 1005 | if data.len() >= DELTA_MIN { |
| 1006 | pack.bases.as_mut().unwrap().insert(path.to_string(), (id, data, depth)); |
| 1007 | } |
| 1008 | id |
| 1009 | } |
| 1010 |
| 1011 | fn with_pack(f: impl FnOnce(&mut GitPack) -> Result<Value, String>) -> i32 { |
| 1012 | let result = PACK.with(|p| match p.borrow_mut().as_mut() { |
| 1013 | Some(pack) => f(pack), |
| 1014 | None => Err("no pack started".into()), |
| 1015 | }); |
| 1016 | match result { |
| 1017 | Ok(v) => answer(v), |
| 1018 | Err(e) => fail(e), |
| 1019 | } |
| 1020 | } |
| 1021 |
| 1022 | /// Starts a pack of `count` objects; with `deltas`, a folder's tree can be |
| 1023 | /// written as a delta on its tree written earlier in the same pack. |
| 1024 | #[unsafe(no_mangle)] |
| 1025 | pub extern "C" fn pack_begin(count: u32, deltas: u32) -> i32 { |
| 1026 | let mut pack = GitPack { sha: Sha1::new(), out: Vec::new(), blob: None, known: HashMap::new(), bases: (deltas != 0).then(HashMap::new) }; |
| 1027 | let mut head = b"PACK".to_vec(); |
| 1028 | head.extend_from_slice(&2u32.to_be_bytes()); |
| 1029 | head.extend_from_slice(&count.to_be_bytes()); |
| 1030 | emit(&mut pack, &head); |
| 1031 | PACK.with(|p| *p.borrow_mut() = Some(pack)); |
| 1032 | answer(json!({})) |
| 1033 | } |
| 1034 |
| 1035 | /// Pack bytes made so far (and forgets them). |
| 1036 | #[unsafe(no_mangle)] |
| 1037 | pub extern "C" fn pack_take() -> i32 { |
| 1038 | let bytes = PACK.with(|p| p.borrow_mut().as_mut().map(|pack| std::mem::take(&mut pack.out)).unwrap_or_default()); |
| 1039 | set_result(bytes); |
| 1040 | 0 |
| 1041 | } |
| 1042 |
| 1043 | /// Ends the pack: the last bytes, with the checksum. |
| 1044 | #[unsafe(no_mangle)] |
| 1045 | pub extern "C" fn pack_end() -> i32 { |
| 1046 | let Some(mut pack) = PACK.with(|p| p.borrow_mut().take()) else { return fail("no pack started".into()) }; |
| 1047 | if pack.blob.is_some() { |
| 1048 | return fail("a file is still open".into()); |
| 1049 | } |
| 1050 | let sum = pack.sha.finalize(); |
| 1051 | pack.out.extend_from_slice(&sum); |
| 1052 | set_result(pack.out); |
| 1053 | 0 |
| 1054 | } |
| 1055 |
| 1056 | /// Starts a file of `size` bytes (a JS number: files under 2^53 bytes). |
| 1057 | /// With `write` 0 the file is only hashed; with 1 it goes into the pack. |
| 1058 | #[unsafe(no_mangle)] |
| 1059 | pub extern "C" fn blob_begin(size: f64, write: u32) -> i32 { |
| 1060 | let size = size as u64; |
| 1061 | with_pack(|pack| { |
| 1062 | if pack.blob.is_some() { |
| 1063 | return Err("a file is already open".into()); |
| 1064 | } |
| 1065 | let mut sha = Sha1::new(); |
| 1066 | sha.update(git_header("blob", size)); |
| 1067 | if write != 0 { |
| 1068 | emit(pack, &entry_header(3, size)); |
| 1069 | zlib_start(); |
| 1070 | } |
| 1071 | pack.blob = Some(GitBlob { sha, write: write != 0, size, fed: 0 }); |
| 1072 | Ok(json!({})) |
| 1073 | }) |
| 1074 | } |
| 1075 |
| 1076 | /// One stored frame of the open file: the whole blob, or its next chunk. |
| 1077 | #[unsafe(no_mangle)] |
| 1078 | pub extern "C" fn blob_feed(ptr: *const u8, len: usize) -> i32 { |
| 1079 | let frame = match one_frame(input(ptr, len)) { |
| 1080 | Ok(f) => f, |
| 1081 | Err(e) => return fail(e), |
| 1082 | }; |
| 1083 | with_pack(|pack| { |
| 1084 | let data = decode(&frame)?; |
| 1085 | bundle::verify(&frame, &data).map_err(|e| e.to_string())?; |
| 1086 | let blob = pack.blob.as_mut().ok_or("no file open")?; |
| 1087 | blob.sha.update(&data); |
| 1088 | blob.fed += data.len() as u64; |
| 1089 | if blob.write { |
| 1090 | let out = deflate(&data, false); |
| 1091 | emit(pack, &out); |
| 1092 | } |
| 1093 | Ok(json!({})) |
| 1094 | }) |
| 1095 | } |
| 1096 |
| 1097 | #[unsafe(no_mangle)] |
| 1098 | pub extern "C" fn blob_end() -> i32 { |
| 1099 | with_pack(|pack| { |
| 1100 | let blob = pack.blob.take().ok_or("no file open")?; |
| 1101 | if blob.fed != blob.size { |
| 1102 | return Err(format!("file was {} bytes, expected {}", blob.fed, blob.size)); |
| 1103 | } |
| 1104 | if blob.write { |
| 1105 | let rest = deflate(&[], true); |
| 1106 | emit(pack, &rest); |
| 1107 | } |
| 1108 | Ok(json!({ "git": hex(&blob.sha.finalize()) })) |
| 1109 | }) |
| 1110 | } |
| 1111 |
| 1112 | /// One frame as stored in a pack (no bundle header). |
| 1113 | fn one_frame(bytes: &[u8]) -> Result<Frame, String> { |
| 1114 | let mut b = Vec::with_capacity(bundle::MAGIC.len() + bytes.len() + 32); |
| 1115 | bundle::write_header(&mut b); |
| 1116 | b.extend_from_slice(bytes); |
| 1117 | bundle::write_end(&mut b); |
| 1118 | let mut frames = bundle::read(&b).map_err(|e| e.to_string())?; |
| 1119 | if frames.len() != 1 { |
| 1120 | return Err("expected one object".into()); |
| 1121 | } |
| 1122 | Ok(frames.remove(0)) |
| 1123 | } |
| 1124 |
| 1125 | /// A big file's chunk list (one stored frame): `{"chunks": [[id, size]], "size"}`. |
| 1126 | #[unsafe(no_mangle)] |
| 1127 | pub extern "C" fn chunk_list(ptr: *const u8, len: usize) -> i32 { |
| 1128 | let result = (|| { |
| 1129 | let frame = one_frame(input(ptr, len))?; |
| 1130 | let data = decode(&frame)?; |
| 1131 | bundle::verify(&frame, &data).map_err(|e| e.to_string())?; |
| 1132 | if frame.kind != Kind::Chunks { |
| 1133 | return Err("not a chunk list".to_string()); |
| 1134 | } |
| 1135 | let chunks = decode_chunks(&data).map_err(|e| e.to_string())?; |
| 1136 | let size: u64 = chunks.iter().map(|(_, n)| n).sum(); |
| 1137 | Ok(json!({ "chunks": chunks.iter().map(|(c, n)| json!([c.hex(), n])).collect::<Vec<_>>(), "size": size })) |
| 1138 | })(); |
| 1139 | match result { |
| 1140 | Ok(v) => answer(v), |
| 1141 | Err(e) => fail(e), |
| 1142 | } |
| 1143 | } |
| 1144 |
| 1145 | #[derive(Deserialize)] |
| 1146 | struct PlanReq { |
| 1147 | tree: String, |
| 1148 | #[serde(default)] |
| 1149 | have: Option<String>, |
| 1150 | /// IDs whose git form isn't known: treated as new. |
| 1151 | #[serde(default)] |
| 1152 | force: Vec<String>, |
| 1153 | /// The first version of a pack: entries looked up for earlier ones |
| 1154 | /// aren't answered again until the next pack starts. |
| 1155 | #[serde(default)] |
| 1156 | start: bool, |
| 1157 | } |
| 1158 |
| 1159 | thread_local! { |
| 1160 | /// Entries `git_plan` answered for lookup since the pack's first version. |
| 1161 | static LOOKED: RefCell<HashSet<Id>> = RefCell::new(HashSet::new()); |
| 1162 | } |
| 1163 |
| 1164 | #[derive(Default)] |
| 1165 | struct Plan { |
| 1166 | trees: Vec<Id>, |
| 1167 | files: Vec<Id>, |
| 1168 | lookup: Vec<Id>, |
| 1169 | seen: HashSet<Id>, |
| 1170 | looked: HashSet<Id>, |
| 1171 | } |
| 1172 |
| 1173 | fn plan_tree(t: &Id, have: Option<&Id>, force: &HashSet<Id>, plan: &mut Plan) -> Result<(), Error> { |
| 1174 | if !plan.seen.insert(*t) { |
| 1175 | return Ok(()); |
| 1176 | } |
| 1177 | plan.trees.push(*t); |
| 1178 | // Both folders' entries are sorted by name (as encode writes them): |
| 1179 | // walked side by side, without copying names. |
| 1180 | let tree_of = |id: &Id| -> Result<Object, Error> { |
| 1181 | let o = Cache.must(id)?; |
| 1182 | if o.kind != Kind::Tree { |
| 1183 | return Err(Error::Corrupt(format!("{} isn't a tree", id.short()))); |
| 1184 | } |
| 1185 | Ok(o) |
| 1186 | }; |
| 1187 | let new = tree_of(t)?; |
| 1188 | let old = have.map(tree_of).transpose()?; |
| 1189 | if let (Some(entries), Some(before)) = (tree::raw_entries(&new.data)?, tree::raw_entries(old.as_ref().map_or(&[][..], |o| &o.data))?) { |
| 1190 | let mut at = 0; |
| 1191 | for e in &entries { |
| 1192 | while at < before.len() && before[at].name.as_bytes() < e.name.as_bytes() { |
| 1193 | at += 1; |
| 1194 | } |
| 1195 | let b = before.get(at).filter(|b| b.name == e.name); |
| 1196 | if e.kind == EntryKind::Gitlink { |
| 1197 | continue; |
| 1198 | } |
| 1199 | if b.is_some_and(|b| b.id == e.id) && !force.contains(&e.id) { |
| 1200 | if plan.looked.insert(e.id) { |
| 1201 | plan.lookup.push(e.id); |
| 1202 | } |
| 1203 | continue; |
| 1204 | } |
| 1205 | if e.kind == EntryKind::Tree { |
| 1206 | let old_sub = if force.contains(&e.id) { None } else { b.filter(|b| b.kind == EntryKind::Tree).map(|b| b.id) }; |
| 1207 | plan_tree(&e.id, old_sub.as_ref(), force, plan)?; |
| 1208 | } else if plan.seen.insert(e.id) { |
| 1209 | plan.files.push(e.id); |
| 1210 | } |
| 1211 | } |
| 1212 | return Ok(()); |
| 1213 | } |
| 1214 | let old: HashMap<String, tree::TreeEntry> = match have { |
| 1215 | Some(h) => tree::read(&Cache, h)?.into_iter().map(|e| (e.name.clone(), e)).collect(), |
| 1216 | None => HashMap::new(), |
| 1217 | }; |
| 1218 | for e in tree::read(&Cache, t)? { |
| 1219 | if e.kind == EntryKind::Gitlink { |
| 1220 | // A submodule's commit isn't an object the pack carries. |
| 1221 | continue; |
| 1222 | } |
| 1223 | let before = old.get(&e.name); |
| 1224 | if before.is_some_and(|b| b.id == e.id) && !force.contains(&e.id) { |
| 1225 | if plan.looked.insert(e.id) { |
| 1226 | plan.lookup.push(e.id); |
| 1227 | } |
| 1228 | continue; |
| 1229 | } |
| 1230 | if e.kind == EntryKind::Tree { |
| 1231 | // A forced tree is rebuilt whole. |
| 1232 | let old_sub = if force.contains(&e.id) { None } else { before.filter(|b| b.kind == EntryKind::Tree).map(|b| b.id) }; |
| 1233 | plan_tree(&e.id, old_sub.as_ref(), force, plan)?; |
| 1234 | } else if plan.seen.insert(e.id) { |
| 1235 | plan.files.push(e.id); |
| 1236 | } |
| 1237 | } |
| 1238 | Ok(()) |
| 1239 | } |
| 1240 |
| 1241 | #[derive(Deserialize)] |
| 1242 | struct PathsReq { |
| 1243 | /// (the version before, a version): top folders. |
| 1244 | pairs: Vec<(Option<String>, String)>, |
| 1245 | } |
| 1246 |
| 1247 | /// The folders along `new`'s changed paths (against `old`) that the cache |
| 1248 | /// doesn't have, as deep as what it has lets the walk see. |
| 1249 | fn missing_on_paths(old: Option<&Id>, new: &Id, out: &mut Vec<Id>, seen: &mut HashSet<Id>) -> Result<(), Error> { |
| 1250 | if old == Some(new) || !seen.insert(*new) { |
| 1251 | return Ok(()); |
| 1252 | } |
| 1253 | let Some(n) = Cache.get(new)? else { |
| 1254 | out.push(*new); |
| 1255 | return Ok(()); |
| 1256 | }; |
| 1257 | let o = match old { |
| 1258 | Some(id) => match Cache.get(id)? { |
| 1259 | Some(o) => Some(o), |
| 1260 | None => { |
| 1261 | if seen.insert(*id) { |
| 1262 | out.push(*id); |
| 1263 | } |
| 1264 | return Ok(()); |
| 1265 | } |
| 1266 | }, |
| 1267 | None => None, |
| 1268 | }; |
| 1269 | if n.kind != Kind::Tree || o.as_ref().is_some_and(|o| o.kind != Kind::Tree) { |
| 1270 | return Ok(()); |
| 1271 | } |
| 1272 | let (Some(entries), Some(before)) = (tree::raw_entries(&n.data)?, tree::raw_entries(o.as_ref().map_or(&[][..], |o| &o.data))?) else { return Ok(()) }; |
| 1273 | let mut at = 0; |
| 1274 | for e in entries.iter().filter(|e| e.kind == EntryKind::Tree) { |
| 1275 | while at < before.len() && before[at].name.as_bytes() < e.name.as_bytes() { |
| 1276 | at += 1; |
| 1277 | } |
| 1278 | let b = before.get(at).filter(|b| b.name == e.name && b.kind == EntryKind::Tree).map(|b| b.id); |
| 1279 | missing_on_paths(b.as_ref(), &e.id, out, seen)?; |
| 1280 | } |
| 1281 | Ok(()) |
| 1282 | } |
| 1283 |
| 1284 | /// Folders a batch of versions will read for git that aren't loaded: the |
| 1285 | /// Worker loads them all at once, a level a round, before planning. |
| 1286 | #[unsafe(no_mangle)] |
| 1287 | pub extern "C" fn paths_missing(ptr: *const u8, len: usize) -> i32 { |
| 1288 | let req: PathsReq = match parse(ptr, len) { |
| 1289 | Ok(r) => r, |
| 1290 | Err(e) => return fail(e), |
| 1291 | }; |
| 1292 | let mut out = Vec::new(); |
| 1293 | let mut seen = HashSet::new(); |
| 1294 | for (old, new) in &req.pairs { |
| 1295 | let (Some(new), old) = (Id::parse(new), old.as_deref().and_then(Id::parse)) else { return fail("bad tree id".into()) }; |
| 1296 | if let Err(e) = missing_on_paths(old.as_ref(), &new, &mut out, &mut seen) { |
| 1297 | return fail(e.to_string()); |
| 1298 | } |
| 1299 | } |
| 1300 | answer(json!({ "missing": out.iter().map(|i| i.hex()).collect::<Vec<_>>() })) |
| 1301 | } |
| 1302 |
| 1303 | /// What a version adds over the one before it, for git: new trees, new |
| 1304 | /// files, and unchanged entries whose git IDs the Worker looks up. |
| 1305 | #[unsafe(no_mangle)] |
| 1306 | pub extern "C" fn git_plan(ptr: *const u8, len: usize) -> i32 { |
| 1307 | let req: PlanReq = match parse(ptr, len) { |
| 1308 | Ok(r) => r, |
| 1309 | Err(e) => return fail(e), |
| 1310 | }; |
| 1311 | let root = match id(&req.tree) { |
| 1312 | Ok(t) => t, |
| 1313 | Err(e) => return fail(e), |
| 1314 | }; |
| 1315 | let have = match req.have.as_deref().map(id) { |
| 1316 | Some(Ok(h)) => Some(h), |
| 1317 | Some(Err(e)) => return fail(e), |
| 1318 | None => None, |
| 1319 | }; |
| 1320 | let force: HashSet<Id> = req.force.iter().filter_map(|f| Id::parse(f)).collect(); |
| 1321 | run(|| { |
| 1322 | let mut plan = Plan::default(); |
| 1323 | if have == Some(root) && !force.contains(&root) { |
| 1324 | plan.lookup.push(root); |
| 1325 | } else { |
| 1326 | let have = if force.contains(&root) { None } else { have }; |
| 1327 | plan_tree(&root, have.as_ref(), &force, &mut plan)?; |
| 1328 | } |
| 1329 | // A big folder's unchanged entries are answered once a pack. |
| 1330 | LOOKED.with(|l| { |
| 1331 | let mut looked = l.borrow_mut(); |
| 1332 | if req.start { |
| 1333 | looked.clear(); |
| 1334 | } |
| 1335 | plan.lookup.retain(|id| looked.insert(*id)); |
| 1336 | }); |
| 1337 | let list = |ids: &[Id]| ids.iter().map(|i| i.hex()).collect::<Vec<_>>(); |
| 1338 | Ok(json!({ "trees": list(&plan.trees), "files": list(&plan.files), "lookup": list(&plan.lookup) })) |
| 1339 | }) |
| 1340 | } |
| 1341 |
| 1342 | #[derive(Deserialize)] |
| 1343 | struct TreesReq { |
| 1344 | tree: String, |
| 1345 | /// The plan's new trees: each is written to the pack once. |
| 1346 | trees: Vec<String>, |
| 1347 | /// Native ID → git ID for everything else the trees name that wasn't |
| 1348 | /// sent for this pack before (the pack keeps them). |
| 1349 | known: HashMap<String, String>, |
| 1350 | #[serde(default)] |
| 1351 | parents: Vec<String>, |
| 1352 | message: String, |
| 1353 | author: String, |
| 1354 | time: i64, |
| 1355 | } |
| 1356 |
| 1357 | fn git_tree(t: &Id, path: &str, fresh: &HashSet<Id>, made: &mut HashMap<Id, [u8; 20]>, pack: &mut GitPack) -> Result<[u8; 20], Error> { |
| 1358 | if let Some(g) = made.get(t) { |
| 1359 | return Ok(*g); |
| 1360 | } |
| 1361 | if !fresh.contains(t) { |
| 1362 | return pack.known.get(t).copied().ok_or_else(|| Error::Corrupt(format!("git id of tree {} isn't known", t.short()))); |
| 1363 | } |
| 1364 | let entries = tree::read(&Cache, t)?; |
| 1365 | let mut rows: Vec<(&str, bool, &'static [u8], [u8; 20])> = Vec::with_capacity(entries.len()); |
| 1366 | for e in &entries { |
| 1367 | let (mode, gid): (&'static [u8], [u8; 20]) = match e.kind { |
| 1368 | EntryKind::Tree => { |
| 1369 | let sub = if path.is_empty() { e.name.clone() } else { format!("{path}/{}", e.name) }; |
| 1370 | (b"40000", git_tree(&e.id, &sub, fresh, made, pack)?) |
| 1371 | } |
| 1372 | EntryKind::Gitlink => (b"160000", gitlink(&e.id)?), |
| 1373 | kind => { |
| 1374 | let gid = pack.known.get(&e.id).copied().ok_or_else(|| Error::Corrupt(format!("git id of file {} isn't known", e.id.short())))?; |
| 1375 | (match kind { |
| 1376 | EntryKind::Exec => b"100755", |
| 1377 | EntryKind::Link => b"120000", |
| 1378 | _ => b"100644", |
| 1379 | }, gid) |
| 1380 | } |
| 1381 | }; |
| 1382 | rows.push((&e.name, e.kind == EntryKind::Tree, mode, gid)); |
| 1383 | } |
| 1384 | // Git sorts entries by name, with folders compared as if they end in '/'. |
| 1385 | fn key(name: &str, folder: bool) -> impl Iterator<Item = u8> + '_ { |
| 1386 | name.bytes().chain(folder.then_some(b'/')) |
| 1387 | } |
| 1388 | rows.sort_by(|a, b| key(a.0, a.1).cmp(key(b.0, b.1))); |
| 1389 | let mut data = Vec::with_capacity(rows.iter().map(|r| r.0.len() + r.2.len() + 22).sum()); |
| 1390 | for (name, _, mode, gid) in &rows { |
| 1391 | data.extend_from_slice(mode); |
| 1392 | data.push(b' '); |
| 1393 | data.extend_from_slice(name.as_bytes()); |
| 1394 | data.push(0); |
| 1395 | data.extend_from_slice(gid); |
| 1396 | } |
| 1397 | let g = emit_tree(pack, path, data); |
| 1398 | made.insert(*t, g); |
| 1399 | pack.known.insert(*t, g); |
| 1400 | Ok(g) |
| 1401 | } |
| 1402 |
| 1403 | /// The commit a submodule entry points at (its content, 40 hex digits). |
| 1404 | fn gitlink(id: &Id) -> Result<[u8; 20], Error> { |
| 1405 | let text = String::from_utf8(onset_core::chunk::read_file(&Cache, id)?).map_err(|_| Error::Corrupt("bad submodule entry".into()))?; |
| 1406 | git_bytes(text.trim()).ok_or_else(|| Error::Corrupt("bad submodule entry".into())) |
| 1407 | } |
| 1408 |
| 1409 | /// A git ID's 20 bytes from its 40 hex digits. |
| 1410 | fn git_bytes(hex: &str) -> Option<[u8; 20]> { |
| 1411 | if hex.len() != 40 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 1412 | return None; |
| 1413 | } |
| 1414 | let mut out = [0u8; 20]; |
| 1415 | for (i, o) in out.iter_mut().enumerate() { |
| 1416 | *o = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).ok()?; |
| 1417 | } |
| 1418 | Some(out) |
| 1419 | } |
| 1420 |
| 1421 | /// Writes the version's new trees and its commit to the pack. |
| 1422 | #[unsafe(no_mangle)] |
| 1423 | pub extern "C" fn git_trees(ptr: *const u8, len: usize) -> i32 { |
| 1424 | let req: TreesReq = match parse(ptr, len) { |
| 1425 | Ok(r) => r, |
| 1426 | Err(e) => return fail(e), |
| 1427 | }; |
| 1428 | let root = match id(&req.tree) { |
| 1429 | Ok(t) => t, |
| 1430 | Err(e) => return fail(e), |
| 1431 | }; |
| 1432 | let fresh: HashSet<Id> = req.trees.iter().filter_map(|t| Id::parse(t)).collect(); |
| 1433 | // Every new tree is loaded first, so nothing reaches the pack twice, |
| 1434 | // and so are the submodule entries in them. |
| 1435 | let mut need: Vec<String> = fresh.iter().filter(|t| Cache.get(t).ok().flatten().is_none()).map(|t| t.hex()).collect(); |
| 1436 | if need.is_empty() { |
| 1437 | for t in &fresh { |
| 1438 | if let Ok(entries) = tree::read(&Cache, t) { |
| 1439 | need.extend(entries.iter().filter(|e| e.kind == EntryKind::Gitlink && Cache.get(&e.id).ok().flatten().is_none()).map(|e| e.id.hex())); |
| 1440 | } |
| 1441 | } |
| 1442 | } |
| 1443 | if !need.is_empty() { |
| 1444 | return answer(json!({ "need": need })); |
| 1445 | } |
| 1446 | with_pack(|pack| { |
| 1447 | for (native, git) in &req.known { |
| 1448 | match (Id::parse(native), git_bytes(git)) { |
| 1449 | (Some(n), Some(g)) => { |
| 1450 | pack.known.insert(n, g); |
| 1451 | } |
| 1452 | _ => return Err(format!("bad git id for {native}")), |
| 1453 | } |
| 1454 | } |
| 1455 | let mut made = HashMap::new(); |
| 1456 | let tree_id = hex(&git_tree(&root, "", &fresh, &mut made, pack).map_err(|e| e.to_string())?); |
| 1457 | if made.len() != fresh.len() { |
| 1458 | return Err(format!("wrote {} trees, planned {}", made.len(), fresh.len())); |
| 1459 | } |
| 1460 | let (name, email) = match req.author.split_once(" <") { |
| 1461 | Some((n, e)) => (n.to_string(), e.trim_end_matches('>').to_string()), |
| 1462 | None => (req.author.clone(), "vcs@localhost".into()), |
| 1463 | }; |
| 1464 | let mut commit = format!("tree {tree_id}\n"); |
| 1465 | for p in &req.parents { |
| 1466 | if p.len() != 40 || !p.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 1467 | return Err(format!("bad parent {p}")); |
| 1468 | } |
| 1469 | commit.push_str(&format!("parent {p}\n")); |
| 1470 | } |
| 1471 | commit.push_str(&format!("author {name} <{email}> {} +0000\ncommitter {name} <{email}> {} +0000\n\n{}", req.time, req.time, req.message)); |
| 1472 | if !commit.ends_with('\n') { |
| 1473 | commit.push('\n'); |
| 1474 | } |
| 1475 | let commit_id = emit_object(pack, "commit", 1, commit.as_bytes()); |
| 1476 | let trees: HashMap<String, String> = made.into_iter().map(|(k, v)| (k.hex(), hex(&v))).collect(); |
| 1477 | Ok(json!({ "commit": commit_id, "tree": tree_id, "trees": trees })) |
| 1478 | }) |
| 1479 | } |
| 1480 |
| 1481 | // Git main's new commits, coming in: a pack fetched from the git view is |
| 1482 | // read once, then its commits and trees are turned into versions. |
| 1483 |
| 1484 | /// The most a fetched pack's objects can add up to. |
| 1485 | const GIT_IN_MAX: usize = 48 << 20; |
| 1486 |
| 1487 | thread_local! { |
| 1488 | static GIT_IN: RefCell<Option<onset_core::git::Pack>> = const { RefCell::new(None) }; |
| 1489 | } |
| 1490 |
| 1491 | /// Reads a pack (raw bytes): `{"objects": n}`. |
| 1492 | #[unsafe(no_mangle)] |
| 1493 | pub extern "C" fn git_in_read(ptr: *const u8, len: usize) -> i32 { |
| 1494 | match onset_core::git::read_pack(input(ptr, len), GIT_IN_MAX) { |
| 1495 | Ok(pack) => { |
| 1496 | let n = pack.objects.len(); |
| 1497 | GIT_IN.with(|g| *g.borrow_mut() = Some(pack)); |
| 1498 | answer(json!({ "objects": n })) |
| 1499 | } |
| 1500 | Err(e) => fail(e.to_string()), |
| 1501 | } |
| 1502 | } |
| 1503 |
| 1504 | #[unsafe(no_mangle)] |
| 1505 | pub extern "C" fn git_in_drop() { |
| 1506 | GIT_IN.with(|g| *g.borrow_mut() = None); |
| 1507 | } |
| 1508 |
| 1509 | fn with_git_in(f: impl FnOnce(&onset_core::git::Pack) -> Result<Value, String>) -> i32 { |
| 1510 | let result = GIT_IN.with(|g| match g.borrow().as_ref() { |
| 1511 | Some(pack) => f(pack), |
| 1512 | None => Err("no git pack read".into()), |
| 1513 | }); |
| 1514 | match result { |
| 1515 | Ok(v) => answer(v), |
| 1516 | Err(e) => fail(e), |
| 1517 | } |
| 1518 | } |
| 1519 |
| 1520 | #[derive(Deserialize)] |
| 1521 | struct GitInCommitsReq { |
| 1522 | from: String, |
| 1523 | to: String, |
| 1524 | } |
| 1525 |
| 1526 | /// The commits that took git main from `from` to `to`, oldest first: |
| 1527 | /// each on the first-parent line, or only `to` when `from` is in its |
| 1528 | /// history some other way. `{"rewritten": true}` when it isn't (a force push). |
| 1529 | #[unsafe(no_mangle)] |
| 1530 | pub extern "C" fn git_in_commits(ptr: *const u8, len: usize) -> i32 { |
| 1531 | use onset_core::git; |
| 1532 | let req: GitInCommitsReq = match parse(ptr, len) { |
| 1533 | Ok(r) => r, |
| 1534 | Err(e) => return fail(e), |
| 1535 | }; |
| 1536 | let (Some(from), Some(to)) = (git::parse_id(&req.from), git::parse_id(&req.to)) else { return fail("bad git ids".into()) }; |
| 1537 | with_git_in(|pack| { |
| 1538 | 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 }); |
| 1539 | if let Some(line) = git::first_parents(pack, &from, &to, 1000).map_err(|e| e.to_string())? { |
| 1540 | return Ok(json!({ "commits": line.iter().map(|(id, c)| view(id, c)).collect::<Vec<_>>() })); |
| 1541 | } |
| 1542 | if !git::descends(pack, &from, &to).map_err(|e| e.to_string())? { |
| 1543 | return Ok(json!({ "rewritten": true })); |
| 1544 | } |
| 1545 | let Some((git::GitKind::Commit, data)) = pack.objects.get(&to) else { return Err("git main's commit isn't in the pack".into()) }; |
| 1546 | let c = git::Commit::parse(data).map_err(|e| e.to_string())?; |
| 1547 | Ok(json!({ "commits": [view(&to, &c)] })) |
| 1548 | }) |
| 1549 | } |
| 1550 |
| 1551 | #[derive(Deserialize)] |
| 1552 | struct GitInTreeReq { |
| 1553 | tree: String, |
| 1554 | /// git ID → Onset ID for trees and files outside the pack. |
| 1555 | #[serde(default)] |
| 1556 | known: HashMap<String, String>, |
| 1557 | } |
| 1558 |
| 1559 | /// A git tree as an Onset tree: `{"tree", "ids": [[onset, git]]}` with its new |
| 1560 | /// objects made, or `{"unknown": [git ids]}` to look up first. |
| 1561 | #[unsafe(no_mangle)] |
| 1562 | pub extern "C" fn git_in_tree(ptr: *const u8, len: usize) -> i32 { |
| 1563 | use onset_core::git; |
| 1564 | let req: GitInTreeReq = match parse(ptr, len) { |
| 1565 | Ok(r) => r, |
| 1566 | Err(e) => return fail(e), |
| 1567 | }; |
| 1568 | let Some(root) = git::parse_id(&req.tree) else { return fail("bad git id".into()) }; |
| 1569 | let known: HashMap<git::GitId, Id> = req.known.iter().filter_map(|(g, v)| Some((git::parse_id(g)?, Id::parse(v)?))).collect(); |
| 1570 | with_git_in(|pack| { |
| 1571 | let mut to = git::ToOnset::new(pack, &known); |
| 1572 | let tree = to.tree(root, true).map_err(|e| e.to_string())?.unwrap_or_else(tree::empty_id); |
| 1573 | if !to.unknown.is_empty() { |
| 1574 | return Ok(json!({ "unknown": to.unknown.iter().map(git::hex).collect::<Vec<_>>() })); |
| 1575 | } |
| 1576 | NEW.with(|n| { |
| 1577 | let mut n = n.borrow_mut(); |
| 1578 | for o in to.objects.drain(..) { |
| 1579 | n.put(o); |
| 1580 | } |
| 1581 | }); |
| 1582 | Ok(json!({ "tree": tree.hex(), "ids": to.ids.iter().map(|(v, g)| json!([v.hex(), git::hex(g)])).collect::<Vec<_>>() })) |
| 1583 | }) |
| 1584 | } |
| 1585 |
| 1586 |
| 1587 | #[cfg(test)] |
| 1588 | mod tests { |
| 1589 | use super::*; |
| 1590 | use std::io::Write; |
| 1591 | use onset_core::tree::{Entry, Files}; |
| 1592 |
| 1593 | fn sha1_git(kind: &str, data: &[u8]) -> String { |
| 1594 | let mut h = Sha1::new(); |
| 1595 | h.update(git_header(kind, data.len() as u64)); |
| 1596 | h.update(data); |
| 1597 | hex(&h.finalize()) |
| 1598 | } |
| 1599 |
| 1600 | #[test] |
| 1601 | fn git_ids_match_git() { |
| 1602 | // `printf 'hello\n' | git hash-object --stdin` |
| 1603 | assert_eq!(sha1_git("blob", b"hello\n"), "ce013625030ba8dba906f756967f9e9ca394464a"); |
| 1604 | } |
| 1605 |
| 1606 | fn feed(o: &Object) { |
| 1607 | let mut b = Vec::new(); |
| 1608 | bundle::write_frame(&mut b, &Frame::raw(o)); |
| 1609 | assert_eq!(blob_feed(b.as_ptr(), b.len()), 0); |
| 1610 | } |
| 1611 |
| 1612 | fn result() -> Vec<u8> { |
| 1613 | RESULT.with(|r| r.borrow().clone()) |
| 1614 | } |
| 1615 |
| 1616 | fn call_json(f: extern "C" fn(*const u8, usize) -> i32, v: Value) -> Value { |
| 1617 | let b = serde_json::to_vec(&v).unwrap(); |
| 1618 | assert_eq!(f(b.as_ptr(), b.len()), 0, "{}", String::from_utf8_lossy(&result())); |
| 1619 | serde_json::from_slice(&result()).unwrap() |
| 1620 | } |
| 1621 |
| 1622 | /// A version's pack is one git accepts, with the IDs git computes. |
| 1623 | #[test] |
| 1624 | fn git_pack_is_git() { |
| 1625 | let small = Object::blob(b"fn main() {}\n".to_vec()); |
| 1626 | let big: Vec<u8> = (0..3_000_000u32).map(|i| (i.wrapping_mul(2654435761) >> 13) as u8).collect(); |
| 1627 | let big_parts = onset_core::chunk::file_objects(&big); |
| 1628 | let big_id = big_parts[0].id(); |
| 1629 | let mut files = Files::new(); |
| 1630 | files.insert("src/main.rs".into(), Entry { kind: EntryKind::File, id: small.id() }); |
| 1631 | files.insert("run.sh".into(), Entry { kind: EntryKind::Exec, id: small.id() }); |
| 1632 | files.insert("data/big.bin".into(), Entry { kind: EntryKind::File, id: big_id }); |
| 1633 | let (root, trees) = tree::build(&files); |
| 1634 | cache_drop(0); |
| 1635 | for t in &trees { |
| 1636 | insert(t.id(), t.clone()); |
| 1637 | } |
| 1638 | let plan = call_json(git_plan, json!({ "tree": root.hex() })); |
| 1639 | let new_trees: Vec<String> = serde_json::from_value(plan["trees"].clone()).unwrap(); |
| 1640 | let new_files: Vec<String> = serde_json::from_value(plan["files"].clone()).unwrap(); |
| 1641 | assert_eq!(new_trees.len(), 3); |
| 1642 | assert_eq!(new_files.len(), 2); |
| 1643 |
| 1644 | assert_eq!(pack_begin((new_trees.len() + new_files.len() + 1) as u32, 1), 0); |
| 1645 | let mut known = HashMap::new(); |
| 1646 | let list = big_parts.iter().find(|o| o.kind == Kind::Chunks).unwrap(); |
| 1647 | let chunks: HashMap<Id, &Object> = big_parts.iter().map(|o| (o.id(), o)).collect(); |
| 1648 | let files_pass = |write: u32, pack: &mut Vec<u8>| -> Vec<String> { |
| 1649 | let mut ids = Vec::new(); |
| 1650 | assert_eq!(blob_begin(small.data.len() as f64, write), 0); |
| 1651 | feed(&small); |
| 1652 | assert_eq!(blob_end(), 0); |
| 1653 | let v: Value = serde_json::from_slice(&result()).unwrap(); |
| 1654 | ids.push(v["git"].as_str().unwrap().to_string()); |
| 1655 | assert_eq!(blob_begin(big.len() as f64, write), 0); |
| 1656 | for (c, _) in decode_chunks(&list.data).unwrap() { |
| 1657 | feed(chunks[&c]); |
| 1658 | pack_take(); |
| 1659 | pack.extend(result()); |
| 1660 | } |
| 1661 | assert_eq!(blob_end(), 0); |
| 1662 | let v: Value = serde_json::from_slice(&result()).unwrap(); |
| 1663 | ids.push(v["git"].as_str().unwrap().to_string()); |
| 1664 | ids |
| 1665 | }; |
| 1666 | let mut pack = Vec::new(); |
| 1667 | let hashed = files_pass(0, &mut pack); |
| 1668 | known.insert(small.id().hex(), hashed[0].clone()); |
| 1669 | known.insert(big_id.hex(), hashed[1].clone()); |
| 1670 | let done = call_json( |
| 1671 | git_trees, |
| 1672 | json!({ "tree": root.hex(), "trees": new_trees, "known": known, "parents": [], "message": "First\n", "author": "Ada <ada@example.com>", "time": 1700000000 }), |
| 1673 | ); |
| 1674 | let written = files_pass(1, &mut pack); |
| 1675 | assert_eq!(hashed, written); |
| 1676 | pack_take(); |
| 1677 | pack.extend(result()); |
| 1678 | assert_eq!(pack_end(), 0); |
| 1679 | pack.extend(result()); |
| 1680 | let dir = std::env::temp_dir().join(format!("onset-wasm-git-{}", std::process::id())); |
| 1681 | let _ = std::fs::remove_dir_all(&dir); |
| 1682 | std::fs::create_dir_all(&dir).unwrap(); |
| 1683 | let git = |args: &[&str], input: Option<&[u8]>| -> String { |
| 1684 | let mut c = std::process::Command::new("git"); |
| 1685 | c.args(args).current_dir(&dir).stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()); |
| 1686 | let mut child = c.spawn().unwrap(); |
| 1687 | if let Some(i) = input { |
| 1688 | child.stdin.take().unwrap().write_all(i).unwrap(); |
| 1689 | } else { |
| 1690 | drop(child.stdin.take()); |
| 1691 | } |
| 1692 | let out = child.wait_with_output().unwrap(); |
| 1693 | assert!(out.status.success(), "git {args:?} failed"); |
| 1694 | String::from_utf8(out.stdout).unwrap() |
| 1695 | }; |
| 1696 | git(&["init", "-q", "--bare", "."], None); |
| 1697 | git(&["index-pack", "--stdin", "--strict"], Some(&pack)); |
| 1698 | let commit = done["commit"].as_str().unwrap(); |
| 1699 | git(&["update-ref", "refs/heads/main", commit], None); |
| 1700 | git(&["fsck", "--strict", "--no-dangling"], None); |
| 1701 | let listing = git(&["ls-tree", "-r", "main"], None); |
| 1702 | assert!(listing.contains("100755 blob") && listing.contains("run.sh"), "{listing}"); |
| 1703 | assert_eq!(git(&["cat-file", "-p", "main:src/main.rs"], None), "fn main() {}\n"); |
| 1704 | assert_eq!(git(&["cat-file", "-s", "main:data/big.bin"], None).trim(), big.len().to_string()); |
| 1705 | let _ = std::fs::remove_dir_all(&dir); |
| 1706 | } |
| 1707 | } |
| 1708 |