zlayer-registry 0.13.0

OCI container registry client with blob caching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
//! Local OCI registry for storing images built by zlayer
//!
//! This module implements a minimal OCI Distribution-compliant local registry
//! that stores images on the local filesystem. It can be used to store images
//! built locally before pushing to a remote registry.
//!
//! ## Directory Structure
//!
//! ```text
//! {data_dir}/registry/
//! |-- blobs/
//! |   |-- sha256/
//! |       |-- <digest>   # blob content
//! |-- manifests/
//! |   |-- <name>/
//! |       |-- tags/
//! |       |   |-- <tag>     # file containing manifest digest
//! |       |-- sha256/
//! |           |-- <digest>  # manifest content
//! |-- index.json         # index of all images
//! ```

use crate::cache::{compute_digest, validate_digest};
use crate::error::CacheError;
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use tokio::fs;
use tokio::sync::RwLock;

/// Result type alias for local registry operations
pub type Result<T> = std::result::Result<T, LocalRegistryError>;

/// Atomically write `data` to `path` via a uniquely-named temp file in the SAME
/// directory followed by a rename.
///
/// The rename only needs write permission on the PARENT directory — never on a
/// pre-existing `path` — so a member of the `zlayer` group can replace an
/// `index.json` / tag file the root daemon created (and vice versa) as long as
/// the directory is group-writable (see the daemon's `normalize_shared_build_dirs`
/// startup self-heal). An in-place `fs::write` instead truncates the existing
/// file, which requires write permission on the FILE and fails with EACCES across
/// the root-daemon / non-root-builder ownership split. Also crash-safe: a reader
/// never observes a torn file.
async fn atomic_write(path: &Path, data: &[u8]) -> Result<()> {
    use std::sync::atomic::{AtomicU64, Ordering};
    static SEQ: AtomicU64 = AtomicU64::new(0);
    let seq = SEQ.fetch_add(1, Ordering::Relaxed);
    let file_name = path
        .file_name()
        .map_or_else(|| "tmp".to_string(), |n| n.to_string_lossy().into_owned());
    let tmp = path.parent().map_or_else(
        || path.with_extension("tmp"),
        |dir| dir.join(format!(".{file_name}.{}.{seq}.tmp", std::process::id())),
    );
    fs::write(&tmp, data).await?;
    fs::rename(&tmp, path).await?;
    Ok(())
}

