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 no_done = fetch_features.iter().any(|(n, _)| *n == "no-done");
77    let mut arguments = Arguments::new(protocol_version, fetch_features, trace_packetlines);
78    if matches!(tags, Tags::Included) {
79        if !arguments.can_use_include_tag() {
80            bail!(gix_error::unsupported(
81                "Server lack feature \"include-tag\": To make this work we would have to implement another pass to fetch attached tags separately"
82            ));
83        }
84        arguments.use_include_tag();
85    }
86    let (shallow_commits, mut shallow_lock) = add_shallow_args(&mut arguments, shallow, &shallow_file)?;
87
88    let negotiate_span = gix_trace::detail!(
89        "negotiate",
90        protocol_version = handshake.server_protocol_version as usize
91    );
92    let action = negotiate
93        .mark_complete_and_common_ref()
94        .or_raise(|| message("Failed to prepare fetch negotiation"))?;
95    let mut previous_response = None::<crate::fetch::Response>;
96    match &action {
97        negotiate::Action::NoChange | negotiate::Action::SkipToRefUpdate => Ok(None),
98        negotiate::Action::MustNegotiate {
99            remote_ref_target_known,
100        } => {
101            if !negotiate.add_wants(&mut arguments, remote_ref_target_known) {
102                return Ok(None);
103            }
104            let mut rounds = Vec::new();
105            let is_stateless = arguments.is_stateless(!transport.connection_persists_across_multiple_requests());
106            let mut state = negotiate::one_round::State::new(is_stateless);
107            let reader = 'negotiation: loop {
108                let _round = gix_trace::detail!("negotiate round", round = rounds.len() + 1);
109                progress.step();
110                progress.set_name(format!("negotiate (round {})", rounds.len() + 1));
111                if should_interrupt.load(Ordering::Relaxed) {
112                    bail!(
113                        "We were unable to figure out what objects the server should send after {} round(s)"
114                            .cancelled(),
115                        rounds.len()
116                    );
117                }
118
119                let (round, is_done) = negotiate
120                    .one_round(&mut state, &mut arguments, previous_response.as_ref())
121                    .or_raise(|| message("Failed to negotiate objects with the server"))?;
122                rounds.push(round);
123                let mut reader = arguments
124                    .send(transport, is_done)
125                    .await
126                    .or_raise(|| message("Failed to send fetch arguments"))?;
127                if sideband_all {
128                    setup_remote_progress(&mut progress, &mut reader, should_interrupt);
129                }
130                let response = crate::fetch::Response::from_line_reader(
131                    protocol_version,
132                    &mut reader,
133                    is_done || no_done,
134                    !is_done,
135                )
136                .await
137                .or_raise(|| message("Could not decode server reply"))?;
138                let has_pack = response.has_pack();
139                previous_response = Some(response);
140                if has_pack {
141                    progress.step();
142                    progress.set_name("receiving pack".into());
143                    if !sideband_all {
144                        setup_remote_progress(&mut progress, &mut reader, should_interrupt);
145                    }
146                    break 'negotiation reader;
147                }
148            };
149            // This needs drop if tracing is compiled in. We just don't know it.
150            drop(negotiate_span);
151
152            let mut previous_response = previous_response.expect("knowledge of a pack means a response was received");
153            previous_response.append_v1_shallow_updates(v1_shallow_updates);
154            if !previous_response.shallow_updates().is_empty() && shallow_lock.is_none() {
155                if reject_shallow_remote {
156                    bail!(validation(
157                        "Receiving objects from shallow remotes is prohibited due to the value of `clone.rejectShallow`"
158                    ));
159                }
160                shallow_lock = acquire_shallow_lock(&shallow_file).map(Some)?;
161            }
162
163            let (mut reader, may_read_to_end) =
164                consume_received_pack(reader, consume_pack, &mut progress, should_interrupt)?;
165
166            if may_read_to_end {
167                // Assure the final flush packet is consumed.
168                let has_read_to_end = reader.stopped_at().is_some();
169                if !has_read_to_end {
170                    read_remaining(&mut reader)
171                        .await
172                        .or_raise(|| message("Failed to read remaining bytes in stream"))?;
173                }
174            }
175            drop(reader);
176
177            if let Some(shallow_lock) = shallow_lock
178                && !previous_response.shallow_updates().is_empty()
179            {
180                gix_shallow::write(shallow_lock, shallow_commits, previous_response.shallow_updates()).or_raise(
181                    || message("Could not write 'shallow' file to incorporate remote updates after fetching"),
182                )?;
183            }
184            Ok(Some(Outcome {
185                last_response: previous_response,
186                negotiate: NegotiateOutcome { action, rounds },
187            }))
188        }
189    }
190}
191
192#[crate::bisync::only_async]
193fn consume_received_pack<R>(
194    reader: R,
195    consume: impl FnOnce(&mut dyn std::io::BufRead, &mut dyn DynNestedProgress, &AtomicBool) -> Result<bool>,
196    progress: &mut dyn DynNestedProgress,
197    should_interrupt: &AtomicBool,
198) -> Result<(R, bool)>
199where
200    R: crate::futures_io::AsyncBufRead + Unpin,
201{
202    let mut reader = crate::futures_lite::io::BlockOn::new(reader);
203    let may_read_to_end = consume(&mut reader, progress, should_interrupt)
204        .or_raise(|| message("Failed to consume the pack sent by the remote"))?;
205    Ok((reader.into_inner(), may_read_to_end))
206}
207
208#[crate::bisync::only_sync]
209fn consume_received_pack<R>(
210    mut reader: R,
211    consume: impl FnOnce(&mut dyn std::io::BufRead, &mut dyn DynNestedProgress, &AtomicBool) -> Result<bool>,
212    progress: &mut dyn DynNestedProgress,
213    should_interrupt: &AtomicBool,
214) -> Result<(R, bool)>
215where
216    R: std::io::BufRead,
217{
218    let may_read_to_end = consume(&mut reader, progress, should_interrupt)
219        .or_raise(|| message("Failed to consume the pack sent by the remote"))?;
220    Ok((reader, may_read_to_end))
221}
222
223#[crate::bisync::only_async]
224async fn read_remaining(reader: &mut (impl crate::futures_io::AsyncRead + Unpin)) -> std::io::Result<()> {
225    crate::futures_lite::io::copy(reader, &mut crate::futures_lite::io::sink())
226        .await
227        .map(|_| ())
228}
229
230#[crate::bisync::only_sync]
231fn read_remaining(reader: &mut impl std::io::Read) -> std::io::Result<()> {
232    std::io::copy(reader, &mut std::io::sink()).map(|_| ())
233}
234
235fn acquire_shallow_lock(shallow_file: &Path) -> Result<gix_lock::File> {
236    gix_lock::File::acquire_to_update_resource(shallow_file, gix_lock::acquire::Fail::Immediately, None, 0)
237        .or_raise(|| message("'shallow' file could not be locked in preparation for writing changes"))
238}
239
240fn add_shallow_args(
241    args: &mut Arguments,
242    shallow: &Shallow,
243    shallow_file: &std::path::Path,
244) -> Result<(Option<nonempty::NonEmpty<gix_hash::ObjectId>>, Option<gix_lock::File>)> {
245    let expect_change = *shallow != Shallow::NoChange;
246    let shallow_lock = expect_change.then(|| acquire_shallow_lock(shallow_file)).transpose()?;
247
248    let shallow_commits = gix_shallow::read(shallow_file)
249        .or_raise(|| message("Could not read 'shallow' file to send current shallow boundary"))?;
250    if (shallow_commits.is_some() || expect_change) && !args.can_use_shallow() {
251        // NOTE: if this is an issue, we can always unshallow the repo ourselves.
252        bail!(validation(
253            "Server lack feature \"shallow\": shallow clones need server support to remain shallow, otherwise bigger than expected packs are sent effectively unshallowing the repository"
254        ));
255    }
256    if let Some(shallow_commits) = &shallow_commits {
257        for commit in shallow_commits.iter() {
258            args.shallow(commit);
259        }
260    }
261    match shallow {
262        Shallow::NoChange => {}
263        Shallow::DepthAtRemote(commits) => args.deepen(commits.get() as usize),
264        Shallow::Deepen(commits) => {
265            args.deepen(*commits as usize);
266            args.deepen_relative();
267        }
268        Shallow::Since { cutoff } => {
269            args.deepen_since(cutoff.seconds);
270        }
271        Shallow::Exclude {
272            remote_refs,
273            since_cutoff,
274        } => {
275            if let Some(cutoff) = since_cutoff {
276                args.deepen_since(cutoff.seconds);
277            }
278            for ref_ in remote_refs {
279                args.deepen_not(ref_.as_ref().as_bstr());
280            }
281        }
282    }
283    Ok((shallow_commits, shallow_lock))
284}
285
286fn setup_remote_progress<'a>(
287    progress: &mut dyn gix_utils::progress::DynNestedProgress,
288    reader: &mut Box<dyn ExtendedBufRead<'a> + Unpin + 'a>,
289    should_interrupt: &'a AtomicBool,
290) {
291    reader.set_progress_handler(Some(Box::new({
292        let mut remote_progress = progress.add_child_with_id("remote".to_string(), ProgressId::RemoteProgress.into());
293        move |is_err: bool, data: &[u8]| {
294            crate::RemoteProgress::translate_to_progress(is_err, data, &mut remote_progress);
295            if should_interrupt.load(Ordering::Relaxed) {
296                std::ops::ControlFlow::Break(())
297            } else {
298                std::ops::ControlFlow::Continue(())
299            }
300        }
301    }) as HandleProgress<'a>));
302}