advent_of_code_data/
cache.rs

1use std::{
2    fmt::Debug,
3    path::{Path, PathBuf},
4};
5
6use base64::{prelude::BASE64_STANDARD, Engine};
7use core::str;
8use simple_crypt::{decrypt, encrypt};
9use thiserror::Error;
10
11use crate::{
12    data::{Answers, Puzzle, Session},
13    Day, Part, Year,
14};
15
16/// Represents an error occurring when interacting with the cache.
17#[derive(Debug, Error)]
18pub enum CacheError {
19    #[error("passphrase expected but not provided (check your config)")]
20    PassphraseRequired,
21    #[error("Cached input file is not encrypted but encryption passphrase was provided")]
22    // TODO: Should this be a warning and not an error?
23    PassphraseNotNeeded,
24    #[error("base 64 decoding failed: {}", .0)]
25    DecodeBase64(#[from] base64::DecodeError),
26    #[error("decryption failed: {}", .0)]
27    Decryption(#[source] anyhow::Error),
28    #[error("encryption failed: {}", .0)]
29    Encryption(#[source] anyhow::Error),
30    #[error("decoding utf8 failed: {}", .0)]
31    DecodeUtf8(#[from] std::string::FromUtf8Error),
32    #[error("serializing or deserializing failed: {}", .0)]
33    JsonSerde(#[from] serde_json::Error),
34    #[error("a file i/o error occured while reading/writing the cache: {}", .0)]
35    Io(#[from] std::io::Error),
36    #[error("an error occurred while parsing a cached answer dataset: {}", .0)]
37    AnswerParsing(#[from] crate::data::AnswerDeserializationError),
38}
39
40/// Caches puzzle inputs and answers to allow retrieval without having to request data from the
41/// Advent of Code service.
42///
43/// Input data should be encrypted when written to storage, as requested by the Advent of Code
44/// owner. Answers do not need to be encrypted.
45pub trait PuzzleCache: Debug {
46    /// Load input for the given day and year. Returns the decrypted input if cached, or `Ok(None)`
47    /// if no cache entry exists.
48    fn load_input(&self, day: Day, year: Year) -> Result<Option<String>, CacheError>;
49
50    /// Load answers for the given part, day and year. Returns `Ok(None)` if no cache entry exists.
51    fn load_answers(&self, part: Part, day: Day, year: Year)
52        -> Result<Option<Answers>, CacheError>;
53
54    /// Save a puzzle's input and answers for both parts to the cache.
55    fn save(&self, puzzle: Puzzle) -> Result<(), CacheError> {
56        self.save_input(&puzzle.input, puzzle.day, puzzle.year)?;
57        self.save_answers(&puzzle.part_one_answers, Part::One, puzzle.day, puzzle.year)?;
58        self.save_answers(&puzzle.part_two_answers, Part::Two, puzzle.day, puzzle.year)?;
59
60        Ok(())
61    }
62
63    /// Save input for the given day and year. The input is encrypted before being written to disk
64    /// if a passphrase is provided. Any previously saved input for this day and year will be
65    /// overwritten.
66    fn save_input(&self, input: &str, day: Day, year: Year) -> Result<(), CacheError>;
67
68    /// Save answers for the given part, day and year. Any previously saved answers for this day and
69    /// year will be overwritten.
70    fn save_answers(
71        &self,
72        answers: &Answers,
73        part: Part,
74        day: Day,
75        year: Year,
76    ) -> Result<(), CacheError>;
77}
78
79/// Stores cached data specific to a session, such as submission timeouts.
80pub trait SessionCache: Debug {
81    /// Load session data linked to a session from the cache.
82    fn load(&self, session_id: &str) -> Result<Session, CacheError>;
83    /// Writes session data to the cache.
84    fn save(&self, session: &Session) -> Result<(), CacheError>;
85}
86
87/// A file system backed implementation of `PuzzleCache`.
88///
89/// Cached puzzle data is grouped together by day and year into a directory. The cache layout
90/// follows this general pattern:
91///
92///    <cache_dir>/y<year>/<day>/input.encrypted.txt
93///                             /part-1-answers.txt
94///                             /part-2-answers.txt
95///
96/// `cache_dir` is specified when `PuzzleFsCache::new(...)` is called.
97/// `year` is four digit puzzle year.
98/// `day` is the puzzle day with no leading zeroes, and starting from index one.
99///
100/// **Encryption**: If a passphrase is configured, inputs are automatically encrypted when saved and
101/// decrypted when loaded. The `.encrypted.txt` suffix indicates an encrypted file. Unencrypted
102/// input files use the `.txt` extension.
103#[derive(Debug)]
104pub struct PuzzleFsCache {
105    cache_dir: PathBuf,
106    passphrase: Option<String>,
107}
108
109impl PuzzleFsCache {
110    const INPUT_FILE_NAME: &'static str = "input.txt";
111    const ENCRYPTED_INPUT_FILE_NAME: &'static str = "input.encrypted.txt";
112    const PART_ONE_ANSWERS_FILE_NAME: &'static str = "part-1-answers.txt";
113    const PART_TWO_ANSWERS_FILE_NAME: &'static str = "part-2-answers.txt";
114
115    /// Creates a new `PuzzleFsCache` that reads/writes cache data stored in `cache_dir`. Inputs are
116    /// are encrypted on disk using the provided passphrase.
117    pub fn new<P: Into<PathBuf>, S: Into<String>>(cache_dir: P, passphrase: Option<S>) -> Self {
118        Self {
119            cache_dir: cache_dir.into(),
120            passphrase: passphrase.map(|x| x.into()),
121        }
122    }
123
124    /// Get the directory path for a puzzle day and year.
125    pub fn dir_for_puzzle(cache_dir: &Path, day: Day, year: Year) -> PathBuf {
126        cache_dir.join(format!("y{}", year)).join(day.to_string())
127    }
128
129    /// Returns the file path for puzzle input, with the appropriate extension based on encryption status.
130    pub fn input_file_path(cache_dir: &Path, day: Day, year: Year, encrypted: bool) -> PathBuf {
131        Self::dir_for_puzzle(cache_dir, day, year).join(if encrypted {
132            Self::ENCRYPTED_INPUT_FILE_NAME
133        } else {
134            Self::INPUT_FILE_NAME
135        })
136    }
137
138    /// Returns the file path for answers of a given part.
139    pub fn answers_file_path(cache_dir: &Path, part: Part, day: Day, year: Year) -> PathBuf {
140        Self::dir_for_puzzle(cache_dir, day, year).join(match part {
141            Part::One => Self::PART_ONE_ANSWERS_FILE_NAME,
142            Part::Two => Self::PART_TWO_ANSWERS_FILE_NAME,
143        })
144    }
145}
146
147impl PuzzleCache for PuzzleFsCache {
148    fn load_input(&self, day: Day, year: Year) -> Result<Option<String>, CacheError> {
149        // Check for common encryption misconfiguration scenarios and warn or return an error
150        // depending on severity.
151        let using_encryption = self.passphrase.is_some();
152        let input_path = Self::input_file_path(&self.cache_dir, day, year, using_encryption);
153        let input_path_exists = std::fs::exists(&input_path).unwrap_or(false);
154
155        let alt_input_path = Self::input_file_path(&self.cache_dir, day, year, !using_encryption);
156        let alt_input_path_exists = std::fs::exists(alt_input_path).unwrap_or(false);
157
158        match (using_encryption, input_path_exists, alt_input_path_exists) {
159            (true, true, true) => {
160                tracing::warn!(
161                    "mixed input (encrypted and unencrypted) for year {year} day {day} found in cache"
162                );
163            }
164            (true, false, true) => return Err(CacheError::PassphraseNotNeeded),
165            (false, true, true) => {
166                tracing::warn!(
167                    "mixed input (encrypted and unencrypted) input for year {year} day {day} found in cache"
168                );
169            }
170            (false, false, true) => return Err(CacheError::PassphraseRequired),
171            (_, false, _) => return Ok(None),
172            _ => {}
173        }
174
175        // Read the cached input file.
176        tracing::debug!("loading input for day {day} year {year} from {input_path:?}");
177
178        match std::fs::read_to_string(input_path) {
179            Ok(input_text) => {
180                // Check if the input file needs to be decrypted before returning it.
181                if let Some(passphrase) = &self.passphrase {
182                    // Input needs decryption before it can be returned.
183                    let encrypted_bytes = BASE64_STANDARD
184                        .decode(input_text.as_bytes())
185                        .map_err(CacheError::DecodeBase64)?;
186                    let input_bytes = decrypt(&encrypted_bytes, passphrase.as_bytes())
187                        .map_err(CacheError::Decryption)?;
188                    let decrypted_input_text =
189                        String::from_utf8(input_bytes).map_err(CacheError::DecodeUtf8)?;
190
191                    tracing::debug!("succesfully decrypted input for puzzle day {day} year {year}");
192
193                    Ok(Some(decrypted_input_text))
194                } else {
195                    // Input does not need decryption.
196                    Ok(Some(input_text))
197                }
198            }
199            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
200            Err(e) => Err(CacheError::Io(e)),
201        }
202    }
203
204    fn load_answers(
205        &self,
206        part: Part,
207        day: Day,
208        year: Year,
209    ) -> Result<Option<Answers>, CacheError> {
210        match std::fs::read_to_string(Self::answers_file_path(&self.cache_dir, part, day, year)) {
211            Ok(answers_data) => Ok(Some(Answers::deserialize_from_str(&answers_data)?)),
212            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
213            Err(e) => Err(CacheError::Io(e)),
214        }
215    }
216
217    fn save(&self, puzzle: Puzzle) -> Result<(), CacheError> {
218        // Create the puzzle directory in the cache if it doesn't already exist.
219        let puzzle_dir = Self::dir_for_puzzle(&self.cache_dir, puzzle.day, puzzle.year);
220        std::fs::create_dir_all(puzzle_dir)?;
221
222        self.save_input(&puzzle.input, puzzle.day, puzzle.year)?;
223        self.save_answers(&puzzle.part_one_answers, Part::One, puzzle.day, puzzle.year)?;
224        self.save_answers(&puzzle.part_two_answers, Part::Two, puzzle.day, puzzle.year)?;
225
226        Ok(())
227    }
228
229    fn save_input(&self, input: &str, day: Day, year: Year) -> Result<(), CacheError> {
230        // Calculate the path to the puzzle's input file.
231        let input_path =
232            Self::input_file_path(&self.cache_dir, day, year, self.passphrase.is_some());
233
234        // Create puzzle directory if it does not already exist.
235        let mut puzzle_dir = input_path.clone();
236        puzzle_dir.pop();
237
238        std::fs::create_dir_all(puzzle_dir)?;
239
240        // Write the input to disk and encrypt the input file when stored on disk.
241        if let Some(passphrase) = &self.passphrase {
242            // Encrypt then base64 encode for better version control handling.
243            let encrypted_data =
244                encrypt(input.as_bytes(), passphrase.as_bytes()).map_err(CacheError::Encryption)?;
245            let b64_encrypted_text = BASE64_STANDARD.encode(encrypted_data);
246
247            tracing::debug!("saving encrypted input for day {day} year {year} to {input_path:?}");
248            Ok(std::fs::write(input_path, b64_encrypted_text)?)
249        } else {
250            // No encryption.
251            tracing::debug!("saving unencrypted input for day {day} year {year} to {input_path:?}");
252            Ok(std::fs::write(input_path, input)?)
253        }
254    }
255
256    fn save_answers(
257        &self,
258        answers: &Answers,
259        part: Part,
260        day: Day,
261        year: Year,
262    ) -> Result<(), CacheError> {
263        let answers_path = Self::answers_file_path(&self.cache_dir, part, day, year);
264
265        // Create the puzzle directory if it doesn't already exist.
266        let mut puzzle_dir = answers_path.clone();
267        puzzle_dir.pop();
268
269        std::fs::create_dir_all(puzzle_dir)?;
270
271        tracing::debug!("saving answer for part {part} day {day} year {year} to {answers_path:?}");
272        Ok(std::fs::write(answers_path, answers.serialize_to_string())?)
273    }
274}
275
276#[derive(Debug)]
277pub struct SessionFsCache {
278    cache_dir: PathBuf,
279}
280
281impl SessionFsCache {
282    pub fn new<P: Into<PathBuf>>(cache_dir: P) -> Self {
283        Self {
284            cache_dir: cache_dir.into(),
285        }
286    }
287
288    /// Returns the cache file path for session data. The session ID is used directly as the filename.
289    /// Note: Assumes the session ID is already sanitized and safe for use as a filename.
290    pub fn session_data_filepath(&self, session_id: &str) -> PathBuf {
291        self.cache_dir.join(format!("{}.json", session_id))
292    }
293}
294
295impl SessionCache for SessionFsCache {
296    fn load(&self, session_id: &str) -> Result<Session, CacheError> {
297        let session_filepath = self.session_data_filepath(session_id);
298
299        if session_filepath.is_file() {
300            tracing::debug!("cached session data for {session_id} is at `{session_filepath:?}`");
301
302            let json_text = std::fs::read_to_string(session_filepath)?;
303            let session: Session = serde_json::from_str(&json_text)?;
304
305            Ok(session)
306        } else {
307            tracing::debug!("no cached session data for {session_id} at `{session_filepath:?}`, returning new Session object");
308            Ok(Session::new(session_id))
309        }
310    }
311
312    fn save(&self, session: &Session) -> Result<(), CacheError> {
313        let session_filepath = self.session_data_filepath(&session.session_id);
314
315        // Create puzzle directory if it does not already exist.
316        let mut session_dir = session_filepath.clone();
317        session_dir.pop();
318
319        std::fs::create_dir_all(session_dir)?;
320
321        // Write the serialized session data to disk.
322        let json_text = serde_json::to_string(&session)?;
323        tracing::debug!("saving session data to `{session_filepath:?}`");
324
325        std::fs::write(session_filepath, json_text)?;
326        Ok(())
327    }
328}