/// Local registry errors
#[derive(Debug, thiserror::Error)]
pub enum LocalRegistryError {
    /// IO error
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// Cache error (digest validation, etc.)
    #[error("cache error: {0}")]
    Cache(#[from] CacheError),

    /// Manifest not found
    #[error("manifest not found: {name}:{reference}")]
    ManifestNotFound { name: String, reference: String },

    /// Blob not found
    #[error("blob not found: {digest}")]
    BlobNotFound { digest: String },

    /// Image not found
    #[error("image not found: {name}")]
    ImageNotFound { name: String },

    /// Invalid reference format
    #[error("invalid reference format: {0}")]
    InvalidReference(String),

    /// JSON serialization error
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
}

/// Index entry for a stored image
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageEntry {
    /// Image name (e.g., "myapp")
    pub name: String,
    /// Tags for this image
    pub tags: Vec<String>,
    /// Last modified timestamp (unix epoch seconds)
    pub updated_at: u64,
}

/// Local registry index stored in index.json
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RegistryIndex {
    /// Schema version for future compatibility
    pub schema_version: u32,
    /// All images in the registry
    pub images: HashMap<String, ImageEntry>,
}

impl RegistryIndex {
    /// Create a new empty index
    #[must_use]
    pub fn new() -> Self {
        Self {
            schema_version: 1,
            images: HashMap::new(),
        }
    }
}

/// A small in-memory record of a previously-resolved local image, keyed by
/// `(name, reference)`.
///
/// This fronts the filesystem-index / blob-cache reads on the create hot path:
/// when a container is created with `PullPolicy::IfNotPresent` for an image that
/// is already stored locally, the resolve no longer needs to read the tag file,
/// the manifest file, or the persistent blob-cache DB — the answer is served
/// from this map.
///
/// ## Invalidation contract (correctness)
///
/// The local registry is content-addressed by what is on disk: a tag file maps
/// `(name, tag)` -> a manifest digest, and that mapping is the *local* source of
/// truth (there is no remote-freshness concern at this layer — that is handled
/// in `client.rs` against the persistent blob cache before a manifest is ever
/// stored locally). Therefore a cached entry is valid exactly as long as the
/// on-disk `(name, reference)` mapping is unchanged. Every mutator that can
/// change that mapping evicts the affected keys:
///
/// - [`LocalRegistry::put_manifest`] — evicts `(name, reference)` (the tag, or
///   the digest ref) so a re-tag of e.g. `:latest` to a new digest is observed
///   on the next read instead of serving the previous digest.
/// - [`LocalRegistry::delete_tag`] — evicts `(name, tag)`.
/// - [`LocalRegistry::delete_image`] — evicts every entry for `name`.
/// - [`LocalRegistry::garbage_collect`] — clears the whole cache (a GC sweep can
///   remove blobs underneath many manifests at once).
///
/// Because eviction is keyed precisely to the on-disk mutation, a mutable tag
/// like `:latest` is never served stale: the moment `put_manifest` re-points it,
/// the stale entry is gone. The cache only ever returns a value that matches the
/// last write through this `LocalRegistry`.
#[derive(Debug, Clone)]
struct ResolvedEntry {
    /// Manifest digest (`sha256:...`) the reference currently resolves to.
    manifest_digest: String,
    /// Total on-disk size (sum of layer + config descriptor sizes), matching
    /// [`LocalRegistry::manifest_digest_and_size`]. `None` when the entry was
    /// populated by a path that did not parse the manifest size (e.g. an
    /// `exists`-only probe), in which case a size query falls through to disk.
    total_size: Option<u64>,
    /// Raw manifest bytes, cached so [`LocalRegistry::get_manifest`] can serve
    /// the body without re-reading the manifest file.
    manifest_bytes: std::sync::Arc<Vec<u8>>,
}

/// Local OCI registry for storing images built by zlayer build
///
/// This provides a minimal OCI Distribution-compliant registry that stores
/// images on the local filesystem. It's designed for:
/// - Storing locally-built images before pushing to remote registries
/// - Caching images pulled from remote registries
/// - Development and testing workflows
///
/// ## Example
///
/// ```rust,no_run
/// use zlayer_registry::local_registry::LocalRegistry;
/// use std::path::PathBuf;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let registry = LocalRegistry::new(PathBuf::from("/tmp/zlayer/registry")).await?;
///
/// // Store a blob
/// let data = b"layer data";
/// let digest = registry.put_blob(data).await?;
///
/// // Store a manifest
/// let manifest = br#"{"schemaVersion": 2, "layers": []}"#;
/// let manifest_digest = registry.put_manifest("myapp", "latest", manifest).await?;
///
/// // List tags
/// let tags = registry.list_tags("myapp").await?;
/// # Ok(())
/// # }
/// ```
pub struct LocalRegistry {
    /// Root directory for storing blobs and manifests
    root: PathBuf,
    /// In-memory index of tags to digests (cached from disk)
    index: RwLock<RegistryIndex>,
    /// In-memory resolve/exists cache keyed by `(name, reference)`.
    ///
    /// Fronts the hot read path so a 2nd `IfNotPresent`-style resolve of an
    /// already-local image is served without touching the filesystem index or
    /// the blob cache. See [`ResolvedEntry`] for the invalidation contract.
    resolve_cache: DashMap<(String, String), ResolvedEntry>,
    /// Count of resolve-cache misses that fell through to the filesystem
    /// (incremented in [`LocalRegistry::resolve_cached`] on a miss). Used by
    /// tests to assert a cache hit performed zero filesystem work.
    resolve_misses: AtomicU64,
}

impl LocalRegistry {
    /// Create a new local registry at the given path
    ///
    /// Creates the directory structure if it doesn't exist.
    ///
    /// # Errors
    ///
    /// Returns an error if the directory structure cannot be created or the index cannot be loaded.
    pub async fn new(root: PathBuf) -> Result<Self> {
        // Create directory structure
        let blobs_dir = root.join("blobs").join("sha256");
        let manifests_dir = root.join("manifests");

        fs::create_dir_all(&blobs_dir).await?;
        fs::create_dir_all(&manifests_dir).await?;

        // Load or create index
        let index_path = root.join("index.json");
        let index = if index_path.exists() {
            let content = fs::read_to_string(&index_path).await?;
            match serde_json::from_str(&content) {
                Ok(idx) => idx,
                Err(e) => {
                    // A stale or schema-drifted index.json (e.g. written by an
                    // older zlayer that stored `images` as a JSON array instead
                    // of the current map) must NOT brick every build/push on this
                    // host. Reset to an empty index and rewrite it on disk.
                    tracing::warn!(
                        path = %index_path.display(),
                        error = %e,
                        "failed to parse registry index; resetting to an empty index"
                    );
                    let fresh = RegistryIndex::new();
                    if let Ok(content) = serde_json::to_string_pretty(&fresh) {
                        // Best-effort: never fail construction on a write error.
                        let _ = atomic_write(&index_path, content.as_bytes()).await;
                    }
                    fresh
                }
            }
        } else {
            RegistryIndex::new()
        };

        Ok(Self {
            root,
            index: RwLock::new(index),
            resolve_cache: DashMap::new(),
            resolve_misses: AtomicU64::new(0),
        })
    }

    /// Get the root directory of this registry
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Get the path to the blobs directory
    fn blobs_dir(&self) -> PathBuf {
        self.root.join("blobs").join("sha256")
    }

    /// Get the path to the manifests directory for a specific image
    fn manifests_dir(&self, name: &str) -> PathBuf {
        self.root.join("manifests").join(sanitize_name(name))
    }

    /// Get the path for a blob given its digest
    fn blob_path(&self, digest: &str) -> PathBuf {
        let hash = digest.strip_prefix("sha256:").unwrap_or(digest);
        self.blobs_dir().join(hash)
    }

    /// Get the path for a manifest given name and digest
    fn manifest_path(&self, name: &str, digest: &str) -> PathBuf {
        let hash = digest.strip_prefix("sha256:").unwrap_or(digest);
        self.manifests_dir(name).join("sha256").join(hash)
    }

    /// Get the path for a tag file
    fn tag_path(&self, name: &str, tag: &str) -> PathBuf {
        self.manifests_dir(name)
            .join("tags")
            .join(sanitize_tag(tag))
    }

