Skip to main content

gitpoulpi_hosting/
list_cache.rs

1//! A saved copy of an integration's repository list, so the Clone dialog
2//! shows it at once while a fresh request runs.
3//!
4//! One JSON file per key (`integration id`, `host`, `login`) in a cache
5//! directory the caller names. Read leniently: a missing, corrupt, foreign
6//! version or colliding-name file is no cache. Writes go through a temp file
7//! and a rename. Never holds a token: the key is the profile id, the host and
8//! the connected login, so another account on the same profile is another
9//! entry.
10
11use std::path::{Path, PathBuf};
12
13use gitpoulpi_config::Integration;
14use serde::{Deserialize, Serialize};
15
16use crate::HostedProject;
17
18/// File format version; any other value reads as no cache.
19pub const VERSION: u32 = 1;
20/// A list longer than this is cut when stored (bounds a file to a few MB).
21pub const MAX_PROJECTS: usize = 5000;
22/// Stored descriptions are cut to this many characters.
23pub const MAX_DESCRIPTION: usize = 200;
24/// [`prune`] keeps at most this many files, newest first.
25pub const MAX_FILES: usize = 32;
26
27/// What a saved list belongs to.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct ListKey {
30    pub integration_id: String,
31    pub host: String,
32    /// The connected login, empty when none.
33    pub login: String,
34}
35
36impl ListKey {
37    /// The key of `integration` (`login` is the connected user's login), or
38    /// `None` when it has no host to key on.
39    pub fn of(integration: &Integration, login: Option<&str>) -> Option<Self> {
40        Some(Self {
41            integration_id: integration.id.clone(),
42            host: integration.host()?,
43            login: login.unwrap_or("").to_string(),
44        })
45    }
46
47    fn file_name(&self) -> String {
48        let clean = |s: &str| -> String {
49            s.chars()
50                .map(|c| {
51                    if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
52                        c
53                    } else {
54                        '_'
55                    }
56                })
57                .collect()
58        };
59        format!(
60            "{}@{}@{}.json",
61            clean(&self.integration_id),
62            clean(&self.host),
63            clean(&self.login)
64        )
65    }
66}
67
68/// One saved list.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70pub struct CachedList {
71    pub version: u32,
72    pub key: ListKey,
73    /// Unix seconds.
74    pub fetched_at: u64,
75    pub projects: Vec<HostedProject>,
76}
77
78impl CachedList {
79    pub fn new(key: ListKey, fetched_at: u64, projects: Vec<HostedProject>) -> Self {
80        Self {
81            version: VERSION,
82            key,
83            fetched_at,
84            projects,
85        }
86    }
87}
88
89fn path_of(dir: &Path, key: &ListKey) -> PathBuf {
90    dir.join(key.file_name())
91}
92
93/// The saved list of `key`, or `None` when absent or unreadable.
94pub fn load(dir: &Path, key: &ListKey) -> Option<CachedList> {
95    let raw = std::fs::read_to_string(path_of(dir, key)).ok()?;
96    let list: CachedList = serde_json::from_str(&raw).ok()?;
97    (list.version == VERSION && list.key == *key).then_some(list)
98}
99
100/// Removes any `user:password@` from an `https://` clone URL.
101fn strip_userinfo(url: &str) -> String {
102    let Some(rest) = url
103        .strip_prefix("https://")
104        .or_else(|| url.strip_prefix("http://"))
105    else {
106        return url.to_string();
107    };
108    let scheme_len = url.len() - rest.len();
109    let end = rest.find('/').unwrap_or(rest.len());
110    match rest[..end].rfind('@') {
111        Some(at) => format!("{}{}", &url[..scheme_len], &rest[at + 1..]),
112        None => url.to_string(),
113    }
114}
115
116/// Saves `list` (temp file, then rename), capped and stripped of user info.
117pub fn store(dir: &Path, list: &CachedList) -> std::io::Result<()> {
118    gitpoulpi_config::secure_fs::create_private_dir_all(dir)?;
119    let mut list = list.clone();
120    list.projects.truncate(MAX_PROJECTS);
121    for p in &mut list.projects {
122        if let Some(d) = &mut p.description {
123            if d.chars().count() > MAX_DESCRIPTION {
124                *d = d.chars().take(MAX_DESCRIPTION).collect();
125            }
126        }
127        p.https_url = p.https_url.as_deref().map(strip_userinfo);
128    }
129    let path = path_of(dir, &list.key);
130    let text = serde_json::to_string(&list).map_err(std::io::Error::other)?;
131    gitpoulpi_config::secure_fs::write_private(&path, text.as_bytes())
132}
133
134/// Deletes the saved list of `key`.
135pub fn remove(dir: &Path, key: &ListKey) {
136    let _ = std::fs::remove_file(path_of(dir, key));
137}
138
139/// Deletes every saved list of the integration `id`, whatever its host and
140/// login; returns how many files went. Files that do not parse are left to
141/// [`prune`].
142pub fn remove_integration(dir: &Path, id: &str) -> usize {
143    let Ok(entries) = std::fs::read_dir(dir) else {
144        return 0;
145    };
146    let mut removed = 0;
147    for entry in entries.flatten() {
148        let path = entry.path();
149        if path.extension().and_then(|e| e.to_str()) != Some("json") {
150            continue;
151        }
152        let owned = std::fs::read_to_string(&path)
153            .ok()
154            .and_then(|raw| serde_json::from_str::<CachedList>(&raw).ok())
155            .is_some_and(|l| l.key.integration_id == id);
156        if owned && std::fs::remove_file(&path).is_ok() {
157            removed += 1;
158        }
159    }
160    removed
161}
162
163/// Deletes every file whose key is not in `live` (a removed profile, a
164/// disconnected or other account), then keeps only the [`MAX_FILES`] newest.
165/// Files that do not parse are deleted too.
166pub fn prune(dir: &Path, live: &[ListKey]) {
167    let Ok(entries) = std::fs::read_dir(dir) else {
168        return;
169    };
170    let mut kept: Vec<(u64, PathBuf)> = Vec::new();
171    for entry in entries.flatten() {
172        let path = entry.path();
173        if path.extension().and_then(|e| e.to_str()) != Some("json") {
174            continue;
175        }
176        let parsed = std::fs::read_to_string(&path)
177            .ok()
178            .and_then(|raw| serde_json::from_str::<CachedList>(&raw).ok())
179            .filter(|l| l.version == VERSION && live.contains(&l.key));
180        match parsed {
181            Some(l) => kept.push((l.fetched_at, path)),
182            None => {
183                let _ = std::fs::remove_file(&path);
184            }
185        }
186    }
187    kept.sort_by_key(|(at, _)| std::cmp::Reverse(*at));
188    for (_, path) in kept.into_iter().skip(MAX_FILES) {
189        let _ = std::fs::remove_file(path);
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    fn key(id: &str, login: &str) -> ListKey {
198        ListKey {
199            integration_id: id.into(),
200            host: "github.com".into(),
201            login: login.into(),
202        }
203    }
204
205    fn project(full: &str) -> HostedProject {
206        HostedProject {
207            integration_id: "gh".into(),
208            id: full.into(),
209            name: full.rsplit('/').next().unwrap().into(),
210            full_name: full.into(),
211            description: None,
212            default_branch: None,
213            ssh_url: None,
214            https_url: None,
215            web_url: None,
216            private: false,
217        }
218    }
219
220    #[test]
221    fn round_trip() {
222        let dir = tempfile::tempdir().unwrap();
223        let list = CachedList::new(
224            key("gh", "ann"),
225            5,
226            vec![project("ann/a"), project("org/b")],
227        );
228        store(dir.path(), &list).unwrap();
229        assert_eq!(load(dir.path(), &key("gh", "ann")), Some(list));
230        assert_eq!(load(dir.path(), &key("gh", "bob")), None);
231    }
232
233    #[test]
234    fn corrupt_wrong_version_and_collision_read_as_none() {
235        let dir = tempfile::tempdir().unwrap();
236        let k = key("gh", "ann");
237        std::fs::write(path_of(dir.path(), &k), "{ not json").unwrap();
238        assert_eq!(load(dir.path(), &k), None);
239
240        let mut list = CachedList::new(k.clone(), 1, vec![]);
241        list.version = 99;
242        std::fs::write(
243            path_of(dir.path(), &k),
244            serde_json::to_string(&list).unwrap(),
245        )
246        .unwrap();
247        assert_eq!(load(dir.path(), &k), None);
248
249        // "a b" and "a_b" sanitize to the same file name; the stored key wins.
250        let (k1, k2) = (key("a b", "x"), key("a_b", "x"));
251        store(dir.path(), &CachedList::new(k1.clone(), 1, vec![])).unwrap();
252        assert_eq!(path_of(dir.path(), &k1), path_of(dir.path(), &k2));
253        assert_eq!(load(dir.path(), &k2), None);
254        assert!(load(dir.path(), &k1).is_some());
255    }
256
257    #[test]
258    fn store_caps_and_strips_user_info() {
259        let dir = tempfile::tempdir().unwrap();
260        let mut many: Vec<HostedProject> = (0..MAX_PROJECTS + 3)
261            .map(|i| project(&format!("o/r{i}")))
262            .collect();
263        many[0].description = Some("x".repeat(MAX_DESCRIPTION + 50));
264        many[0].https_url = Some("https://user:secret@host.example/o/r0.git".into());
265        many[1].https_url = Some("https://host.example/o/r1.git".into());
266        let k = key("gh", "ann");
267        store(dir.path(), &CachedList::new(k.clone(), 1, many)).unwrap();
268        let back = load(dir.path(), &k).unwrap();
269        assert_eq!(back.projects.len(), MAX_PROJECTS);
270        assert_eq!(
271            back.projects[0].description.as_ref().unwrap().len(),
272            MAX_DESCRIPTION
273        );
274        assert_eq!(
275            back.projects[0].https_url.as_deref(),
276            Some("https://host.example/o/r0.git")
277        );
278        assert_eq!(
279            back.projects[1].https_url.as_deref(),
280            Some("https://host.example/o/r1.git")
281        );
282        let raw = std::fs::read_to_string(path_of(dir.path(), &k)).unwrap();
283        assert!(!raw.contains("secret"));
284    }
285
286    #[test]
287    fn prune_drops_unknown_ids_and_changed_login() {
288        let dir = tempfile::tempdir().unwrap();
289        for k in [key("gh", "ann"), key("gh", "bob"), key("gone", "ann")] {
290            store(dir.path(), &CachedList::new(k, 1, vec![])).unwrap();
291        }
292        prune(dir.path(), &[key("gh", "bob")]);
293        assert_eq!(load(dir.path(), &key("gh", "ann")), None);
294        assert_eq!(load(dir.path(), &key("gone", "ann")), None);
295        assert!(load(dir.path(), &key("gh", "bob")).is_some());
296    }
297
298    #[test]
299    fn prune_keeps_the_newest_files() {
300        let dir = tempfile::tempdir().unwrap();
301        let keys: Vec<ListKey> = (0..MAX_FILES + 3)
302            .map(|i| key(&format!("p{i}"), ""))
303            .collect();
304        for (i, k) in keys.iter().enumerate() {
305            store(dir.path(), &CachedList::new(k.clone(), i as u64, vec![])).unwrap();
306        }
307        prune(dir.path(), &keys);
308        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), MAX_FILES);
309        assert!(load(dir.path(), &keys[0]).is_none());
310        assert!(load(dir.path(), keys.last().unwrap()).is_some());
311    }
312}