Skip to main content

gitiverse_git/
pack.rs

1use std::path::Path;
2
3use crate::store::{CliGitStore, GitError, GitStore, Oid, run_git_bytes, validate_ref_name};
4
5/// Compare-and-swap reference update specification passed to [`quarantine_ingest`].
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct RefUpdateSpec {
8    pub ref_name: String,
9    pub expected_old_oid: Option<Oid>,
10    pub new_oid: Option<Oid>,
11}
12
13/// Builds a thin delta packfile containing objects reachable from `wants` and not reachable from `haves`.
14pub async fn build_pack(
15    repo_dir: &Path,
16    wants: &[Oid],
17    haves: &[Oid],
18) -> Result<Vec<u8>, GitError> {
19    if wants.is_empty() {
20        return Err(GitError::InvalidInput(
21            "pack build requires at least one want OID".to_owned(),
22        ));
23    }
24
25    let mut stdin_lines = String::new();
26    for want in wants {
27        stdin_lines.push_str(want.as_str());
28        stdin_lines.push('\n');
29    }
30    for have in haves {
31        stdin_lines.push('^');
32        stdin_lines.push_str(have.as_str());
33        stdin_lines.push('\n');
34    }
35
36    let output = run_git_bytes(
37        repo_dir,
38        &["pack-objects", "--revs", "--thin", "--stdout", "-q"],
39        Some(stdin_lines.as_bytes()),
40        &[],
41    )
42    .await?;
43
44    if !output.status.success() {
45        return Err(GitError::CommandFailed {
46            command: "git pack-objects --revs --thin --stdout".to_owned(),
47            status: output.status.code(),
48            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
49        });
50    }
51
52    Ok(output.stdout)
53}
54
55/// Ingests `pack_bytes` into an isolated quarantine object directory, runs strict `index-pack`, `fsck --strict`, and object connectivity checks before promoting objects and applying CAS ref updates atomically.
56pub async fn quarantine_ingest(
57    repo_dir: &Path,
58    pack_bytes: &[u8],
59    updates: &[RefUpdateSpec],
60) -> Result<Vec<String>, GitError> {
61    quarantine_ingest_inner(repo_dir, pack_bytes, updates, true).await
62}
63
64/// Strictly verifies `pack_bytes` inside an isolated quarantine object directory via `index-pack --strict` and promotes the resulting packfile without running repository-wide `fsck` (safe for freshly initialised `git clone` directories whose `HEAD` temporarily points to `refs/heads/.invalid`).
65pub async fn quarantine_index_pack(repo_dir: &Path, pack_bytes: &[u8]) -> Result<(), GitError> {
66    if pack_bytes.is_empty() {
67        return Ok(());
68    }
69    let _ = quarantine_ingest_inner(repo_dir, pack_bytes, &[], false).await?;
70    Ok(())
71}
72
73/// Ingests `pack_bytes` into an isolated quarantine object directory, runs strict `index-pack` (and `fsck --strict` when `run_repo_fsck` is true), and promotes verified packfiles into `objects/pack`.
74async fn quarantine_ingest_inner(
75    repo_dir: &Path,
76    pack_bytes: &[u8],
77    updates: &[RefUpdateSpec],
78    run_repo_fsck: bool,
79) -> Result<Vec<String>, GitError> {
80    for update in updates {
81        validate_ref_name(&update.ref_name)?;
82    }
83
84    let objects_dir = repo_dir.join("objects");
85    let target_pack_dir = objects_dir.join("pack");
86    tokio::fs::create_dir_all(&target_pack_dir).await?;
87
88    let quarantine = tempfile::Builder::new()
89        .prefix("quarantine-")
90        .tempdir_in(&objects_dir)?;
91    let quarantine_dir = quarantine.path();
92    let quarantine_pack_dir = quarantine_dir.join("pack");
93    tokio::fs::create_dir_all(&quarantine_pack_dir).await?;
94
95    let env_vars = [
96        ("GIT_OBJECT_DIRECTORY", quarantine_dir),
97        ("GIT_ALTERNATE_OBJECT_DIRECTORIES", objects_dir.as_path()),
98    ];
99
100    if !pack_bytes.is_empty() {
101        let index_out = run_git_bytes(
102            repo_dir,
103            &["index-pack", "--stdin", "--fix-thin", "--strict"],
104            Some(pack_bytes),
105            &env_vars,
106        )
107        .await?;
108        if !index_out.status.success() {
109            return Err(GitError::VerificationFailed(format!(
110                "index-pack --strict failed: {}",
111                String::from_utf8_lossy(&index_out.stderr).trim()
112            )));
113        }
114
115        if run_repo_fsck {
116            let fsck_out = run_git_bytes(
117                repo_dir,
118                &["fsck", "--strict", "--no-dangling"],
119                None,
120                &env_vars,
121            )
122            .await?;
123            if !fsck_out.status.success() {
124                return Err(GitError::VerificationFailed(format!(
125                    "fsck --strict failed: {}",
126                    String::from_utf8_lossy(&fsck_out.stderr).trim()
127                )));
128            }
129        }
130    }
131
132    // Verify full object graph connectivity for every proposed non-delete target before promoting.
133    let new_oids: Vec<&str> = updates
134        .iter()
135        .filter_map(|u| u.new_oid.as_ref().map(Oid::as_str))
136        .collect();
137    if !new_oids.is_empty() {
138        let mut args = vec!["rev-list", "--objects"];
139        args.extend(new_oids);
140        args.push("--not");
141        args.push("--all");
142        let conn_out = run_git_bytes(repo_dir, &args, None, &env_vars).await?;
143        if !conn_out.status.success() {
144            return Err(GitError::VerificationFailed(format!(
145                "connectivity check failed: {}",
146                String::from_utf8_lossy(&conn_out.stderr).trim()
147            )));
148        }
149    }
150
151    // Check compare-and-swap preconditions before promoting any objects out of quarantine.
152    let store = CliGitStore::new(repo_dir);
153    for update in updates {
154        let current = store.resolve_ref(&update.ref_name).await?;
155        match (&current, &update.expected_old_oid) {
156            (Some(curr), Some(expected)) if curr == expected => {}
157            (None, None) => {}
158            (curr, expected) => {
159                return Err(GitError::CasConflict {
160                    ref_name: update.ref_name.clone(),
161                    details: format!("expected {expected:?}, found {curr:?}"),
162                });
163            }
164        }
165    }
166
167    // Promote verified pack and index files from quarantine into objects/pack.
168    if !pack_bytes.is_empty() {
169        let mut entries = tokio::fs::read_dir(&quarantine_pack_dir).await?;
170        let mut files = Vec::new();
171        while let Some(entry) = entries.next_entry().await? {
172            let path = entry.path();
173            if let Some(name) = path.file_name().and_then(|n| n.to_str())
174                && (name.ends_with(".pack") || name.ends_with(".idx"))
175            {
176                let dst = target_pack_dir.join(name);
177                files.push((path, dst));
178            }
179        }
180        // Promote `.pack` files before `.idx` files so Git never observes a dangling index.
181        files.sort_by_key(|(src, _)| src.extension().and_then(|e| e.to_str()) == Some("idx"));
182        for (src, dst) in files {
183            tokio::fs::rename(src, dst).await?;
184        }
185    }
186
187    if !updates.is_empty() {
188        let mut batch = String::new();
189        for update in updates {
190            match (&update.new_oid, &update.expected_old_oid) {
191                (Some(new_oid), Some(old_oid)) => {
192                    batch.push_str(&format!(
193                        "update {} {} {}\n",
194                        update.ref_name,
195                        new_oid.as_str(),
196                        old_oid.as_str()
197                    ));
198                }
199                (Some(new_oid), None) => {
200                    batch.push_str(&format!(
201                        "create {} {}\n",
202                        update.ref_name,
203                        new_oid.as_str()
204                    ));
205                }
206                (None, Some(old_oid)) => {
207                    batch.push_str(&format!(
208                        "delete {} {}\n",
209                        update.ref_name,
210                        old_oid.as_str()
211                    ));
212                }
213                (None, None) => {
214                    batch.push_str(&format!("delete {}\n", update.ref_name));
215                }
216            }
217        }
218
219        let ref_out = run_git_bytes(
220            repo_dir,
221            &["update-ref", "--stdin"],
222            Some(batch.as_bytes()),
223            &[],
224        )
225        .await?;
226        if !ref_out.status.success() {
227            let stderr = String::from_utf8_lossy(&ref_out.stderr).into_owned();
228            if stderr.contains("cannot lock ref")
229                || stderr.contains("is at")
230                || stderr.contains("expected")
231                || stderr.contains("already exists")
232            {
233                return Err(GitError::CasConflict {
234                    ref_name: updates
235                        .iter()
236                        .map(|u| u.ref_name.as_str())
237                        .collect::<Vec<_>>()
238                        .join(", "),
239                    details: stderr.trim().to_owned(),
240                });
241            }
242            return Err(GitError::CommandFailed {
243                command: "git update-ref --stdin".to_owned(),
244                status: ref_out.status.code(),
245                stderr,
246            });
247        }
248    }
249
250    Ok(updates.iter().map(|u| u.ref_name.clone()).collect())
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256    use crate::store::test_helpers::create_commit_in_bare;
257
258    #[tokio::test]
259    async fn thin_pack_build_and_quarantine_ingest_round_trip() {
260        let src_dir = tempfile::tempdir().unwrap();
261        let dst_dir = tempfile::tempdir().unwrap();
262        let src = CliGitStore::init_bare_at(src_dir.path()).await.unwrap();
263        let dst = CliGitStore::init_bare_at(dst_dir.path()).await.unwrap();
264
265        let c1 = create_commit_in_bare(
266            src_dir.path(),
267            "refs/heads/main",
268            &[],
269            &[("a.txt", b"first version\n")],
270            "c1",
271        )
272        .await;
273
274        let full_pack = build_pack(src_dir.path(), std::slice::from_ref(&c1), &[])
275            .await
276            .unwrap();
277        quarantine_ingest(
278            dst_dir.path(),
279            &full_pack,
280            &[RefUpdateSpec {
281                ref_name: "refs/heads/main".to_owned(),
282                expected_old_oid: None,
283                new_oid: Some(c1.clone()),
284            }],
285        )
286        .await
287        .unwrap();
288        assert_eq!(
289            dst.resolve_ref("refs/heads/main").await.unwrap(),
290            Some(c1.clone())
291        );
292
293        // Now create a second commit in src and build a thin delta pack against c1.
294        let c2 = create_commit_in_bare(
295            src_dir.path(),
296            "refs/heads/main",
297            &[&c1],
298            &[("a.txt", b"first version\nsecond line\n")],
299            "c2",
300        )
301        .await;
302        let thin_pack = build_pack(
303            src_dir.path(),
304            std::slice::from_ref(&c2),
305            std::slice::from_ref(&c1),
306        )
307        .await
308        .unwrap();
309
310        quarantine_ingest(
311            dst_dir.path(),
312            &thin_pack,
313            &[RefUpdateSpec {
314                ref_name: "refs/heads/main".to_owned(),
315                expected_old_oid: Some(c1.clone()),
316                new_oid: Some(c2.clone()),
317            }],
318        )
319        .await
320        .unwrap();
321        assert_eq!(dst.resolve_ref("refs/heads/main").await.unwrap(), Some(c2));
322        assert!(src.object_exists(&c1).await.unwrap());
323    }
324
325    #[tokio::test]
326    async fn corrupt_pack_and_missing_parent_are_rejected_without_mutating_dst() {
327        let src_dir = tempfile::tempdir().unwrap();
328        let dst_dir = tempfile::tempdir().unwrap();
329        CliGitStore::init_bare_at(src_dir.path()).await.unwrap();
330        let dst = CliGitStore::init_bare_at(dst_dir.path()).await.unwrap();
331
332        let fake_oid = Oid::parse(&"1".repeat(40)).unwrap();
333        let err = quarantine_ingest(
334            dst_dir.path(),
335            b"not a valid git packfile",
336            &[RefUpdateSpec {
337                ref_name: "refs/heads/main".to_owned(),
338                expected_old_oid: None,
339                new_oid: Some(fake_oid),
340            }],
341        )
342        .await
343        .unwrap_err();
344        assert!(
345            matches!(err, GitError::VerificationFailed(_)),
346            "got {err:?}"
347        );
348        assert_eq!(dst.resolve_ref("refs/heads/main").await.unwrap(), None);
349
350        // Missing parent commit (thin pack built against c1 pushed into empty dst without c1).
351        let c1 = create_commit_in_bare(
352            src_dir.path(),
353            "refs/heads/main",
354            &[],
355            &[("a.txt", b"hello\n")],
356            "c1",
357        )
358        .await;
359        let c2 = create_commit_in_bare(
360            src_dir.path(),
361            "refs/heads/main",
362            &[&c1],
363            &[("a.txt", b"hello world\n")],
364            "c2",
365        )
366        .await;
367        let thin_only = build_pack(
368            src_dir.path(),
369            std::slice::from_ref(&c2),
370            std::slice::from_ref(&c1),
371        )
372        .await
373        .unwrap();
374        let err_missing = quarantine_ingest(
375            dst_dir.path(),
376            &thin_only,
377            &[RefUpdateSpec {
378                ref_name: "refs/heads/main".to_owned(),
379                expected_old_oid: None,
380                new_oid: Some(c2.clone()),
381            }],
382        )
383        .await
384        .unwrap_err();
385        assert!(
386            matches!(err_missing, GitError::VerificationFailed(_)),
387            "got {err_missing:?}"
388        );
389        // Quarantined c2 must NOT have leaked into dst's object database.
390        assert!(!dst.object_exists(&c2).await.unwrap());
391        assert_eq!(dst.resolve_ref("refs/heads/main").await.unwrap(), None);
392    }
393}