Repository navigation
Expand file tree
/
Copy pathupdate_notifier.rs
More file actions
484 lines (451 loc) · 17.2 KB
/
Copy pathupdate_notifier.rs
File metadata and controls
484 lines (451 loc) · 17.2 KB
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Passive update-check notifier: at most once a day, on interactive
//! human-facing runs only, mention on stderr that a newer release exists.
//!
//! Model: after clap parses (and never for `--update` itself — `main`
//! skips the hook structurally), a guard stack decides whether a check may
//! run at all. If one is due, a spawned tokio task first records the
//! attempt (so "once a day" holds even if the process exits mid-fetch),
//! then fetches while the real command does its work; at the end of the
//! run the task is joined with a 500 ms grace budget. A fetch that misses
//! the budget is abandoned — a completed result surfaces as a zero-latency
//! cached notice on the NEXT run, a killed one waits for tomorrow's
//! attempt.
//!
//! Invariants (enforced by `update_notifier_e2e.rs`):
//! - a silenced run performs **zero network I/O**, not just zero output;
//! - the notifier can never change a command's exit code or stdout;
//! - it can never delay a command beyond the grace budget;
//! - state corruption/unwritability is silently absorbed.
use std::io::IsTerminal;
use std::time::Duration;
use socket_patch_core::update::{
self as core_update, detect_channel, is_newer, upgrade_hint, upgrade_hint_for, ChannelEnv,
InstallChannel, UpdateEndpoints, UpdateTimeouts,
};
use socket_patch_core::utils::socket_cli_config::env_truthy;
use crate::args::GlobalArgs;
/// Everything the guard stack looks at, captured up front so the decision
/// logic is a pure, table-testable function.
#[derive(Debug, Clone)]
pub struct GuardCtx {
/// `SOCKET_NO_UPDATE_CHECK` truthy — the kill switch. Wins over
/// everything, including the force knob.
pub opted_out: bool,
pub offline: bool,
pub silent: bool,
pub json: bool,
/// `CI`/`GITHUB_ACTIONS` say a robot is watching. Always silences —
/// the force knob does NOT bypass it (tests neutralize with `CI=""`).
pub ci: bool,
pub stderr_tty: bool,
/// `SOCKET_UPDATE_NOTIFIER_FORCE` truthy — undocumented test hook that
/// bypasses ONLY the stderr-TTY guard (e2e children write to pipes).
pub forced: bool,
pub state_dir_resolvable: bool,
}
/// Why the notifier stayed quiet (debug-logged under `--debug`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkipReason {
OptedOut,
Offline,
Silent,
Json,
Ci,
NotATty,
NoStateDir,
}
impl SkipReason {
fn as_str(self) -> &'static str {
match self {
SkipReason::OptedOut => "SOCKET_NO_UPDATE_CHECK is set",
SkipReason::Offline => "offline mode",
SkipReason::Silent => "--silent",
SkipReason::Json => "--json",
SkipReason::Ci => "CI environment",
SkipReason::NotATty => "stderr is not a terminal",
SkipReason::NoStateDir => "no resolvable state directory",
}
}
}
/// The single place notifier-guard precedence is defined:
/// opt-out, offline, `--silent`, `--json`, and CI always silence;
/// the force knob bypasses the TTY guard alone.
pub fn should_check(ctx: &GuardCtx) -> Result<(), SkipReason> {
if ctx.opted_out {
return Err(SkipReason::OptedOut);
}
if ctx.offline {
return Err(SkipReason::Offline);
}
if ctx.silent {
return Err(SkipReason::Silent);
}
if ctx.json {
return Err(SkipReason::Json);
}
if ctx.ci {
return Err(SkipReason::Ci);
}
if !ctx.stderr_tty && !ctx.forced {
return Err(SkipReason::NotATty);
}
if !ctx.state_dir_resolvable {
return Err(SkipReason::NoStateDir);
}
Ok(())
}
/// `CI` set to anything non-empty except an explicit falsy counts;
/// `GITHUB_ACTIONS` counts whenever non-empty. Deliberately short list —
/// the TTY guard covers other vendors' runners anyway.
fn in_ci() -> bool {
let ci = std::env::var("CI").unwrap_or_default();
if !ci.is_empty() && !matches!(ci.trim().to_ascii_lowercase().as_str(), "0" | "false") {
return true;
}
!std::env::var("GITHUB_ACTIONS")
.unwrap_or_default()
.is_empty()
}
impl GuardCtx {
/// Capture the real environment + the parsed global flags.
pub fn capture(common: &GlobalArgs) -> Self {
GuardCtx {
opted_out: env_truthy("SOCKET_NO_UPDATE_CHECK"),
offline: common.offline,
silent: common.silent,
json: common.json,
ci: in_ci(),
// The notice prints on stderr; stdout may be legitimately piped
// (`list | jq`) in a perfectly interactive session.
stderr_tty: std::io::stderr().is_terminal(),
forced: env_truthy("SOCKET_UPDATE_NOTIFIER_FORCE"),
state_dir_resolvable: core_update::state::state_dir().is_some(),
}
}
}
/// Handle carried across the command run.
pub struct Notifier {
/// Running fetch, present only when a check was due this run.
task: Option<tokio::task::JoinHandle<Option<semver::Version>>>,
/// `latestSeen` loaded at spawn time — the cached fallback the notice
/// uses when the in-run fetch misses the grace budget (or none ran).
cached_latest: Option<semver::Version>,
last_notified_at: Option<u64>,
debug: bool,
}
fn debug_log(debug: bool, message: &str) {
if debug {
eprintln!("[socket-patch update] {message}");
}
}
/// Evaluate the guards and, when a check is due, start the background
/// fetch. Cheap on every path: env reads plus one tiny state-file read.
/// Returns `None` when the notifier is fully silenced for this run.
pub fn spawn_if_due(common: &GlobalArgs) -> Option<Notifier> {
let ctx = GuardCtx::capture(common);
let debug = common.debug;
if let Err(reason) = should_check(&ctx) {
debug_log(debug, &format!("skipped: {}", reason.as_str()));
return None;
}
let state = core_update::load_state();
let cached_latest = state
.latest_seen
.as_deref()
.and_then(|v| semver::Version::parse(v).ok());
let now = core_update::unix_now();
let task = if core_update::check_is_due(state.last_check_at, now) {
debug_log(debug, "checking for updates in the background");
Some(tokio::spawn(refresh_latest(debug)))
} else {
debug_log(debug, "check not due; using cached state");
None
};
Some(Notifier {
task,
cached_latest,
last_notified_at: state.last_notified_at,
debug,
})
}
/// The background fetch, bounded hard at 2 s (or the test override).
///
/// The ATTEMPT is persisted before the fetch, not after: the process may
/// exit (and kill this task) as soon as the carrier command finishes, and
/// on some platforms even a dead endpoint takes seconds to fail (Windows
/// retries SYNs to a closed port) — recording afterwards would let every
/// sub-grace command on a broken network burn a fresh fetch attempt.
/// Writing first makes "at most one attempt per day" hold unconditionally;
/// the cost is that a killed fetch's result waits for tomorrow's retry.
/// All errors are swallowed into debug logs.
async fn refresh_latest(debug: bool) -> Option<semver::Version> {
let mut state = core_update::load_state();
state.last_check_at = Some(core_update::unix_now());
if let Err(e) = core_update::save_state(&state).await {
debug_log(debug, &format!("could not persist update state: {e}"));
}
let endpoints = UpdateEndpoints::from_env();
let override_ms = std::env::var("SOCKET_UPDATE_TIMEOUT_MS")
.ok()
.filter(|v| !v.is_empty())
.and_then(|v| v.parse::<u64>().ok());
let budget = Duration::from_millis(override_ms.unwrap_or(2000));
let timeouts = UpdateTimeouts {
connect: budget,
metadata: budget,
download: budget,
};
let fetched = match core_update::fetch_latest_version(&endpoints, &timeouts).await {
Ok(v) => Some(v),
Err(e) => {
debug_log(debug, &format!("check failed: {e}"));
None
}
};
if let Some(v) = &fetched {
let mut state = core_update::load_state();
state.last_check_at = Some(core_update::unix_now());
state.latest_seen = Some(v.to_string());
if let Err(e) = core_update::save_state(&state).await {
debug_log(debug, &format!("could not persist update state: {e}"));
}
}
fetched
}
/// The channel-aware upgrade command for the notice's second line —
/// pointing an npm-installed user at `--update` would only route them into
/// its managed-install refusal.
fn upgrade_command() -> &'static str {
match core_update::resolve_install_path() {
Ok(p) => upgrade_hint_for(detect_channel(&p, &ChannelEnv::from_env()), &p),
Err(_) => upgrade_hint(InstallChannel::Standalone),
}
}
/// Render the two-line notice. Pure for unit tests. The caller prints a
/// blank line before it (it follows the command's own output, often an
/// `Error: ...` line, and must not read as part of that error).
fn format_notice(
current: &semver::Version,
latest: &semver::Version,
hint: &str,
use_color: bool,
) -> String {
let new_version = crate::ui::paint(&latest.to_string(), "32", use_color);
format!(
"[socket-patch] Update available: {current} \u{2192} {new_version}\n\
[socket-patch] Run `{hint}` to upgrade (set SOCKET_NO_UPDATE_CHECK=1 to hide)"
)
}
const DEFAULT_GRACE_MS: u64 = 500;
/// How long `finish` waits for the background fetch before abandoning it.
///
/// 500 ms in production — deliberately tight so a real command never stalls
/// on the notifier. The catch: `main` calls `std::process::exit` the instant
/// `finish` returns, which kills a still-running detached fetch before its
/// state write (or even its outbound request) can land. On a fast host the
/// loopback fetch finishes in milliseconds and comfortably beats the ceiling;
/// on a slow one (a loaded Windows CI runner, fsync latency, a cold TLS/HTTP
/// client) the fetch can miss the 500 ms window, the task is killed, and its
/// `latestSeen` write / `expect`-counted request simply never happens — an
/// e2e that asserts on that observable effect then fails intermittently.
///
/// `SOCKET_UPDATE_GRACE_MS` lets the e2e suite lift the ceiling so the fetch
/// is awaited to completion instead of raced. Same shape as the
/// `SOCKET_UPDATE_TIMEOUT_MS` fetch-budget hook; the default is preserved, so
/// production behavior is byte-identical.
fn grace_budget() -> Duration {
grace_budget_from(std::env::var("SOCKET_UPDATE_GRACE_MS").ok().as_deref())
}
/// Pure core of [`grace_budget`]: parse the raw env value, falling back to
/// the production default on absence, emptiness, or garbage.
fn grace_budget_from(raw: Option<&str>) -> Duration {
let ms = raw
.filter(|v| !v.is_empty())
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(DEFAULT_GRACE_MS);
Duration::from_millis(ms)
}
/// Join the background fetch within the grace budget and print the notice
/// if one is warranted. Runs after all command output; never touches
/// stdout or the exit code.
pub async fn finish(notifier: Option<Notifier>) {
let Some(notifier) = notifier else {
return;
};
let fetched = match notifier.task {
Some(handle) => {
match tokio::time::timeout(grace_budget(), handle).await {
Ok(Ok(result)) => result,
// Timed out (the task keeps running until process exit —
// its own state write may still land) or panicked; either
// way fall back to the cached value.
Ok(Err(_)) | Err(_) => {
debug_log(notifier.debug, "check missed the grace budget; will retry");
None
}
}
}
None => None,
};
let latest_known = fetched.or(notifier.cached_latest);
let Some(latest) = latest_known else {
return;
};
let current = core_update::current_version();
if !is_newer(&latest, ¤t) {
return;
}
let now = core_update::unix_now();
if !core_update::notice_is_due(notifier.last_notified_at, now) {
debug_log(
notifier.debug,
"update pending but notice already shown today",
);
return;
}
// Separator: the notice follows the command's own output.
eprintln!();
eprintln!(
"{}",
format_notice(
¤t,
&latest,
upgrade_command(),
crate::ui::stderr_color()
)
);
let mut state = core_update::load_state();
state.last_notified_at = Some(now);
if let Err(e) = core_update::save_state(&state).await {
debug_log(
notifier.debug,
&format!("could not persist notice time: {e}"),
);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn open_ctx() -> GuardCtx {
GuardCtx {
opted_out: false,
offline: false,
silent: false,
json: false,
ci: false,
stderr_tty: true,
forced: false,
state_dir_resolvable: true,
}
}
#[test]
fn guard_precedence_table() {
// (mutation, expected outcome) — the full precedence contract in
// one table. e2e spot-checks a subset of rows end-to-end.
type GuardCase = (&'static str, fn(&mut GuardCtx), Result<(), SkipReason>);
let cases: &[GuardCase] = &[
("all open", |_| {}, Ok(())),
("opt-out", |c| c.opted_out = true, Err(SkipReason::OptedOut)),
(
"opt-out beats force",
|c| {
c.opted_out = true;
c.forced = true;
},
Err(SkipReason::OptedOut),
),
("offline", |c| c.offline = true, Err(SkipReason::Offline)),
(
"offline beats force",
|c| {
c.offline = true;
c.forced = true;
},
Err(SkipReason::Offline),
),
("silent", |c| c.silent = true, Err(SkipReason::Silent)),
("json", |c| c.json = true, Err(SkipReason::Json)),
(
"json beats force",
|c| {
c.json = true;
c.forced = true;
},
Err(SkipReason::Json),
),
("ci", |c| c.ci = true, Err(SkipReason::Ci)),
(
"ci beats force — force bypasses ONLY the TTY guard",
|c| {
c.ci = true;
c.forced = true;
},
Err(SkipReason::Ci),
),
("no tty", |c| c.stderr_tty = false, Err(SkipReason::NotATty)),
(
"force bypasses the tty guard",
|c| {
c.stderr_tty = false;
c.forced = true;
},
Ok(()),
),
(
"no state dir",
|c| c.state_dir_resolvable = false,
Err(SkipReason::NoStateDir),
),
];
for (name, mutate, expected) in cases {
let mut ctx = open_ctx();
mutate(&mut ctx);
assert_eq!(&should_check(&ctx), expected, "case: {name}");
}
}
#[test]
fn grace_budget_defaults_preserved_and_override_honored() {
// Absence, emptiness, and garbage all keep the tight production
// ceiling — the override never silently changes shipped behavior.
assert_eq!(grace_budget_from(None), Duration::from_millis(500));
assert_eq!(grace_budget_from(Some("")), Duration::from_millis(500));
assert_eq!(
grace_budget_from(Some("not-a-number")),
Duration::from_millis(500)
);
// A valid value lifts the ceiling (the e2e suite's escape hatch).
assert_eq!(
grace_budget_from(Some("30000")),
Duration::from_millis(30_000)
);
assert_eq!(grace_budget_from(Some("0")), Duration::from_millis(0));
}
#[test]
fn notice_names_versions_hint_and_optout() {
let current = semver::Version::new(3, 3, 0);
let latest = semver::Version::new(3, 4, 0);
let plain = format_notice(¤t, &latest, "socket-patch --update", false);
assert!(plain.contains("3.3.0"), "{plain}");
assert!(plain.contains("3.4.0"), "{plain}");
assert!(plain.contains("socket-patch --update"), "{plain}");
assert!(plain.contains("SOCKET_NO_UPDATE_CHECK=1"), "{plain}");
assert!(
!plain.contains("\u{1b}["),
"no ANSI codes without a terminal: {plain}"
);
let colored = format_notice(¤t, &latest, "socket-patch --update", true);
assert!(colored.contains("\u{1b}["), "{colored}");
// Exactly two lines (the caller prints the separating blank line),
// both prefixed for grep-ability.
assert_eq!(
plain,
"[socket-patch] Update available: 3.3.0 \u{2192} 3.4.0\n\
[socket-patch] Run `socket-patch --update` to upgrade \
(set SOCKET_NO_UPDATE_CHECK=1 to hide)"
);
for line in plain.lines() {
assert!(line.starts_with("[socket-patch]"), "{line}");
}
assert_eq!(plain.lines().count(), 2);
}
}