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