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