Skip to main content

docsrs_cli/cache/disk/
store.rs

1//! Persisting a response: temp file, fsync, rename.
2//!
3//! The entry is two files that must agree, so neither may become visible before
4//! both are durable. Body and meta are written to temporaries, synced, then
5//! renamed into place; a RAII guard removes the temporaries on any early return
6//! or panic, so an interrupted put leaves no half-entry for `read` to reject.
7
8use std::fs;
9use std::io::Write;
10use std::path::PathBuf;
11
12use reqwest::Url;
13use tracing::debug;
14
15use crate::cache::hex::{input_checksum, key_hex, sha256_hex};
16use crate::cache::types::{CACHE_PARSER_VERSION, CacheMeta};
17use crate::error::{AppError, AppResult, ErrorDetail, InternalOp, IoOp, io_at};
18use crate::http::HttpResponse;
19
20use super::{DiskCache, unix_now};
21
22/// Removes leftover temporaries unless disarmed after both renames succeed.
23struct TempCleanup {
24    paths: [PathBuf; 2],
25    armed: bool,
26}
27
28impl Drop for TempCleanup {
29    fn drop(&mut self) {
30        if !self.armed {
31            return;
32        }
33        for p in &self.paths {
34            if p.as_os_str().is_empty() {
35                continue;
36            }
37            let _ = fs::remove_file(p);
38        }
39    }
40}
41
42impl DiskCache {
43    /// Persist a successful response. Best-effort; failures are non-fatal at call sites.
44    ///
45    /// # Errors
46    ///
47    /// Returns [`crate::error::ErrorKind::Internal`] on filesystem create/write/rename
48    /// failures or when cache metadata cannot be serialized.
49    pub fn put(&self, url: &Url, accept: &str, resp: &HttpResponse) -> AppResult<()> {
50        if !resp.status.is_success() {
51            return Ok(());
52        }
53        // Soft budget: never store a single body that already exceeds the cap.
54        if self.max_bytes > 0 && (resp.body.len() as u64) > self.max_bytes {
55            debug!(
56                body = resp.body.len(),
57                max = self.max_bytes,
58                "cache skip: body exceeds max_bytes"
59            );
60            return Ok(());
61        }
62        let dir = self.entry_dir();
63        fs::create_dir_all(&dir).map_err(io_at(IoOp::CreateDir, &dir))?;
64        crate::platform::restrict_private_dir(&dir);
65        let key = key_hex(url.as_str(), CACHE_PARSER_VERSION, accept);
66        let input_sha = input_checksum(url.as_str(), CACHE_PARSER_VERSION, accept);
67        let body_sha = sha256_hex(resp.body.as_ref());
68        let meta = CacheMeta {
69            url: url.as_str().to_string(),
70            parser_version: CACHE_PARSER_VERSION.to_string(),
71            accept: accept.to_string(),
72            status: resp.status.as_u16(),
73            content_type: resp.content_type.clone(),
74            final_url: resp.final_url.as_str().to_string(),
75            stored_at_unix: unix_now(),
76            body_sha256: body_sha,
77            input_sha256: input_sha,
78        };
79        let (meta_path, body_path) = self.paths_for_key(&key).ok_or_else(|| {
80            AppError::of(ErrorDetail::Internal {
81                op: InternalOp::CacheKeyMalformed,
82            })
83        })?;
84        let meta_tmp = meta_path.with_extension("meta.json.tmp");
85        let body_tmp = body_path.with_extension("bin.tmp");
86
87        // RAII: remove temps on any early return / panic; disarmed after successful renames.
88        let mut temps = TempCleanup {
89            paths: [body_tmp, meta_tmp],
90            armed: true,
91        };
92
93        {
94            let tmp = temps.paths[0].clone();
95            let mut f = fs::File::create(&tmp).map_err(io_at(IoOp::CreateTemp, &tmp))?;
96            f.write_all(resp.body.as_ref())
97                .map_err(io_at(IoOp::Write, &tmp))?;
98            f.sync_all().map_err(io_at(IoOp::Sync, &tmp))?;
99        }
100        {
101            let text = serde_json::to_string(&meta).map_err(|e| {
102                AppError::of_with_source(
103                    ErrorDetail::Internal {
104                        op: InternalOp::JsonSerialize,
105                    },
106                    e,
107                )
108            })?;
109            let tmp = temps.paths[1].clone();
110            let mut f = fs::File::create(&tmp).map_err(io_at(IoOp::CreateTemp, &tmp))?;
111            f.write_all(text.as_bytes())
112                .map_err(io_at(IoOp::Write, &tmp))?;
113            f.sync_all().map_err(io_at(IoOp::Sync, &tmp))?;
114        }
115
116        fs::rename(&temps.paths[0], &body_path).map_err(io_at(IoOp::Rename, &body_path))?;
117        crate::platform::restrict_private_file(&body_path);
118        temps.paths[0] = PathBuf::new();
119        fs::rename(&temps.paths[1], &meta_path).map_err(io_at(IoOp::Rename, &meta_path))?;
120        crate::platform::restrict_private_file(&meta_path);
121        temps.armed = false;
122        debug!(%key, "cache store");
123        self.enforce_max_bytes(Some(&key));
124        Ok(())
125    }
126}