Skip to main content

dag/
protocol.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8//! # protocol
9//!
10//! Abstractions used for communication between `(sparse_idmap1, segments1)`
11//! (usually, a client) and `(complete_idmap2, segments2)` (usually, a server).
12//!
13//! When the sparse idmap gets asked to convert unknown id or name, it goes
14//! through the following flow to find the answer:
15//!
16//! - Id -> Name: Id -> RequestLocationToName -> ResponseIdNamePair -> Name
17//! - Name -> Id: Name -> RequestNameToLocation -> ResponseIdNamePair -> Id
18
19use std::cell::RefCell;
20use std::fmt;
21use std::thread_local;
22
23use futures::stream;
24use futures::stream::StreamExt;
25use futures::stream::TryStreamExt;
26
27use crate::Group;
28use crate::Id;
29#[cfg(any(test, feature = "indexedlog-backend"))]
30use crate::IdMap;
31use crate::IdSet;
32use crate::Result;
33use crate::id::Vertex;
34use crate::iddag::FirstAncestorConstraint;
35use crate::iddag::IdDag;
36use crate::iddagstore::IdDagStore;
37use crate::ops::IdConvert;
38
39// Request and Response structures -------------------------------------------
40
41/// Request for locating names (commit hashes) in a IdDag.
42/// Useful for converting names to ids.
43#[derive(Debug, Clone)]
44pub struct RequestNameToLocation {
45    pub names: Vec<Vertex>,
46    pub heads: Vec<Vertex>,
47}
48
49/// Request for converting locations to names (commit hashes).
50/// Useful for converting ids to names.
51#[derive(Debug, Clone)]
52pub struct RequestLocationToName {
53    pub paths: Vec<AncestorPath>,
54}
55
56/// Response for converting names to ids or converting names to ids.
57#[derive(Debug, Clone)]
58pub struct ResponseIdNamePair {
59    // For converting Id -> Name, the client provides AncestorPath, the server provides
60    // Vec<Box<[u8]>>.
61    //
62    // For converting Name -> Id, the client provides Box<[u8]>, the server provides
63    // AncestorPath.
64    pub path_names: Vec<(AncestorPath, Vec<Vertex>)>,
65}
66
67/// The `n`-th first ancestor of `x`. `x~n` in hg revset syntax.
68/// Usually, `x` is commonly known by the client and the server.
69///
70/// This can be seen as a kind of "location".
71#[derive(Clone)]
72pub struct AncestorPath {
73    pub x: Vertex,
74
75    pub n: u64,
76
77    // Starting from x~n, get a chain of commits following p1.
78    pub batch_size: u64,
79}
80
81impl fmt::Display for AncestorPath {
82    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
83        write!(f, "{:?}~{}", self.x, self.n)
84    }
85}
86
87impl fmt::Debug for AncestorPath {
88    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89        write!(f, "{self}")?;
90        if self.batch_size != 1 {
91            write!(f, "(+{})", self.batch_size)?;
92        }
93        Ok(())
94    }
95}
96
97// Async Remote Protocols ----------------------------------------------------
98
99/// Abstraction of network protocols.
100#[async_trait::async_trait]
101pub trait RemoteIdConvertProtocol: Send + Sync + 'static {
102    /// Ask the server to convert names to "x~n" relative paths.
103    ///
104    /// If a "name" cannot be resolved using "x~n" form in "::heads", aka. the
105    /// "heads" are known to the server, and the server can calculate "::heads",
106    /// and knows all names (commit hashes) in "::heads". And the server
107    /// confirms "name" is outside "::heads" (either because "name" is unknown
108    /// to the server's IdMap, or because "name" is known in the server's IdMap,
109    /// but the matching Id is outside "::heads"), this method should skip it in
110    /// the resulting list (instead of returning an error).
111    async fn resolve_names_to_relative_paths(
112        &self,
113        heads: Vec<Vertex>,
114        names: Vec<Vertex>,
115    ) -> Result<Vec<(AncestorPath, Vec<Vertex>)>>;
116
117    /// Ask the server to convert "x~n" relative paths back to commit hashes.
118    ///
119    /// Unlike resolve_names_to_relative_paths, failures are not expected.
120    /// They usually indicate rare events like master moving backwards.
121    async fn resolve_relative_paths_to_names(
122        &self,
123        paths: Vec<AncestorPath>,
124    ) -> Result<Vec<(AncestorPath, Vec<Vertex>)>>;
125
126    /// Return `true` if the protocol is local and queries do not need to
127    /// optimize for batching or latency.
128    fn is_local(&self) -> bool {
129        false
130    }
131}
132
133#[async_trait::async_trait]
134impl RemoteIdConvertProtocol for () {
135    async fn resolve_names_to_relative_paths(
136        &self,
137        _heads: Vec<Vertex>,
138        _names: Vec<Vertex>,
139    ) -> Result<Vec<(AncestorPath, Vec<Vertex>)>> {
140        Ok(Default::default())
141    }
142
143    async fn resolve_relative_paths_to_names(
144        &self,
145        paths: Vec<AncestorPath>,
146    ) -> Result<Vec<(AncestorPath, Vec<Vertex>)>> {
147        let msg =
148            format!("Asked to resolve {paths:?} in graph but remote protocol is not configured");
149        crate::errors::programming(msg)
150    }
151
152    fn is_local(&self) -> bool {
153        true
154    }
155}
156
157// Traits --------------------------------------------------------------------
158
159/// Similar to `From::from(I) -> O`, but with `self` as context.
160///
161/// Example use-cases:
162/// - Convert a query to a request (client-side).
163/// - Convert a request to a response (server-side).
164/// - Handle a response from the server (client-side).
165#[async_trait::async_trait]
166pub(crate) trait Process<I, O> {
167    async fn process(self, input: I) -> Result<O>;
168}
169
170// Basic implementation ------------------------------------------------------
171
172// Name -> Id, step 1: Name -> RequestNameToLocation
173// Works on an incomplete IdMap, client-side.
174#[async_trait::async_trait]
175impl<M: IdConvert, DagStore: IdDagStore> Process<Vec<Vertex>, RequestNameToLocation>
176    for (&M, &IdDag<DagStore>)
177{
178    async fn process(self, names: Vec<Vertex>) -> Result<RequestNameToLocation> {
179        let map = &self.0;
180        let dag = &self.1;
181        // Only provides heads in the master group, since it's expected that the
182        // non-master group is already locally known.
183        let heads = stream::iter(dag.heads_ancestors(dag.master_group()?)?).boxed();
184        let heads = heads
185            .then(|id| map.vertex_name(id))
186            .try_collect::<Vec<Vertex>>()
187            .await
188            .map_err(|e| {
189                let msg = format!(
190                    concat!(
191                        "Cannot resolve heads in master group to vertex name. ",
192                        "The vertex name is required for remote vertex resolution. ",
193                        "This probably indicates the Dag update logic does not ensure the ",
194                        "vertex name of heads exist as it should. ",
195                        "(Error: {})",
196                    ),
197                    e
198                );
199                crate::Error::Programming(msg)
200            })?;
201        Ok(RequestNameToLocation { names, heads })
202    }
203}
204
205// Id -> Name, step 1: Id -> RequestLocationToName
206// Works on an incomplete IdMap, client-side.
207#[async_trait::async_trait]
208impl<M: IdConvert, DagStore: IdDagStore> Process<IdSet, RequestLocationToName>
209    for (&M, &IdDag<DagStore>)
210{
211    async fn process(self, ids: IdSet) -> Result<RequestLocationToName> {
212        let map = &self.0;
213        let dag = &self.1;
214        let heads = dag.heads_ancestors(dag.master_group()?)?;
215
216        let mut id_path: Vec<(Id, u64, u64)> = Vec::with_capacity(ids.as_spans().len());
217        let mut last_id_opt = None;
218        for id in ids.into_iter() {
219            if let Some(last_id) = last_id_opt {
220                if dag.try_first_ancestor_nth(last_id, 1)? == Some(id) {
221                    // Reuse the last path.
222                    if let Some(last) = id_path.last_mut() {
223                        last.2 += 1;
224                        last_id_opt = Some(id);
225                        continue;
226                    }
227                }
228            }
229            let (x, n) = dag
230                .to_first_ancestor_nth(
231                    id,
232                    FirstAncestorConstraint::KnownUniversally {
233                        heads: heads.clone(),
234                    },
235                )?
236                .ok_or_else(|| {
237                    if id.group() == Group::MASTER {
238                        let msg = format!(
239                            concat!(
240                                "Cannot convert {} to x~n form using heads {:?}. ",
241                                "This is unexpected. It indicates some serious bugs in graph ",
242                                "calculation or the graph is corrupted (ex. has cycles).",
243                            ),
244                            id, &heads,
245                        );
246                        crate::Error::Bug(msg)
247                    } else {
248                        let msg = format!(
249                            concat!(
250                                "Cannot convert {} to x~n form. This is unexpected for non-master ",
251                                "vertexes since they are expected to be non-lazy.",
252                            ),
253                            id
254                        );
255                        crate::Error::Programming(msg)
256                    }
257                })?;
258            id_path.push((x, n, 1));
259            last_id_opt = Some(id);
260        }
261
262        let paths = stream::iter(id_path)
263            .then(|(x, n, batch_size)| async move {
264                let x = map.vertex_name(x).await.map_err(|e| {
265                    let msg = format!(
266                        concat!(
267                            "Cannot resolve {} in to vertex name (Error: {}). ",
268                            "The vertex name is required for remote vertex resolution. ",
269                            "This probably indicates the Dag clone or update logic does ",
270                            "not maintain \"universally known\" vertexes as it should.",
271                        ),
272                        x, e,
273                    );
274                    crate::Error::Programming(msg)
275                })?;
276                Ok::<_, crate::Error>(AncestorPath { x, n, batch_size })
277            })
278            .try_collect::<Vec<_>>()
279            .await?;
280
281        Ok(RequestLocationToName { paths })
282    }
283}
284
285// Name -> Id, step 2: RequestNameToLocation -> ResponseIdNamePair
286// Works on a complete IdMap, server-side.
287#[async_trait::async_trait]
288impl<M: IdConvert, DagStore: IdDagStore> Process<RequestNameToLocation, ResponseIdNamePair>
289    for (&M, &IdDag<DagStore>)
290{
291    async fn process(self, request: RequestNameToLocation) -> Result<ResponseIdNamePair> {
292        let map = &self.0;
293        let dag = &self.1;
294
295        let heads: IdSet = {
296            let heads = stream::iter(request.heads);
297            let heads = heads
298                .then(|s| map.vertex_id(s))
299                .try_collect::<Vec<Id>>()
300                .await?;
301            IdSet::from_spans(heads)
302        };
303        let resolvable = dag.ancestors(heads.clone())?;
304
305        let id_names: Vec<(Id, Vertex)> = {
306            let ids_result = map.vertex_id_batch(&request.names).await?;
307            let mut id_names = Vec::with_capacity(ids_result.len());
308            for (name, id_result) in request.names.into_iter().zip(ids_result) {
309                match id_result {
310                    // If one of the names cannot be resolved to id, just skip it.
311                    Err(crate::Error::VertexNotFound(n)) => {
312                        tracing::trace!(
313                            "RequestNameToLocation -> ResponseIdNamePair: skip unknown name {:?}",
314                            &n
315                        );
316                        continue;
317                    }
318                    Err(e) => {
319                        return Err(e);
320                    }
321                    Ok(id) => {
322                        if resolvable.contains(id) {
323                            id_names.push((id, name))
324                        }
325                    }
326                }
327            }
328            id_names
329        };
330
331        let path_names: Vec<(AncestorPath, Vec<Vertex>)> = {
332            let x_n_names: Vec<(Id, u64, Vertex)> = id_names
333                .into_iter()
334                .filter_map(|(id, name)| {
335                    match dag.to_first_ancestor_nth(
336                        id,
337                        FirstAncestorConstraint::KnownUniversally {
338                            heads: heads.clone(),
339                        },
340                    ) {
341                        Err(e) => Some(Err(e)),
342                        // Skip ids that cannot be translated.
343                        Ok(None) => None,
344                        Ok(Some((x, n))) => Some(Ok((x, n, name))),
345                    }
346                })
347                .collect::<Result<Vec<_>>>()?;
348
349            // Convert x from Id to Vertex.
350            stream::iter(x_n_names)
351                .then(|(x, n, name)| async move {
352                    let x = map.vertex_name(x).await?;
353                    Ok::<_, crate::Error>((
354                        AncestorPath {
355                            x,
356                            n,
357                            batch_size: 1,
358                        },
359                        vec![name],
360                    ))
361                })
362                .try_collect()
363                .await?
364        };
365
366        Ok(ResponseIdNamePair { path_names })
367    }
368}
369
370// Id -> Name, step 2: RequestLocationToName -> ResponseIdNamePair
371// Works on a complete IdMap, server-side.
372#[async_trait::async_trait]
373impl<M: IdConvert, DagStore: IdDagStore> Process<RequestLocationToName, ResponseIdNamePair>
374    for (&M, &IdDag<DagStore>)
375{
376    async fn process(self, request: RequestLocationToName) -> Result<ResponseIdNamePair> {
377        let map = &self.0;
378        let dag = &self.1;
379
380        let path_names: Vec<(AncestorPath, Vec<Vertex>)> = stream::iter(request.paths)
381            .then(|path| async move {
382                let id = map.vertex_id(path.x.clone()).await?;
383                let mut id = dag.first_ancestor_nth(id, path.n)?;
384                let mut ids = Vec::with_capacity(path.batch_size as _);
385                for i in 0..path.batch_size {
386                    if i > 0 {
387                        id = dag.first_ancestor_nth(id, 1)?;
388                    }
389                    ids.push(id);
390                }
391                let fallible_names = map.vertex_name_batch(&ids).await?;
392                let mut names = Vec::with_capacity(fallible_names.len());
393                for name in fallible_names {
394                    names.push(name?);
395                }
396                debug_assert_eq!(path.batch_size, names.len() as u64);
397                Ok::<_, crate::Error>((path, names))
398            })
399            .try_collect()
400            .await?;
401        Ok(ResponseIdNamePair { path_names })
402    }
403}
404
405// Name -> Id or Id -> Name, step 3: Apply RequestNameToLocation to a local IdMap.
406// Works on an incomplete IdMap, client-side.
407#[cfg(any(test, feature = "indexedlog-backend"))]
408#[async_trait::async_trait]
409impl<'a, DagStore: IdDagStore> Process<ResponseIdNamePair, ()>
410    for (&'a mut IdMap, &'a IdDag<DagStore>)
411{
412    async fn process(mut self, res: ResponseIdNamePair) -> Result<()> {
413        use crate::errors::NotFoundError;
414
415        let map = &mut self.0;
416        let dag = &self.1;
417        for (path, names) in res.path_names.iter() {
418            let x: Id = map
419                .find_id_by_name(path.x.as_ref())?
420                .ok_or_else(|| path.x.not_found_error())?;
421            let mut id = dag.first_ancestor_nth(x, path.n)?;
422            tracing::trace!("insert path {:?} names {:?} (x = {})", &path, &names, id);
423            for (i, name) in names.iter().enumerate() {
424                if i > 0 {
425                    id = dag.first_ancestor_nth(id, 1)?;
426                }
427                tracing::trace!(" insert {:?} = {:?}", id, &name);
428                map.insert(id, name.as_ref())?;
429            }
430        }
431        Ok(())
432    }
433}
434
435// Disable remote protocol temporarily ---------------------------------------
436// This can be useful for Debug::fmt to disable remote fetching which might
437// panic (ex. calling tokio without tokio runtime) when executing futures
438// via nonblocking.
439
440thread_local! {
441    static NON_BLOCKING_DEPTH: RefCell<usize> = const { RefCell::new(0) };
442}
443
444/// Check if the current future is running inside a "non-blocking" block.
445pub(crate) fn disable_remote_protocol<F, R>(f: F) -> R
446where
447    F: FnOnce() -> R,
448{
449    NON_BLOCKING_DEPTH.with(|v| *v.borrow_mut() += 1);
450    let result = f();
451    NON_BLOCKING_DEPTH.with(|v| *v.borrow_mut() -= 1);
452    result
453}
454
455pub(crate) fn is_remote_protocol_disabled() -> bool {
456    NON_BLOCKING_DEPTH.with(|v| *v.borrow() != 0)
457}