    /// Save the index to disk
    async fn save_index(&self) -> Result<()> {
        let index = self.index.read().await;
        let content = serde_json::to_string_pretty(&*index)?;
        let index_path = self.root.join("index.json");
        atomic_write(&index_path, content.as_bytes()).await?;
        Ok(())
    }

    /// Store a blob and return its digest
    ///
    /// The digest is computed from the data using SHA-256.
    /// If the blob already exists, this is a no-op.
    ///
    /// # Errors
    ///
    /// Returns an error if the blob cannot be written to disk.
    pub async fn put_blob(&self, data: &[u8]) -> Result<String> {
        let digest = compute_digest(data);

        let blob_path = self.blob_path(&digest);

        // Check if already exists
        if blob_path.exists() {
            tracing::debug!(digest = %digest, "blob already exists");
            return Ok(digest);
        }

        // Write blob atomically
        let temp_path = blob_path.with_extension("tmp");
        fs::write(&temp_path, data).await?;
        fs::rename(&temp_path, &blob_path).await?;

        tracing::debug!(digest = %digest, size = data.len(), "stored blob");
        Ok(digest)
    }

    /// Store a blob that already exists on disk, computing its digest by
    /// streaming the file (never buffering it in memory), and hardlinking it
    /// into the blob store (falling back to a copy across filesystems).
    ///
    /// Returns the computed `sha256:<hex>` digest. If a blob with that digest is
    /// already present this is a no-op.
    ///
    /// # Errors
    ///
    /// Returns an error if the source cannot be read or the blob cannot be
    /// linked/copied into the store.
    pub async fn put_blob_from_path(&self, src: &Path) -> Result<String> {
        use sha2::{Digest, Sha256};
        use tokio::io::AsyncReadExt as _;

        // Stream-hash the file so a multi-GB layer is never held in RAM.
        let mut file = fs::File::open(src).await?;
        let mut hasher = Sha256::new();
        let mut buf = vec![0u8; 1024 * 1024];
        loop {
            let n = file.read(&mut buf).await?;
            if n == 0 {
                break;
            }
            hasher.update(&buf[..n]);
        }
        let digest = format!("sha256:{}", hex::encode(hasher.finalize()));

        let blob_path = self.blob_path(&digest);
        if blob_path.exists() {
            tracing::debug!(digest = %digest, "blob already exists");
            return Ok(digest);
        }

        // Hardlink (same filesystem, O(1)); fall back to copy across devices.
        if fs::hard_link(src, &blob_path).await.is_err() {
            let temp_path = blob_path.with_extension("tmp");
            fs::copy(src, &temp_path).await?;
            fs::rename(&temp_path, &blob_path).await?;
        }

        tracing::debug!(digest = %digest, "stored blob from path");
        Ok(digest)
    }

    /// Get a blob by digest
    ///
    /// Returns the blob data if found, or an error if not found.
    ///
    /// # Errors
    ///
    /// Returns an error if the digest is invalid, the blob is not found, or integrity check fails.
    pub async fn get_blob(&self, digest: &str) -> Result<Vec<u8>> {
        validate_digest(digest)?;

        let blob_path = self.blob_path(digest);

        if !blob_path.exists() {
            return Err(LocalRegistryError::BlobNotFound {
                digest: digest.to_string(),
            });
        }

        let data = fs::read(&blob_path).await?;

        // Verify integrity
        let actual_digest = compute_digest(&data);
        if actual_digest != digest {
            return Err(LocalRegistryError::Cache(CacheError::Corrupted(format!(
                "blob integrity check failed: expected {digest}, got {actual_digest}"
            ))));
        }

        Ok(data)
    }

    /// Check if a blob exists
    #[allow(clippy::unused_async)]
    pub async fn has_blob(&self, digest: &str) -> bool {
        if validate_digest(digest).is_err() {
            return false;
        }
        self.blob_path(digest).exists()
    }

    /// Store a manifest for an image
    ///
    /// If reference is a tag (not starting with "sha256:"), it creates a tag
    /// pointing to the manifest digest. Returns the manifest digest.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest cannot be written to disk or the index cannot be saved.
    pub async fn put_manifest(
        &self,
        name: &str,
        reference: &str,
        manifest: &[u8],
    ) -> Result<String> {
        let digest = compute_digest(manifest);

        // Create image directories
        let manifest_dir = self.manifests_dir(name).join("sha256");
        let tags_dir = self.manifests_dir(name).join("tags");
        fs::create_dir_all(&manifest_dir).await?;
        fs::create_dir_all(&tags_dir).await?;

        // Write manifest
        let manifest_path = self.manifest_path(name, &digest);
        if !manifest_path.exists() {
            let temp_path = manifest_path.with_extension("tmp");
            fs::write(&temp_path, manifest).await?;
            fs::rename(&temp_path, &manifest_path).await?;
            tracing::debug!(name = %name, digest = %digest, "stored manifest");
        }

        // Handle tag vs digest reference
        let is_tag = !reference.starts_with("sha256:");
        if is_tag {
            let tag_path = self.tag_path(name, reference);
            atomic_write(&tag_path, digest.as_bytes()).await?;
            tracing::debug!(name = %name, tag = %reference, digest = %digest, "created tag");
        }

        // Invalidate the in-memory resolve cache for the affected refs: the tag
        // (or digest ref) just got (re)pointed, and the by-digest ref now has a
        // manifest body on disk. Evicting both keeps a mutable tag like
        // `:latest` from being served stale after it is re-tagged.
        self.invalidate_ref(name, reference);
        self.invalidate_ref(name, &digest);

        // Update index
        {
            let mut index = self.index.write().await;
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();

            let entry = index
                .images
                .entry(name.to_string())
                .or_insert_with(|| ImageEntry {
                    name: name.to_string(),
                    tags: Vec::new(),
                    updated_at: now,
                });

            if is_tag && !entry.tags.contains(&reference.to_string()) {
                entry.tags.push(reference.to_string());
            }
            entry.updated_at = now;
        }

        self.save_index().await?;

        Ok(digest)
    }

