Skip to main content

git_internal/protocol/
pack.rs

1//! Transport-agnostic pack generator that reuses repository storage traits to walk commits, expand
2//! trees/blobs, and either stream packs to clients or unpack uploads for server-side ingestion.
3
4use std::{
5    collections::{HashSet, VecDeque},
6    io::Cursor,
7};
8
9use bytes::Bytes;
10use tokio::{self, sync::mpsc};
11use tokio_stream::wrappers::ReceiverStream;
12
13use super::{core::RepositoryAccess, types::ProtocolError};
14use crate::{
15    hash::{HashKind, ObjectHash},
16    internal::{
17        metadata::{EntryMeta, MetaAttached},
18        object::{ObjectTrait, blob::Blob, commit::Commit, tree::Tree, types::ObjectType},
19        pack::{Pack, encode::PackEncoder, entry::Entry},
20    },
21};
22
23/// Pack generation service for Git protocol operations
24///
25/// This handles the core Git pack generation logic internally within git-internal,
26/// using the RepositoryAccess trait only for data access. Pack trailers, object IDs and
27/// decoding are bound to the repository's `object_hash_kind()` (SHA-1, SHA-256, or the
28/// BLAKE3 extension); nothing is inferred from ID widths.
29pub struct PackGenerator<'a, R>
30where
31    R: RepositoryAccess,
32{
33    repo_access: &'a R,
34    /// Object format every pack produced or consumed by this generator is bound to. Captured
35    /// once (at construction, on the caller's thread) and never re-read across `.await`s.
36    hash_kind: HashKind,
37}
38
39impl<'a, R> PackGenerator<'a, R>
40where
41    R: RepositoryAccess,
42{
43    /// Create a generator bound to `repo_access.object_hash_kind()` as observed right now.
44    pub fn new(repo_access: &'a R) -> Self {
45        Self::new_with_hash_kind(repo_access, repo_access.object_hash_kind())
46    }
47
48    /// Create a generator bound to an explicit, already validated `hash_kind` (what
49    /// `SmartProtocol` passes after its consistency check).
50    pub fn new_with_hash_kind(repo_access: &'a R, hash_kind: HashKind) -> Self {
51        Self {
52            repo_access,
53            hash_kind,
54        }
55    }
56
57    /// The object format this generator is bound to.
58    pub fn hash_kind(&self) -> HashKind {
59        self.hash_kind
60    }
61
62    /// Generate a full pack containing all requested objects.
63    ///
64    /// Object collection (and its kind checks) happens before this returns; the pack bytes
65    /// are produced on a background task and delivered as `Ok` chunks, and any failure of
66    /// that task is delivered as a final `Err` item (fail-closed, never a silent EOF).
67    pub async fn generate_full_pack(
68        &self,
69        want: Vec<String>,
70    ) -> Result<ReceiverStream<Result<Vec<u8>, ProtocolError>>, ProtocolError> {
71        // The pack is bound to the kind captured at construction, never to a re-read of
72        // `object_hash_kind()` after an `.await`.
73        let kind = self.hash_kind;
74
75        // Collect all objects needed for the wanted commits
76        let all_objects = self.collect_all_objects(kind, want).await?;
77
78        Ok(Self::spawn_pack_stream(kind, all_objects))
79    }
80
81    /// Produce the pack for `objects` on a background task, forwarding a producer failure
82    /// into the stream as an `Err` item.
83    fn spawn_pack_stream(
84        kind: HashKind,
85        objects: (Vec<Commit>, Vec<Tree>, Vec<Blob>),
86    ) -> ReceiverStream<Result<Vec<u8>, ProtocolError>> {
87        let (tx, rx) = mpsc::channel(1024);
88        tokio::spawn(async move {
89            if let Err(e) = Self::generate_pack_stream(kind, objects, tx.clone()).await {
90                tracing::error!("Failed to generate pack stream: {}", e);
91                // A dropped receiver is not an error for the producer.
92                let _ = tx.send(Err(e)).await;
93            }
94        });
95        ReceiverStream::new(rx)
96    }
97
98    /// Generate an incremental pack containing only objects not in 'have' (see
99    /// [`PackGenerator::generate_full_pack`] for the stream's error contract).
100    pub async fn generate_incremental_pack(
101        &self,
102        want: Vec<String>,
103        have: Vec<String>,
104    ) -> Result<ReceiverStream<Result<Vec<u8>, ProtocolError>>, ProtocolError> {
105        let kind = self.hash_kind;
106
107        // Collect objects for wanted commits
108        let wanted_objects = self.collect_all_objects(kind, want).await?;
109
110        // Collect objects for have commits (to exclude)
111        let have_objects = self.collect_all_objects(kind, have).await?;
112
113        // Filter out objects that are already in 'have'
114        let incremental_objects = Self::filter_objects(wanted_objects, have_objects);
115
116        Ok(Self::spawn_pack_stream(kind, incremental_objects))
117    }
118
119    /// Unpack incoming pack stream and extract objects.
120    ///
121    /// The pack is decoded against the generator's bound object format: object IDs, ref-delta
122    /// bases and the trailer checksum are computed and verified with that kind, so a pack of
123    /// another format (for example a BLAKE3 pack pushed to a SHA-256 repository) fails closed.
124    pub async fn unpack_stream(
125        &self,
126        pack_data: Bytes,
127    ) -> Result<(Vec<Commit>, Vec<Tree>, Vec<Blob>), ProtocolError> {
128        use std::sync::{Arc, Mutex};
129
130        let commits = Arc::new(Mutex::new(Vec::new()));
131        let trees = Arc::new(Mutex::new(Vec::new()));
132        let blobs = Arc::new(Mutex::new(Vec::new()));
133
134        let commits_clone = commits.clone();
135        let trees_clone = trees.clone();
136        let blobs_clone = blobs.clone();
137
138        // Create a Pack instance for decoding, bound to the generator's object format
139        let mut pack = Pack::new_with_hash_kind(self.hash_kind, None, None, None, true);
140        let mut cursor = Cursor::new(pack_data.to_vec());
141
142        // Decode the pack and collect entries
143        pack.decode(
144            &mut cursor,
145            move |entry: MetaAttached<Entry, EntryMeta>| match entry.inner.obj_type {
146                ObjectType::Commit => {
147                    if let Ok(commit) = Commit::from_bytes(&entry.inner.data, entry.inner.hash) {
148                        commits_clone.lock().unwrap().push(commit);
149                    } else {
150                        tracing::warn!("Failed to parse commit from pack entry");
151                    }
152                }
153                ObjectType::Tree => {
154                    if let Ok(tree) = Tree::from_bytes(&entry.inner.data, entry.inner.hash) {
155                        trees_clone.lock().unwrap().push(tree);
156                    } else {
157                        tracing::warn!("Failed to parse tree from pack entry");
158                    }
159                }
160                ObjectType::Blob => {
161                    if let Ok(blob) = Blob::from_bytes(&entry.inner.data, entry.inner.hash) {
162                        blobs_clone.lock().unwrap().push(blob);
163                    } else {
164                        tracing::warn!("Failed to parse blob from pack entry");
165                    }
166                }
167                _ => {
168                    tracing::warn!("Unknown object type in pack: {:?}", entry.inner.obj_type);
169                }
170            },
171            None::<fn(ObjectHash)>,
172        )
173        .map_err(|e| ProtocolError::invalid_request(&format!("Failed to decode pack: {e}")))?;
174
175        // Extract the results
176        let commits_result = Arc::try_unwrap(commits).unwrap().into_inner().unwrap();
177        let trees_result = Arc::try_unwrap(trees).unwrap().into_inner().unwrap();
178        let blobs_result = Arc::try_unwrap(blobs).unwrap().into_inner().unwrap();
179
180        Ok((commits_result, trees_result, blobs_result))
181    }
182
183    /// Collect all objects reachable from the given commit hashes.
184    ///
185    /// Every object handed back by the repository must carry an ID of `kind` (the kind
186    /// captured before the first `.await`): a `RepositoryAccess` whose default accessors
187    /// follow a drifting thread-local kind fails closed here instead of feeding foreign IDs
188    /// into the pack.
189    async fn collect_all_objects(
190        &self,
191        kind: HashKind,
192        commit_hashes: Vec<String>,
193    ) -> Result<(Vec<Commit>, Vec<Tree>, Vec<Blob>), ProtocolError> {
194        let mut commits = Vec::new();
195        let mut trees = Vec::new();
196        let mut blobs = Vec::new();
197
198        let mut visited_commits = HashSet::new();
199        let mut visited_trees = HashSet::new();
200        let mut visited_blobs = HashSet::new();
201
202        let mut commit_queue = VecDeque::from(commit_hashes);
203
204        // BFS traversal of commit graph
205        while let Some(commit_hash) = commit_queue.pop_front() {
206            if visited_commits.contains(&commit_hash) {
207                continue;
208            }
209            visited_commits.insert(commit_hash.clone());
210
211            // Get commit object
212            let commit = self
213                .repo_access
214                .get_commit(&commit_hash)
215                .await
216                .map_err(|e| {
217                    ProtocolError::repository_error(format!(
218                        "Failed to get commit {commit_hash}: {e}"
219                    ))
220                })?;
221            Self::ensure_object_kind(kind, "commit", commit.id)?;
222            // Embedded references are validated before they are turned into raw strings: a
223            // same-width ID of another namespace must never be re-interpreted as `kind`.
224            Self::ensure_object_kind(kind, "commit tree reference", commit.tree_id)?;
225
226            // Add parent commits to queue
227            for parent in &commit.parent_commit_ids {
228                Self::ensure_object_kind(kind, "commit parent reference", *parent)?;
229                let parent_str = parent.to_string();
230                if !visited_commits.contains(&parent_str) {
231                    commit_queue.push_back(parent_str);
232                }
233            }
234
235            // Collect tree objects
236            Box::pin(self.collect_tree_objects(
237                kind,
238                &commit.tree_id.to_string(),
239                &mut trees,
240                &mut blobs,
241                &mut visited_trees,
242                &mut visited_blobs,
243            ))
244            .await?;
245
246            commits.push(commit);
247        }
248
249        Ok((commits, trees, blobs))
250    }
251
252    /// Reject an object whose ID belongs to another format than the repository's `kind`.
253    fn ensure_object_kind(kind: HashKind, what: &str, id: ObjectHash) -> Result<(), ProtocolError> {
254        id.ensure_kind(kind).map_err(|e| {
255            ProtocolError::repository_error(format!(
256                "Repository returned {what} {} of another object format: {e}",
257                id.to_tagged_string()
258            ))
259        })
260    }
261
262    /// Recursively collect tree and blob objects
263    async fn collect_tree_objects(
264        &self,
265        kind: HashKind,
266        tree_hash: &str,
267        trees: &mut Vec<Tree>,
268        blobs: &mut Vec<Blob>,
269        visited_trees: &mut HashSet<String>,
270        visited_blobs: &mut HashSet<String>,
271    ) -> Result<(), ProtocolError> {
272        if visited_trees.contains(tree_hash) {
273            return Ok(());
274        }
275        visited_trees.insert(tree_hash.to_string());
276
277        let tree = self.repo_access.get_tree(tree_hash).await.map_err(|e| {
278            ProtocolError::repository_error(format!("Failed to get tree {tree_hash}: {e}"))
279        })?;
280        Self::ensure_object_kind(kind, "tree", tree.id)?;
281
282        for entry in &tree.tree_items {
283            Self::ensure_object_kind(kind, "tree entry reference", entry.id)?;
284            let entry_hash = entry.id.to_string();
285            match entry.mode {
286                crate::internal::object::tree::TreeItemMode::Tree => {
287                    Box::pin(self.collect_tree_objects(
288                        kind,
289                        &entry_hash,
290                        trees,
291                        blobs,
292                        visited_trees,
293                        visited_blobs,
294                    ))
295                    .await?;
296                }
297                crate::internal::object::tree::TreeItemMode::Blob
298                | crate::internal::object::tree::TreeItemMode::BlobExecutable
299                    if !visited_blobs.contains(&entry_hash) =>
300                {
301                    visited_blobs.insert(entry_hash.clone());
302                    let blob = self.repo_access.get_blob(&entry_hash).await.map_err(|e| {
303                        ProtocolError::repository_error(format!(
304                            "Failed to get blob {entry_hash}: {e}"
305                        ))
306                    })?;
307                    Self::ensure_object_kind(kind, "blob", blob.id)?;
308                    blobs.push(blob);
309                }
310                _ => {}
311            }
312        }
313
314        trees.push(tree);
315        Ok(())
316    }
317
318    /// Filter objects to exclude those already in 'have'
319    fn filter_objects(
320        wanted: (Vec<Commit>, Vec<Tree>, Vec<Blob>),
321        have: (Vec<Commit>, Vec<Tree>, Vec<Blob>),
322    ) -> (Vec<Commit>, Vec<Tree>, Vec<Blob>) {
323        let (wanted_commits, wanted_trees, wanted_blobs) = wanted;
324        let (have_commits, have_trees, have_blobs) = have;
325
326        // Create hash sets for efficient lookup
327        let have_commit_hashes: HashSet<String> =
328            have_commits.iter().map(|c| c.id.to_string()).collect();
329        let have_tree_hashes: HashSet<String> =
330            have_trees.iter().map(|t| t.id.to_string()).collect();
331        let have_blob_hashes: HashSet<String> =
332            have_blobs.iter().map(|b| b.id.to_string()).collect();
333
334        // Filter out objects that are in 'have'
335        let filtered_commits: Vec<Commit> = wanted_commits
336            .into_iter()
337            .filter(|c| !have_commit_hashes.contains(&c.id.to_string()))
338            .collect();
339
340        let filtered_trees: Vec<Tree> = wanted_trees
341            .into_iter()
342            .filter(|t| !have_tree_hashes.contains(&t.id.to_string()))
343            .collect();
344
345        let filtered_blobs: Vec<Blob> = wanted_blobs
346            .into_iter()
347            .filter(|b| !have_blob_hashes.contains(&b.id.to_string()))
348            .collect();
349
350        (filtered_commits, filtered_trees, filtered_blobs)
351    }
352
353    /// Generate pack stream from objects, hashing the trailer with the repository `kind`;
354    /// the encoder refuses entries whose IDs belong to another kind.
355    async fn generate_pack_stream(
356        kind: HashKind,
357        objects: (Vec<Commit>, Vec<Tree>, Vec<Blob>),
358        tx: mpsc::Sender<Result<Vec<u8>, ProtocolError>>,
359    ) -> Result<(), ProtocolError> {
360        let (commits, trees, blobs) = objects;
361
362        // Convert objects to entries
363        let mut entries = Vec::new();
364
365        for commit in commits {
366            entries.push(Entry::from(commit));
367        }
368
369        for tree in trees {
370            entries.push(Entry::from(tree));
371        }
372
373        for blob in blobs {
374            entries.push(Entry::from(blob));
375        }
376
377        // Fail closed before a single PACK byte is emitted: every entry must carry an ID of
378        // the repository kind (the encoder checks this too, but only after the header).
379        for entry in &entries {
380            entry.hash.ensure_kind(kind).map_err(|e| {
381                ProtocolError::Pack(format!(
382                    "Pack entry {} does not belong to the repository object format: {e}",
383                    entry.hash.to_tagged_string()
384                ))
385            })?;
386        }
387
388        // Nothing to send (every wanted object is already on the `have` side): emit a valid
389        // empty pack — header with zero objects plus the trailer of the repository kind —
390        // instead of driving the encoder, which requires at least one object.
391        if entries.is_empty() {
392            let mut header = Vec::with_capacity(12 + kind.size());
393            header.extend_from_slice(b"PACK");
394            header.extend_from_slice(&2u32.to_be_bytes());
395            header.extend_from_slice(&0u32.to_be_bytes());
396            let trailer = ObjectHash::new_for_kind(kind, &header);
397            header.extend_from_slice(trailer.as_ref());
398            // A dropped receiver is not an error for the producer.
399            let _ = tx.send(Ok(header)).await;
400            return Ok(());
401        }
402
403        // Create PackEncoder and encode entries
404        let (pack_tx, mut pack_rx) = mpsc::channel(1024);
405        let (entry_tx, entry_rx) = mpsc::channel(1024);
406        let mut encoder = PackEncoder::new_with_hash_kind(kind, entries.len(), 10, pack_tx); // window_size = 10
407
408        // Spawn encoding task; its result is surfaced below instead of being logged and lost.
409        let encode_task = tokio::spawn(async move { encoder.encode(entry_rx).await });
410
411        // Send entries to encoder
412        tokio::spawn(async move {
413            for entry in entries {
414                if entry_tx
415                    .send(MetaAttached {
416                        inner: entry,
417                        meta: EntryMeta::new(),
418                    })
419                    .await
420                    .is_err()
421                {
422                    break; // Receiver dropped
423                }
424            }
425            // Drop sender to signal end of entries
426        });
427
428        // Forward pack data to output channel
429        let mut consumer_gone = false;
430        while let Some(chunk) = pack_rx.recv().await {
431            if tx.send(Ok(chunk)).await.is_err() {
432                consumer_gone = true; // Receiver dropped
433                break;
434            }
435        }
436        if consumer_gone {
437            // Nobody is listening: drop our end of the encoder channel so the encoder's next
438            // send fails immediately instead of blocking on a full channel forever, then let
439            // the task wind down. There is no one left to report to.
440            drop(pack_rx);
441            let _ = encode_task.await;
442            return Ok(());
443        }
444
445        // An encoder failure is an error of this call, never a "successful" partial stream.
446        match encode_task.await {
447            Ok(Ok(())) => Ok(()),
448            Ok(Err(e)) => Err(ProtocolError::Pack(format!("Failed to encode pack: {e}"))),
449            Err(e) => Err(ProtocolError::Pack(format!(
450                "Pack encoder task failed: {e}"
451            ))),
452        }
453    }
454}
455
456#[cfg(test)]
457mod tests {
458    use async_trait::async_trait;
459    use bytes::Bytes;
460
461    use super::*;
462    use crate::{
463        hash::{HashKind, set_hash_kind_for_test},
464        internal::object::{
465            blob::Blob,
466            commit::Commit,
467            signature::{Signature, SignatureType},
468            tree::{Tree, TreeItem, TreeItemMode},
469        },
470        utils::HashAlgorithm,
471    };
472    /// Dummy repository access for testing
473    #[derive(Clone)]
474    struct DummyRepoAccess;
475
476    #[async_trait]
477    impl RepositoryAccess for DummyRepoAccess {
478        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
479            Ok(vec![])
480        }
481        async fn has_object(&self, _object_hash: &str) -> Result<bool, ProtocolError> {
482            Ok(false)
483        }
484        async fn get_object(&self, _object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
485            Err(ProtocolError::repository_error(
486                "not implemented".to_string(),
487            ))
488        }
489        async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
490            Ok(())
491        }
492        async fn update_reference(
493            &self,
494            _ref_name: &str,
495            _old_hash: Option<&str>,
496            _new_hash: &str,
497        ) -> Result<(), ProtocolError> {
498            Ok(())
499        }
500        async fn get_objects_for_pack(
501            &self,
502            _wants: &[String],
503            _haves: &[String],
504        ) -> Result<Vec<String>, ProtocolError> {
505            Ok(vec![])
506        }
507        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
508            Ok(false)
509        }
510        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
511            Ok(())
512        }
513    }
514
515    /// Encode and decode a pack, asserting that all object IDs survive the roundtrip.
516    async fn run_pack_roundtrip(kind: HashKind) {
517        let _guard = set_hash_kind_for_test(kind);
518        let blob1 = Blob::from_content("hello");
519        let blob2 = Blob::from_content("world");
520
521        let item1 = TreeItem::new(TreeItemMode::Blob, blob1.id, "hello.txt".to_string());
522        let item2 = TreeItem::new(TreeItemMode::Blob, blob2.id, "world.txt".to_string());
523        let tree = Tree::from_tree_items(vec![item1, item2]).unwrap();
524
525        let author = Signature::new(
526            SignatureType::Author,
527            "tester".to_string(),
528            "tester@example.com".to_string(),
529        );
530        let committer = Signature::new(
531            SignatureType::Committer,
532            "tester".to_string(),
533            "tester@example.com".to_string(),
534        );
535        let commit = Commit::new(author, committer, tree.id, vec![], "init commit");
536
537        let (tx, mut rx) = mpsc::channel::<Result<Vec<u8>, ProtocolError>>(64);
538        PackGenerator::<DummyRepoAccess>::generate_pack_stream(
539            kind,
540            (
541                vec![commit.clone()],
542                vec![tree.clone()],
543                vec![blob1.clone(), blob2.clone()],
544            ),
545            tx,
546        )
547        .await
548        .unwrap();
549
550        let mut pack_bytes: Vec<u8> = Vec::new();
551        while let Some(chunk) = rx.recv().await {
552            pack_bytes.extend_from_slice(&chunk.unwrap());
553        }
554
555        let dummy = DummyRepoAccess;
556        let generator = PackGenerator::new(&dummy);
557        let (decoded_commits, decoded_trees, decoded_blobs) = generator
558            .unpack_stream(Bytes::from(pack_bytes))
559            .await
560            .unwrap();
561
562        assert_eq!(decoded_commits.len(), 1);
563        assert_eq!(decoded_trees.len(), 1);
564        assert_eq!(decoded_blobs.len(), 2);
565
566        assert_eq!(decoded_commits[0].id, commit.id);
567        assert_eq!(decoded_trees[0].id, tree.id);
568
569        let mut orig_blob_ids = vec![blob1.id.to_string(), blob2.id.to_string()];
570        orig_blob_ids.sort_unstable();
571        let mut decoded_blob_ids = decoded_blobs
572            .iter()
573            .map(|b| b.id.to_string())
574            .collect::<Vec<_>>();
575        decoded_blob_ids.sort_unstable();
576        assert_eq!(orig_blob_ids, decoded_blob_ids);
577    }
578
579    /// Pack encode/decode roundtrip using SHA-1 and SHA-256
580    #[tokio::test]
581    async fn test_pack_roundtrip_encode_decode() {
582        run_pack_roundtrip(HashKind::Sha1).await;
583        run_pack_roundtrip(HashKind::Sha256).await;
584    }
585
586    /// Repository access that reports a fixed object format.
587    #[derive(Clone)]
588    struct KindRepoAccess(HashKind);
589
590    #[async_trait]
591    impl RepositoryAccess for KindRepoAccess {
592        fn object_hash_kind(&self) -> HashKind {
593            self.0
594        }
595        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
596            Ok(vec![])
597        }
598        async fn has_object(&self, _object_hash: &str) -> Result<bool, ProtocolError> {
599            Ok(false)
600        }
601        async fn get_object(&self, _object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
602            Err(ProtocolError::ObjectNotFound("dummy".to_string()))
603        }
604        async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
605            Ok(())
606        }
607        async fn update_reference(
608            &self,
609            _ref_name: &str,
610            _old_hash: Option<&str>,
611            _new_hash: &str,
612        ) -> Result<(), ProtocolError> {
613            Ok(())
614        }
615        async fn get_objects_for_pack(
616            &self,
617            _wants: &[String],
618            _haves: &[String],
619        ) -> Result<Vec<String>, ProtocolError> {
620            Ok(vec![])
621        }
622        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
623            Ok(false)
624        }
625        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
626            Ok(())
627        }
628    }
629
630    /// BLAKE3 repository: the protocol pack path consumes explicit-kind `ObjectHash`es —
631    /// generation and unpacking follow `object_hash_kind()` (thread-local kind is SHA-1), the
632    /// trailer is a BLAKE3 checksum, a SHA-256 repository rejects the same bytes (same ID
633    /// width, different kind: nothing is inferred from the width), and cross-kind entries
634    /// never produce a decodable BLAKE3 pack.
635    #[tokio::test]
636    async fn blake3_round_trip() {
637        let _guard = set_hash_kind_for_test(HashKind::Sha1);
638        let kind = HashKind::Blake3;
639        let blob1 = Blob::from_content_with_kind(kind, "hello").unwrap();
640        let blob2 = Blob::from_content_with_kind(kind, "world").unwrap();
641        let item1 = TreeItem::new(TreeItemMode::Blob, blob1.id, "hello.txt".to_string());
642        let item2 = TreeItem::new(TreeItemMode::Blob, blob2.id, "world.txt".to_string());
643        let tree = Tree::from_tree_items_with_kind(kind, vec![item1, item2]).unwrap();
644        let author = Signature::new(
645            SignatureType::Author,
646            "tester".to_string(),
647            "tester@example.com".to_string(),
648        );
649        let committer = Signature::new(
650            SignatureType::Committer,
651            "tester".to_string(),
652            "tester@example.com".to_string(),
653        );
654        let commit =
655            Commit::new_with_kind(kind, author, committer, tree.id, vec![], "init commit").unwrap();
656        assert_eq!(commit.id.kind(), HashKind::Blake3);
657
658        let (tx, mut rx) = mpsc::channel::<Result<Vec<u8>, ProtocolError>>(64);
659        PackGenerator::<KindRepoAccess>::generate_pack_stream(
660            kind,
661            (
662                vec![commit.clone()],
663                vec![tree.clone()],
664                vec![blob1.clone(), blob2.clone()],
665            ),
666            tx,
667        )
668        .await
669        .unwrap();
670        let mut pack_bytes: Vec<u8> = Vec::new();
671        while let Some(chunk) = rx.recv().await {
672            pack_bytes.extend_from_slice(&chunk.unwrap());
673        }
674
675        // Trailer: 32-byte BLAKE3 checksum of the payload (not SHA-256).
676        let (payload, trailer) = pack_bytes.split_at(pack_bytes.len() - kind.size());
677        let mut hasher = HashAlgorithm::new_for_kind(kind);
678        hasher.update(payload);
679        let expected = hasher.finalize_object_hash();
680        assert_eq!(
681            ObjectHash::from_bytes_for_kind(kind, trailer).unwrap(),
682            expected
683        );
684        let mut sha256 = HashAlgorithm::new_for_kind(HashKind::Sha256);
685        sha256.update(payload);
686        assert_ne!(sha256.finalize_object_hash().as_ref(), trailer);
687
688        let repo = KindRepoAccess(kind);
689        let (commits, trees, blobs) = PackGenerator::new(&repo)
690            .unpack_stream(Bytes::from(pack_bytes.clone()))
691            .await
692            .unwrap();
693        assert_eq!(commits.len(), 1);
694        assert_eq!(trees.len(), 1);
695        assert_eq!(blobs.len(), 2);
696        assert_eq!(commits[0].id, commit.id);
697        assert_eq!(trees[0].id, tree.id);
698        let mut blob_ids = blobs.iter().map(|b| b.id).collect::<Vec<_>>();
699        blob_ids.sort_unstable_by_key(|id| id.to_string());
700        let mut expected_ids = vec![blob1.id, blob2.id];
701        expected_ids.sort_unstable_by_key(|id| id.to_string());
702        assert_eq!(blob_ids, expected_ids);
703        for id in commits
704            .iter()
705            .map(|c| c.id)
706            .chain(trees.iter().map(|t| t.id))
707            .chain(blob_ids)
708        {
709            assert_eq!(id.kind(), HashKind::Blake3);
710        }
711
712        // Same bytes offered to a SHA-256 repository: rejected, never re-interpreted.
713        let sha256_repo = KindRepoAccess(HashKind::Sha256);
714        assert!(
715            PackGenerator::new(&sha256_repo)
716                .unpack_stream(Bytes::from(pack_bytes))
717                .await
718                .is_err()
719        );
720
721        // A SHA-1 entry cannot be packed as BLAKE3: refused before a single byte is emitted.
722        let sha1_blob = Blob::from_content("hello");
723        assert_eq!(sha1_blob.id.kind(), HashKind::Sha1);
724        let (tx, mut rx) = mpsc::channel::<Result<Vec<u8>, ProtocolError>>(64);
725        let err = PackGenerator::<KindRepoAccess>::generate_pack_stream(
726            kind,
727            (vec![], vec![], vec![sha1_blob.clone()]),
728            tx,
729        )
730        .await
731        .unwrap_err();
732        assert!(matches!(err, ProtocolError::Pack(_)), "{err:?}");
733        assert!(err.to_string().contains("sha1:"), "{err}");
734        assert!(rx.recv().await.is_none(), "no pack bytes may be emitted");
735
736        // Through the background producer the same failure is delivered as the stream's only
737        // item, an `Err` (never a silent EOF / truncated pack).
738        let mut stream = PackGenerator::<KindRepoAccess>::spawn_pack_stream(
739            kind,
740            (vec![], vec![], vec![sha1_blob]),
741        );
742        let first = futures::StreamExt::next(&mut stream)
743            .await
744            .expect("an item");
745        let err = first.expect_err("producer failure must surface as Err");
746        assert!(matches!(err, ProtocolError::Pack(_)), "{err:?}");
747        assert!(futures::StreamExt::next(&mut stream).await.is_none());
748
749        // A repository that reports BLAKE3 but hands back objects of another format (kind
750        // drift behind the default accessors) is refused during collection.
751        let drift = DriftRepo {
752            commit: Commit::from_tree_id_with_kind(
753                HashKind::Sha1,
754                Tree::from_tree_items_with_kind(
755                    HashKind::Sha1,
756                    vec![TreeItem::new(
757                        TreeItemMode::Blob,
758                        Blob::from_content("d").id,
759                        "d".to_string(),
760                    )],
761                )
762                .unwrap()
763                .id,
764                vec![],
765                "drift",
766            )
767            .unwrap(),
768        };
769        let err = PackGenerator::new(&drift)
770            .collect_all_objects(HashKind::Blake3, vec![drift.commit.id.to_string()])
771            .await
772            .unwrap_err();
773        assert!(
774            err.to_string().contains("another object format")
775                && err.to_string().contains("expected blake3"),
776            "{err}"
777        );
778        // The generator's kind is captured at construction (`new` observes the repository
779        // once; `new_with_hash_kind` takes the validated kind) and is what every pack uses.
780        assert_eq!(PackGenerator::new(&drift).hash_kind(), HashKind::Blake3);
781        assert_eq!(
782            PackGenerator::new_with_hash_kind(&repo, HashKind::Blake3).hash_kind(),
783            HashKind::Blake3
784        );
785
786        // A BLAKE3 commit whose *embedded* parent reference is a same-width SHA-256 ID is
787        // refused before the reference is turned into a raw string (never re-interpreted).
788        let mut poisoned = commit.clone();
789        poisoned.parent_commit_ids.push(ObjectHash::new_for_kind(
790            HashKind::Sha256,
791            b"foreign parent",
792        ));
793        let err = PackGenerator::new(&DriftRepo { commit: poisoned })
794            .collect_all_objects(HashKind::Blake3, vec![commit.id.to_string()])
795            .await
796            .unwrap_err();
797        assert!(
798            err.to_string().contains("commit parent reference")
799                && err.to_string().contains("expected blake3")
800                && err.to_string().contains("got sha256"),
801            "{err}"
802        );
803
804        // A consumer that drops the stream must not hang the producer.
805        let (tx, rx) = mpsc::channel::<Result<Vec<u8>, ProtocolError>>(1);
806        drop(rx);
807        let big: Vec<Blob> = (0..64)
808            .map(|i| {
809                Blob::from_content_with_kind(kind, &format!("chunk {i} {}", "y".repeat(4096)))
810                    .unwrap()
811            })
812            .collect();
813        tokio::time::timeout(
814            std::time::Duration::from_secs(30),
815            PackGenerator::<KindRepoAccess>::generate_pack_stream(kind, (vec![], vec![], big), tx),
816        )
817        .await
818        .expect("producer must finish when the consumer is gone")
819        .unwrap();
820    }
821
822    /// Reports BLAKE3 but returns a SHA-1 commit from `get_commit`.
823    #[derive(Clone)]
824    struct DriftRepo {
825        commit: Commit,
826    }
827
828    #[async_trait]
829    impl RepositoryAccess for DriftRepo {
830        fn object_hash_kind(&self) -> HashKind {
831            HashKind::Blake3
832        }
833        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
834            Ok(vec![])
835        }
836        async fn has_object(&self, _object_hash: &str) -> Result<bool, ProtocolError> {
837            Ok(true)
838        }
839        async fn get_object(&self, _object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
840            Err(ProtocolError::ObjectNotFound("drift".to_string()))
841        }
842        async fn get_commit(&self, _commit_hash: &str) -> Result<Commit, ProtocolError> {
843            Ok(self.commit.clone())
844        }
845        async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
846            Ok(())
847        }
848        async fn update_reference(
849            &self,
850            _ref_name: &str,
851            _old_hash: Option<&str>,
852            _new_hash: &str,
853        ) -> Result<(), ProtocolError> {
854            Ok(())
855        }
856        async fn get_objects_for_pack(
857            &self,
858            _wants: &[String],
859            _haves: &[String],
860        ) -> Result<Vec<String>, ProtocolError> {
861            Ok(vec![])
862        }
863        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
864            Ok(false)
865        }
866        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
867            Ok(())
868        }
869    }
870}