1#[cfg(test)]
9mod tests;
10
11use std::{
12 io::Write,
13 path::Path,
14 time::{Duration, SystemTime},
15};
16
17use semver::Version;
18use serde::{Deserialize, Serialize};
19
20const LATEST_URL: &str = "https://api.github.com/repos/lhj6102/artifactize/releases/latest";
22const SITE: &str = "https://github.com/lhj6102/artifactize";
24const TEST_LATEST_PATH: &str = "/api/releases/latest";
26pub const OFF_VARIABLE: &str = "ARTIFACTIZE_NO_UPDATE_CHECK";
28pub const TEST_ENDPOINT_VARIABLE: &str = "ARTIFACTIZE_RELEASES_URL";
32const INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
35const RECHECK: Duration = Duration::from_secs(60 * 60);
38const TEST_RECHECK: Duration = Duration::from_secs(1);
40const TIMEOUT: Duration = Duration::from_secs(10);
42const CACHE: &str = "release-check.json";
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
47#[serde(rename_all = "camelCase")]
48pub enum Channel {
49 Store,
51 InstallSh,
53 InstallPs1,
55 Homebrew,
57 HomebrewCask,
59 Cargo,
61 Dmg,
63 Deb,
65 AppImage,
67 Unknown,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
73#[serde(tag = "kind", rename_all = "camelCase")]
74pub enum Update {
75 Command { command: String },
77 Download {
79 url: String,
80 #[serde(skip_serializing_if = "Option::is_none")]
81 command: Option<String>,
82 },
83 Page { url: String },
85}
86
87impl Channel {
88 pub fn update(self, latest: &Version) -> Option<Update> {
90 crate::platform::install::update(self, latest, SITE)
91 }
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
96#[serde(rename_all = "camelCase")]
97pub enum Unchecked {
98 Store,
100 Off,
102 Development,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
108pub enum Outcome {
109 Unchecked(Unchecked),
111 Latest(Version),
113 Newer { latest: Version, update: Update },
115 Failed(String),
117}
118
119#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Status {
122 pub running: Version,
123 pub channel: Channel,
124 pub outcome: Outcome,
125}
126
127struct Source {
129 url: String,
130 site: String,
131}
132
133pub async fn check(state: &Path) -> Status {
136 let clock = crate::platform::environment::var("ARTIFACTIZE_E2E_RELEASE_CLOCK")
137 .filter(|_| crate::platform::environment::var(TEST_ENDPOINT_VARIABLE).is_some());
138 let now = match clock {
139 None => SystemTime::now(),
140 Some(file) => match controlled_time(Path::new(&file)) {
141 Ok(now) => now,
142 Err(message) => {
143 return Status {
144 running: running(),
145 channel: crate::platform::install::channel(),
146 outcome: Outcome::Failed(message),
147 };
148 }
149 },
150 };
151 check_at(state, now).await
152}
153
154fn controlled_time(file: &Path) -> Result<SystemTime, String> {
155 let text = std::fs::read_to_string(file).map_err(|error| error.to_string())?;
156 let seconds = text
157 .trim()
158 .parse::<u64>()
159 .map_err(|error| error.to_string())?;
160 SystemTime::UNIX_EPOCH
161 .checked_add(Duration::from_secs(seconds))
162 .ok_or_else(|| "release fixture clock is out of range".into())
163}
164
165pub async fn check_at(state: &Path, now: SystemTime) -> Status {
167 let running = running();
168 let channel = crate::platform::install::channel();
169 let outcome = match source(&running, channel, crate::platform::environment::var) {
170 Ok(source) => look_up(&running, channel, &source, state, now).await,
171 Err(outcome) => outcome,
172 };
173 Status {
174 running,
175 channel,
176 outcome,
177 }
178}
179
180pub fn recheck_interval() -> Duration {
182 if crate::platform::environment::var(TEST_ENDPOINT_VARIABLE)
183 .is_some_and(|value| !value.is_empty())
184 {
185 TEST_RECHECK
186 } else {
187 RECHECK
188 }
189}
190
191pub fn shown_update(version: &str) -> Result<Update, String> {
193 let latest =
194 Version::parse(version).map_err(|error| format!("Invalid release version: {error}"))?;
195 let running = running();
196 let channel = crate::platform::install::channel();
197 let source = source(&running, channel, crate::platform::environment::var)
198 .map_err(|_| "This install has no available release link.")?;
199 if let Outcome::Newer { update, .. } = decide(&running, channel, latest, &source.site) {
200 Ok(update)
201 } else {
202 Err("This install has no available release link for that version.".into())
203 }
204}
205
206pub fn running() -> Version {
208 Version::parse(env!("CARGO_PKG_VERSION")).expect("the crate version is semantic")
209}
210
211fn source(
213 running: &Version,
214 channel: Channel,
215 var: impl Fn(&str) -> Option<std::ffi::OsString>,
216) -> Result<Source, Outcome> {
217 if var(OFF_VARIABLE).is_some_and(|value| !value.is_empty()) {
218 return Err(Outcome::Unchecked(Unchecked::Off));
219 }
220 if channel == Channel::Store {
221 return Err(Outcome::Unchecked(Unchecked::Store));
222 }
223 match crate::llm::variable_endpoint_in(TEST_ENDPOINT_VARIABLE, var) {
224 Ok(Some(site)) => Ok(Source {
225 url: format!("{site}{TEST_LATEST_PATH}"),
226 site: site.root().to_owned(),
227 }),
228 Ok(None) if running.pre.as_str() == "dev" => {
230 Err(Outcome::Unchecked(Unchecked::Development))
231 }
232 Ok(None) => Ok(Source {
233 url: LATEST_URL.into(),
234 site: SITE.into(),
235 }),
236 Err(error) => Err(Outcome::Failed(error)),
237 }
238}
239
240async fn look_up(
241 running: &Version,
242 channel: Channel,
243 source: &Source,
244 state: &Path,
245 now: SystemTime,
246) -> Outcome {
247 match latest(source, state, now).await {
248 Ok(latest) => decide(running, channel, latest, &source.site),
249 Err(error) => Outcome::Failed(error),
250 }
251}
252
253fn decide(running: &Version, channel: Channel, latest: Version, site: &str) -> Outcome {
255 if latest <= *running {
256 return Outcome::Latest(latest);
257 }
258 match crate::platform::install::update(channel, &latest, site) {
259 Some(update) => Outcome::Newer { latest, update },
260 None => Outcome::Unchecked(Unchecked::Store),
261 }
262}
263
264#[derive(Debug, Serialize, Deserialize)]
266#[serde(rename_all = "camelCase")]
267struct Cached {
268 #[serde(with = "epoch_seconds")]
269 checked_at: SystemTime,
270 site: String,
271 latest: Version,
272}
273
274async fn latest(source: &Source, state: &Path, now: SystemTime) -> Result<Version, String> {
276 let cache = state.join(CACHE);
277 if let Some(cached) = read_cache(&cache)
278 .filter(|cached| cached.site == source.site && fresh(cached.checked_at, now))
279 {
280 return Ok(cached.latest);
281 }
282 let latest = fetch(&source.url).await?;
283 let _ = write_cache(
285 state,
286 &Cached {
287 checked_at: now,
288 site: source.site.clone(),
289 latest: latest.clone(),
290 },
291 );
292 Ok(latest)
293}
294
295fn fresh(checked_at: SystemTime, now: SystemTime) -> bool {
298 now.duration_since(checked_at)
299 .is_ok_and(|age| age < INTERVAL)
300}
301
302mod epoch_seconds {
304 use serde::{Deserialize, Deserializer, Serializer, de::Error};
305 use std::time::{Duration, SystemTime, UNIX_EPOCH};
306
307 pub fn serialize<S: Serializer>(time: &SystemTime, serializer: S) -> Result<S::Ok, S::Error> {
308 serializer.serialize_u64(
309 time.duration_since(UNIX_EPOCH)
310 .map_or(0, |since| since.as_secs()),
311 )
312 }
313
314 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<SystemTime, D::Error> {
316 let seconds = u64::deserialize(deserializer)?;
317 UNIX_EPOCH
318 .checked_add(Duration::from_secs(seconds))
319 .ok_or_else(|| D::Error::custom("checkedAt is past any clock"))
320 }
321}
322
323fn read_cache(path: &Path) -> Option<Cached> {
325 serde_json::from_slice(&std::fs::read(path).ok()?).ok()
326}
327
328fn write_cache(state: &Path, cached: &Cached) -> Result<(), String> {
330 let mut file = tempfile::NamedTempFile::new_in(state).map_err(|e| e.to_string())?;
331 serde_json::to_writer(&mut file, cached).map_err(|e| e.to_string())?;
332 file.flush().map_err(|e| e.to_string())?;
333 crate::platform::paths::replace_open_file(file, &state.join(CACHE)).map_err(|e| e.to_string())
334}
335
336async fn fetch(url: &str) -> Result<Version, String> {
338 #[derive(Deserialize)]
339 struct Latest {
340 tag_name: String,
341 }
342 let client = reqwest::Client::builder()
343 .timeout(TIMEOUT)
344 .user_agent(concat!("artifactize/", env!("CARGO_PKG_VERSION")))
345 .build()
346 .map_err(|e| e.to_string())?;
347 let latest: Latest = client
348 .get(url)
349 .header(reqwest::header::ACCEPT, "application/vnd.github+json")
350 .send()
351 .await
352 .and_then(reqwest::Response::error_for_status)
353 .map_err(|e| e.without_url().to_string())?
354 .json()
355 .await
356 .map_err(|e| e.without_url().to_string())?;
357 let tag = &latest.tag_name;
358 let version = Version::parse(tag.strip_prefix('v').unwrap_or(tag))
359 .map_err(|e| format!("the latest release's tag {tag:?} is not a version: {e}"))?;
360 if !version.pre.is_empty() {
361 return Err(format!(
362 "the latest release's tag {tag:?} is not a stable version"
363 ));
364 }
365 Ok(version)
366}