1use std::cmp::Ordering;
2use std::collections::BTreeMap;
3
4use serde::Serialize;
5
6use crate::manifest::{Manifest, ManifestOutput};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub struct ManifestCompareOptions {
10 pub top_limit: usize,
11}
12
13impl Default for ManifestCompareOptions {
14 fn default() -> Self {
15 Self { top_limit: 5 }
16 }
17}
18
19#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
20pub struct ManifestCompare {
21 pub base_generated_at: String,
22 pub head_generated_at: String,
23 pub base_config_hash: String,
24 pub head_config_hash: String,
25 pub summary: ManifestCompareSummary,
26 pub added: Vec<ManifestCompareOutput>,
27 pub removed: Vec<ManifestCompareOutput>,
28 pub changed: Vec<ManifestCompareChange>,
29 pub metadata_changed: Vec<ManifestCompareMetadataChange>,
30 pub top_byte_contributors: Vec<ManifestCompareOutput>,
31}
32
33#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
34pub struct ManifestCompareSummary {
35 pub base_variant_count: u64,
36 pub head_variant_count: u64,
37 pub variant_count_delta: i64,
38 pub base_output_bytes: u64,
39 pub head_output_bytes: u64,
40 pub output_bytes_delta: i64,
41 pub added_count: u64,
42 pub removed_count: u64,
43 pub changed_count: u64,
44 pub metadata_changed_count: u64,
45 pub unchanged_count: u64,
46}
47
48#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
49pub struct ManifestCompareOutput {
50 pub source_path: String,
51 pub output_path: String,
52 pub preset: String,
53 pub fit: String,
54 pub width: u32,
55 pub height: u32,
56 pub format: String,
57 pub bytes: u64,
58 pub hash: String,
59}
60
61#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
62pub struct ManifestCompareChange {
63 pub source_path: String,
64 pub preset: String,
65 pub width: u32,
66 pub height: u32,
67 pub format: String,
68 pub base_fit: String,
69 pub head_fit: String,
70 pub base_output_path: String,
71 pub head_output_path: String,
72 pub base_bytes: u64,
73 pub head_bytes: u64,
74 pub byte_delta: i64,
75 pub base_hash: String,
76 pub head_hash: String,
77}
78
79#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
80pub struct ManifestCompareMetadataChange {
81 pub source_path: String,
82 pub preset: String,
83 pub width: u32,
84 pub height: u32,
85 pub format: String,
86 pub output_path: String,
87 pub bytes: u64,
88 pub hash: String,
89 pub base_operation_hash: String,
90 pub head_operation_hash: String,
91}
92
93pub fn compare_manifests(
94 base: &Manifest,
95 head: &Manifest,
96 options: ManifestCompareOptions,
97) -> ManifestCompare {
98 let base_outputs = outputs_by_identity(base);
99 let mut head_outputs = outputs_by_identity(head);
100 let mut added = Vec::new();
101 let mut removed = Vec::new();
102 let mut changed = Vec::new();
103 let mut metadata_changed = Vec::new();
104 let mut unchanged_count = 0u64;
105
106 for (identity, base_output) in base_outputs {
107 match head_outputs.remove(&identity) {
108 Some(head_output) => {
109 if outputs_match(base_output, head_output) {
110 unchanged_count += 1;
111 } else if outputs_match_except_operation_hash(base_output, head_output) {
112 metadata_changed.push(ManifestCompareMetadataChange::from_outputs(
113 base_output,
114 head_output,
115 ));
116 } else {
117 changed.push(ManifestCompareChange::from_outputs(
118 base_output,
119 head_output,
120 ));
121 }
122 }
123 None => removed.push(ManifestCompareOutput::from_output(base_output)),
124 }
125 }
126
127 for head_output in head_outputs.into_values() {
128 added.push(ManifestCompareOutput::from_output(head_output));
129 }
130
131 let base_variant_count = base.outputs.len() as u64;
132 let head_variant_count = head.outputs.len() as u64;
133 let base_output_bytes = base.output_bytes_total();
134 let head_output_bytes = head.output_bytes_total();
135 let top_byte_contributors = top_byte_contributors(head, options.top_limit);
136
137 ManifestCompare {
138 base_generated_at: base.generated_at.clone(),
139 head_generated_at: head.generated_at.clone(),
140 base_config_hash: base.config_hash.clone(),
141 head_config_hash: head.config_hash.clone(),
142 summary: ManifestCompareSummary {
143 base_variant_count,
144 head_variant_count,
145 variant_count_delta: signed_delta(head_variant_count, base_variant_count),
146 base_output_bytes,
147 head_output_bytes,
148 output_bytes_delta: signed_delta(head_output_bytes, base_output_bytes),
149 added_count: added.len() as u64,
150 removed_count: removed.len() as u64,
151 changed_count: changed.len() as u64,
152 metadata_changed_count: metadata_changed.len() as u64,
153 unchanged_count,
154 },
155 added,
156 removed,
157 changed,
158 metadata_changed,
159 top_byte_contributors,
160 }
161}
162
163pub fn manifest_compare_to_json(compare: &ManifestCompare) -> String {
164 serde_json::to_string_pretty(compare).expect("manifest compare serialization cannot fail")
165 + "\n"
166}
167
168impl ManifestCompareOutput {
169 fn from_output(output: &ManifestOutput) -> Self {
170 Self {
171 source_path: output.source_path.clone(),
172 output_path: output.output_path.clone(),
173 preset: output.preset.clone(),
174 fit: output.fit.clone(),
175 width: output.width,
176 height: output.height,
177 format: output.format.clone(),
178 bytes: output.bytes,
179 hash: output.hash.clone(),
180 }
181 }
182}
183
184impl ManifestCompareChange {
185 fn from_outputs(base: &ManifestOutput, head: &ManifestOutput) -> Self {
186 Self {
187 source_path: head.source_path.clone(),
188 preset: head.preset.clone(),
189 width: head.width,
190 height: head.height,
191 format: head.format.clone(),
192 base_fit: base.fit.clone(),
193 head_fit: head.fit.clone(),
194 base_output_path: base.output_path.clone(),
195 head_output_path: head.output_path.clone(),
196 base_bytes: base.bytes,
197 head_bytes: head.bytes,
198 byte_delta: signed_delta(head.bytes, base.bytes),
199 base_hash: base.hash.clone(),
200 head_hash: head.hash.clone(),
201 }
202 }
203}
204
205impl ManifestCompareMetadataChange {
206 fn from_outputs(base: &ManifestOutput, head: &ManifestOutput) -> Self {
207 Self {
208 source_path: head.source_path.clone(),
209 preset: head.preset.clone(),
210 width: head.width,
211 height: head.height,
212 format: head.format.clone(),
213 output_path: head.output_path.clone(),
214 bytes: head.bytes,
215 hash: head.hash.clone(),
216 base_operation_hash: base.operation_hash.clone(),
217 head_operation_hash: head.operation_hash.clone(),
218 }
219 }
220}
221
222#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
223struct ManifestOutputIdentity {
224 source_path: String,
225 preset: String,
226 width: u32,
227 height: u32,
228 format: String,
229}
230
231impl ManifestOutputIdentity {
232 fn from_output(output: &ManifestOutput) -> Self {
233 Self {
234 source_path: output.source_path.clone(),
235 preset: output.preset.clone(),
236 width: output.width,
237 height: output.height,
238 format: output.format.clone(),
239 }
240 }
241}
242
243fn outputs_by_identity(manifest: &Manifest) -> BTreeMap<ManifestOutputIdentity, &ManifestOutput> {
244 manifest
245 .outputs
246 .iter()
247 .map(|output| (ManifestOutputIdentity::from_output(output), output))
248 .collect()
249}
250
251fn outputs_match(base: &ManifestOutput, head: &ManifestOutput) -> bool {
252 outputs_match_except_operation_hash(base, head) && base.operation_hash == head.operation_hash
253}
254
255fn outputs_match_except_operation_hash(base: &ManifestOutput, head: &ManifestOutput) -> bool {
256 base.source_hash == head.source_hash
257 && base.source_width == head.source_width
258 && base.source_height == head.source_height
259 && base.source_bytes == head.source_bytes
260 && base.output_path == head.output_path
261 && base.fit == head.fit
262 && base.bytes == head.bytes
263 && base.hash == head.hash
264}
265
266fn top_byte_contributors(manifest: &Manifest, limit: usize) -> Vec<ManifestCompareOutput> {
267 let mut outputs = manifest.outputs.iter().collect::<Vec<_>>();
268 outputs.sort_by(|a, b| match b.bytes.cmp(&a.bytes) {
269 Ordering::Equal => a.output_path.cmp(&b.output_path),
270 ordering => ordering,
271 });
272 outputs
273 .into_iter()
274 .take(limit)
275 .map(ManifestCompareOutput::from_output)
276 .collect()
277}
278
279fn signed_delta(head: u64, base: u64) -> i64 {
280 if head >= base {
281 head.saturating_sub(base).min(i64::MAX as u64) as i64
282 } else {
283 -(base.saturating_sub(head).min(i64::MAX as u64) as i64)
284 }
285}
286
287#[cfg(test)]
288mod tests {
289 use super::{compare_manifests, manifest_compare_to_json, ManifestCompareOptions};
290 use crate::manifest::{Manifest, ManifestOutput};
291
292 #[test]
293 fn compare_manifest_records_added_removed_changed_and_unchanged_outputs() {
294 let base = Manifest {
295 version: 1,
296 generated_at: "unix:1".to_string(),
297 config_path: "devimg.toml".to_string(),
298 config_hash: "blake3:base".to_string(),
299 outputs: vec![
300 output(
301 "assets/card.png",
302 "project-card",
303 640,
304 360,
305 "webp",
306 100,
307 "same",
308 ),
309 output(
310 "assets/card.png",
311 "project-card",
312 960,
313 540,
314 "webp",
315 200,
316 "old",
317 ),
318 output(
319 "assets/card.png",
320 "project-card",
321 1280,
322 720,
323 "webp",
324 300,
325 "removed",
326 ),
327 ],
328 };
329 let mut changed = output(
330 "assets/card.png",
331 "project-card",
332 960,
333 540,
334 "webp",
335 260,
336 "new",
337 );
338 changed.output_path =
339 "public/images/generated/card.project-card.960.newhash.webp".to_string();
340 changed.operation_hash = "blake3:new-operation".to_string();
341 let head = Manifest {
342 version: 1,
343 generated_at: "unix:2".to_string(),
344 config_path: "devimg.toml".to_string(),
345 config_hash: "blake3:head".to_string(),
346 outputs: vec![
347 output(
348 "assets/card.png",
349 "project-card",
350 640,
351 360,
352 "webp",
353 100,
354 "same",
355 ),
356 changed,
357 output("assets/avatar.png", "avatar", 256, 256, "jpeg", 50, "added"),
358 ],
359 };
360
361 let compare = compare_manifests(&base, &head, ManifestCompareOptions { top_limit: 2 });
362
363 assert_eq!(compare.summary.base_variant_count, 3);
364 assert_eq!(compare.summary.head_variant_count, 3);
365 assert_eq!(compare.summary.variant_count_delta, 0);
366 assert_eq!(compare.summary.base_output_bytes, 600);
367 assert_eq!(compare.summary.head_output_bytes, 410);
368 assert_eq!(compare.summary.output_bytes_delta, -190);
369 assert_eq!(compare.summary.added_count, 1);
370 assert_eq!(compare.summary.removed_count, 1);
371 assert_eq!(compare.summary.changed_count, 1);
372 assert_eq!(compare.summary.metadata_changed_count, 0);
373 assert_eq!(compare.summary.unchanged_count, 1);
374 assert_eq!(
375 compare.added[0].output_path,
376 "public/images/generated/avatar.avatar.256.jpeg"
377 );
378 assert_eq!(compare.removed[0].hash, "blake3:removed");
379 assert_eq!(compare.changed[0].base_bytes, 200);
380 assert_eq!(compare.changed[0].head_bytes, 260);
381 assert_eq!(compare.changed[0].byte_delta, 60);
382 assert_eq!(
383 compare.changed[0].base_output_path,
384 "public/images/generated/card.project-card.960.webp"
385 );
386 assert_eq!(
387 compare.changed[0].head_output_path,
388 "public/images/generated/card.project-card.960.newhash.webp"
389 );
390 assert_eq!(compare.top_byte_contributors.len(), 2);
391 assert_eq!(compare.top_byte_contributors[0].bytes, 260);
392 assert_eq!(compare.top_byte_contributors[1].bytes, 100);
393 }
394
395 #[test]
396 fn compare_manifest_separates_metadata_only_operation_changes() {
397 let base = Manifest {
398 version: 1,
399 generated_at: "unix:1".to_string(),
400 config_path: "devimg.toml".to_string(),
401 config_hash: "blake3:base".to_string(),
402 outputs: vec![output(
403 "assets/card.png",
404 "project-card",
405 640,
406 360,
407 "webp",
408 100,
409 "same",
410 )],
411 };
412 let mut head = base.clone();
413 head.generated_at = "unix:2".to_string();
414 head.config_hash = "blake3:head".to_string();
415 head.outputs[0].operation_hash = "blake3:operation-new-metadata".to_string();
416
417 let compare = compare_manifests(&base, &head, ManifestCompareOptions::default());
418
419 assert_eq!(compare.summary.changed_count, 0);
420 assert_eq!(compare.summary.metadata_changed_count, 1);
421 assert_eq!(compare.summary.unchanged_count, 0);
422 assert_eq!(
423 compare.metadata_changed[0].output_path,
424 base.outputs[0].output_path
425 );
426 assert_eq!(compare.metadata_changed[0].bytes, 100);
427 assert_eq!(compare.metadata_changed[0].hash, "blake3:same");
428 }
429
430 #[test]
431 fn compare_manifest_json_is_machine_readable() {
432 let manifest = Manifest {
433 version: 1,
434 generated_at: "unix:1".to_string(),
435 config_path: "devimg.toml".to_string(),
436 config_hash: "blake3:config".to_string(),
437 outputs: vec![output(
438 "assets/card.png",
439 "project-card",
440 640,
441 360,
442 "webp",
443 100,
444 "same",
445 )],
446 };
447
448 let compare = compare_manifests(&manifest, &manifest, ManifestCompareOptions::default());
449 let json = manifest_compare_to_json(&compare);
450
451 assert!(json.contains("\"unchanged_count\": 1"));
452 assert!(json.contains("\"metadata_changed_count\": 0"));
453 assert!(json.contains("\"top_byte_contributors\""));
454 }
455
456 fn output(
457 source_path: &str,
458 preset: &str,
459 width: u32,
460 height: u32,
461 format: &str,
462 bytes: u64,
463 hash_suffix: &str,
464 ) -> ManifestOutput {
465 let stem = source_path
466 .rsplit('/')
467 .next()
468 .expect("source filename")
469 .split('.')
470 .next()
471 .expect("source stem");
472 ManifestOutput {
473 source_path: source_path.to_string(),
474 source_hash: format!("blake3:source-{stem}"),
475 source_width: 1600,
476 source_height: 900,
477 source_bytes: 1000,
478 output_path: format!("public/images/generated/{stem}.{preset}.{width}.{format}"),
479 preset: preset.to_string(),
480 fit: "cover".to_string(),
481 width,
482 height,
483 format: format.to_string(),
484 bytes,
485 hash: format!("blake3:{hash_suffix}"),
486 operation_hash: format!("blake3:operation-{hash_suffix}"),
487 }
488 }
489}