Skip to main content

subc_daemon/config_gate/
project_registry.rs

1//! Registry authority and retained-root captures for project settings.
2
3use std::{
4    collections::{BTreeMap, BTreeSet},
5    fs::File,
6    future::Future,
7    path::{Path, PathBuf},
8    pin::Pin,
9    sync::Arc,
10};
11
12pub use super::root_io::RootIoPool;
13use super::{root_io::RootIoError, GateError, Result};
14use cortexkit_project_identity::{
15    Approval, ApprovalState, EnumerateReply, Project, RootIdentity, RootIncarnation, RootRecord,
16};
17use serde::{Deserialize, Serialize};
18use subc_config::Digest;
19
20mod layers;
21mod rpc;
22use layers::{open_root, OpenedRoot};
23pub use layers::{LayerFile, LayerLocation};
24pub use rpc::EntorhinalProjectRegistry;
25
26pub const ENUMERATE_OP: &str = "projects.enumerate";
27
28fn unavailable(detail: impl std::fmt::Display) -> GateError {
29    GateError::new("project_registry_unavailable", detail)
30}
31
32fn layer_unavailable(detail: impl std::fmt::Display) -> GateError {
33    GateError::new("config_unavailable", detail)
34}
35
36fn changed() -> GateError {
37    GateError::new(
38        "config_changed_since_review",
39        "affected project registry entries or layer locations changed; plan again",
40    )
41}
42
43/// The registry publishes the legacy Windows file index, not FILE_ID_INFO's
44/// 128-bit id. Keep this comparison identity separate from file capture ids.
45#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
46#[serde(tag = "platform", rename_all = "snake_case")]
47pub enum RegistryFileId {
48    Unix {
49        #[serde(with = "super::capture::decimal_id")]
50        device: u64,
51        #[serde(with = "super::capture::decimal_id")]
52        inode: u64,
53    },
54    Windows {
55        volume_serial: u32,
56        #[serde(with = "super::capture::decimal_id")]
57        file_index: u64,
58    },
59}
60
61impl RegistryFileId {
62    pub fn parse(text: &str) -> Result<Self> {
63        let parts: Vec<_> = text.split(':').collect();
64        let invalid = || unavailable("registry fileId is not a supported decimal identity");
65        if parts.len() != 3
66            || parts[1..]
67                .iter()
68                .any(|part| part.is_empty() || !part.bytes().all(|c| c.is_ascii_digit()))
69        {
70            return Err(invalid());
71        }
72        match parts[0] {
73            "unix" => Ok(Self::Unix {
74                device: parts[1].parse().map_err(|_| invalid())?,
75                inode: parts[2].parse().map_err(|_| invalid())?,
76            }),
77            "windows" => Ok(Self::Windows {
78                volume_serial: parts[1].parse().map_err(|_| invalid())?,
79                file_index: parts[2].parse().map_err(|_| invalid())?,
80            }),
81            _ => Err(invalid()),
82        }
83    }
84
85    fn read(file: &File) -> std::io::Result<Self> {
86        #[cfg(unix)]
87        {
88            let id = subc_os::retained_file_identity(file)?;
89            Ok(Self::Unix {
90                device: id.device,
91                inode: id.inode,
92            })
93        }
94        #[cfg(windows)]
95        {
96            let id = subc_os::retained_file_index(file)?;
97            Ok(Self::Windows {
98                volume_serial: id.volume_serial,
99                file_index: id.file_index,
100            })
101        }
102    }
103}
104
105#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
106pub struct RegistryRoot {
107    pub path: PathBuf,
108    pub file_id: Option<RegistryFileId>,
109    pub incarnation: Option<RootIncarnation>,
110    pub approval: Option<Approval>,
111    pub identity: Option<RootIdentity>,
112}
113
114#[derive(Clone, Debug)]
115enum RootCheckFailure {
116    Pool(RootIoError),
117    InvalidPath,
118    OpenRefused(Arc<subc_os::OpenRegularError>),
119    IdentityUnreadable(Arc<std::io::Error>),
120    IdentityMismatch,
121}
122
123impl std::fmt::Display for RootCheckFailure {
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        match self {
126            Self::Pool(error) => std::fmt::Display::fmt(&GateError::from(*error), f),
127            Self::InvalidPath => f.write_str("root must be a canonical absolute path"),
128            Self::OpenRefused(error) => write!(f, "root open refused: {error}"),
129            Self::IdentityUnreadable(error) => write!(f, "root identity is unreadable: {error}"),
130            Self::IdentityMismatch => f.write_str("root fileId changed"),
131        }
132    }
133}
134
135impl RootCheckFailure {
136    fn error(&self, project: &str, path: &Path, rechecking: bool) -> GateError {
137        use subc_os::OpenRegularError;
138        let code = match self {
139            Self::InvalidPath => "layer_root_invalid",
140            Self::OpenRefused(error) => match error.as_ref() {
141                OpenRegularError::Symlink => "layer_symlink",
142                OpenRegularError::NotRegularFile => "layer_not_regular",
143                OpenRegularError::Io(error)
144                    if error.kind() == std::io::ErrorKind::NotFound && rechecking =>
145                {
146                    return changed()
147                }
148                OpenRegularError::Io(_) => "config_unavailable",
149            },
150            Self::IdentityMismatch if rechecking => return changed(),
151            _ => "config_unavailable",
152        };
153        if rechecking && code.starts_with("layer_") {
154            return changed();
155        }
156        GateError::new(code, format!("{project}: root {}: {self}", path.display()))
157    }
158}
159
160#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
161pub struct RegistryProject {
162    pub project_id: String,
163    pub workspace_id: Option<String>,
164    pub project_roots: Vec<RegistryRoot>,
165    pub workspace_root: Option<RegistryRoot>,
166}
167
168impl RegistryProject {
169    pub(super) fn roots(&self) -> impl Iterator<Item = &RegistryRoot> {
170        self.project_roots.iter().chain(&self.workspace_root)
171    }
172}
173
174/// Select explicit project IDs and every reader of the named paths or workspaces.
175#[derive(Clone, Debug, Default)]
176pub struct RegistryScope {
177    pub projects: BTreeSet<String>,
178    pub paths: BTreeSet<PathBuf>,
179    pub workspaces: BTreeSet<String>,
180    all_registered: bool,
181    capture: CaptureLayers,
182}
183
184#[derive(Clone, Copy, Debug, Default)]
185enum CaptureLayers {
186    #[default]
187    All,
188    Targets,
189}
190
191impl RegistryScope {
192    pub fn new(
193        projects: BTreeSet<String>,
194        paths: BTreeSet<PathBuf>,
195        workspaces: BTreeSet<String>,
196    ) -> Self {
197        Self {
198            projects,
199            paths,
200            workspaces,
201            ..Self::default()
202        }
203    }
204
205    /// Scope a capture to all currently registered projects (including rootless projects).
206    pub fn all() -> Self {
207        Self {
208            all_registered: true,
209            ..Self::default()
210        }
211    }
212
213    pub(super) fn include_all(&mut self) {
214        self.all_registered = true;
215    }
216
217    fn includes(
218        &self,
219        id: &str,
220        workspace: Option<&String>,
221        roots: impl IntoIterator<Item = impl AsRef<Path>>,
222        module: &str,
223    ) -> bool {
224        self.all_registered
225            || self.projects.contains(id)
226            || workspace.is_some_and(|id| self.workspaces.contains(id))
227            || roots
228                .into_iter()
229                .any(|root| self.paths.contains(&layer_path(root.as_ref(), module)))
230    }
231}
232
233/// Inputs of one tuple, after assigning a same-root layer to the project only.
234pub struct ProjectLayers<'a> {
235    pub workspace: Option<(&'a Path, &'a LayerFile)>,
236    pub project: Option<(&'a Path, &'a LayerFile)>,
237}
238
239/// Only the affected entries participate in the digest; a global enumeration
240/// generation would invalidate reviews after unrelated registry edits.
241#[derive(Clone, Serialize, Deserialize)]
242pub struct RegistryRevision {
243    pub module: String,
244    pub projects: Vec<RegistryProject>,
245    #[serde(skip)]
246    opened: Arc<BTreeMap<PathBuf, std::result::Result<OpenedRoot, RootCheckFailure>>>,
247    #[serde(skip)]
248    metadata_errors: BTreeMap<String, GateError>,
249}
250
251impl std::fmt::Debug for RegistryRevision {
252    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253        f.debug_struct("RegistryRevision")
254            .field("module", &self.module)
255            .field("projects", &self.projects)
256            .finish_non_exhaustive()
257    }
258}
259
260impl PartialEq for RegistryRevision {
261    fn eq(&self, other: &Self) -> bool {
262        self.module == other.module && self.projects == other.projects
263    }
264}
265impl Eq for RegistryRevision {}
266
267impl RegistryRevision {
268    pub async fn from_enumerate(
269        pool: &RootIoPool,
270        reply: &EnumerateReply,
271        module: &str,
272        affected: &BTreeSet<String>,
273    ) -> Result<Self> {
274        let mut revision = Self::parse_enumeration(reply, module, affected)?;
275        revision
276            .capture_roots(pool, &RegistryScope::default())
277            .await;
278        Ok(revision)
279    }
280
281    pub async fn from_scope(
282        pool: &RootIoPool,
283        reply: &EnumerateReply,
284        module: &str,
285        scope: &RegistryScope,
286    ) -> Result<Self> {
287        let affected = reply
288            .projects
289            .iter()
290            .filter_map(|project| {
291                let roots = project
292                    .root_records
293                    .iter()
294                    .flatten()
295                    .filter(|root| eligible(root))
296                    .map(|root| root.root.as_str());
297                let workspace = reply
298                    .workspaces
299                    .iter()
300                    .filter(|workspace| {
301                        project.workspace_id.as_ref() == Some(&workspace.workspace_id)
302                    })
303                    .filter_map(|workspace| workspace.root.as_deref());
304                scope
305                    .includes(
306                        &project.project_id,
307                        project.workspace_id.as_ref(),
308                        roots.chain(workspace),
309                        module,
310                    )
311                    .then(|| project.project_id.clone())
312            })
313            .collect();
314        let mut revision = Self::parse_enumeration(reply, module, &affected)?;
315        revision.capture_roots(pool, scope).await;
316        Ok(revision)
317    }
318
319    fn parse_enumeration(
320        reply: &EnumerateReply,
321        module: &str,
322        affected: &BTreeSet<String>,
323    ) -> Result<Self> {
324        validate_module(module)?;
325        let mut projects = Vec::new();
326        let mut metadata_errors = BTreeMap::new();
327        for id in affected {
328            let mut matches = reply
329                .projects
330                .iter()
331                .filter(|project| project.project_id == *id);
332            let project = matches
333                .next()
334                .ok_or_else(|| unavailable(format!("{id}: project is not registered")))?;
335            if matches.next().is_some() {
336                return Err(unavailable(format!("{id}: duplicate project identity")));
337            }
338            let read_id =
339                |text, path, errors: &mut BTreeMap<String, GateError>| match parse_id(text) {
340                    Ok(file_id) => file_id,
341                    Err(_) => {
342                        errors.entry(id.clone()).or_insert_with(|| {
343                            layer_unavailable(format!("{id}: root {path}: invalid registry fileId"))
344                        });
345                        None
346                    }
347                };
348            let mut project_roots = project
349                .root_records
350                .iter()
351                .flatten()
352                .filter(|root| eligible(root))
353                .map(|root| RegistryRoot {
354                    path: root.root.clone().into(),
355                    file_id: read_id(
356                        root.file_id.as_deref(),
357                        root.root.as_str(),
358                        &mut metadata_errors,
359                    ),
360                    incarnation: root.incarnation.clone(),
361                    approval: Some(root.approval.clone()),
362                    identity: Some(root.identity.clone()),
363                })
364                .collect::<Vec<_>>();
365            project_roots.sort_by(|a, b| a.path.cmp(&b.path));
366            if project_roots
367                .windows(2)
368                .any(|pair| pair[0].path == pair[1].path)
369            {
370                return Err(unavailable(format!("{id}: duplicate root path")));
371            }
372            let workspace_root = if let Some(workspace_id) = &project.workspace_id {
373                let mut matches = reply
374                    .workspaces
375                    .iter()
376                    .filter(|workspace| workspace.workspace_id == *workspace_id);
377                let workspace = matches.next().ok_or_else(|| {
378                    unavailable(format!("{id}: workspace {workspace_id} is not registered"))
379                })?;
380                if matches.next().is_some() {
381                    return Err(unavailable(format!("{id}: duplicate workspace identity")));
382                }
383                workspace.root.as_ref().map(|path| {
384                    let file_id = read_id(workspace.file_id.as_deref(), path, &mut metadata_errors);
385                    if workspace.file_id.is_none() {
386                        metadata_errors.entry(id.clone()).or_insert_with(|| {
387                            layer_unavailable(format!("{id}: workspace root {path} has no fileId"))
388                        });
389                    }
390                    RegistryRoot {
391                        path: path.into(),
392                        file_id,
393                        incarnation: None,
394                        approval: None,
395                        identity: None,
396                    }
397                })
398            } else {
399                None
400            };
401            projects.push(RegistryProject {
402                project_id: id.clone(),
403                workspace_id: project.workspace_id.clone(),
404                project_roots,
405                workspace_root,
406            });
407        }
408        Ok(Self {
409            module: module.into(),
410            projects,
411            opened: Arc::default(),
412            metadata_errors,
413        })
414    }
415
416    async fn capture_roots(&mut self, pool: &RootIoPool, scope: &RegistryScope) {
417        // Open and read once per physical path, regardless of the layer role.
418        let mut paths = BTreeMap::<_, Vec<_>>::new();
419        for project in &self.projects {
420            for root in project.roots() {
421                let allowed = paths.entry(root.path.clone()).or_default();
422                if !self.metadata_errors.contains_key(&project.project_id) {
423                    allowed.push(root.file_id.clone());
424                }
425            }
426        }
427        let mut probes = paths.into_iter();
428        let leaf = std::ffi::OsString::from(format!("{}.jsonc", self.module));
429        let mut observed = BTreeMap::new();
430        loop {
431            let jobs: Vec<_> = probes
432                .by_ref()
433                .take(pool.batch_slots())
434                .map(|(root, allowed)| {
435                    let path = root.clone();
436                    let leaf = (matches!(scope.capture, CaptureLayers::All)
437                        || scope.paths.contains(&layer_path(&path, &self.module)))
438                    .then(|| leaf.clone());
439                    (
440                        root,
441                        pool.submit(path.clone(), move || {
442                            open_root(&path, leaf.as_deref(), &allowed)
443                        }),
444                    )
445                })
446                .collect();
447            if jobs.is_empty() {
448                break;
449            }
450            for (root, job) in jobs {
451                let result = match job {
452                    Ok(job) => job.wait().await,
453                    Err(error) => Err(error),
454                };
455                observed.insert(
456                    root,
457                    result
458                        .map_err(RootCheckFailure::Pool)
459                        .and_then(|probe| probe),
460                );
461            }
462        }
463        // A registry record may name a root without its file id. Fill that gap
464        // from the identity of the root handle we actually opened, so a later
465        // recheck can tell when the folder at that path was swapped, even when
466        // the registry's own token is unchanged.
467        for project in &mut self.projects {
468            for root in project
469                .project_roots
470                .iter_mut()
471                .chain(&mut project.workspace_root)
472            {
473                if let (None, Some(Ok(opened))) = (&root.file_id, observed.get(&root.path)) {
474                    root.file_id = Some(opened.id.clone());
475                }
476            }
477        }
478        self.opened = Arc::new(observed);
479    }
480
481    fn opened_root(
482        &self,
483        project: &str,
484        root: &RegistryRoot,
485        rechecking: bool,
486    ) -> Result<&OpenedRoot> {
487        let opened = self
488            .opened
489            .get(&root.path)
490            .ok_or_else(|| layer_unavailable("registry root was not captured"))?
491            .as_ref()
492            .map_err(|error| error.error(project, &root.path, rechecking))?;
493        if root.file_id.as_ref() != Some(&opened.id) {
494            return Err(RootCheckFailure::IdentityMismatch.error(project, &root.path, rechecking));
495        }
496        Ok(opened)
497    }
498
499    fn project(&self, id: &str) -> Result<&RegistryProject> {
500        self.projects
501            .iter()
502            .find(|project| project.project_id == id)
503            .ok_or_else(|| {
504                GateError::new(
505                    "unknown_project",
506                    format!("{id}: project is not registered"),
507                )
508            })
509    }
510
511    /// Borrow a retained root and its layer observation for a registered project.
512    pub fn layer_location(&self, id: &str, root: &Path) -> Result<(&File, &LayerLocation)> {
513        let project = self.project(id)?;
514        if let Some(error) = self.metadata_errors.get(id) {
515            return Err(error.clone());
516        }
517        let mut opened = None;
518        for record in project.roots().filter(|record| record.path == root) {
519            opened = Some(self.opened_root(id, record, false)?);
520        }
521        let opened = opened.ok_or_else(|| {
522            GateError::new(
523                "layer_root_invalid",
524                "project does not authorize this layer root",
525            )
526        })?;
527        Ok((&opened.handle, location(opened, id, root)?))
528    }
529
530    /// Resolve present tuple inputs or return this project's refusal alone.
531    pub fn project_layers(&self, id: &str) -> Result<ProjectLayers<'_>> {
532        let project = self.project(id)?;
533        if let Some(error) = self.metadata_errors.get(id) {
534            return Err(error.clone());
535        }
536        let input = |root: &RegistryRoot| -> Result<_> {
537            let opened = self.opened_root(id, root, false)?;
538            Ok(location(opened, id, &root.path)?.file.as_ref())
539        };
540        let mut project_layer = None;
541        for root in &project.project_roots {
542            if let Some(file) = input(root)? {
543                if project_layer.is_some() {
544                    return Err(ambiguous(id));
545                }
546                project_layer = Some((root.path.as_path(), file));
547            }
548        }
549        let workspace = if let Some(root) = &project.workspace_root {
550            let file = input(root)?;
551            file.filter(|_| !project_layer.is_some_and(|(path, _)| path == root.path))
552                .map(|file| (root.path.as_path(), file))
553        } else {
554            None
555        };
556        Ok(ProjectLayers {
557            workspace,
558            project: project_layer,
559        })
560    }
561
562    /// Include authorized locations even if the file is absent, unreadable,
563    /// deleted or not selected as the tuple's current project layer.
564    pub fn readers(&self, path: &Path) -> BTreeSet<String> {
565        self.projects
566            .iter()
567            .filter(|project| {
568                project
569                    .roots()
570                    .any(|root| layer_path(&root.path, &self.module) == path)
571            })
572            .map(|project| project.project_id.clone())
573            .collect()
574    }
575
576    pub fn readers_before_or_proposed(&self, proposed: &Self, path: &Path) -> BTreeSet<String> {
577        self.readers(path)
578            .into_iter()
579            .chain(proposed.readers(path))
580            .collect()
581    }
582
583    pub fn digest(&self) -> Result<Digest> {
584        subc_config::digest(
585            subc_config::PURPOSE_SNAPSHOT,
586            &serde_json::json!({"kind":"project-registry-v1","registry":self}),
587        )
588        .map_err(GateError::invalid)
589    }
590
591    pub(super) fn digest_for_project(&self, id: &str) -> Result<Digest> {
592        subc_config::digest(
593            subc_config::PURPOSE_SNAPSHOT,
594            &serde_json::json!(["project-registry-entry-v1", self.module, self.project(id)?]),
595        )
596        .map_err(GateError::invalid)
597    }
598
599    /// Compare freshly derived affected entries and touched layer identities,
600    /// not the enumeration generation or bytes of other layer files.
601    pub fn recheck(&self, current: &Self, scope: &RegistryScope) -> Result<()> {
602        fn affected<'a>(
603            revision: &'a RegistryRevision,
604            scope: &RegistryScope,
605        ) -> BTreeMap<&'a str, &'a RegistryProject> {
606            revision
607                .projects
608                .iter()
609                .filter(|project| {
610                    scope.includes(
611                        &project.project_id,
612                        project.workspace_id.as_ref(),
613                        project.roots().map(|root| &root.path),
614                        &revision.module,
615                    )
616                })
617                .map(|project| (project.project_id.as_str(), project))
618                .collect()
619        }
620        let before = affected(self, scope);
621        let after = affected(current, scope);
622        if self.module != current.module || before != after {
623            return Err(changed());
624        }
625        for (id, project) in after {
626            if let Some(error) = current.metadata_errors.get(id) {
627                return Err(error.clone());
628            }
629            for root in project.roots() {
630                let opened = current.opened_root(id, root, true)?;
631                if !scope.paths.contains(&layer_path(&root.path, &self.module)) {
632                    continue;
633                }
634                let previous = self.opened_root(id, root, true)?;
635                let now = location(opened, id, &root.path).map_err(|error| {
636                    if error.code.starts_with("layer_") {
637                        changed()
638                    } else {
639                        error
640                    }
641                })?;
642                if !location(previous, id, &root.path)?.same_identity(now) {
643                    return Err(changed());
644                }
645            }
646        }
647        Ok(())
648    }
649}
650
651fn location<'a>(opened: &'a OpenedRoot, project: &str, root: &Path) -> Result<&'a LayerLocation> {
652    opened
653        .layer
654        .as_ref()
655        .ok_or_else(|| layer_unavailable("registry layer was not captured"))?
656        .as_ref()
657        .map_err(|error| {
658            GateError::new(
659                &error.code,
660                format!("{project}: root {}: {}", root.display(), error.detail),
661            )
662        })
663}
664
665fn parse_id(text: Option<&str>) -> Result<Option<RegistryFileId>> {
666    text.map(RegistryFileId::parse).transpose()
667}
668
669fn validate_module(module: &str) -> Result<()> {
670    if module.is_empty()
671        || module.contains(['/', '\\', ':', '\0'])
672        || module == "."
673        || module == ".."
674    {
675        return Err(unavailable("module identity cannot form a layer path"));
676    }
677    Ok(())
678}
679
680pub(super) fn layer_path(root: &Path, module: &str) -> PathBuf {
681    root.join(".cortexkit").join(format!("{module}.jsonc"))
682}
683
684/// Entorhinal's enumerate contract makes every listed root canonical; only one
685/// eligible root may contain a given module's project layer.
686/// Presence must come from opens beneath retained root handles, never from a
687/// caller-proposed root or an unanchored pathname probe.
688pub fn project_layer_root<'a>(
689    project: &'a Project,
690    module: &str,
691    present: &BTreeSet<PathBuf>,
692) -> Result<Option<&'a RootRecord>> {
693    validate_module(module)?;
694    let candidates: Vec<_> = project
695        .root_records
696        .iter()
697        .flatten()
698        .filter(|root| {
699            eligible(root) && present.contains(&layer_path(Path::new(&root.root), module))
700        })
701        .collect();
702    if candidates.len() > 1 {
703        return Err(GateError::new(
704            "layer_root_ambiguous",
705            format!(
706                "{}: multiple project layer roots: {}",
707                project.project_id,
708                candidates
709                    .iter()
710                    .map(|root| root.root.as_str())
711                    .collect::<Vec<_>>()
712                    .join(", ")
713            ),
714        ));
715    }
716    Ok(candidates.into_iter().next())
717}
718
719fn ambiguous(project: &str) -> GateError {
720    GateError::new(
721        "layer_root_ambiguous",
722        format!("{project}: more than one project root contains the layer"),
723    )
724}
725
726fn eligible(root: &RootRecord) -> bool {
727    root.approval.state == ApprovalState::Approved
728        && matches!(
729            root.identity,
730            RootIdentity::Bound | RootIdentity::Unverifiable
731        )
732        && (root.identity == RootIdentity::Bound && root.incarnation.is_some()
733            || root.file_id.is_some())
734}
735
736pub type RegistryFuture<'a> = Pin<Box<dyn Future<Output = Result<RegistryRevision>> + Send + 'a>>;
737#[doc(hidden)]
738pub type RegistryBatch = (Option<EnumerateReply>, BTreeMap<String, RegistryRevision>);
739#[doc(hidden)]
740pub type RegistryBatchFuture<'a> = Pin<Box<dyn Future<Output = Result<RegistryBatch>> + Send + 'a>>;
741
742pub trait ProjectRegistry: Send + Sync {
743    fn snapshot_scoped<'a>(
744        &'a self,
745        module: &'a str,
746        scope: &'a RegistryScope,
747    ) -> RegistryFuture<'a>;
748
749    /// Capture several modules against one complete enumeration when the
750    /// registry supplies it. Root I/O is independent of the runtime owner.
751    #[doc(hidden)]
752    fn capture_batch<'a>(
753        &'a self,
754        scopes: &'a BTreeMap<String, RegistryScope>,
755    ) -> RegistryBatchFuture<'a> {
756        Box::pin(async move {
757            let mut revisions = BTreeMap::new();
758            for (module, scope) in scopes {
759                revisions.insert(module.clone(), self.snapshot_scoped(module, scope).await?);
760            }
761            Ok((None, revisions))
762        })
763    }
764
765    fn snapshot<'a>(
766        &'a self,
767        module: &'a str,
768        affected: &'a BTreeSet<String>,
769    ) -> RegistryFuture<'a> {
770        Box::pin(async move {
771            let scope = RegistryScope {
772                projects: affected.clone(),
773                ..RegistryScope::default()
774            };
775            self.snapshot_scoped(module, &scope).await
776        })
777    }
778
779    #[doc(hidden)]
780    fn root_io_health(&self) -> Option<subc_control::config::ConfigRootIo> {
781        None
782    }
783
784    fn recheck<'a>(
785        &'a self,
786        saved: &'a RegistryRevision,
787        scope: &'a RegistryScope,
788    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
789        Box::pin(async move {
790            let mut scope = scope.clone();
791            scope.capture = CaptureLayers::Targets;
792            let current = self.snapshot_scoped(&saved.module, &scope).await?;
793            saved.recheck(&current, &scope)
794        })
795    }
796}
797
798#[cfg(test)]
799pub(crate) struct OfflineProjectRegistry;
800#[cfg(test)]
801impl ProjectRegistry for OfflineProjectRegistry {
802    fn snapshot_scoped<'a>(&'a self, _: &'a str, _: &'a RegistryScope) -> RegistryFuture<'a> {
803        Box::pin(async { Err(unavailable("entorhinal is not registered")) })
804    }
805}
806
807#[cfg(test)]
808mod tests;