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