    /// Resolve `(name, reference)` from disk, building the full
    /// [`ResolvedEntry`] (digest + parsed total size + manifest bytes) and
    /// populating the in-memory resolve cache. This is the single miss-path:
    /// every public resolve/exists/size method routes through
    /// [`Self::resolve_cached`], which calls this only on a cache miss.
    ///
    /// Increments [`Self::resolve_misses`] so tests can assert that a cache hit
    /// performed zero filesystem work.
    async fn resolve_from_disk(&self, name: &str, reference: &str) -> Result<ResolvedEntry> {
        self.resolve_misses.fetch_add(1, Ordering::Relaxed);

        let digest = if reference.starts_with("sha256:") {
            reference.to_string()
        } else {
            // It's a tag, resolve to digest
            let tag_path = self.tag_path(name, reference);
            if !tag_path.exists() {
                return Err(LocalRegistryError::ManifestNotFound {
                    name: name.to_string(),
                    reference: reference.to_string(),
                });
            }
            fs::read_to_string(&tag_path).await?.trim().to_string()
        };

        let manifest_path = self.manifest_path(name, &digest);
        if !manifest_path.exists() {
            return Err(LocalRegistryError::ManifestNotFound {
                name: name.to_string(),
                reference: reference.to_string(),
            });
        }

        let data = fs::read(&manifest_path).await?;

        // Verify integrity
        let actual_digest = compute_digest(&data);
        if actual_digest != digest {
            return Err(LocalRegistryError::Cache(CacheError::Corrupted(format!(
                "manifest integrity check failed: expected {digest}, got {actual_digest}"
            ))));
        }

        // Parse the size; if the body isn't a parseable OCI manifest we still
        // cache the bytes/digest (size = None) so resolve/exists hits stay fast
        // and only `manifest_digest_and_size` falls back to (re-)parsing.
        let total_size = serde_json::from_slice::<oci_client::manifest::OciImageManifest>(&data)
            .ok()
            .map(|m| {
                let layers_size: i64 = m.layers.iter().map(|l| l.size).sum();
                let total = layers_size.saturating_add(m.config.size);
                u64::try_from(total).unwrap_or(0)
            });

        let entry = ResolvedEntry {
            manifest_digest: digest,
            total_size,
            manifest_bytes: std::sync::Arc::new(data),
        };
        self.resolve_cache
            .insert((name.to_string(), reference.to_string()), entry.clone());
        Ok(entry)
    }

    /// Return the cached [`ResolvedEntry`] for `(name, reference)`, resolving
    /// from disk and populating the cache on a miss. A hit never touches the
    /// filesystem index or the blob cache.
    async fn resolve_cached(&self, name: &str, reference: &str) -> Result<ResolvedEntry> {
        let key = (name.to_string(), reference.to_string());
        if let Some(hit) = self.resolve_cache.get(&key) {
            return Ok(hit.clone());
        }
        self.resolve_from_disk(name, reference).await
    }

    /// Evict the cached resolve entry for a specific `(name, reference)`.
    fn invalidate_ref(&self, name: &str, reference: &str) {
        self.resolve_cache
            .remove(&(name.to_string(), reference.to_string()));
    }

    /// Evict every cached resolve entry belonging to `name` (any tag/digest).
    fn invalidate_image(&self, name: &str) {
        self.resolve_cache.retain(|(n, _), _| n != name);
    }

    /// Number of resolve-cache misses that fell through to the filesystem.
    /// Used by tests to prove a cache hit performed zero filesystem work.
    #[cfg(test)]
    fn resolve_miss_count(&self) -> u64 {
        self.resolve_misses.load(Ordering::Relaxed)
    }

    /// Get a manifest by name and reference (tag or digest)
    ///
    /// Served from the in-memory resolve cache on a hit; otherwise reads the
    /// manifest from disk and populates the cache.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest is not found or integrity check fails.
    pub async fn get_manifest(&self, name: &str, reference: &str) -> Result<Vec<u8>> {
        let entry = self.resolve_cached(name, reference).await?;
        Ok((*entry.manifest_bytes).clone())
    }

    /// Check if a manifest exists.
    ///
    /// Served from the in-memory resolve cache on a hit (no filesystem work).
    pub async fn has_manifest(&self, name: &str, reference: &str) -> bool {
        self.resolve_cached(name, reference).await.is_ok()
    }

    /// List all tags for an image
    ///
    /// # Errors
    ///
    /// Returns an error if the image is not found or the directory cannot be read.
    pub async fn list_tags(&self, name: &str) -> Result<Vec<String>> {
        let tags_dir = self.manifests_dir(name).join("tags");

        if !tags_dir.exists() {
            return Err(LocalRegistryError::ImageNotFound {
                name: name.to_string(),
            });
        }

        let mut tags = Vec::new();
        let mut entries = fs::read_dir(&tags_dir).await?;

        while let Some(entry) = entries.next_entry().await? {
            if let Some(name) = entry.file_name().to_str() {
                tags.push(name.to_string());
            }
        }

        tags.sort();
        Ok(tags)
    }

