1use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6
7use crate::error::ErrorCode;
8use crate::model::StoreModel;
9use crate::model::clients::known_client;
10use crate::model::ids::{self, IdKind};
11use crate::model::validate::{Diagnostics, at, join};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
15#[serde(rename_all = "lowercase")]
16pub enum ApplyTrigger {
17 Instant,
18 Review,
19 Restore,
20 Rollback,
21 Pull,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
26#[serde(rename_all = "lowercase")]
27pub enum ApplyOutcome {
28 Ok,
29 Partial,
30 Blocked,
31 Failed,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
36#[serde(rename_all = "kebab-case")]
37pub enum Scope {
38 User,
39 Project,
40 ProjectLocal,
41}
42
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
44#[schemars(title = "Surjection apply record (store/machines/<machine-id>.applied.toml)")]
45pub struct AppliedRecord {
46 #[schemars(extend("const" = 1))]
48 pub schema: i64,
49 #[schemars(extend("pattern" = ids::ULID_PATTERN))]
51 pub machine_id: String,
52 #[schemars(extend("pattern" = ids::ULID_PATTERN))]
54 pub apply_id: String,
55 #[schemars(with = "String", extend("format" = "date-time"))]
57 pub time: toml::value::Datetime,
58 pub store_revision: String,
60 pub trigger: ApplyTrigger,
61 pub outcome: ApplyOutcome,
62 #[serde(default, skip_serializing_if = "Vec::is_empty")]
64 pub targets: Vec<AppliedTarget>,
65 #[serde(flatten)]
66 #[schemars(skip)]
67 pub extra: toml::Table,
68}
69
70impl StoreModel for AppliedRecord {
71 const SCHEMA_NAME: &'static str = "applied";
72}
73
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
75pub struct AppliedTarget {
76 pub client: String,
77 pub scope: Scope,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub project_id: Option<String>,
81 pub file: String,
84 pub create: u32,
85 pub update: u32,
86 pub remove: u32,
87 pub disable: u32,
88 pub outcome: ApplyOutcome,
89 #[serde(flatten)]
90 #[schemars(skip)]
91 pub extra: toml::Table,
92}
93
94impl AppliedRecord {
95 pub fn validate(&self, file_id: Option<&str>) -> Diagnostics {
98 let mut d = Diagnostics::new();
99 d.check_named_id(IdKind::Machine, &self.machine_id, "machine_id", file_id);
100 d.check_id(IdKind::Apply, &self.apply_id, "apply_id");
101 let complete = self.time.date.is_some() && self.time.time.is_some();
102 if !complete || self.time.offset.is_none() {
103 d.error(
104 ErrorCode::InvalidValue,
105 "time",
106 "`time` must be an offset date-time such as 2026-01-01T00:00:00Z",
107 );
108 }
109 if !ids::is_commit_id(&self.store_revision) {
110 d.error(
111 ErrorCode::InvalidValue,
112 "store_revision",
113 format!("{:?} is not a git commit id", self.store_revision),
114 );
115 }
116 for (index, target) in self.targets.iter().enumerate() {
117 let path = at("targets", index);
118 if known_client(&target.client).is_none() {
119 d.warning(
120 ErrorCode::UnknownClient,
121 join(&path, "client"),
122 format!("unknown client {:?}; kept as written", target.client),
123 );
124 }
125 match (target.scope, &target.project_id) {
126 (Scope::Project | Scope::ProjectLocal, None) => d.error(
127 ErrorCode::MissingField,
128 join(&path, "project_id"),
129 "project targets need `project_id`",
130 ),
131 (_, Some(id)) => {
132 d.check_id(IdKind::Project, id, &join(&path, "project_id"));
133 }
134 (Scope::User, None) => {}
135 }
136 if !has_placeholder_root(&target.file) {
137 d.error(
138 ErrorCode::InvalidPath,
139 join(&path, "file"),
140 format!(
141 "{:?} must start with `~/`, `<P>/`, `%NAME%/` or `$NAME/`",
142 target.file
143 ),
144 );
145 }
146 }
147 d
148 }
149}
150
151fn has_placeholder_root(file: &str) -> bool {
155 if ["~/", "<P>/"].iter().any(|root| file.starts_with(root)) {
156 return true;
157 }
158 let var = |name: &str| ids::is_valid(IdKind::EnvVar, name);
159 if let Some(rest) = file.strip_prefix('%')
160 && let Some((name, _)) = rest.split_once("%/")
161 {
162 return var(name);
163 }
164 file.strip_prefix('$')
165 .and_then(|rest| rest.split_once('/'))
166 .is_some_and(|(name, _)| var(name))
167}