Skip to main content

gix_protocol/fetch/
function.rs

1use std::{
2    path::Path,
3    sync::atomic::{AtomicBool, Ordering},
4};
5
6use gix_error::{Result, ResultExt, bail, message, validation};
7use gix_utils::progress::DynNestedProgress;
8
9use crate::fetch::{
10    Arguments, Context, Negotiate, NegotiateOutcome, Options, Outcome, ProgressId, Shallow, Tags, negotiate,
11};
12#[crate::bisync::only_async]
13use crate::transport::client::async_io::{ExtendedBufRead, HandleProgress, Transport};
14#[crate::bisync::only_sync]
15use crate::transport::client::blocking_io::{ExtendedBufRead, HandleProgress, Transport};
16
17/// Perform one fetch operation, relying on a `transport`.
18/// `negotiate` is used to run the negotiation of objects that should be contained in the pack, *if* one is to be received.
19/// `progress` and `should_interrupt` is passed to all potentially long-running parts of the operation.
20///
21/// `consume_pack(pack_read, progress, interrupt) -> bool` is always called to consume all bytes that are sent by the server, returning `true` if we should assure the pack is read to the end,
22/// or `false` to do nothing. Dropping the reader without reading to EOF (i.e. returning `false`) is an offense to the server, and
23/// `transport` won't be in the correct state to perform additional operations, or indicate the end of operation.
24/// Note that the passed reader blocking as the pack-writing is blocking as well.
25///
26/// The `Context` and `Options` further define parts of this `fetch` operation.
27///
28/// As opposed to a full `git fetch`, this operation does *not*…
29///
30/// * …update local refs
31/// * …end the interaction after the fetch
32///
33/// **Note that the interaction will never be ended**, even on error or failure, leaving it up to the caller to do that, maybe
34/// with the help of [`SendFlushOnDrop`](crate::SendFlushOnDrop) which can wrap `transport`.
35/// Generally, the `transport` is left in a state that allows for more commands to be run.
36///
37/// Return `Ok(None)` if there was nothing to do because all remote refs are at the same state as they are locally,
38/// or there was nothing wanted, or `Ok(Some(outcome))` to inform about all the changes that were made.
39#[crate::bisync::bisync]
40pub async fn fetch<P, T>(
41    negotiate: &mut impl Negotiate,
42    consume_pack: impl FnOnce(&mut dyn std::io::BufRead, &mut dyn DynNestedProgress, &AtomicBool) -> Result<bool>,
43    mut progress: P,
44    should_interrupt: &AtomicBool,
45    Context {
46        handshake,
47        transport,
48        user_agent,
49        trace_packetlines,
50    }: Context<'_, T>,
51    Options {
52        shallow_file,
53        shallow,
54        tags,
55        reject_shallow_remote,
56    }: Options<'_>,
57) -> Result<Option<Outcome>>
58where
59    P: gix_utils::progress::NestedProgress,
60    P::SubProgress: 'static,
61    T: Transport,
62{
63    let _span = gix_trace::coarse!("gix_protocol::fetch()");
64    let v1_shallow_updates = handshake.v1_shallow_updates.take();
65    let protocol_version = handshake.server_protocol_version;
66
67    let fetch = crate::Command::Fetch;
68    let fetch_features = {
69        let mut f = fetch.default_features(protocol_version, &handshake.capabilities);
70        f.push(user_agent);
71        f
72    };
73
74    crate::fetch::Response::check_required_features(protocol_version, &fetch_features)?;
75    let sideband_all = fetch_features.iter().any(|(n, _)| *n == "sideband-all");
76    let mut arguments = Arguments::new(protocol_version, fetch_features, trace_packetlines);
77    if matches!(tags, Tags::Included) {
78        if !arguments.can_use_include_tag() {
79            bail!(gix_error::unsupported(
80                "Server lack feature \"include-tag\": To make this work we would have to implement another pass to fetch attached tags separately"
81            ));
82        }
83        arguments.use_include_tag();
84    }
85    let (shallow_commits, mut shallow_lock) = add_shallow_args(&mut arguments, shallow, &shallow_file)?;
86
87    let negotiate_span = gix_trace::detail!(
88        "negotiate",
89        protocol_version = handshake.server_protocol_version as usize
90    );
91    let action = negotiate
92        .mark_complete_and_common_ref()
93        .or_raise(|| message("Failed to prepare fetch negotiation"))?;
94    let mut previous_response = None::<crate::fetch::Response>;
95    match &action {
96        negotiate::Action::NoChange | negotiate::Action::SkipToRefUpdate => Ok(None),
97        negotiate::Action::MustNegotiate {
98            remote_ref_target_known,
99        } => {
100            if !negotiate.add_wants(&mut arguments, remote_ref_target_known) {
101                return Ok(None);
102            }
103            let mut rounds = Vec::new();
104            let is_stateless = arguments.is_stateless(!transport.connection_persists_across_multiple_requests());
105            let mut state = negotiate::one_round::State::new(is_stateless);
106            let reader = 'negotiation: loop {
107                let _round = gix_trace::detail!("negotiate round", round = rounds.len() + 1);
108                progress.step();
109                progress.set_name(format!("negotiate (round {})", rounds.len() + 1));
110                if should_interrupt.load(Ordering::Relaxed) {
111                    bail!(
112                        "We were unable to figure out what objects the server should send after {} round(s)"
113                            .cancelled(),
114                        rounds.len()
115                    );
116                }
117
118                let (round, is_done) = negotiate
119                    .one_round(&mut state, &mut arguments, previous_response.as_ref())
120                    .or_raise(|| message("Failed to negotiate objects with the server"))?;
121                rounds.push(round);
122                let mut reader = arguments
123                    .send(transport, is_done)
124                    .await
125                    .or_raise(|| message("Failed to send fetch arguments"))?;
126                if sideband_all {
127                    setup_remote_progress(&mut progress, &mut reader, should_interrupt);
128                }
129                let response =
130                    crate::fetch::Response::from_line_reader(protocol_version, &mut reader, is_done, !is_done)
131                        .await
132                        .or_raise(|| message("Could not decode server reply"))?;
133                let has_pack = response.has_pack();
134                previous_response = Some(response);
135                if has_pack {
136                    progress.step();
137                    progress.set_name("receiving pack".into());
138                    if !sideband_all {
139                        setup_remote_progress(&mut progress, &mut reader, should_interrupt);
140                    }
141                    break 'negotiation reader;
142                }
143            };
144            // This needs drop if tracing is compiled in. We just don't know it.
145            drop(negotiate_span);
146
147            let mut previous_response = previous_response.expect("knowledge of a pack means a response was received");
148            previous_response.append_v1_shallow_updates(v1_shallow_updates);
149            if !previous_response.shallow_updates().is_empty() && shallow_lock.is_none() {
150                if reject_shallow_remote {
151                    bail!(validation(
152                        "Receiving objects from shallow remotes is prohibited due to the value of `clone.rejectShallow`"
153                    ));
154                }
155                shallow_lock = acquire_shallow_lock(&shallow_file).map(Some)?;
156            }
157
158            let (mut reader, may_read_to_end) =
159                consume_received_pack(reader, consume_pack, &mut progress, should_interrupt)?;
160
161            if may_read_to_end {
162                // Assure the final flush packet is consumed.
163                let has_read_to_end = reader.stopped_at().is_some();
164                if !has_read_to_end {
165                    read_remaining(&mut reader)
166                        .await
167                        .or_raise(|| message("Failed to read remaining bytes in stream"))?;
168                }
169            }
170            drop(reader);
171
172            if let Some(shallow_lock) = shallow_lock
173                && !previous_response.shallow_updates().is_empty()
174            {
175                gix_shallow::write(shallow_lock, shallow_commits, previous_response.shallow_updates()).or_raise(
176                    || message("Could not write 'shallow' file to incorporate remote updates after fetching"),
177                )?;
178            }
179            Ok(Some(Outcome {
180                last_response: previous_response,
181                negotiate: NegotiateOutcome { action, rounds },
182            }))
183        }
184    }
185}
186
187#[crate::bisync::only_async]
188fn consume_received_pack<R>(
189    reader: R,
190    consume: impl FnOnce(&mut dyn std::io::BufRead, &mut dyn DynNestedProgress, &AtomicBool) -> Result<bool>,
191    progress: &mut dyn DynNestedProgress,
192    should_interrupt: &AtomicBool,
193) -> Result<(R, bool)>
194where
195    R: crate::futures_io::AsyncBufRead + Unpin,
196{
197    let mut reader = crate::futures_lite::io::BlockOn::new(reader);
198    let may_read_to_end = consume(&mut reader, progress, should_interrupt)
199        .or_raise(|| message("Failed to consume the pack sent by the remote"))?;
200    Ok((reader.into_inner(), may_read_to_end))
201}
202
203#[crate::bisync::only_sync]
204fn consume_received_pack<R>(
205    mut reader: R,
206    consume: impl FnOnce(&mut dyn std::io::BufRead, &mut dyn DynNestedProgress, &AtomicBool) -> Result<bool>,
207    progress: &mut dyn DynNestedProgress,
208    should_interrupt: &AtomicBool,
209) -> Result<(R, bool)>
210where
211    R: std::io::BufRead,
212{
213    let may_read_to_end = consume(&mut reader, progress, should_interrupt)
214        .or_raise(|| message("Failed to consume the pack sent by the remote"))?;
215    Ok((reader, may_read_to_end))
216}
217
218#[crate::bisync::only_async]
219async fn read_remaining(reader: &mut (impl crate::futures_io::AsyncRead + Unpin)) -> std::io::Result<()> {
220    crate::futures_lite::io::copy(reader, &mut crate::futures_lite::io::sink())
221        .await
222        .map(|_| ())
223}
224
225#[crate::bisync::only_sync]
226fn read_remaining(reader: &mut impl std::io::Read) -> std::io::Result<()> {
227    std::io::copy(reader, &mut std::io::sink()).map(|_| ())
228}
229
230fn acquire_shallow_lock(shallow_file: &Path) -> Result<gix_lock::File> {
231    gix_lock::File::acquire_to_update_resource(shallow_file, gix_lock::acquire::Fail::Immediately, None, 0)
232        .or_raise(|| message("'shallow' file could not be locked in preparation for writing changes"))
233}
234
235fn add_shallow_args(
236    args: &mut Arguments,
237    shallow: &Shallow,
238    shallow_file: &std::path::Path,
239) -> Result<(Option<nonempty::NonEmpty<gix_hash::ObjectId>>, Option<gix_lock::File>)> {
240    let expect_change = *shallow != Shallow::NoChange;
241    let shallow_lock = expect_change.then(|| acquire_shallow_lock(shallow_file)).transpose()?;
242
243    let shallow_commits = gix_shallow::read(shallow_file)
244        .or_raise(|| message("Could not read 'shallow' file to send current shallow boundary"))?;
245    if (shallow_commits.is_some() || expect_change) && !args.can_use_shallow() {
246        // NOTE: if this is an issue, we can always unshallow the repo ourselves.
247        bail!(validation(
248            "Server lack feature \"shallow\": shallow clones need server support to remain shallow, otherwise bigger than expected packs are sent effectively unshallowing the repository"
249        ));
250    }
251    if let Some(shallow_commits) = &shallow_commits {
252        for commit in shallow_commits.iter() {
253            args.shallow(commit);
254        }
255    }
256    match shallow {
257        Shallow::NoChange => {}
258        Shallow::DepthAtRemote(commits) => args.deepen(commits.get() as usize),
259        Shallow::Deepen(commits) => {
260            args.deepen(*commits as usize);
261            args.deepen_relative();
262        }
263        Shallow::Since { cutoff } => {
264            args.deepen_since(cutoff.seconds);
265        }
266        Shallow::Exclude {
267            remote_refs,
268            since_cutoff,
269        } => {
270            if let Some(cutoff) = since_cutoff {
271                args.deepen_since(cutoff.seconds);
272            }
273            for ref_ in remote_refs {
274                args.deepen_not(ref_.as_ref().as_bstr());
275            }
276        }
277    }
278    Ok((shallow_commits, shallow_lock))
279}
280
281fn setup_remote_progress<'a>(
282    progress: &mut dyn gix_utils::progress::DynNestedProgress,
283    reader: &mut Box<dyn ExtendedBufRead<'a> + Unpin + 'a>,
284    should_interrupt: &'a AtomicBool,
285) {
286    reader.set_progress_handler(Some(Box::new({
287        let mut remote_progress = progress.add_child_with_id("remote".to_string(), ProgressId::RemoteProgress.into());
288        move |is_err: bool, data: &[u8]| {
289            crate::RemoteProgress::translate_to_progress(is_err, data, &mut remote_progress);
290            if should_interrupt.load(Ordering::Relaxed) {
291                std::ops::ControlFlow::Break(())
292            } else {
293                std::ops::ControlFlow::Continue(())
294            }
295        }
296    }) as HandleProgress<'a>));
297}