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