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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
//! Crates.io-based update notification helper.
//!
//! Why: User-facing trusty-* CLIs should nudge operators when a newer release
//! is available, so they are not silently running stale binaries. Centralising
//! the check here keeps the throttle, cache, opt-out, and User-Agent logic
//! consistent across every consumer.
//!
//! What: [`check_throttled`] is the main entry point. It:
//! 1. Returns `None` immediately when `TRUSTY_NO_UPDATE_CHECK` or `CI` is set.
//! 2. Returns a cached result when the last network check was < 24 h ago.
//! 3. Performs a non-blocking GET to `https://crates.io/api/v1/crates/{name}`
//! with a descriptive User-Agent, compares semver, caches the result, and
//! returns `Some(UpdateInfo)` when a newer stable version exists.
//!
//! All failures (network, parse, 403, missing field) degrade gracefully to
//! `None` — the check is best-effort and must never panic or stall a CLI.
//!
//! Test: `cargo test -p trusty-common --features update-check`.
use ;
use PathBuf;
use ;
// ─── Opt-out env vars ────────────────────────────────────────────────────────
/// Set to any non-empty value to disable update checks entirely.
pub const NO_UPDATE_CHECK_ENV: &str = "TRUSTY_NO_UPDATE_CHECK";
/// Standard CI environment variable — update checks are suppressed when set.
const CI_ENV: &str = "CI";
/// How frequently to hit crates.io (24 hours in seconds).
const CHECK_INTERVAL_SECS: u64 = 60 * 60 * 24;
/// Network timeout for each crates.io request.
const NETWORK_TIMEOUT_SECS: u64 = 4;
// ─── Public types ────────────────────────────────────────────────────────────
/// Metadata about an available update.
///
/// Why: A typed struct is easier to format and test than raw strings.
/// What: Holds the crate name, the version currently installed, and the latest
/// stable version seen on crates.io.
/// Test: [`notice`] exercises all three fields.
/// Produce a human-readable upgrade notice for `info`.
///
/// Why: A single formatting function keeps the message consistent and
/// testable without coupling consumers to the wording.
/// What: Returns a string like:
/// `"⬆ Update available: trusty-search 0.20.0 (you have 0.19.0) — run: cargo install trusty-search --locked"`.
/// Test: `notice_formats_correctly` in the `tests` module.
// ─── Cache types ─────────────────────────────────────────────────────────────
/// On-disk cache record stored under the OS cache directory.
///
/// Why: Throttle crates.io requests to at most once per 24 h so the check
/// does not add measurable latency on typical runs.
/// What: JSON file with a Unix timestamp of the last check and the latest
/// version string seen. A missing or corrupt file is silently treated as "no
/// cache" — the next invocation will perform a fresh network check.
/// Test: `cache_freshness_*` tests in this module.
// ─── Cache path resolution ───────────────────────────────────────────────────
/// Resolve the path to the per-crate cache file.
///
/// Why: We need a stable, OS-appropriate location that survives reboots and
/// is writable without elevated privileges.
/// What: Returns `<cache_dir>/trusty-tools/update-check/<crate_name>.json`.
/// Falls back to `<temp_dir>/trusty-tools-update-check/<crate_name>.json`
/// when `dirs::cache_dir()` returns `None` (rare in containers).
/// Test: Indirectly covered by the cache read/write helpers.
// ─── Cache I/O ───────────────────────────────────────────────────────────────
/// Read the cache file for `crate_name`, returning `None` on any failure.
///
/// Why: A corrupt or missing cache must not error — the caller treats `None`
/// as "do a fresh network check", which is safe and correct.
/// What: Reads the JSON file at [`cache_path`], deserializes a [`CacheEntry`],
/// and returns it. Returns `None` on I/O errors, missing files, or invalid JSON.
/// Test: `cache_round_trip` and `corrupt_cache_returns_none`.
/// Write a cache entry for `crate_name`, ignoring any I/O errors.
///
/// Why: Cache writes are best-effort — a failure (permissions, disk full)
/// should not propagate to the caller; the next run will simply re-check.
/// What: Serializes `entry` to JSON and writes it to [`cache_path`], creating
/// parent directories if necessary.
/// Test: `cache_round_trip` writes then reads back and checks equality.
// ─── Semver comparison ───────────────────────────────────────────────────────
/// Parse `MAJOR.MINOR.PATCH` from a version string, stripping pre-release /
/// build-metadata suffixes and ignoring non-numeric segments.
///
/// Why: We intentionally avoid the `semver` crate (not a workspace dep) to
/// keep the dependency surface minimal. The comparison logic required here is
/// simple: a tuple of three integers.
/// What: Returns `Some((major, minor, patch))` on success, `None` on any
/// parse failure.
/// Test: `semver_parse_strips_prerelease`, `semver_parse_handles_missing_patch`.
/// Return `true` when `latest_str` is strictly newer than `current_str`.
///
/// Why: The update check only fires for actual upgrades, not downgrades or
/// equal versions.
/// What: Parses both strings via [`parse_version`]; returns `false` on any
/// parse failure (best-effort).
/// Test: `semver_newer_returns_true`, `semver_equal_returns_false`,
/// `semver_older_returns_false`, `semver_prerelease_stripped`.
// ─── crates.io API types ─────────────────────────────────────────────────────
/// Minimal subset of the crates.io `GET /api/v1/crates/{name}` response.
///
/// Why: We only need `max_stable_version` (or fallbacks); deserializing the
/// full response shape is unnecessary and fragile.
/// What: Wraps the `crate` top-level key in the crates.io JSON payload.
/// Test: `check_crates_io` parses this shape.
// ─── Network check ───────────────────────────────────────────────────────────
/// Query crates.io for the latest stable version of `crate_name`.
///
/// Why: One canonical place to encode the User-Agent requirement, timeout,
/// JSON parse, and graceful fallback so callers only see `Option<UpdateInfo>`.
/// What: GETs `https://crates.io/api/v1/crates/{crate_name}` with a
/// descriptive User-Agent (required by crates.io policy; a missing or generic
/// UA returns 403). Parses `crate.max_stable_version`, falls back to
/// `newest_version` / `max_version`. Returns `Some(UpdateInfo)` only when the
/// parsed version is strictly newer than `current_version`. Returns `None` on
/// any error — network failure, timeout, 4xx/5xx, or JSON parse failure.
/// Test: covered by integration; unit tests mock the network path via the
/// throttle + cache layer.
pub async
// ─── Current Unix timestamp ───────────────────────────────────────────────────
/// Return seconds since UNIX_EPOCH, or 0 on error.
///
/// Why: `SystemTime` can theoretically fail on platforms with extreme clock
/// skew; returning 0 causes a cache miss rather than a panic.
/// What: Wraps `SystemTime::now().duration_since(UNIX_EPOCH)`.
/// Test: Used inline in `check_throttled` — the value is observable via
/// cache writes in `cache_round_trip`.
// ─── Throttled public entry point ────────────────────────────────────────────
/// Check crates.io for an update, throttled to at most once per 24 hours.
///
/// Why: User-facing CLIs should inform operators of new releases without
/// adding latency or hammering crates.io on every invocation.
///
/// Behaviour:
/// 1. Returns `None` immediately when `TRUSTY_NO_UPDATE_CHECK` or `CI` is set
/// (no network call, no cache I/O).
/// 2. Reads the per-crate cache file. If `last_check_unix` is less than 24 h
/// ago, returns the cached result (a fresh `UpdateInfo` when a newer version
/// was recorded, `None` when the cache says we are current).
/// 3. Otherwise performs a `check_crates_io` network call, writes the cache,
/// and returns the result.
///
/// Any I/O or network failure degrades to `None` — the check is best-effort.
///
/// What: Returns `Some(UpdateInfo)` when a newer stable version is available,
/// `None` in every other case.
/// Test: `check_throttled_skips_when_env_set`, `check_throttled_uses_cache`,
/// `check_throttled_fresh_check_on_stale_cache` — all without real network.
pub async
// ─── Tests ───────────────────────────────────────────────────────────────────
/// Test suite for semver comparison, notice formatting, env-var opt-out,
/// cache freshness, and cache I/O resilience.
///
/// Why: Split into a sibling file so `mod.rs` stays under the 500-line cap.
/// What: All tests are `#[cfg(test)]`-gated and run with
/// `cargo test -p trusty-common --features update-check`.
/// Test: run the above command to verify all 15 cases pass.