1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
mod error;
pub use error::Error;
use reqwest::{blocking::Client, cookie::Jar};
use std::{
collections::hash_map::DefaultHasher,
fs::{read_to_string, File, OpenOptions},
hash::{Hash, Hasher},
io::{BufRead, BufReader, Write},
path::{Path, PathBuf},
sync::Arc,
};
use tracing::{debug, error, info, instrument};
type Result<T> = std::result::Result<T, Error>;
const INDEX_FILE_NAME: &str = "index.cache";
const TEMP_DIR_NAME: &str = "aoc_cache";
#[instrument(skip(cookie))]
pub fn get_input_from_web_or_cache(url: &str, cookie: &str) -> Result<String> {
if let Some(content) = get_cache_for_url(url)? {
info!("returning content found in cache");
return Ok(content);
}
debug!("content not found in cache, requesting from web");
if cookie.is_empty() {
return Err(Error::InvalidCookie(
"empty cookie is not valid".to_string(),
));
}
let jar = Jar::default();
let url_parsed = url.parse()?;
jar.add_cookie_str(cookie, &url_parsed);
let client = Client::builder()
.cookie_store(true)
.cookie_provider(Arc::new(jar))
.user_agent("https://github.com/glennib/aoc-cache by glennib.pub@gmail.com")
.build()?;
let request = client.get(url_parsed).build()?;
let response = client.execute(request)?.error_for_status()?;
let content = response.text()?.trim().to_string();
add_cache(url, &content)?;
info!("returning content from web");
Ok(content)
}
#[instrument]
fn create_or_get_cache_dir() -> PathBuf {
let cache_dir = scratch::path(TEMP_DIR_NAME);
debug!(?cache_dir);
cache_dir
}
#[instrument(skip(url))]
fn get_cache_for_url(url: &str) -> Result<Option<String>> {
let cache_file_path = get_cache_file_path_from_index(url)?;
match cache_file_path {
None => Ok(None),
Some(path) => {
debug!("cache_file_path={}", path.to_str().unwrap());
Ok(Some(read_to_string(path)?))
}
}
}
#[instrument(skip(url))]
fn encode_url(url: &str) -> String {
let mut hasher = DefaultHasher::new();
url.hash(&mut hasher);
let hash = hasher.finish();
hash.to_string()
}
#[instrument(skip(url))]
fn filename_from_url(url: &str) -> String {
let mut filename = String::from("cache_");
filename.push_str(&encode_url(url));
filename.push_str(".cache");
filename
}
#[instrument(skip(url, content))]
fn add_cache(url: &str, content: &str) -> Result<()> {
let cache_file_path = get_cache_file_path_from_index(url)?;
if cache_file_path.is_some() {
error!("found cache entry for {url} when attempting to add new cache for it");
return Err(Error::Duplicate(format!(
"found cache entry for {url} when attempting to add new cache for it"
)));
}
let cache_dir = create_or_get_cache_dir();
let cache_filename = filename_from_url(url);
let cache_file_path = cache_dir.join(cache_filename);
let mut file = OpenOptions::new()
.create(true)
.write(true)
.open(&cache_file_path)?;
write!(file, "{content}")?;
info!(
"Wrote content (size={}) to {cache_file_path:?}",
content.len()
);
let index_path = create_index_if_non_existent()?;
let mut file = OpenOptions::new().append(true).open(&index_path)?;
let cache_file_path_str = cache_file_path.to_str();
match cache_file_path_str {
None => {
error!(?cache_file_path, "cannot convert to str");
return Err(Error::Path("Cache file path was empty".to_string()));
}
Some(cache_file_path_str) => {
let index_line = format!("{url}: {}", cache_file_path_str);
writeln!(file, "{index_line}")?;
info!("Wrote `{index_line}` to {index_path:?}");
}
}
Ok(())
}
#[instrument]
fn create_file_if_non_existent(path: &Path) -> Result<()> {
if Path::new(path).exists() {
debug!("file already existed, doing nothing");
} else {
info!("file didn't exist, creating");
File::create(path)?;
}
Ok(())
}
#[instrument]
fn create_index_if_non_existent() -> Result<PathBuf> {
let cache_dir = create_or_get_cache_dir();
let index_path = cache_dir.join(INDEX_FILE_NAME);
create_file_if_non_existent(&index_path)?;
Ok(index_path)
}
#[instrument(skip(url))]
fn get_cache_file_path_from_index(url: &str) -> Result<Option<PathBuf>> {
let index_path = create_index_if_non_existent()?;
let file = File::open(index_path)?;
for line in BufReader::new(file).lines() {
let line = line?;
let parts: Vec<_> = line.split(": ").collect();
if parts.len() != 2 {
return Err(Error::Parse(format!("could not parse index line `{line}`")));
}
let url_in_line = parts[0];
if url_in_line == url {
let cache_file_path = parts[1].to_string();
debug!(cache_file_path, "from index");
return Ok(Some(cache_file_path.into()));
}
}
Ok(None)
}