gix-negotiate-0.13.0/.cargo_vcs_info.json0000644000000001530000000000100136600ustar { "git": { "sha1": "b050327e76f234b19be921b78b7b28e034319fdb" }, "path_in_vcs": "gix-negotiate" }gix-negotiate-0.13.0/Cargo.toml0000644000000023370000000000100116640ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.65" name = "gix-negotiate" version = "0.13.0" authors = ["Sebastian Thiel "] include = [ "src/**/*", "LICENSE-*", ] description = "A crate of the gitoxide project implementing negotiation algorithms" license = "MIT OR Apache-2.0" repository = "https://github.com/Byron/gitoxide" [lib] test = false doctest = false [dependencies.bitflags] version = "2" [dependencies.gix-commitgraph] version = "^0.24.2" [dependencies.gix-date] version = "^0.8.5" [dependencies.gix-hash] version = "^0.14.2" [dependencies.gix-object] version = "^0.42.0" [dependencies.gix-revwalk] version = "^0.13.0" [dependencies.smallvec] version = "1.10.0" [dependencies.thiserror] version = "1.0.40" [dev-dependencies] gix-negotiate-0.13.0/Cargo.toml.orig000064400000000000000000000016011046102023000153360ustar 00000000000000[package] name = "gix-negotiate" version = "0.13.0" repository = "https://github.com/Byron/gitoxide" license = "MIT OR Apache-2.0" description = "A crate of the gitoxide project implementing negotiation algorithms" authors = ["Sebastian Thiel "] edition = "2021" rust-version = "1.65" include = ["src/**/*", "LICENSE-*"] [lib] doctest = false test = false [dependencies] gix-hash = { version = "^0.14.2", path = "../gix-hash" } gix-object = { version = "^0.42.0", path = "../gix-object" } gix-date = { version = "^0.8.5", path = "../gix-date" } gix-commitgraph = { version = "^0.24.2", path = "../gix-commitgraph" } gix-revwalk = { version = "^0.13.0", path = "../gix-revwalk" } thiserror = "1.0.40" smallvec = "1.10.0" bitflags = "2" [dev-dependencies] gix-testtools = { path = "../tests/tools" } gix-odb = { path = "../gix-odb" } gix-ref = { path = "../gix-ref" } gix-negotiate-0.13.0/LICENSE-APACHE000064400000000000000000000247461046102023000144120ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. gix-negotiate-0.13.0/LICENSE-MIT000064400000000000000000000017771046102023000141210ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. gix-negotiate-0.13.0/src/consecutive.rs000064400000000000000000000140031046102023000161330ustar 00000000000000use gix_date::SecondsSinceUnixEpoch; use gix_hash::ObjectId; use crate::{Error, Flags, Negotiator}; pub(crate) struct Algorithm { revs: gix_revwalk::PriorityQueue, non_common_revs: usize, } impl Default for Algorithm { fn default() -> Self { Self { revs: gix_revwalk::PriorityQueue::new(), non_common_revs: 0, } } } impl Algorithm { /// Add `id` to our priority queue and *add* `flags` to it. fn add_to_queue(&mut self, id: ObjectId, mark: Flags, graph: &mut crate::Graph<'_>) -> Result<(), Error> { let mut is_common = false; let mut has_mark = false; if let Some(commit) = graph .try_lookup_or_insert_commit(id, |data| { has_mark = data.flags.intersects(mark); data.flags |= mark; is_common = data.flags.contains(Flags::COMMON); })? .filter(|_| !has_mark) { self.revs.insert(commit.commit_time, id); if !is_common { self.non_common_revs += 1; } } Ok(()) } fn mark_common( &mut self, id: ObjectId, mode: Mark, ancestors: Ancestors, graph: &mut crate::Graph<'_>, ) -> Result<(), Error> { let mut is_common = false; if let Some(commit) = graph .try_lookup_or_insert_commit(id, |data| is_common = data.flags.contains(Flags::COMMON))? .filter(|_| !is_common) { let mut queue = gix_revwalk::PriorityQueue::from_iter(Some((commit.commit_time, (id, 0_usize)))); if let Mark::ThisCommitAndAncestors = mode { commit.data.flags |= Flags::COMMON; if commit.data.flags.contains(Flags::SEEN) && !commit.data.flags.contains(Flags::POPPED) { self.non_common_revs -= 1; } } while let Some((id, generation)) = queue.pop_value() { if graph .get(&id) .map_or(true, |commit| !commit.data.flags.contains(Flags::SEEN)) { self.add_to_queue(id, Flags::SEEN, graph)?; } else if matches!(ancestors, Ancestors::AllUnseen) || generation < 2 { if let Some(commit) = graph.try_lookup_or_insert_commit(id, |_| {})? { for parent_id in commit.parents.clone() { let mut prev_flags = Flags::default(); if let Some(parent) = graph .try_lookup_or_insert_commit(parent_id, |data| { prev_flags = data.flags; data.flags |= Flags::COMMON; })? .filter(|_| !prev_flags.contains(Flags::COMMON)) { if prev_flags.contains(Flags::SEEN) && !prev_flags.contains(Flags::POPPED) { self.non_common_revs -= 1; } queue.insert(parent.commit_time, (parent_id, generation + 1)) } } } } } } Ok(()) } } impl Negotiator for Algorithm { fn known_common(&mut self, id: ObjectId, graph: &mut crate::Graph<'_>) -> Result<(), Error> { if graph .get(&id) .map_or(true, |commit| !commit.data.flags.contains(Flags::SEEN)) { self.add_to_queue(id, Flags::COMMON_REF | Flags::SEEN, graph)?; self.mark_common(id, Mark::AncestorsOnly, Ancestors::DirectUnseen, graph)?; } Ok(()) } fn add_tip(&mut self, id: ObjectId, graph: &mut crate::Graph<'_>) -> Result<(), Error> { self.add_to_queue(id, Flags::SEEN, graph) } fn next_have(&mut self, graph: &mut crate::Graph<'_>) -> Option> { loop { let id = self.revs.pop_value().filter(|_| self.non_common_revs != 0)?; let commit = graph.get_mut(&id).expect("it was added to the graph by now"); let flags = &mut commit.data.flags; *flags |= Flags::POPPED; if !flags.contains(Flags::COMMON) { self.non_common_revs -= 1; } let (res, mark) = if flags.contains(Flags::COMMON) { (None, Flags::COMMON | Flags::SEEN) } else if flags.contains(Flags::COMMON_REF) { (Some(id), Flags::COMMON | Flags::SEEN) } else { (Some(id), Flags::SEEN) }; for parent_id in commit.parents.clone() { if graph .get(&parent_id) .map_or(true, |commit| !commit.data.flags.contains(Flags::SEEN)) { if let Err(err) = self.add_to_queue(parent_id, mark, graph) { return Some(Err(err)); } } if mark.contains(Flags::COMMON) { if let Err(err) = self.mark_common(parent_id, Mark::AncestorsOnly, Ancestors::AllUnseen, graph) { return Some(Err(err)); } } } if let Some(id) = res { return Some(Ok(id)); } } } fn in_common_with_remote(&mut self, id: ObjectId, graph: &mut crate::Graph<'_>) -> Result { let known_to_be_common = graph .get(&id) .map_or(false, |commit| commit.data.flags.contains(Flags::COMMON)); self.mark_common(id, Mark::ThisCommitAndAncestors, Ancestors::DirectUnseen, graph)?; Ok(known_to_be_common) } } enum Mark { AncestorsOnly, ThisCommitAndAncestors, } enum Ancestors { /// Traverse only the parents of a commit. DirectUnseen, /// Traverse all ancestors that weren't yet seen. AllUnseen, } gix-negotiate-0.13.0/src/lib.rs000064400000000000000000000141301046102023000143530ustar 00000000000000//! An implementation of negotiation algorithms to help the server figure out what we have in common so it can optimize //! the pack it sends to only contain what we don't have. #![deny(rust_2018_idioms, missing_docs)] #![forbid(unsafe_code)] mod consecutive; mod noop; mod skipping; bitflags::bitflags! { /// Multi purpose, shared flags that are used by negotiation algorithms and by the caller as well /// /// However, in this crate we can't implement the calling side, so we marry this type to whatever is needed in downstream crates. #[derive(Debug, Default, Copy, Clone)] pub struct Flags: u8 { /// The object is already available locally and doesn't need to be fetched by the remote. const COMPLETE = 1 << 0; /// A commit from an alternate object database. const ALTERNATE = 1 << 1; /// The revision is known to be in common with the remote. /// /// Used by `consecutive` and `skipping`. const COMMON = 1 << 2; /// The revision has entered the priority queue. /// /// Used by `consecutive` and `skipping`. const SEEN = 1 << 3; /// The revision was popped off our primary priority queue, used to avoid double-counting of `non_common_revs` /// /// Used by `consecutive` and `skipping`. const POPPED = 1 << 4; /// The revision is common and was set by merit of a remote tracking ref (e.g. `refs/heads/origin/main`). /// /// Used by `consecutive`. const COMMON_REF = 1 << 5; /// The remote let us know it has the object. We still have to tell the server we have this object or one of its descendants. /// We won't tell the server about its ancestors. /// /// Used by `skipping`. const ADVERTISED = 1 << 6; } } /// Additional data to store with each commit when used by any of our algorithms. /// /// It's shared among those who use the [`Negotiator`] trait, and all implementations of it. #[derive(Default, Debug, Copy, Clone)] pub struct Metadata { /// Used by `skipping`. /// Only used if commit is not COMMON pub original_ttl: u16, /// Used by `skipping`. pub ttl: u16, /// Additional information about each commit pub flags: Flags, } /// The graph our callers use to store traversal information, for (re-)use in the negotiation implementation. pub type Graph<'find> = gix_revwalk::Graph<'find, gix_revwalk::graph::Commit>; /// A map associating an object id with its commit-metadata. pub type IdMap = gix_revwalk::graph::IdMap>; /// The way the negotiation is performed. #[derive(Default, Debug, Copy, Clone, Eq, PartialEq)] pub enum Algorithm { /// Do not send any information at all, which typically leads to complete packs to be sent. Noop, /// Walk over consecutive commits and check each one. This can be costly be assures packs are exactly the size they need to be. #[default] Consecutive, /// Like `Consecutive`, but skips commits to converge faster, at the cost of receiving packs that are larger than they have to be. Skipping, } impl std::fmt::Display for Algorithm { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Algorithm::Noop => "noop", Algorithm::Consecutive => "consecutive", Algorithm::Skipping => "skipping", } .fmt(f) } } /// Calculate how many `HAVE` lines we may send in one round, with variation depending on whether the `transport_is_stateless` or not. /// `window_size` is the previous (or initial) value of the window size. pub fn window_size(transport_is_stateless: bool, window_size: Option) -> usize { let current_size = match window_size { None => return 16, Some(cs) => cs, }; const PIPESAFE_FLUSH: usize = 32; const LARGE_FLUSH: usize = 16384; if transport_is_stateless { if current_size < LARGE_FLUSH { current_size * 2 } else { current_size * 11 / 10 } } else if current_size < PIPESAFE_FLUSH { current_size * 2 } else { current_size + PIPESAFE_FLUSH } } impl Algorithm { /// Create an instance of a negotiator which implements this algorithm. pub fn into_negotiator(self) -> Box { match &self { Algorithm::Noop => Box::new(noop::Noop) as Box, Algorithm::Consecutive => Box::::default(), Algorithm::Skipping => Box::::default(), } } } /// A delegate to implement a negotiation algorithm. pub trait Negotiator { /// Mark `id` as common between the remote and us. /// /// These ids are typically the local tips of remote tracking branches. fn known_common(&mut self, id: gix_hash::ObjectId, graph: &mut Graph<'_>) -> Result<(), Error>; /// Add `id` as starting point of a traversal across commits that aren't necessarily common between the remote and us. /// /// These tips are usually the commits of local references whose tips should lead to objects that we have in common with the remote. fn add_tip(&mut self, id: gix_hash::ObjectId, graph: &mut Graph<'_>) -> Result<(), Error>; /// Produce the next id of an object that we want the server to know we have. It's an object we don't know we have in common or not. /// /// Returns `None` if we have exhausted all options, which might mean we have traversed the entire commit graph. fn next_have(&mut self, graph: &mut Graph<'_>) -> Option>; /// Mark `id` as being common with the remote (as informed by the remote itself) and return `true` if we knew it was common already. /// /// We can assume to have already seen `id` as we were the one to inform the remote in a prior `have`. fn in_common_with_remote(&mut self, id: gix_hash::ObjectId, graph: &mut Graph<'_>) -> Result; } /// An error that happened during any of the methods on a [`Negotiator`]. pub type Error = gix_revwalk::graph::try_lookup_or_insert_default::Error; gix-negotiate-0.13.0/src/noop.rs000064400000000000000000000011321046102023000145560ustar 00000000000000use gix_hash::ObjectId; use crate::{Error, Negotiator}; pub(crate) struct Noop; impl Negotiator for Noop { fn known_common(&mut self, _id: ObjectId, _graph: &mut crate::Graph<'_>) -> Result<(), Error> { Ok(()) } fn add_tip(&mut self, _id: ObjectId, _graph: &mut crate::Graph<'_>) -> Result<(), Error> { Ok(()) } fn next_have(&mut self, _graph: &mut crate::Graph<'_>) -> Option> { None } fn in_common_with_remote(&mut self, _id: ObjectId, _graph: &mut crate::Graph<'_>) -> Result { Ok(false) } } gix-negotiate-0.13.0/src/skipping.rs000064400000000000000000000150271046102023000154370ustar 00000000000000use gix_date::SecondsSinceUnixEpoch; use gix_hash::ObjectId; use crate::{Error, Flags, Metadata, Negotiator}; pub(crate) struct Algorithm { revs: gix_revwalk::PriorityQueue, non_common_revs: usize, } impl Default for Algorithm { fn default() -> Self { Self { revs: gix_revwalk::PriorityQueue::new(), non_common_revs: 0, } } } impl Algorithm { /// Add `id` to our priority queue and *add* `flags` to it. fn add_to_queue(&mut self, id: ObjectId, mark: Flags, graph: &mut crate::Graph<'_>) -> Result<(), Error> { let commit = graph.try_lookup_or_insert_commit(id, |entry| { entry.flags |= mark | Flags::SEEN; })?; if let Some(timestamp) = commit.map(|c| c.commit_time) { self.revs.insert(timestamp, id); if !mark.contains(Flags::COMMON) { self.non_common_revs += 1; } } Ok(()) } fn mark_common(&mut self, id: ObjectId, graph: &mut crate::Graph<'_>) -> Result<(), Error> { let mut is_common = false; if let Some(commit) = graph .try_lookup_or_insert_commit(id, |entry| { is_common = entry.flags.contains(Flags::COMMON); entry.flags |= Flags::COMMON; })? .filter(|_| !is_common) { let mut queue = gix_revwalk::PriorityQueue::from_iter(Some((commit.commit_time, id))); while let Some(id) = queue.pop_value() { if let Some(commit) = graph.try_lookup_or_insert_commit(id, |entry| { if !entry.flags.contains(Flags::POPPED) { self.non_common_revs -= 1; } })? { for parent_id in commit.parents.clone() { // This is a bit of a problem as there is no representation of the `parsed` based skip. However, // We assume that parents that aren't in the graph yet haven't been seen, and that's all we need. if !graph.contains(&parent_id) { continue; } let mut was_unseen_or_common = false; if let Some(parent) = graph .try_lookup_or_insert_commit(parent_id, |entry| { was_unseen_or_common = !entry.flags.contains(Flags::SEEN) || entry.flags.contains(Flags::COMMON); entry.flags |= Flags::COMMON })? .filter(|_| !was_unseen_or_common) { queue.insert(parent.commit_time, parent_id); } } } } } Ok(()) } fn push_parent( &mut self, entry: Metadata, parent_id: ObjectId, graph: &mut crate::Graph<'_>, ) -> Result { let mut was_seen = false; if let Some(parent) = graph .get(&parent_id) .map(|parent| { was_seen = parent.data.flags.contains(Flags::SEEN); parent }) .filter(|_| was_seen) { if parent.data.flags.contains(Flags::POPPED) { return Ok(false); } } else { self.add_to_queue(parent_id, Flags::default(), graph)?; } if entry.flags.intersects(Flags::COMMON | Flags::ADVERTISED) { self.mark_common(parent_id, graph)?; } else { let new_original_ttl = if entry.ttl > 0 { entry.original_ttl } else { entry.original_ttl * 3 / 2 + 1 }; let new_ttl = if entry.ttl > 0 { entry.ttl - 1 } else { new_original_ttl }; let parent = graph.get_mut(&parent_id).expect("present or inserted"); if parent.data.original_ttl < new_original_ttl { parent.data.original_ttl = new_original_ttl; parent.data.ttl = new_ttl; } } Ok(true) } } impl Negotiator for Algorithm { fn known_common(&mut self, id: ObjectId, graph: &mut crate::Graph<'_>) -> Result<(), Error> { if graph .get(&id) .map_or(false, |commit| commit.data.flags.contains(Flags::SEEN)) { return Ok(()); } self.add_to_queue(id, Flags::ADVERTISED, graph) } fn add_tip(&mut self, id: ObjectId, graph: &mut crate::Graph<'_>) -> Result<(), Error> { if graph .get(&id) .map_or(false, |commit| commit.data.flags.contains(Flags::SEEN)) { return Ok(()); } self.add_to_queue(id, Flags::default(), graph) } fn next_have(&mut self, graph: &mut crate::Graph<'_>) -> Option> { loop { let id = self.revs.pop_value().filter(|_| self.non_common_revs != 0)?; let commit = graph.get_mut(&id).expect("it was added to the graph by now"); commit.data.flags |= Flags::POPPED; if !commit.data.flags.contains(Flags::COMMON) { self.non_common_revs -= 1; } let mut to_send = None; if !commit.data.flags.contains(Flags::COMMON) && commit.data.ttl == 0 { to_send = Some(id); } let data = commit.data; let mut parent_pushed = false; for parent_id in commit.parents.clone() { parent_pushed |= match self.push_parent(data, parent_id, graph) { Ok(r) => r, Err(err) => return Some(Err(err)), } } if !data.flags.contains(Flags::COMMON) && !parent_pushed { to_send = Some(id); } if let Some(to_send) = to_send { return Some(Ok(to_send)); } } } fn in_common_with_remote(&mut self, id: ObjectId, graph: &mut crate::Graph<'_>) -> Result { let mut was_seen = false; let known_to_be_common = graph.get(&id).map_or(false, |commit| { was_seen = commit.data.flags.contains(Flags::SEEN); commit.data.flags.contains(Flags::COMMON) }); assert!( was_seen, "Cannot receive ACK for commit we didn't send a HAVE for: {id}" ); self.mark_common(id, graph)?; Ok(known_to_be_common) } }