1use std::collections::BTreeMap;
2use std::fmt;
3use std::path::{Path, PathBuf};
4
5use codeint_model::SourceSet;
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8
9use crate::config_error::{
10 ConfigFileKind, ConfigurationFileError, KeyPath, contains_parent_traversal,
11 is_absolute_repo_path,
12};
13use crate::repo_state::{
14 DEPENDENCY_METRIC_KEYS, LoadedForUpdate, MetricVersionMismatch, RepoStateFile,
15 SourceSetEntries, StateFileError, metric_label, read_state_file, recover_invalid_for_update,
16 state_file_exists, write_state_file,
17};
18
19#[cfg(test)]
20mod tests;
21
22pub const DEFAULT_RATCHET_PATH: &str = ".codeint/ratchet.json";
23pub const RATCHET_SCHEMA_VERSION: u32 = 1;
24const DECIMAL_SCALE: f64 = 10_000.0;
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct RatchetConfig {
28 pub path: String,
29}
30
31impl Default for RatchetConfig {
32 fn default() -> RatchetConfig {
33 RatchetConfig {
34 path: DEFAULT_RATCHET_PATH.to_owned(),
35 }
36 }
37}
38
39#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
40#[serde(deny_unknown_fields)]
41pub(crate) struct RatchetConfigFile {
42 #[serde(default, skip_serializing_if = "Option::is_none")]
43 #[schemars(
44 with = "String",
45 description = "Path relative to the repository root of the Ratchet file; .codeint/ratchet.json by default."
46 )]
47 pub(crate) path: Option<String>,
48}
49
50pub(crate) fn is_ratchet_unset(file: &RatchetConfigFile) -> bool {
51 file.path.is_none()
52}
53
54impl RatchetConfig {
55 pub(crate) fn from_file(
56 file: RatchetConfigFile,
57 ) -> Result<RatchetConfig, ConfigurationFileError> {
58 let Some(path) = file.path else {
59 return Ok(RatchetConfig::default());
60 };
61 let key = KeyPath::nested("ratchet", "path");
62 validate_relative_repo_path(&path, &key)?;
63 Ok(RatchetConfig { path })
64 }
65}
66
67fn validate_relative_repo_path(path: &str, key: &KeyPath) -> Result<(), ConfigurationFileError> {
68 if path.trim().is_empty() {
69 return Err(ConfigurationFileError::EmptyRatchetPath {
70 file: ConfigFileKind::Json,
71 key: key.clone(),
72 });
73 }
74 if is_absolute_repo_path(path) {
75 return Err(ConfigurationFileError::AbsoluteRatchetPath {
76 file: ConfigFileKind::Json,
77 key: key.clone(),
78 path: path.to_owned(),
79 });
80 }
81 if contains_parent_traversal(path) {
82 return Err(ConfigurationFileError::ParentTraversalRatchetPath {
83 file: ConfigFileKind::Json,
84 key: key.clone(),
85 path: path.to_owned(),
86 });
87 }
88 Ok(())
89}
90
91pub fn round_ratchet_ratio(ratio: f64) -> f64 {
92 let rounded = (ratio * DECIMAL_SCALE).round() / DECIMAL_SCALE;
93 if rounded == 0.0 { 0.0 } else { rounded }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
97#[serde(deny_unknown_fields)]
98pub struct RatchetEntry {
99 pub ceiling: f64,
100 pub metric_version: u32,
101}
102
103pub type RatchetSourceSets = SourceSetEntries<RatchetEntry>;
104
105#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
106#[serde(deny_unknown_fields)]
107pub struct Ratchet {
108 pub schema_version: u32,
109 #[serde(default)]
110 pub source_sets: RatchetSourceSets,
111 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
112 pub dependencies: BTreeMap<String, RatchetEntry>,
113}
114
115impl Default for Ratchet {
116 fn default() -> Ratchet {
117 Ratchet {
118 schema_version: RATCHET_SCHEMA_VERSION,
119 source_sets: RatchetSourceSets::default(),
120 dependencies: BTreeMap::new(),
121 }
122 }
123}
124
125#[derive(Debug, Clone, PartialEq)]
126pub struct MeasuredRatchetMetric {
127 pub source_set: Option<SourceSet>,
128 pub metric: String,
129 pub ratio: f64,
130 pub metric_version: u32,
131}
132
133#[derive(Debug, Clone, PartialEq)]
134pub struct RatchetViolation {
135 pub source_set: Option<SourceSet>,
136 pub metric: String,
137 pub ratio: f64,
138 pub ceiling: f64,
139}
140
141impl RatchetViolation {
142 pub fn label(&self) -> String {
143 metric_label(self.source_set, &self.metric)
144 }
145}
146
147impl fmt::Display for RatchetViolation {
148 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
149 write!(
150 formatter,
151 "{} ({} > {})",
152 self.label(),
153 self.ratio,
154 self.ceiling
155 )
156 }
157}
158
159pub type RatchetVersionMismatch = MetricVersionMismatch;
160
161#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
162pub struct RatchetUpdateSummary {
163 pub path: String,
164 pub created: bool,
165 pub reset: bool,
166 #[serde(skip_serializing_if = "std::ops::Not::not")]
167 pub replaced_invalid: bool,
168 pub tightened: usize,
169 pub loosened: usize,
170 pub refreshed: usize,
171 pub added: usize,
172 pub unchanged: usize,
173 pub removed: usize,
174 pub total_entries: usize,
175}
176
177pub type RatchetFileError = StateFileError;
178
179impl Ratchet {
180 pub fn exists(repository_root: &Path, relative_path: &str) -> Result<bool, RatchetFileError> {
181 state_file_exists(repository_root, relative_path).map_err(|fault| {
182 StateFileError::from_fault(RepoStateFile::Ratchet, relative_path, fault)
183 })
184 }
185
186 pub fn load_optional(
187 repository_root: &Path,
188 relative_path: &str,
189 ) -> Result<Option<Ratchet>, RatchetFileError> {
190 read_state_file(repository_root, relative_path)
191 .map_err(|fault| {
192 StateFileError::from_fault(RepoStateFile::Ratchet, relative_path, fault)
193 })?
194 .map(|text| Ratchet::parse(&text, relative_path))
195 .transpose()
196 }
197
198 pub fn load_for_update(
199 repository_root: &Path,
200 relative_path: &str,
201 reset: bool,
202 ) -> Result<LoadedForUpdate<Ratchet>, RatchetFileError> {
203 recover_invalid_for_update(
204 Ratchet::load_optional(repository_root, relative_path),
205 reset,
206 )
207 }
208
209 pub fn parse(text: &str, path_label: &str) -> Result<Ratchet, RatchetFileError> {
210 let ratchet: Ratchet =
211 serde_json::from_str(text).map_err(|source| StateFileError::InvalidJson {
212 file: RepoStateFile::Ratchet,
213 path: path_label.to_owned(),
214 source,
215 })?;
216 ratchet.validate(path_label)?;
217 Ok(ratchet)
218 }
219
220 pub fn write_atomic(
221 &self,
222 repository_root: &Path,
223 relative_path: &str,
224 ) -> Result<PathBuf, RatchetFileError> {
225 write_state_file(repository_root, relative_path, self).map_err(|fault| {
226 StateFileError::from_fault(RepoStateFile::Ratchet, relative_path, fault)
227 })
228 }
229
230 pub fn entry(&self, source_set: Option<SourceSet>, metric: &str) -> Option<RatchetEntry> {
231 match source_set {
232 Some(set) => self.source_sets.get(set).get(metric).copied(),
233 None => self.dependencies.get(metric).copied(),
234 }
235 }
236
237 pub fn total_entries(&self) -> usize {
238 self.source_sets
239 .iter()
240 .into_iter()
241 .map(|(_, entries)| entries.len())
242 .sum::<usize>()
243 + self.dependencies.len()
244 }
245
246 pub fn check(
247 &self,
248 measured: &[MeasuredRatchetMetric],
249 ) -> Result<Vec<RatchetViolation>, Vec<RatchetVersionMismatch>> {
250 let mut mismatches = Vec::new();
251 let mut violations = Vec::new();
252 for item in measured {
253 let Some(stored) = self.entry(item.source_set, &item.metric) else {
254 continue;
255 };
256 if stored.metric_version != item.metric_version {
257 mismatches.push(MetricVersionMismatch {
258 state_file: RepoStateFile::Ratchet,
259 source_set: item.source_set,
260 metric: item.metric.clone(),
261 recorded_version: stored.metric_version,
262 current_version: item.metric_version,
263 });
264 continue;
265 }
266 let current = round_ratchet_ratio(item.ratio);
267 let ceiling = round_ratchet_ratio(stored.ceiling);
268 if current > ceiling {
269 violations.push(RatchetViolation {
270 source_set: item.source_set,
271 metric: item.metric.clone(),
272 ratio: current,
273 ceiling,
274 });
275 }
276 }
277 if !mismatches.is_empty() {
278 return Err(mismatches);
279 }
280 Ok(violations)
281 }
282
283 pub fn update(
284 existing: Option<&Ratchet>,
285 measured: &[MeasuredRatchetMetric],
286 reset: bool,
287 path_label: &str,
288 ) -> Result<(Ratchet, RatchetUpdateSummary), Vec<RatchetViolation>> {
289 let mut next = if reset {
290 Ratchet::default()
291 } else {
292 let mut seeded = existing.cloned().unwrap_or_default();
293 seeded.schema_version = RATCHET_SCHEMA_VERSION;
294 seeded
295 };
296 let mut acc = RatchetUpdateAccumulator::default();
297 for item in measured {
298 let previous = existing.and_then(|prev| prev.entry(item.source_set, &item.metric));
299 let new_entry = acc.record(item, previous, reset);
300 next.insert(item.source_set, item.metric.clone(), new_entry);
301 }
302 if !acc.regressions.is_empty() {
303 return Err(acc.regressions);
304 }
305 let summary = acc.into_summary(existing, &next, reset, path_label);
306 Ok((next, summary))
307 }
308
309 fn insert(&mut self, source_set: Option<SourceSet>, metric: String, entry: RatchetEntry) {
310 match source_set {
311 Some(set) => {
312 self.source_sets.get_mut(set).insert(metric, entry);
313 }
314 None => {
315 self.dependencies.insert(metric, entry);
316 }
317 }
318 }
319
320 fn validate(&self, path_label: &str) -> Result<(), RatchetFileError> {
321 if self.schema_version != RATCHET_SCHEMA_VERSION {
322 return Err(StateFileError::UnsupportedSchemaVersion {
323 file: RepoStateFile::Ratchet,
324 path: path_label.to_owned(),
325 found: self.schema_version,
326 expected: RATCHET_SCHEMA_VERSION,
327 });
328 }
329 for (source_set, entries) in self.source_sets.iter() {
330 for (metric, entry) in entries {
331 validate_entry(
332 path_label,
333 &format!("{}.{metric}", source_set.key()),
334 *entry,
335 )?;
336 }
337 }
338 for (metric, entry) in &self.dependencies {
339 if !DEPENDENCY_METRIC_KEYS.contains(&metric.as_str()) {
340 return Err(StateFileError::UnknownDependencyMetric {
341 file: RepoStateFile::Ratchet,
342 path: path_label.to_owned(),
343 metric: metric.clone(),
344 allowed: DEPENDENCY_METRIC_KEYS.join(", "),
345 });
346 }
347 validate_entry(path_label, metric, *entry)?;
348 }
349 Ok(())
350 }
351}
352
353fn validate_entry(
354 path_label: &str,
355 metric_label: &str,
356 entry: RatchetEntry,
357) -> Result<(), RatchetFileError> {
358 if !entry.ceiling.is_finite() || !(0.0..=1.0).contains(&entry.ceiling) {
359 return Err(StateFileError::InvalidCeiling {
360 file: RepoStateFile::Ratchet,
361 path: path_label.to_owned(),
362 metric: metric_label.to_owned(),
363 ceiling: entry.ceiling,
364 });
365 }
366 if entry.metric_version == 0 {
367 return Err(StateFileError::InvalidMetricVersion {
368 file: RepoStateFile::Ratchet,
369 path: path_label.to_owned(),
370 metric: metric_label.to_owned(),
371 });
372 }
373 Ok(())
374}
375
376#[derive(Default)]
377struct RatchetUpdateAccumulator {
378 regressions: Vec<RatchetViolation>,
379 tightened: usize,
380 loosened: usize,
381 refreshed: usize,
382 added: usize,
383 unchanged: usize,
384}
385
386impl RatchetUpdateAccumulator {
387 fn record(
388 &mut self,
389 item: &MeasuredRatchetMetric,
390 previous: Option<RatchetEntry>,
391 reset: bool,
392 ) -> RatchetEntry {
393 let current = round_ratchet_ratio(item.ratio);
394 let Some(stored) = previous else {
395 self.added += 1;
396 return RatchetEntry {
397 ceiling: current,
398 metric_version: item.metric_version,
399 };
400 };
401 if stored.metric_version != item.metric_version {
402 self.refreshed += 1;
403 return RatchetEntry {
404 ceiling: current,
405 metric_version: item.metric_version,
406 };
407 }
408 self.record_same_version(item, current, round_ratchet_ratio(stored.ceiling), reset)
409 }
410
411 fn record_same_version(
412 &mut self,
413 item: &MeasuredRatchetMetric,
414 current: f64,
415 stored_ceiling: f64,
416 reset: bool,
417 ) -> RatchetEntry {
418 let ceiling = if current < stored_ceiling {
419 self.tightened += 1;
420 current
421 } else if current == stored_ceiling {
422 self.unchanged += 1;
423 stored_ceiling
424 } else if reset {
425 self.loosened += 1;
426 current
427 } else {
428 self.regressions.push(RatchetViolation {
429 source_set: item.source_set,
430 metric: item.metric.clone(),
431 ratio: current,
432 ceiling: stored_ceiling,
433 });
434 stored_ceiling
435 };
436 RatchetEntry {
437 ceiling,
438 metric_version: item.metric_version,
439 }
440 }
441
442 fn into_summary(
443 self,
444 existing: Option<&Ratchet>,
445 next: &Ratchet,
446 reset: bool,
447 path_label: &str,
448 ) -> RatchetUpdateSummary {
449 let previous_total = existing.map_or(0, Ratchet::total_entries);
450 let retained = self.tightened + self.loosened + self.refreshed + self.unchanged;
451 let unmeasured = previous_total.saturating_sub(retained);
452 let (removed, unchanged) = if reset {
453 (unmeasured, self.unchanged)
454 } else {
455 (0, self.unchanged + unmeasured)
456 };
457 RatchetUpdateSummary {
458 path: path_label.to_owned(),
459 created: existing.is_none(),
460 reset,
461 replaced_invalid: false,
462 tightened: self.tightened,
463 loosened: self.loosened,
464 refreshed: self.refreshed,
465 added: self.added,
466 unchanged,
467 removed,
468 total_entries: next.total_entries(),
469 }
470 }
471}