Skip to main content

gix_protocol/fetch/response/
mod.rs

1use bstr::BString;
2use gix_error::{Error, Result, ResultExt, bail, message, unsupported};
3use gix_transport::Protocol;
4
5use crate::{command::Feature, fetch::Response};
6
7fn unknown_line(line: &str) -> Error {
8    message!("Encountered an unknown line prefix in {line:?}").corrupted_error()
9}
10
11/// An 'ACK' line received from the server.
12#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)]
13#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
14pub enum Acknowledgement {
15    /// The contained `id` is in common.
16    Common(gix_hash::ObjectId),
17    /// The server is ready to receive more lines.
18    Ready,
19    /// The server isn't ready yet.
20    Nak,
21}
22
23pub use gix_shallow::Update as ShallowUpdate;
24
25/// A wanted-ref line received from the server.
26#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
28pub struct WantedRef {
29    /// The object id of the wanted ref, as seen by the server.
30    pub id: gix_hash::ObjectId,
31    /// The name of the ref, as requested by the client as a `want-ref` argument.
32    pub path: BString,
33}
34
35/// Parse a `ShallowUpdate` from a `line` as received to the server.
36pub fn shallow_update_from_line(line: &str) -> Result<ShallowUpdate> {
37    match line.trim_end().split_once(' ') {
38        Some((prefix, id)) => {
39            let id = gix_hash::ObjectId::from_hex(id.as_bytes())
40                .or_raise(|| message!("Encountered an unknown line prefix in {line:?}").corrupted())?;
41            Ok(match prefix {
42                "shallow" => ShallowUpdate::Shallow(id),
43                "unshallow" => ShallowUpdate::Unshallow(id),
44                _ => return Err(unknown_line(line)),
45            })
46        }
47        None => Err(unknown_line(line)),
48    }
49}
50
51impl Acknowledgement {
52    /// Parse an `Acknowledgement` from a `line` as received to the server.
53    pub fn from_line(line: &str) -> Result<Acknowledgement> {
54        let mut tokens = line.trim_end().splitn(3, ' ');
55        match (tokens.next(), tokens.next(), tokens.next()) {
56            (Some(first), id, description) => Ok(match first {
57                "ready" => Acknowledgement::Ready, // V2
58                "NAK" => Acknowledgement::Nak,     // V1
59                "ACK" => {
60                    let id = match id {
61                        Some(id) => gix_hash::ObjectId::from_hex(id.as_bytes())
62                            .or_raise(|| message!("Encountered an unknown line prefix in {line:?}").corrupted())?,
63                        None => return Err(unknown_line(line)),
64                    };
65                    if let Some(description) = description {
66                        match description {
67                            "common" => {}
68                            "ready" => return Ok(Acknowledgement::Ready),
69                            _ => return Err(unknown_line(line)),
70                        }
71                    }
72                    Acknowledgement::Common(id)
73                }
74                _ => return Err(unknown_line(line)),
75            }),
76            (None, _, _) => Err(unknown_line(line)),
77        }
78    }
79    /// Returns the hash of the acknowledged object if this instance acknowledges a common one.
80    pub fn id(&self) -> Option<&gix_hash::ObjectId> {
81        match self {
82            Acknowledgement::Common(id) => Some(id),
83            _ => None,
84        }
85    }
86}
87
88impl WantedRef {
89    /// Parse a `WantedRef` from a `line` as received from the server.
90    pub fn from_line(line: &str) -> Result<WantedRef> {
91        match line.trim_end().split_once(' ') {
92            Some((id, path)) => {
93                let id = gix_hash::ObjectId::from_hex(id.as_bytes())
94                    .or_raise(|| message!("Encountered an unknown line prefix in {line:?}").corrupted())?;
95                Ok(WantedRef { id, path: path.into() })
96            }
97            None => Err(unknown_line(line)),
98        }
99    }
100}
101
102impl Response {
103    /// Return true if the response has a pack which can be read next.
104    pub fn has_pack(&self) -> bool {
105        self.has_pack
106    }
107
108    /// Return an error if the given `features` don't contain the required ones (the ones this implementation needs)
109    /// for the given `version` of the protocol.
110    ///
111    /// Even though technically any set of features supported by the server could work, we only implement the ones that
112    /// make it easy to maintain all versions with a single code base that aims to be and remain maintainable.
113    pub fn check_required_features(version: Protocol, features: &[Feature]) -> Result {
114        match version {
115            Protocol::V0 | Protocol::V1 => {
116                let has = |name: &str| features.iter().any(|f| f.0 == name);
117                // Let's focus on V2 standards, and simply not support old servers to keep our code simpler
118                if !has("multi_ack_detailed") {
119                    bail!(unsupported(
120                        "Currently we require feature \"multi_ack_detailed\", which is not supported by the server",
121                    ));
122                }
123                // It's easy to NOT do sideband for us, but then again, everyone supports it.
124                // CORRECTION: If sideband is off, it would send the packfile without packet line encoding,
125                // which is nothing we ever want to deal with (despite it being more efficient). In V2, this
126                // is not even an option anymore, sidebands are always present.
127                if !has("side-band") && !has("side-band-64k") {
128                    bail!(unsupported(
129                        "Currently we require feature \"side-band OR side-band-64k\", which is not supported by the server"
130                    ));
131                }
132            }
133            Protocol::V2 => {}
134        }
135        Ok(())
136    }
137
138    /// Return all acknowledgements [parsed previously][Response::from_line_reader()].
139    pub fn acknowledgements(&self) -> &[Acknowledgement] {
140        &self.acks
141    }
142
143    /// Return all shallow update lines [parsed previously][Response::from_line_reader()].
144    pub fn shallow_updates(&self) -> &[ShallowUpdate] {
145        &self.shallows
146    }
147
148    /// Append the given `updates` which may have been obtained from a
149    /// (handshake::Outcome)[crate::Handshake::v1_shallow_updates].
150    ///
151    /// In V2, these are received as part of the pack, but V1 sends them early, so we
152    /// offer to re-integrate them here.
153    pub fn append_v1_shallow_updates(&mut self, updates: Option<Vec<ShallowUpdate>>) {
154        self.shallows.extend(updates.into_iter().flatten());
155    }
156
157    /// Return all wanted-refs [parsed previously][Response::from_line_reader()].
158    pub fn wanted_refs(&self) -> &[WantedRef] {
159        &self.wanted_refs
160    }
161}
162
163#[cfg(any(feature = "async-client", feature = "blocking-client"))]
164impl Response {
165    /// with a friendly server, we just assume that a non-ack line is a pack line
166    /// which is our hint to stop here.
167    fn parse_v1_ack_or_shallow_or_assume_pack(
168        acks: &mut Vec<Acknowledgement>,
169        shallows: &mut Vec<ShallowUpdate>,
170        peeked_line: &str,
171    ) -> bool {
172        match Acknowledgement::from_line(peeked_line) {
173            Ok(ack) => match ack.id() {
174                Some(id) => {
175                    if !acks.iter().any(|a| a.id() == Some(id)) {
176                        acks.push(ack);
177                    }
178                }
179                None => acks.push(ack),
180            },
181            Err(_) => match shallow_update_from_line(peeked_line) {
182                Ok(shallow) => {
183                    shallows.push(shallow);
184                }
185                Err(_) => return true,
186            },
187        }
188        false
189    }
190}
191
192#[cfg(any(feature = "async-client", feature = "blocking-client"))]
193mod io;