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/// Observed state of one module's physical repository file. The two flags
111/// are independent: a pending write can coexist with an external proposal.
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
113pub struct ProjectWriteBackStatus {
114    /// A committed edit still has an intent. No matching file was confirmed
115    /// by the writer or by a fresh authorized read.
116    pub write_back_behind: bool,
117    /// The observed digest or presence differs from the approved snapshot.
118    /// Only capture approval or reconciliation of matching bytes clears this.
119    pub pending_proposal: bool,
120}
121
122#[derive(Clone, Serialize, Deserialize)]
123pub struct ProjectWriteBackIntent {
124    pub target: ProjectFileTarget,
125    pub expected: ExpectedProjectFile,
126    pub generation: u64,
127    // A deleted approved file is dirty, not an authorized first publish.
128    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
129    pub missing_approved: bool,
130    #[serde(with = "encoded_bytes")]
131    pub bytes: Vec<u8>,
132}
133
134impl std::fmt::Debug for ProjectWriteBackIntent {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        f.debug_struct("ProjectWriteBackIntent")
137            .field("target", &self.target)
138            .field("expected", &self.expected)
139            .field("generation", &self.generation)
140            .finish_non_exhaustive()
141    }
142}
143
144/// Include one update per physical file in an approved plan. `Write` carries
145/// the reviewed candidate bytes and expected on-disk state. Use `Adopt` only
146/// when capture approves that file's current bytes (or absence).
147#[derive(Clone)]
148pub enum ProjectFileApproval {
149    Write {
150        target: ProjectFileTarget,
151        expected: ExpectedProjectFile,
152        bytes: Vec<u8>,
153        missing_approved: bool,
154    },
155    Adopt {
156        target: ProjectFileTarget,
157        observed_digest: Option<Digest>,
158    },
159}
160
161impl ProjectFileApproval {
162    pub(crate) fn target(&self) -> &ProjectFileTarget {
163        match self {
164            Self::Write { target, .. } | Self::Adopt { target, .. } => target,
165        }
166    }
167
168    pub(crate) fn bound_record(&self) -> serde_json::Value {
169        match self {
170            Self::Write {
171                target,
172                expected,
173                bytes,
174                missing_approved,
175            } => serde_json::json!({
176                "operation": "write", "target": target, "expected": expected,
177                "candidate_digest": subc_config::raw_digest(bytes),
178                "missing_approved": missing_approved,
179            }),
180            Self::Adopt {
181                target,
182                observed_digest,
183            } => serde_json::json!({
184                "operation": "adopt", "target": target, "candidate_digest": observed_digest,
185            }),
186        }
187    }
188
189    pub(crate) fn into_intent(self, generation: u64) -> Option<ProjectWriteBackIntent> {
190        match self {
191            Self::Write {
192                target,
193                expected,
194                bytes,
195                missing_approved,
196            } => Some(ProjectWriteBackIntent {
197                target,
198                expected,
199                generation,
200                bytes,
201                missing_approved,
202            }),
203            Self::Adopt { .. } => None,
204        }
205    }
206}
207
208impl StoreBody {
209    /// Read the write-back/proposal inputs for a settings row without opening
210    /// any roots. A cleared intent with matching observations is in sync; the
211    /// store does not retain a separate record of which writes were adopted.
212    pub fn project_write_back_status(
213        &self,
214        module: &str,
215        path: &Path,
216    ) -> Result<ProjectWriteBackStatus, GateError> {
217        use crate::config_gate::{CapturedInput, InputKey};
218        use crate::config_store::Snapshot;
219        use subc_config::{InputState, RecordedValue};
220        let invalid = || GateError::new("config_unavailable", "invalid project file observation");
221        let key = serde_json::to_string(&InputKey::ProjectFile {
222            module: module.into(),
223            path: path.to_string_lossy().into_owned(),
224        })
225        .map_err(|_| invalid())?;
226        let state = |snapshot: &Snapshot| -> Result<InputState, GateError> {
227            match snapshot.get(&key) {
228                None => Ok(InputState::Absent),
229                Some(RecordedValue::Value { value }) => {
230                    serde_json::from_value::<CapturedInput>(value.clone())
231                        .map(|input| input.state)
232                        .map_err(|_| invalid())
233                }
234                _ => Err(invalid()),
235            }
236        };
237        let pending_proposal = if let Some(observed) = &self.observed {
238            state(observed)? != state(&self.approved)?
239        } else {
240            false
241        };
242        Ok(ProjectWriteBackStatus {
243            write_back_behind: self
244                .project_write_back
245                .get(path)
246                .is_some_and(|intent| intent.target.module == module),
247            pending_proposal,
248        })
249    }
250
251    pub(in crate::config_store) fn apply_project_file_approvals(
252        &mut self,
253        files: Vec<ProjectFileApproval>,
254        generation: u64,
255    ) -> Result<(), StoreError> {
256        let mut seen = std::collections::BTreeSet::new();
257        for file in files {
258            let path = file.target().path().ok_or_else(|| {
259                StoreError::new(
260                    StoreErrorCode::InvalidState,
261                    "project write-back target has an invalid layer path",
262                )
263            })?;
264            if !seen.insert(path.clone()) {
265                return Err(StoreError::new(
266                    StoreErrorCode::InvalidState,
267                    "project write-back target occurs more than once",
268                ));
269            }
270            if let Some(intent) = file.into_intent(generation) {
271                self.project_write_back.insert(path, intent);
272            } else {
273                self.project_write_back.remove(&path);
274            }
275        }
276        Ok(())
277    }
278}
279
280mod encoded_bytes {
281    use base64::{engine::general_purpose::STANDARD, Engine};
282    use serde::{Deserialize, Deserializer, Serializer};
283
284    pub(super) fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
285        serializer.serialize_str(&STANDARD.encode(bytes))
286    }
287
288    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
289        deserializer: D,
290    ) -> Result<Vec<u8>, D::Error> {
291        STANDARD
292            .decode(String::deserialize(deserializer)?)
293            .map_err(serde::de::Error::custom)
294    }
295}