    /// List all images in the registry
    ///
    /// # Errors
    ///
    /// Returns an error if the index cannot be read.
    pub async fn list_images(&self) -> Result<Vec<String>> {
        let index = self.index.read().await;
        let mut images: Vec<String> = index.images.keys().cloned().collect();
        images.sort();
        Ok(images)
    }

    /// Get image information
    ///
    /// # Errors
    ///
    /// Returns an error if the image is not found.
    pub async fn get_image_info(&self, name: &str) -> Result<ImageEntry> {
        let index = self.index.read().await;
        index
            .images
            .get(name)
            .cloned()
            .ok_or_else(|| LocalRegistryError::ImageNotFound {
                name: name.to_string(),
            })
    }

    /// Resolve a stored image's manifest digest and total on-disk size for a
    /// given name + reference (tag or `sha256:` digest).
    ///
    /// The returned digest is the manifest digest (`sha256:...`). The size is
    /// the sum of every layer descriptor size plus the config descriptor size
    /// recorded in the manifest, which mirrors the size accounting used when
    /// listing images from the blob cache.
    ///
    /// # Errors
    ///
    /// Returns an error if the manifest is not found or cannot be parsed.
    pub async fn manifest_digest_and_size(
        &self,
        name: &str,
        reference: &str,
    ) -> Result<(String, u64)> {
        let entry = self.resolve_cached(name, reference).await?;
        if let Some(size) = entry.total_size {
            return Ok((entry.manifest_digest, size));
        }

        // The cached entry was populated without a parsed size (manifest body
        // wasn't a parseable OCI manifest at resolve time). Parse from the
        // cached bytes — still no extra filesystem read.
        let manifest: oci_client::manifest::OciImageManifest =
            serde_json::from_slice(&entry.manifest_bytes)?;
        let layers_size: i64 = manifest.layers.iter().map(|l| l.size).sum();
        let total = layers_size.saturating_add(manifest.config.size);
        let size = u64::try_from(total).unwrap_or(0);

        Ok((entry.manifest_digest, size))
    }

    /// Delete a tag from an image
    ///
    /// # Errors
    ///
    /// Returns an error if the tag is not found or cannot be deleted.
    pub async fn delete_tag(&self, name: &str, tag: &str) -> Result<()> {
        let tag_path = self.tag_path(name, tag);

        if !tag_path.exists() {
            return Err(LocalRegistryError::ManifestNotFound {
                name: name.to_string(),
                reference: tag.to_string(),
            });
        }

        fs::remove_file(&tag_path).await?;

        // Invalidate the in-memory resolve cache for this tag.
        self.invalidate_ref(name, tag);

        // Update index
        {
            let mut index = self.index.write().await;
            if let Some(entry) = index.images.get_mut(name) {
                entry.tags.retain(|t| t != tag);
                if entry.tags.is_empty() {
                    index.images.remove(name);
                }
            }
        }

        self.save_index().await?;
        tracing::info!(name = %name, tag = %tag, "deleted tag");

        Ok(())
    }

    /// Delete an image and all its tags and manifests
    ///
    /// # Errors
    ///
    /// Returns an error if the image is not found or the directory cannot be deleted.
    pub async fn delete_image(&self, name: &str) -> Result<()> {
        let manifests_dir = self.manifests_dir(name);

        if !manifests_dir.exists() {
            return Err(LocalRegistryError::ImageNotFound {
                name: name.to_string(),
            });
        }

        // Note: This doesn't delete blobs as they may be shared
        fs::remove_dir_all(&manifests_dir).await?;

        // Invalidate every cached resolve entry for this image (all tags/digests).
        self.invalidate_image(name);

        // Update index
        {
            let mut index = self.index.write().await;
            index.images.remove(name);
        }

        self.save_index().await?;
        tracing::info!(name = %name, "deleted image");

        Ok(())
    }

