1use 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#[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 fn roots(&self) -> impl Iterator<Item = &RegistryRoot> {
170 self.project_roots.iter().chain(&self.workspace_root)
171 }
172}
173
174#[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 pub fn all() -> Self {
207 Self {
208 all_registered: true,
209 ..Self::default()
210 }
211 }
212
213 fn includes(
214 &self,
215 id: &str,
216 workspace: Option<&String>,
217 roots: impl IntoIterator<Item = impl AsRef<Path>>,
218 module: &str,
219 ) -> bool {
220 self.all_registered
221 || self.projects.contains(id)
222 || workspace.is_some_and(|id| self.workspaces.contains(id))
223 || roots
224 .into_iter()
225 .any(|root| self.paths.contains(&layer_path(root.as_ref(), module)))
226 }
227}
228
229pub struct ProjectLayers<'a> {
231 pub workspace: Option<(&'a Path, &'a LayerFile)>,
232 pub project: Option<(&'a Path, &'a LayerFile)>,
233}
234
235#[derive(Clone, Serialize, Deserialize)]
238pub struct RegistryRevision {
239 pub module: String,
240 pub projects: Vec<RegistryProject>,
241 #[serde(skip)]
242 opened: Arc<BTreeMap<PathBuf, std::result::Result<OpenedRoot, RootCheckFailure>>>,
243 #[serde(skip)]
244 metadata_errors: BTreeMap<String, GateError>,
245}
246
247impl std::fmt::Debug for RegistryRevision {
248 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
249 f.debug_struct("RegistryRevision")
250 .field("module", &self.module)
251 .field("projects", &self.projects)
252 .finish_non_exhaustive()
253 }
254}
255
256impl PartialEq for RegistryRevision {
257 fn eq(&self, other: &Self) -> bool {
258 self.module == other.module && self.projects == other.projects
259 }
260}
261impl Eq for RegistryRevision {}
262
263impl RegistryRevision {
264 pub async fn from_enumerate(
265 pool: &RootIoPool,
266 reply: &EnumerateReply,
267 module: &str,
268 affected: &BTreeSet<String>,
269 ) -> Result<Self> {
270 let mut revision = Self::parse_enumeration(reply, module, affected)?;
271 revision
272 .capture_roots(pool, &RegistryScope::default())
273 .await;
274 Ok(revision)
275 }
276
277 pub async fn from_scope(
278 pool: &RootIoPool,
279 reply: &EnumerateReply,
280 module: &str,
281 scope: &RegistryScope,
282 ) -> Result<Self> {
283 let affected = reply
284 .projects
285 .iter()
286 .filter_map(|project| {
287 let roots = project
288 .root_records
289 .iter()
290 .flatten()
291 .filter(|root| eligible(root))
292 .map(|root| root.root.as_str());
293 let workspace = reply
294 .workspaces
295 .iter()
296 .filter(|workspace| {
297 project.workspace_id.as_ref() == Some(&workspace.workspace_id)
298 })
299 .filter_map(|workspace| workspace.root.as_deref());
300 scope
301 .includes(
302 &project.project_id,
303 project.workspace_id.as_ref(),
304 roots.chain(workspace),
305 module,
306 )
307 .then(|| project.project_id.clone())
308 })
309 .collect();
310 let mut revision = Self::parse_enumeration(reply, module, &affected)?;
311 revision.capture_roots(pool, scope).await;
312 Ok(revision)
313 }
314
315 fn parse_enumeration(
316 reply: &EnumerateReply,
317 module: &str,
318 affected: &BTreeSet<String>,
319 ) -> Result<Self> {
320 validate_module(module)?;
321 let mut projects = Vec::new();
322 let mut metadata_errors = BTreeMap::new();
323 for id in affected {
324 let mut matches = reply
325 .projects
326 .iter()
327 .filter(|project| project.project_id == *id);
328 let project = matches
329 .next()
330 .ok_or_else(|| unavailable(format!("{id}: project is not registered")))?;
331 if matches.next().is_some() {
332 return Err(unavailable(format!("{id}: duplicate project identity")));
333 }
334 let read_id =
335 |text, path, errors: &mut BTreeMap<String, GateError>| match parse_id(text) {
336 Ok(file_id) => file_id,
337 Err(_) => {
338 errors.entry(id.clone()).or_insert_with(|| {
339 layer_unavailable(format!("{id}: root {path}: invalid registry fileId"))
340 });
341 None
342 }
343 };
344 let mut project_roots = project
345 .root_records
346 .iter()
347 .flatten()
348 .filter(|root| eligible(root))
349 .map(|root| RegistryRoot {
350 path: root.root.clone().into(),
351 file_id: read_id(
352 root.file_id.as_deref(),
353 root.root.as_str(),
354 &mut metadata_errors,
355 ),
356 incarnation: root.incarnation.clone(),
357 approval: Some(root.approval.clone()),
358 identity: Some(root.identity.clone()),
359 })
360 .collect::<Vec<_>>();
361 project_roots.sort_by(|a, b| a.path.cmp(&b.path));
362 if project_roots
363 .windows(2)
364 .any(|pair| pair[0].path == pair[1].path)
365 {
366 return Err(unavailable(format!("{id}: duplicate root path")));
367 }
368 let workspace_root = if let Some(workspace_id) = &project.workspace_id {
369 let mut matches = reply
370 .workspaces
371 .iter()
372 .filter(|workspace| workspace.workspace_id == *workspace_id);
373 let workspace = matches.next().ok_or_else(|| {
374 unavailable(format!("{id}: workspace {workspace_id} is not registered"))
375 })?;
376 if matches.next().is_some() {
377 return Err(unavailable(format!("{id}: duplicate workspace identity")));
378 }
379 workspace.root.as_ref().map(|path| {
380 let file_id = read_id(workspace.file_id.as_deref(), path, &mut metadata_errors);
381 if workspace.file_id.is_none() {
382 metadata_errors.entry(id.clone()).or_insert_with(|| {
383 layer_unavailable(format!("{id}: workspace root {path} has no fileId"))
384 });
385 }
386 RegistryRoot {
387 path: path.into(),
388 file_id,
389 incarnation: None,
390 approval: None,
391 identity: None,
392 }
393 })
394 } else {
395 None
396 };
397 projects.push(RegistryProject {
398 project_id: id.clone(),
399 workspace_id: project.workspace_id.clone(),
400 project_roots,
401 workspace_root,
402 });
403 }
404 Ok(Self {
405 module: module.into(),
406 projects,
407 opened: Arc::default(),
408 metadata_errors,
409 })
410 }
411
412 async fn capture_roots(&mut self, pool: &RootIoPool, scope: &RegistryScope) {
413 let mut paths = BTreeMap::<_, Vec<_>>::new();
415 for project in &self.projects {
416 for root in project.roots() {
417 let allowed = paths.entry(root.path.clone()).or_default();
418 if !self.metadata_errors.contains_key(&project.project_id) {
419 allowed.push(root.file_id.clone());
420 }
421 }
422 }
423 let mut probes = paths.into_iter();
424 let leaf = std::ffi::OsString::from(format!("{}.jsonc", self.module));
425 let mut observed = BTreeMap::new();
426 loop {
427 let jobs: Vec<_> = probes
428 .by_ref()
429 .take(pool.batch_slots())
430 .map(|(root, allowed)| {
431 let path = root.clone();
432 let leaf = (matches!(scope.capture, CaptureLayers::All)
433 || scope.paths.contains(&layer_path(&path, &self.module)))
434 .then(|| leaf.clone());
435 (
436 root,
437 pool.submit(path.clone(), move || {
438 open_root(&path, leaf.as_deref(), &allowed)
439 }),
440 )
441 })
442 .collect();
443 if jobs.is_empty() {
444 break;
445 }
446 for (root, job) in jobs {
447 let result = match job {
448 Ok(job) => job.wait().await,
449 Err(error) => Err(error),
450 };
451 observed.insert(
452 root,
453 result
454 .map_err(RootCheckFailure::Pool)
455 .and_then(|probe| probe),
456 );
457 }
458 }
459 for project in &mut self.projects {
464 for root in project
465 .project_roots
466 .iter_mut()
467 .chain(&mut project.workspace_root)
468 {
469 if let (None, Some(Ok(opened))) = (&root.file_id, observed.get(&root.path)) {
470 root.file_id = Some(opened.id.clone());
471 }
472 }
473 }
474 self.opened = Arc::new(observed);
475 }
476
477 fn opened_root(
478 &self,
479 project: &str,
480 root: &RegistryRoot,
481 rechecking: bool,
482 ) -> Result<&OpenedRoot> {
483 let opened = self
484 .opened
485 .get(&root.path)
486 .ok_or_else(|| layer_unavailable("registry root was not captured"))?
487 .as_ref()
488 .map_err(|error| error.error(project, &root.path, rechecking))?;
489 if root.file_id.as_ref() != Some(&opened.id) {
490 return Err(RootCheckFailure::IdentityMismatch.error(project, &root.path, rechecking));
491 }
492 Ok(opened)
493 }
494
495 fn project(&self, id: &str) -> Result<&RegistryProject> {
496 self.projects
497 .iter()
498 .find(|project| project.project_id == id)
499 .ok_or_else(|| {
500 GateError::new(
501 "unknown_project",
502 format!("{id}: project is not registered"),
503 )
504 })
505 }
506
507 pub fn layer_location(&self, id: &str, root: &Path) -> Result<(&File, &LayerLocation)> {
509 let project = self.project(id)?;
510 if let Some(error) = self.metadata_errors.get(id) {
511 return Err(error.clone());
512 }
513 let mut opened = None;
514 for record in project.roots().filter(|record| record.path == root) {
515 opened = Some(self.opened_root(id, record, false)?);
516 }
517 let opened = opened.ok_or_else(|| {
518 GateError::new(
519 "layer_root_invalid",
520 "project does not authorize this layer root",
521 )
522 })?;
523 Ok((&opened.handle, location(opened, id, root)?))
524 }
525
526 pub fn project_layers(&self, id: &str) -> Result<ProjectLayers<'_>> {
528 let project = self.project(id)?;
529 if let Some(error) = self.metadata_errors.get(id) {
530 return Err(error.clone());
531 }
532 let input = |root: &RegistryRoot| -> Result<_> {
533 let opened = self.opened_root(id, root, false)?;
534 Ok(location(opened, id, &root.path)?.file.as_ref())
535 };
536 let mut project_layer = None;
537 for root in &project.project_roots {
538 if let Some(file) = input(root)? {
539 if project_layer.is_some() {
540 return Err(ambiguous(id));
541 }
542 project_layer = Some((root.path.as_path(), file));
543 }
544 }
545 let workspace = if let Some(root) = &project.workspace_root {
546 let file = input(root)?;
547 file.filter(|_| !project_layer.is_some_and(|(path, _)| path == root.path))
548 .map(|file| (root.path.as_path(), file))
549 } else {
550 None
551 };
552 Ok(ProjectLayers {
553 workspace,
554 project: project_layer,
555 })
556 }
557
558 pub fn readers(&self, path: &Path) -> BTreeSet<String> {
561 self.projects
562 .iter()
563 .filter(|project| {
564 project
565 .roots()
566 .any(|root| layer_path(&root.path, &self.module) == path)
567 })
568 .map(|project| project.project_id.clone())
569 .collect()
570 }
571
572 pub fn readers_before_or_proposed(&self, proposed: &Self, path: &Path) -> BTreeSet<String> {
573 self.readers(path)
574 .into_iter()
575 .chain(proposed.readers(path))
576 .collect()
577 }
578
579 pub fn digest(&self) -> Result<Digest> {
580 subc_config::digest(
581 subc_config::PURPOSE_SNAPSHOT,
582 &serde_json::json!({"kind":"project-registry-v1","registry":self}),
583 )
584 .map_err(GateError::invalid)
585 }
586
587 pub fn recheck(&self, current: &Self, scope: &RegistryScope) -> Result<()> {
590 fn affected<'a>(
591 revision: &'a RegistryRevision,
592 scope: &RegistryScope,
593 ) -> BTreeMap<&'a str, &'a RegistryProject> {
594 revision
595 .projects
596 .iter()
597 .filter(|project| {
598 scope.includes(
599 &project.project_id,
600 project.workspace_id.as_ref(),
601 project.roots().map(|root| &root.path),
602 &revision.module,
603 )
604 })
605 .map(|project| (project.project_id.as_str(), project))
606 .collect()
607 }
608 let before = affected(self, scope);
609 let after = affected(current, scope);
610 if self.module != current.module || before != after {
611 return Err(changed());
612 }
613 for (id, project) in after {
614 if let Some(error) = current.metadata_errors.get(id) {
615 return Err(error.clone());
616 }
617 for root in project.roots() {
618 let opened = current.opened_root(id, root, true)?;
619 if !scope.paths.contains(&layer_path(&root.path, &self.module)) {
620 continue;
621 }
622 let previous = self.opened_root(id, root, true)?;
623 let now = location(opened, id, &root.path).map_err(|error| {
624 if error.code.starts_with("layer_") {
625 changed()
626 } else {
627 error
628 }
629 })?;
630 if !location(previous, id, &root.path)?.same_identity(now) {
631 return Err(changed());
632 }
633 }
634 }
635 Ok(())
636 }
637}
638
639fn location<'a>(opened: &'a OpenedRoot, project: &str, root: &Path) -> Result<&'a LayerLocation> {
640 opened
641 .layer
642 .as_ref()
643 .ok_or_else(|| layer_unavailable("registry layer was not captured"))?
644 .as_ref()
645 .map_err(|error| {
646 GateError::new(
647 &error.code,
648 format!("{project}: root {}: {}", root.display(), error.detail),
649 )
650 })
651}
652
653fn parse_id(text: Option<&str>) -> Result<Option<RegistryFileId>> {
654 text.map(RegistryFileId::parse).transpose()
655}
656
657fn validate_module(module: &str) -> Result<()> {
658 if module.is_empty()
659 || module.contains(['/', '\\', ':', '\0'])
660 || module == "."
661 || module == ".."
662 {
663 return Err(unavailable("module identity cannot form a layer path"));
664 }
665 Ok(())
666}
667
668fn layer_path(root: &Path, module: &str) -> PathBuf {
669 root.join(".cortexkit").join(format!("{module}.jsonc"))
670}
671
672pub fn project_layer_root<'a>(
677 project: &'a Project,
678 module: &str,
679 present: &BTreeSet<PathBuf>,
680) -> Result<Option<&'a RootRecord>> {
681 validate_module(module)?;
682 let candidates: Vec<_> = project
683 .root_records
684 .iter()
685 .flatten()
686 .filter(|root| {
687 eligible(root) && present.contains(&layer_path(Path::new(&root.root), module))
688 })
689 .collect();
690 if candidates.len() > 1 {
691 return Err(GateError::new(
692 "layer_root_ambiguous",
693 format!(
694 "{}: multiple project layer roots: {}",
695 project.project_id,
696 candidates
697 .iter()
698 .map(|root| root.root.as_str())
699 .collect::<Vec<_>>()
700 .join(", ")
701 ),
702 ));
703 }
704 Ok(candidates.into_iter().next())
705}
706
707fn ambiguous(project: &str) -> GateError {
708 GateError::new(
709 "layer_root_ambiguous",
710 format!("{project}: more than one project root contains the layer"),
711 )
712}
713
714fn eligible(root: &RootRecord) -> bool {
715 root.approval.state == ApprovalState::Approved
716 && matches!(
717 root.identity,
718 RootIdentity::Bound | RootIdentity::Unverifiable
719 )
720 && (root.identity == RootIdentity::Bound && root.incarnation.is_some()
721 || root.file_id.is_some())
722}
723
724pub type RegistryFuture<'a> = Pin<Box<dyn Future<Output = Result<RegistryRevision>> + Send + 'a>>;
725pub trait ProjectRegistry: Send + Sync {
726 fn snapshot_scoped<'a>(
727 &'a self,
728 module: &'a str,
729 scope: &'a RegistryScope,
730 ) -> RegistryFuture<'a>;
731
732 fn snapshot<'a>(
733 &'a self,
734 module: &'a str,
735 affected: &'a BTreeSet<String>,
736 ) -> RegistryFuture<'a> {
737 Box::pin(async move {
738 let scope = RegistryScope {
739 projects: affected.clone(),
740 ..RegistryScope::default()
741 };
742 self.snapshot_scoped(module, &scope).await
743 })
744 }
745
746 #[doc(hidden)]
747 fn root_io_health(&self) -> Option<subc_control::config::ConfigRootIo> {
748 None
749 }
750
751 fn recheck<'a>(
752 &'a self,
753 saved: &'a RegistryRevision,
754 scope: &'a RegistryScope,
755 ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
756 Box::pin(async move {
757 let mut scope = scope.clone();
758 scope.capture = CaptureLayers::Targets;
759 let current = self.snapshot_scoped(&saved.module, &scope).await?;
760 saved.recheck(¤t, &scope)
761 })
762 }
763}
764
765#[cfg(test)]
766pub(crate) struct OfflineProjectRegistry;
767#[cfg(test)]
768impl ProjectRegistry for OfflineProjectRegistry {
769 fn snapshot_scoped<'a>(&'a self, _: &'a str, _: &'a RegistryScope) -> RegistryFuture<'a> {
770 Box::pin(async { Err(unavailable("entorhinal is not registered")) })
771 }
772}
773
774#[cfg(test)]
775mod tests;