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#[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 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
40pub trait PuzzleCache: Debug {
46 fn load_input(&self, day: Day, year: Year) -> Result<Option<String>, CacheError>;
49
50 fn load_answers(&self, part: Part, day: Day, year: Year)
52 -> Result<Option<Answers>, CacheError>;
53
54 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 fn save_input(&self, input: &str, day: Day, year: Year) -> Result<(), CacheError>;
67
68 fn save_answers(
71 &self,
72 answers: &Answers,
73 part: Part,
74 day: Day,
75 year: Year,
76 ) -> Result<(), CacheError>;
77}
78
79pub trait SessionCache: Debug {
81 fn load(&self, session_id: &str) -> Result<Session, CacheError>;
83 fn save(&self, session: &Session) -> Result<(), CacheError>;
85}
86
87#[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 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 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 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 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 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 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 if let Some(passphrase) = &self.passphrase {
182 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 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 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 let input_path =
232 Self::input_file_path(&self.cache_dir, day, year, self.passphrase.is_some());
233
234 let mut puzzle_dir = input_path.clone();
236 puzzle_dir.pop();
237
238 std::fs::create_dir_all(puzzle_dir)?;
239
240 if let Some(passphrase) = &self.passphrase {
242 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 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 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 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 let mut session_dir = session_filepath.clone();
317 session_dir.pop();
318
319 std::fs::create_dir_all(session_dir)?;
320
321 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}