    /// Garbage collect unreferenced blobs
    ///
    /// This finds all blobs that are not referenced by any manifest
    /// and deletes them. Returns the number of bytes freed.
    ///
    /// # Errors
    ///
    /// Returns an error if the directory cannot be read or blobs cannot be deleted.
    pub async fn garbage_collect(&self) -> Result<u64> {
        // Collect all referenced digests from manifests
        let mut referenced: std::collections::HashSet<String> = std::collections::HashSet::new();

        let manifests_base = self.root.join("manifests");
        if manifests_base.exists() {
            let mut images = fs::read_dir(&manifests_base).await?;
            while let Some(image_entry) = images.next_entry().await? {
                let sha256_dir = image_entry.path().join("sha256");
                if sha256_dir.exists() {
                    let mut manifests = fs::read_dir(&sha256_dir).await?;
                    while let Some(manifest_entry) = manifests.next_entry().await? {
                        // Read manifest and extract layer digests
                        if let Ok(content) = fs::read(&manifest_entry.path()).await {
                            if let Ok(manifest) =
                                serde_json::from_slice::<serde_json::Value>(&content)
                            {
                                // Add config digest if present
                                if let Some(config) = manifest.get("config") {
                                    if let Some(digest) =
                                        config.get("digest").and_then(|d| d.as_str())
                                    {
                                        referenced.insert(digest.to_string());
                                    }
                                }
                                // Add layer digests
                                if let Some(layers) =
                                    manifest.get("layers").and_then(|l| l.as_array())
                                {
                                    for layer in layers {
                                        if let Some(digest) =
                                            layer.get("digest").and_then(|d| d.as_str())
                                        {
                                            referenced.insert(digest.to_string());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // Find and delete unreferenced blobs
        let mut freed: u64 = 0;
        let blobs_dir = self.blobs_dir();

        if blobs_dir.exists() {
            let mut blobs = fs::read_dir(&blobs_dir).await?;
            while let Some(blob_entry) = blobs.next_entry().await? {
                let file_name = blob_entry.file_name();
                let digest = format!("sha256:{}", file_name.to_string_lossy());

                if !referenced.contains(&digest) {
                    if let Ok(metadata) = blob_entry.metadata().await {
                        freed += metadata.len();
                    }
                    fs::remove_file(blob_entry.path()).await?;
                    tracing::debug!(digest = %digest, "garbage collected blob");
                }
            }
        }

        if freed > 0 {
            tracing::info!(bytes_freed = freed, "garbage collection complete");
        }

        // A GC sweep can remove blobs underneath many manifests at once; clear
        // the resolve cache broadly so no entry can outlive its backing blobs.
        self.resolve_cache.clear();

        Ok(freed)
    }

    /// Get the total size of the registry in bytes
    ///
    /// # Errors
    ///
    /// Returns an error if the directory cannot be read.
    pub async fn size(&self) -> Result<u64> {
        let mut total: u64 = 0;

        // Sum blob sizes
        let blobs_dir = self.blobs_dir();
        if blobs_dir.exists() {
            let mut blobs = fs::read_dir(&blobs_dir).await?;
            while let Some(entry) = blobs.next_entry().await? {
                if let Ok(metadata) = entry.metadata().await {
                    total += metadata.len();
                }
            }
        }

        // Sum manifest sizes
        let manifests_base = self.root.join("manifests");
        if manifests_base.exists() {
            total += dir_size_recursive(manifests_base.clone()).await?;
        }

        Ok(total)
    }
}

/// Sanitize an image name for use as a directory name
fn sanitize_name(name: &str) -> String {
    // Replace / with _ to flatten namespaces, keep alphanumeric and -._
    name.chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '.' || c == '_' {
                c
            } else {
                // Replace / and any other special characters with _
                '_'
            }
        })
        .collect()
}

/// Sanitize a tag for use as a filename
fn sanitize_tag(tag: &str) -> String {
    // Tags are more restrictive, keep alphanumeric, -, ., _
    tag.chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '.' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect()
}

/// Recursively calculate directory size
fn dir_size_recursive(
    path: PathBuf,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<u64>> + Send>> {
    Box::pin(async move {
        let mut total: u64 = 0;
        let mut entries = fs::read_dir(&path).await?;

        while let Some(entry) = entries.next_entry().await? {
            let metadata = entry.metadata().await?;
            if metadata.is_dir() {
                total += dir_size_recursive(entry.path()).await?;
            } else {
                total += metadata.len();
            }
        }

        Ok(total)
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    async fn create_test_registry() -> (LocalRegistry, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let registry = LocalRegistry::new(temp_dir.path().to_path_buf())
            .await
            .unwrap();
        (registry, temp_dir)
    }

    /// Regression: `atomic_write` must replace an existing file that has NO write
    /// bit (mode 0444), proving it never needs write permission on the file
    /// itself — only on the parent dir. This is the exact property that lets a
    /// `zlayer`-group member's `zlayer build` overwrite an `index.json` / tag
    /// the root daemon created. An in-place `fs::write` to a 0444 file fails with
    /// EACCES (verified here first), while `atomic_write` succeeds.
    #[cfg(unix)]
    #[tokio::test]
    async fn atomic_write_replaces_unwritable_file() {
        use std::os::unix::fs::PermissionsExt;
        let temp = TempDir::new().unwrap();
        let target = temp.path().join("index.json");
        fs::write(&target, b"old").await.unwrap();
        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o444)).unwrap();

        // Sanity: an in-place truncating write fails on the read-only file.
        assert!(
            fs::write(&target, b"new").await.is_err(),
            "precondition: in-place write to a 0444 file should fail"
        );

        // The fix: atomic temp+rename replaces it (needs only parent-dir write).
        atomic_write(&target, b"new").await.unwrap();
        assert_eq!(fs::read_to_string(&target).await.unwrap(), "new");
        // No leftover temp files in the dir.
        let mut leftovers = vec![];
        let mut rd = fs::read_dir(temp.path()).await.unwrap();
        while let Ok(Some(e)) = rd.next_entry().await {
            if e.path().extension().and_then(|x| x.to_str()) == Some("tmp") {
                leftovers.push(e.file_name().to_string_lossy().into_owned());
            }
        }
        assert!(leftovers.is_empty(), "stray temp files: {leftovers:?}");
    }

    #[tokio::test]
    async fn test_put_get_blob() {
        let (registry, _temp) = create_test_registry().await;

        let data = b"test blob data";
        let digest = registry.put_blob(data).await.unwrap();

        assert!(digest.starts_with("sha256:"));
        assert!(registry.has_blob(&digest).await);

        let retrieved = registry.get_blob(&digest).await.unwrap();
        assert_eq!(retrieved, data);
    }

    #[tokio::test]
    async fn test_put_get_manifest() {
        let (registry, _temp) = create_test_registry().await;

        let manifest = br#"{"schemaVersion": 2, "layers": []}"#;
        let digest = registry
            .put_manifest("myapp", "latest", manifest)
            .await
            .unwrap();

        assert!(digest.starts_with("sha256:"));
        assert!(registry.has_manifest("myapp", "latest").await);
        assert!(registry.has_manifest("myapp", &digest).await);

        // Get by tag
        let retrieved = registry.get_manifest("myapp", "latest").await.unwrap();
        assert_eq!(retrieved, manifest);

        // Get by digest
        let retrieved = registry.get_manifest("myapp", &digest).await.unwrap();
        assert_eq!(retrieved, manifest);
    }

    #[tokio::test]
    async fn test_list_tags() {
        let (registry, _temp) = create_test_registry().await;

        let manifest = br#"{"schemaVersion": 2, "layers": []}"#;
        registry
            .put_manifest("myapp", "v1.0.0", manifest)
            .await
            .unwrap();
        registry
            .put_manifest("myapp", "v1.1.0", manifest)
            .await
            .unwrap();
        registry
            .put_manifest("myapp", "latest", manifest)
            .await
            .unwrap();

        let tags = registry.list_tags("myapp").await.unwrap();
        assert_eq!(tags, vec!["latest", "v1.0.0", "v1.1.0"]);
    }

    #[tokio::test]
    async fn test_list_images() {
        let (registry, _temp) = create_test_registry().await;

        let manifest = br#"{"schemaVersion": 2, "layers": []}"#;
        registry
            .put_manifest("app1", "latest", manifest)
            .await
            .unwrap();
        registry
            .put_manifest("app2", "latest", manifest)
            .await
            .unwrap();

        let images = registry.list_images().await.unwrap();
        assert_eq!(images, vec!["app1", "app2"]);
    }

    #[tokio::test]
    async fn test_delete_tag() {
        let (registry, _temp) = create_test_registry().await;

        let manifest = br#"{"schemaVersion": 2, "layers": []}"#;
        registry
            .put_manifest("myapp", "v1.0.0", manifest)
            .await
            .unwrap();
        registry
            .put_manifest("myapp", "latest", manifest)
            .await
            .unwrap();

        registry.delete_tag("myapp", "v1.0.0").await.unwrap();

        let tags = registry.list_tags("myapp").await.unwrap();
        assert_eq!(tags, vec!["latest"]);
    }

    #[tokio::test]
    async fn test_delete_image() {
        let (registry, _temp) = create_test_registry().await;

        let manifest = br#"{"schemaVersion": 2, "layers": []}"#;
        registry
            .put_manifest("myapp", "latest", manifest)
            .await
            .unwrap();

        registry.delete_image("myapp").await.unwrap();

        let images = registry.list_images().await.unwrap();
        assert!(images.is_empty());
    }

    #[tokio::test]
    async fn test_garbage_collect() {
        let (registry, _temp) = create_test_registry().await;

        // Store some blobs
        let blob1 = b"blob 1 data";
        let digest1 = registry.put_blob(blob1).await.unwrap();

        let blob2 = b"unreferenced blob";
        let _digest2 = registry.put_blob(blob2).await.unwrap();

        // Store a manifest that references blob1
        let manifest = format!(
            r#"{{"schemaVersion": 2, "layers": [{{"digest": "{}", "size": {}}}]}}"#,
            digest1,
            blob1.len()
        );
        registry
            .put_manifest("myapp", "latest", manifest.as_bytes())
            .await
            .unwrap();

        // GC should remove blob2 but keep blob1
        let freed = registry.garbage_collect().await.unwrap();
        assert!(freed > 0);

        // blob1 should still exist
        assert!(registry.has_blob(&digest1).await);
    }

    /// A minimal-but-parseable OCI image manifest pointing config + one layer
    /// at the given digests/sizes, so `manifest_digest_and_size` can parse it.
    fn oci_manifest(config_size: i64, layer_size: i64) -> Vec<u8> {
        format!(
            r#"{{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{{"mediaType":"application/vnd.oci.image.config.v1+json","digest":"sha256:{:0>64}","size":{config_size}}},"layers":[{{"mediaType":"application/vnd.oci.image.layer.v1.tar+gzip","digest":"sha256:{:0>64}","size":{layer_size}}}]}}"#,
            "c0", "1a",
        )
        .into_bytes()
    }

    /// Phase 3: a 2nd `IfNotPresent`-style resolve of a local image is served
    /// from the in-memory cache and performs ZERO filesystem work. Proven two
    /// ways: (1) the miss counter does not advance on the 2nd resolve, and
    /// (2) deleting the on-disk tag + manifest behind the cache still returns
    /// the cached value (a disk read would have failed).
    #[tokio::test]
    async fn resolve_cache_hit_skips_filesystem() {
        let (registry, _temp) = create_test_registry().await;
        let manifest = oci_manifest(11, 22);

        registry
            .put_manifest("myapp", "latest", &manifest)
            .await
            .unwrap();

        // First resolve: cache miss, reads from disk.
        let (d1, s1) = registry
            .manifest_digest_and_size("myapp", "latest")
            .await
            .unwrap();
        assert_eq!(s1, 33, "size = config(11) + layer(22)");
        let misses_after_first = registry.resolve_miss_count();
        assert_eq!(misses_after_first, 1, "first resolve is a miss");

        // Second resolve: must be a cache hit — miss counter unchanged.
        let (d2, s2) = registry
            .manifest_digest_and_size("myapp", "latest")
            .await
            .unwrap();
        assert_eq!((d1.clone(), s1), (d2.clone(), s2));
        assert_eq!(
            registry.resolve_miss_count(),
            misses_after_first,
            "second resolve must not touch the filesystem (no new miss)"
        );

        // Mutate the on-disk state behind the cache (delete tag + manifest
        // files directly, bypassing the invalidating mutators). The cache must
        // still serve the old value, proving the hit path never reads disk.
        let tag_path = registry.tag_path("myapp", "latest");
        let manifest_path = registry.manifest_path("myapp", &d1);
        fs::remove_file(&tag_path).await.unwrap();
        fs::remove_file(&manifest_path).await.unwrap();

        let bytes = registry.get_manifest("myapp", "latest").await.unwrap();
        assert_eq!(bytes, manifest, "served from cache despite missing files");
        assert!(registry.has_manifest("myapp", "latest").await);
        assert_eq!(
            registry.resolve_miss_count(),
            misses_after_first,
            "still no filesystem reads after on-disk deletion"
        );
    }

    /// Invalidation fires on `put_manifest`: re-tagging a mutable tag like
    /// `:latest` to a NEW manifest must NOT serve the stale digest.
    #[tokio::test]
    async fn put_manifest_invalidates_and_mutable_tag_not_stale() {
        let (registry, _temp) = create_test_registry().await;

        let m_v1 = oci_manifest(1, 2);
        let d_v1 = registry
            .put_manifest("myapp", "latest", &m_v1)
            .await
            .unwrap();

        // Prime the cache for :latest -> v1.
        let (before_digest, before_size) = registry
            .manifest_digest_and_size("myapp", "latest")
            .await
            .unwrap();
        assert_eq!(before_digest, d_v1);
        assert_eq!(before_size, 3);

        // Re-point :latest at a different manifest (new digest).
        let m_v2 = oci_manifest(100, 200);
        let d_v2 = registry
            .put_manifest("myapp", "latest", &m_v2)
            .await
            .unwrap();
        assert_ne!(d_v1, d_v2, "v2 must hash to a different digest");

        // The mutable tag must now resolve to v2, never the stale v1.
        let (after_digest, after_size) = registry
            .manifest_digest_and_size("myapp", "latest")
            .await
            .unwrap();
        assert_eq!(
            after_digest, d_v2,
            "mutable tag served stale digest after re-tag"
        );
        assert_eq!(after_size, 300);
        assert_eq!(
            registry.get_manifest("myapp", "latest").await.unwrap(),
            m_v2
        );
    }

    /// Invalidation fires on `delete_tag`: a cached tag that is deleted must no
    /// longer resolve (the entry is evicted, and disk read now fails).
    #[tokio::test]
    async fn delete_tag_invalidates_cache() {
        let (registry, _temp) = create_test_registry().await;
        let manifest = oci_manifest(5, 5);

        registry
            .put_manifest("myapp", "latest", &manifest)
            .await
            .unwrap();
        registry
            .put_manifest("myapp", "v1", &manifest)
            .await
            .unwrap();

        // Prime cache for v1.
        assert!(registry.has_manifest("myapp", "v1").await);

        registry.delete_tag("myapp", "v1").await.unwrap();

        // v1 must no longer resolve (evicted + gone on disk).
        assert!(
            !registry.has_manifest("myapp", "v1").await,
            "deleted tag must not be served from a stale cache entry"
        );
        assert!(registry.get_manifest("myapp", "v1").await.is_err());
        // latest is untouched.
        assert!(registry.has_manifest("myapp", "latest").await);
    }

    /// Invalidation fires on `delete_image`: every cached ref for the image is
    /// evicted.
    #[tokio::test]
    async fn delete_image_invalidates_cache() {
        let (registry, _temp) = create_test_registry().await;
        let manifest = oci_manifest(7, 8);

        let digest = registry
            .put_manifest("myapp", "latest", &manifest)
            .await
            .unwrap();

        // Prime cache for both the tag and the by-digest ref.
        assert!(registry.has_manifest("myapp", "latest").await);
        assert!(registry.has_manifest("myapp", &digest).await);

        registry.delete_image("myapp").await.unwrap();

        assert!(
            !registry.has_manifest("myapp", "latest").await,
            "deleted image tag must not be served from cache"
        );
        assert!(
            !registry.has_manifest("myapp", &digest).await,
            "deleted image digest ref must not be served from cache"
        );
    }

    #[test]
    fn test_sanitize_name() {
        assert_eq!(sanitize_name("myapp"), "myapp");
        assert_eq!(sanitize_name("my/app"), "my_app");
        assert_eq!(sanitize_name("my-app_v1.0"), "my-app_v1.0");
    }

    #[test]
    fn test_sanitize_tag() {
        assert_eq!(sanitize_tag("v1.0.0"), "v1.0.0");
        assert_eq!(sanitize_tag("latest"), "latest");
        assert_eq!(sanitize_tag("my-tag_1"), "my-tag_1");
    }
}