Skip to main content

subc_daemon/config_store/records/
project_files.rs

1use std::{
2    collections::BTreeMap,
3    path::{Path, PathBuf},
4};
5
6use cortexkit_project_identity::EnumerateReply;
7use serde::{Deserialize, Serialize};
8use subc_config::Digest;
9
10use crate::config_gate::{capture::FileObjectId, project_registry::RegistryFileId, GateError};
11use crate::config_store::{StoreBody, StoreError, StoreErrorCode};
12
13#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
14pub struct RegistryMembership {
15    pub projects: BTreeMap<String, Option<String>>,
16    pub revision: RegistryMembershipRevision,
17    /// An outage is not a legacy user-only install after projects have been seen.
18    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
19    pub(crate) ever_had_projects: bool,
20}
21
22#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
23pub struct RegistryMembershipRevision {
24    pub generation: i64,
25    pub incarnation: String,
26}
27
28impl RegistryMembership {
29    /// Pass the complete successful `projects.enumerate` reply, before applying
30    /// a module's registry scope. A scoped list cannot establish a project drop.
31    pub(in crate::config_store) fn from_enumeration(
32        reply: &EnumerateReply,
33    ) -> Result<Self, GateError> {
34        let invalid = || {
35            GateError::new(
36                "project_registry_unavailable",
37                "registry membership enumeration is incomplete or contains duplicate identities",
38            )
39        };
40        let mut workspaces = std::collections::BTreeSet::new();
41        for workspace in &reply.workspaces {
42            if !workspaces.insert(&workspace.workspace_id) {
43                return Err(invalid());
44            }
45        }
46        let mut projects = BTreeMap::new();
47        for project in &reply.projects {
48            if project
49                .workspace_id
50                .as_ref()
51                .is_some_and(|workspace| !workspaces.contains(workspace))
52                || projects
53                    .insert(project.project_id.clone(), project.workspace_id.clone())
54                    .is_some()
55            {
56                return Err(invalid());
57            }
58        }
59        Ok(Self {
60            ever_had_projects: !projects.is_empty(),
61            projects,
62            revision: RegistryMembershipRevision {
63                generation: reply.generation,
64                incarnation: reply.incarnation.clone(),
65            },
66        })
67    }
68}
69
70#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(tag = "layer", rename_all = "snake_case")]
72pub enum ProjectFileLayer {
73    Workspace { workspace_id: String },
74    Project { project_id: String },
75}
76
77/// Supply the reviewed registry revision and the file identity of the open
78/// workspace or project root. This record is not authority to reopen by path.
79#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
80pub struct ProjectFileTarget {
81    pub module: String,
82    #[serde(flatten)]
83    pub layer: ProjectFileLayer,
84    pub registry_revision: Digest,
85    pub root: PathBuf,
86    pub root_identity: RegistryFileId,
87    pub relative_path: PathBuf,
88}
89
90impl ProjectFileTarget {
91    pub fn path(&self) -> Option<PathBuf> {
92        let relative = Path::new(".cortexkit").join(format!("{}.jsonc", self.module));
93        (self.root.is_absolute()
94            && self.relative_path == relative
95            && self.relative_path.components().count() == 2)
96            .then(|| self.root.join(&self.relative_path))
97    }
98}
99
100#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(tag = "state", rename_all = "snake_case")]
102pub enum ExpectedProjectFile {
103    Absent,
104    Present {
105        identity: FileObjectId,
106        digest: Digest,
107    },
108}
109
110#[derive(Clone, Serialize, Deserialize)]
111pub struct ProjectWriteBackIntent {
112    pub target: ProjectFileTarget,
113    pub expected: ExpectedProjectFile,
114    pub generation: u64,
115    #[serde(with = "encoded_bytes")]
116    pub bytes: Vec<u8>,
117}
118
119impl std::fmt::Debug for ProjectWriteBackIntent {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        f.debug_struct("ProjectWriteBackIntent")
122            .field("target", &self.target)
123            .field("expected", &self.expected)
124            .field("generation", &self.generation)
125            .finish_non_exhaustive()
126    }
127}
128
129/// Include one update per physical file in an approved plan. `Write` carries
130/// the reviewed candidate bytes and expected on-disk state. Use `Adopt` only
131/// when capture approves that file's current bytes (or absence).
132#[derive(Clone)]
133pub enum ProjectFileApproval {
134    Write {
135        target: ProjectFileTarget,
136        expected: ExpectedProjectFile,
137        bytes: Vec<u8>,
138    },
139    Adopt {
140        target: ProjectFileTarget,
141        observed_digest: Option<Digest>,
142    },
143}
144
145impl ProjectFileApproval {
146    pub(crate) fn target(&self) -> &ProjectFileTarget {
147        match self {
148            Self::Write { target, .. } | Self::Adopt { target, .. } => target,
149        }
150    }
151
152    pub(crate) fn bound_record(&self) -> serde_json::Value {
153        match self {
154            Self::Write {
155                target,
156                expected,
157                bytes,
158            } => serde_json::json!({
159                "operation": "write", "target": target, "expected": expected,
160                "candidate_digest": subc_config::raw_digest(bytes),
161            }),
162            Self::Adopt {
163                target,
164                observed_digest,
165            } => serde_json::json!({
166                "operation": "adopt", "target": target, "candidate_digest": observed_digest,
167            }),
168        }
169    }
170
171    pub(in crate::config_store) fn into_intent(
172        self,
173        generation: u64,
174    ) -> Option<ProjectWriteBackIntent> {
175        match self {
176            Self::Write {
177                target,
178                expected,
179                bytes,
180            } => Some(ProjectWriteBackIntent {
181                target,
182                expected,
183                generation,
184                bytes,
185            }),
186            Self::Adopt { .. } => None,
187        }
188    }
189}
190
191impl StoreBody {
192    pub(in crate::config_store) fn apply_project_file_approvals(
193        &mut self,
194        files: Vec<ProjectFileApproval>,
195        generation: u64,
196    ) -> Result<(), StoreError> {
197        let mut seen = std::collections::BTreeSet::new();
198        for file in files {
199            let path = file.target().path().ok_or_else(|| {
200                StoreError::new(
201                    StoreErrorCode::InvalidState,
202                    "project write-back target has an invalid layer path",
203                )
204            })?;
205            if !seen.insert(path.clone()) {
206                return Err(StoreError::new(
207                    StoreErrorCode::InvalidState,
208                    "project write-back target occurs more than once",
209                ));
210            }
211            if let Some(intent) = file.into_intent(generation) {
212                self.project_write_back.insert(path, intent);
213            } else {
214                self.project_write_back.remove(&path);
215            }
216        }
217        Ok(())
218    }
219}
220
221mod encoded_bytes {
222    use base64::{engine::general_purpose::STANDARD, Engine};
223    use serde::{Deserialize, Deserializer, Serializer};
224
225    pub(super) fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
226        serializer.serialize_str(&STANDARD.encode(bytes))
227    }
228
229    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
230        deserializer: D,
231    ) -> Result<Vec<u8>, D::Error> {
232        STANDARD
233            .decode(String::deserialize(deserializer)?)
234            .map_err(serde::de::Error::custom)
235    }
236}