Skip to main content

capsule_library/library/
paths.rs

1use std::path::{Path, PathBuf};
2
3use uuid::Uuid;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum ThumbnailSize {
7    Xs,
8    S,
9    M,
10    L,
11    Xl,
12    O,
13}
14
15impl ThumbnailSize {
16    pub fn as_str(&self) -> &'static str {
17        match self {
18            ThumbnailSize::Xs => "xs",
19            ThumbnailSize::S => "s",
20            ThumbnailSize::M => "m",
21            ThumbnailSize::L => "l",
22            ThumbnailSize::Xl => "xl",
23            ThumbnailSize::O => "o",
24        }
25    }
26}
27
28/// Returns the first two hex chars and next two hex chars of a UUID string (without hyphens).
29pub fn uuid_shard(uuid: &Uuid) -> (String, String) {
30    let hex = uuid.simple().to_string(); // 32 hex chars, no hyphens
31    (hex[0..2].to_string(), hex[2..4].to_string())
32}
33
34fn shard_dirs(uuid: &Uuid) -> (String, String) {
35    uuid_shard(uuid)
36}
37
38fn date_parts(capture_utc: Option<i64>) -> (u32, u8) {
39    match capture_utc {
40        Some(ts) => {
41            let date = jiff::Timestamp::from_second(ts)
42                .unwrap_or(jiff::Timestamp::UNIX_EPOCH)
43                .to_zoned_datetime(jiff::tz::TimeZone::UTC)
44                .date();
45            (
46                u32::try_from(date.year()).unwrap_or(1970),
47                u8::try_from(date.month()).unwrap_or(1),
48            )
49        }
50        None => (1970, 1),
51    }
52}
53
54/// `media/{YYYY}/{YYYY-MM}/`
55pub fn media_dir(root: &Path, year: u32, month: u8) -> PathBuf {
56    root.join("media")
57        .join(format!("{year:04}"))
58        .join(format!("{year:04}-{month:02}"))
59}
60
61/// `media/{YYYY}/{YYYY-MM}/{uuid}.{ext}` where date comes from capture_utc
62pub fn media_path(root: &Path, uuid: &Uuid, ext: &str, capture_utc: Option<i64>) -> PathBuf {
63    let (year, month) = date_parts(capture_utc);
64    media_dir(root, year, month).join(format!("{}.{}", uuid.simple(), ext))
65}
66
67/// `media/{YYYY}/{YYYY-MM}/{uuid}.cbor`
68pub fn sidecar_path(root: &Path, uuid: &Uuid, _ext: &str, capture_utc: Option<i64>) -> PathBuf {
69    let (year, month) = date_parts(capture_utc);
70    media_dir(root, year, month).join(format!("{}.cbor", uuid.simple()))
71}
72
73/// `media/{YYYY}/{YYYY-MM}/{uuid}.receipts.cbor` — the client's custody-receipt log for the
74/// asset, appended beside the provenance chain (SSoT: Storage Verification — Custody Receipts).
75/// Evidentiary, not a cache: it is included verbatim in the backup artifact.
76pub fn receipts_path(root: &Path, uuid: &Uuid, capture_utc: Option<i64>) -> PathBuf {
77    let (year, month) = date_parts(capture_utc);
78    media_dir(root, year, month).join(format!("{}.receipts.cbor", uuid.simple()))
79}
80
81/// `media/{YYYY}/{YYYY-MM}/{uuid}.attestations.cbor` — the client's signed storage-attestation
82/// log for the asset, kept beside its custody receipts (SSoT: Transfer — Durability: Signed
83/// Storage Attestation). Evidence, not a cache: it is included verbatim in the backup artifact.
84pub fn attestations_path(root: &Path, uuid: &Uuid, capture_utc: Option<i64>) -> PathBuf {
85    let (year, month) = date_parts(capture_utc);
86    media_dir(root, year, month).join(format!("{}.attestations.cbor", uuid.simple()))
87}
88
89/// The `.cbor` files the library keeps under `media/` that are not an asset's sidecar: the
90/// provenance, receipt and attestation logs beside it, and the derivative bundle the lifecycle
91/// writes as `derivatives/{uuid}.derivatives.cbor`. They share the sidecar's suffix, so every
92/// walk that reads `{uuid}.cbor` sidecars must skip them by name.
93pub(crate) const SIBLING_LOG_SUFFIXES: [&str; 4] = [
94    ".provenance.cbor",
95    ".receipts.cbor",
96    ".attestations.cbor",
97    ".derivatives.cbor",
98];
99
100/// Whether a file name under `media/` names an asset's sidecar: exactly `{uuid}.cbor`, never one
101/// of the [sibling logs](SIBLING_LOG_SUFFIXES). The one filter `rebuild_index`, `Workspace::open`
102/// and the unanchored-sidecar scan (`lifecycle/unanchored.rs`) share, so a new sibling cannot be
103/// added to one walk and parsed as a sidecar by another.
104pub(crate) fn is_sidecar_file_name(name: &str) -> bool {
105    // Exact-case on purpose: the library writes every one of these names itself, lowercase.
106    Path::new(name).extension().is_some_and(|ext| ext == "cbor")
107        && !SIBLING_LOG_SUFFIXES
108            .iter()
109            .any(|suffix| name.ends_with(suffix))
110}
111
112/// `index/thumbnails/{size}/{s1}/{s2}/{uuid}.{format}` where format is "jxl" or "webp"
113pub fn thumbnail_path(root: &Path, uuid: &Uuid, size: ThumbnailSize) -> PathBuf {
114    let (s1, s2) = shard_dirs(uuid);
115    root.join("index")
116        .join("thumbnails")
117        .join(size.as_str())
118        .join(&s1)
119        .join(&s2)
120        .join(format!("{}", uuid.simple()))
121    // Note: caller appends .jxl or .webp as needed
122}
123
124/// `index/meta/{s1}/{s2}/{uuid}.meta.cbor`
125pub fn meta_cache_path(root: &Path, uuid: &Uuid) -> PathBuf {
126    let (s1, s2) = shard_dirs(uuid);
127    root.join("index")
128        .join("meta")
129        .join(&s1)
130        .join(&s2)
131        .join(format!("{}.meta.cbor", uuid.simple()))
132}
133
134/// `index/transcodes/h264/{s1}/{s2}/{uuid}.mp4`
135pub fn transcode_h264_path(root: &Path, uuid: &Uuid) -> PathBuf {
136    let (s1, s2) = shard_dirs(uuid);
137    root.join("index")
138        .join("transcodes")
139        .join("h264")
140        .join(&s1)
141        .join(&s2)
142        .join(format!("{}.mp4", uuid.simple()))
143}
144
145/// `index/transcodes/live/{s1}/{s2}/{uuid}.mov`
146pub fn transcode_live_path(root: &Path, uuid: &Uuid) -> PathBuf {
147    let (s1, s2) = shard_dirs(uuid);
148    root.join("index")
149        .join("transcodes")
150        .join("live")
151        .join(&s1)
152        .join(&s2)
153        .join(format!("{}.mov", uuid.simple()))
154}
155
156/// `.library/trash/{uuid}.{ext}`
157pub fn trash_path(root: &Path, uuid: &Uuid, ext: &str) -> PathBuf {
158    root.join(".library")
159        .join("trash")
160        .join(format!("{}.{}", uuid.simple(), ext))
161}
162
163// `tmp_path` encodes no library layout, so it lives in `crate::utils::paths` where
164// `capsule_core::sidecar` can reach it without depending on `library`. Re-exported here so
165// `library::paths::tmp_path` and `library::tmp_path` keep resolving for existing callers.
166pub use crate::utils::paths::tmp_path;
167
168#[cfg(test)]
169mod tests;