1use 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#[derive(Debug, Clone)]
44pub struct RequestNameToLocation {
45 pub names: Vec<Vertex>,
46 pub heads: Vec<Vertex>,
47}
48
49#[derive(Debug, Clone)]
52pub struct RequestLocationToName {
53 pub paths: Vec<AncestorPath>,
54}
55
56#[derive(Debug, Clone)]
58pub struct ResponseIdNamePair {
59 pub path_names: Vec<(AncestorPath, Vec<Vertex>)>,
65}
66
67#[derive(Clone)]
72pub struct AncestorPath {
73 pub x: Vertex,
74
75 pub n: u64,
76
77 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_trait::async_trait]
101pub trait RemoteIdConvertProtocol: Send + Sync + 'static {
102 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 async fn resolve_relative_paths_to_names(
122 &self,
123 paths: Vec<AncestorPath>,
124 ) -> Result<Vec<(AncestorPath, Vec<Vertex>)>>;
125
126 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#[async_trait::async_trait]
166pub(crate) trait Process<I, O> {
167 async fn process(self, input: I) -> Result<O>;
168}
169
170#[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 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#[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 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#[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 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 Ok(None) => None,
344 Ok(Some((x, n))) => Some(Ok((x, n, name))),
345 }
346 })
347 .collect::<Result<Vec<_>>>()?;
348
349 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#[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#[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
435thread_local! {
441 static NON_BLOCKING_DEPTH: RefCell<usize> = const { RefCell::new(0) };
442}
443
444pub(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}