mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-25 07:02:08 +08:00
fix: core runstate review/improve (#7617)
* fix(core): reopen PAC when a start attempt never happens `save_proxy_ports` closes the PAC endpoint before it stages a candidate, because the endpoint resolves the Mixed Port through the draft layer and would otherwise answer with a port nothing is listening on. Most ways out of that function are a rejection, though: the candidate is refused and the Core keeps serving on its old ports, having never been stopped. PAC is re-derived only when the Running Mode changes, and that is exactly what did not happen — so the endpoint stayed shut for the rest of the session, and every browser on PAC silently went direct. Give `core_starting` the counterpart it was missing. `core_start_settled` re-derives PAC from the Running Mode rather than restoring a saved flag, which makes it correct on all three endings — a start that succeeded, one that was abandoned, one that failed and left the Core down — and therefore safe to run from a guard on every path. * fix(config): refuse overlapping draft transactions instead of losing an edit A layer holds exactly one draft, so a second writer's `edit_draft` overwrites the first writer's staged value in place. `DraftTransaction` nonetheless rolled back by calling `discard` on the shared layer, which discarded whatever was staged there — including a change another transaction was about to commit. The other transaction then found no draft, and `apply` on an absent draft does nothing at all. It saved the committed value, returned Ok, and its side effect had already happened: auto-launch registered with the OS while the config that describes it says otherwise, and no log line either way. "Roll back only my edit" cannot be implemented over a single slot, so enforce the exclusivity the type already assumed. Beginning a transaction claims every layer and refuses rather than interleaving, which is the same shape as `try_start_config_update` and `begin_operation` elsewhere. `patch_verge` is the caller that matters: it holds its draft across `process_terminated_flags`, which restarts the Core and can take seconds. The TUN reconciliation runs on every Run State transition and can now lose that race, so it treats a busy layer as "later" rather than as a failure worth telling the user about. * fix(core): reconcile TUN availability when the setting itself changes Moving the TUN availability guard from the frontend into Rust also moved what triggers it. The old effect depended on `enable_tun_mode`; the new reconciliation is spawned from `RealEnv::publish`, so it only runs on a Run State transition. Those two sets are not the same, and the setting itself falls in the gap. Switching TUN on from the global hotkey is the case that reaches it. That path is not gated on availability — unlike the tray item and the settings switch, both of which read `tun_capable` — and the flags a TUN patch raises are answered by a Core reload, which changes no Run State at all. So on a machine with no Service and no elevation the setting stayed on: tray icon, settings switch and `enable_tun_mode` in verge.yaml all reported TUN as enabled while nothing carried its traffic, until some unrelated core lifecycle transition happened to reconcile it. Reconcile after any patch that touched the setting. The reconciliation writes configuration itself, so it goes through the plain apply rather than back through the patch-and-reconcile form; the absence of a cycle is then a property of the call graph rather than of a runtime early-return. `toggle_tun_mode` now reads the setting back instead of returning what it asked for, so the hotkey cannot report TUN as on moments before the notice saying it was turned off. * fix(core): an action already under way is not a decision to put to the user The legacy status could not distinguish a requested privileged operation from one already running, because readers blocked until the operation finished and so never observed the request at all. Run State pushes every transition instead, and `service_needs_attention` treated any pending action as a question for the user. So an install started from the settings page or the home card raised the migration dialog on top of it, and an uninstall raised one offering to reinstall the Service being removed. Both offer a button that can only fail, since the privileged-operation slot is already taken. An operation in flight is a report of progress. The dialog the user is already driving keeps itself open through its own loading state. `tun_should_be_disabled` is unaffected: it already refused to act while an operation was in flight, so the term this adds is redundant there. * fix(core): let the snapshot decide whether the Run State has settled `settled` read the operation slot twice: once to decide whether to wait, then again inside the snapshot it returned. An operation claiming the slot between those two reads was described rather than waited for. `prepare_startup` reads this. A start racing an install would see the requested install, flatten it to `InstallRequired`, and decide `Wait` — leaving the core stopped where waiting for the install to finish would have told it whether the Service came back. Read the slot once, inside the snapshot, so there is no window rather than a second check closing it. The rewrite that introduced this also fixed a lost wakeup here, and that fix stands: the waiter is still registered before the state is read. * fix(ui): re-read the Run State once its listener is live Replacing the poll with a push left a gap. `listen` resolves asynchronously, so between the first `get_runtime_state` and the subscription being registered there is a window, and a transition landing in it is not queued anywhere — it is simply missed. The next event is whenever the backend happens to move again, which during startup can be a long time; the 30-second safety net was all that stood behind it, where the old code polled every two seconds precisely through startup. The Run State is the one thing here that arrives only by event, so it is the one thing a missed event leaves stale. Re-read it once every listener is live, which closes the gap without going back to polling for it. `onSubscribed` fires even when a registration failed, because a resync is most needed when a subscription is missing, and not at all after teardown. * docs(config): state what makes the PAC endpoint's draft read safe `MixedPort::desired` reads the draft layer, so the PAC endpoint can name a port the Core has not moved to yet. That is only safe because the one path staging a listener port closes PAC across the change. Nothing said so at either end, and the two are in different modules. * fix(core): ask again when staging goes silent rather than assume it failed The Service commits the generation before it answers, so a reply that never arrives is not evidence that nothing was written: config.yaml can already hold the new configuration while this side concludes the staging never happened. The Core keeps running the previous configuration, so nothing looks wrong -- until the Core dies and the Service's watchdog restarts it in the same generation from whatever config.yaml says, quietly making live a configuration the app reported as failed. Silence is the one answer that has to be resolved rather than acted on, so ask once more before falling back. It is cheap exactly where it matters: staging plans against the manifest it wrote, so a bundle that already landed copies nothing and answers in milliseconds, and the Service's lifecycle lock makes a second ask wait for a first one still in flight instead of interleaving with it. A deadline keeps that wait off the caller, and a second silence goes where the first one used to.
This commit is contained in:
@@ -97,11 +97,21 @@ impl RunState {
|
||||
|
||||
/// The Service cannot be used and the user has to choose what to do about it.
|
||||
///
|
||||
/// A requested action always needs an answer. Otherwise it is only the states where the
|
||||
/// Service is present but unusable: a Service that is simply absent, or a session that has
|
||||
/// already settled on Sidecar, needs nothing from anyone.
|
||||
/// A requested action always needs an answer — unless it is already being carried out,
|
||||
/// which is a report of progress rather than a question. The legacy status could not tell
|
||||
/// the two apart because readers blocked until the operation finished and so never saw the
|
||||
/// request at all; now that every transition is pushed, an install started from the
|
||||
/// settings page would otherwise raise the migration dialog on top of it, and an uninstall
|
||||
/// would raise one offering to reinstall the very Service being removed.
|
||||
///
|
||||
/// Otherwise it is only the states where the Service is present but unusable: a Service
|
||||
/// that is simply absent, or a session that has already settled on Sidecar, needs nothing
|
||||
/// from anyone.
|
||||
#[must_use]
|
||||
pub const fn service_needs_attention(&self) -> bool {
|
||||
if self.op_in_flight {
|
||||
return false;
|
||||
}
|
||||
if self.pending.is_some() {
|
||||
return true;
|
||||
}
|
||||
@@ -247,7 +257,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_requested_action_always_needs_an_answer() {
|
||||
fn a_requested_action_needs_an_answer_until_it_is_being_carried_out() {
|
||||
for action in [
|
||||
PendingAction::Install,
|
||||
PendingAction::Uninstall,
|
||||
@@ -256,7 +266,34 @@ mod tests {
|
||||
] {
|
||||
let mut run_state = state(ServiceHealth::NotInstalled, false, false);
|
||||
run_state.pending = Some(action);
|
||||
assert!(run_state.service_needs_attention(), "{action:?}");
|
||||
assert!(run_state.service_needs_attention(), "{action:?} is still a question");
|
||||
|
||||
run_state.op_in_flight = true;
|
||||
assert!(
|
||||
!run_state.service_needs_attention(),
|
||||
"{action:?} is under way, which is progress rather than a question"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_operation_under_way_is_never_a_decision_to_put_to_the_user() {
|
||||
// The regression this pins: an install or uninstall started from the settings page
|
||||
// pushes its pending action to the frontend the moment it is requested. Readers used
|
||||
// to block until the operation finished and so never saw it; now that every transition
|
||||
// is pushed, treating it as a decision raises the migration dialog on top of an
|
||||
// operation already running — and for an uninstall, one offering to reinstall.
|
||||
for health in [
|
||||
ServiceHealth::Unknown,
|
||||
ServiceHealth::Ready,
|
||||
ServiceHealth::NotInstalled,
|
||||
ServiceHealth::VersionMismatch,
|
||||
ServiceHealth::Unavailable("boom".into()),
|
||||
] {
|
||||
let mut run_state = state(health.clone(), false, true);
|
||||
run_state.pending = Some(PendingAction::Uninstall);
|
||||
|
||||
assert!(!run_state.service_needs_attention(), "{health:?}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -114,19 +114,26 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
}
|
||||
|
||||
/// The Run State once any in-flight privileged operation has finished.
|
||||
///
|
||||
/// The snapshot is the decision, not a separate check before it. Reading the slot twice —
|
||||
/// once to decide whether to wait, once to build the snapshot — leaves a window in which an
|
||||
/// operation claims it, and the snapshot then *describes* that operation instead of waiting
|
||||
/// for it. `prepare_startup` reads this: it would see a requested install as a reason not to
|
||||
/// start, where waiting would have told it whether the install worked.
|
||||
pub async fn settled(&self) -> RunState {
|
||||
loop {
|
||||
let notified = self.operation_done.notified();
|
||||
tokio::pin!(notified);
|
||||
// Register as a waiter *before* checking the flag. `notify_waiters` wakes only
|
||||
// Register as a waiter *before* reading the state. `notify_waiters` wakes only
|
||||
// those already registered and leaves no permit behind, so without this an
|
||||
// operation finishing between the check and the await is a wakeup lost for good
|
||||
// operation finishing between the read and the await is a wakeup lost for good
|
||||
// — and this future would then wait for some unrelated later operation, or
|
||||
// forever.
|
||||
notified.as_mut().enable();
|
||||
|
||||
if !self.operation_running.load(Ordering::Acquire) {
|
||||
return self.state();
|
||||
let state = self.state();
|
||||
if !state.op_in_flight {
|
||||
return state;
|
||||
}
|
||||
notified.await;
|
||||
}
|
||||
@@ -350,10 +357,27 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
///
|
||||
/// Closes the PAC endpoint without disturbing the Running Mode, so a handover cannot
|
||||
/// hand out a PAC script for a proxy port that is between owners.
|
||||
///
|
||||
/// Every caller must pair this with [`Self::core_start_settled`]. A start attempt that
|
||||
/// never happens — a candidate rejected before anything was stopped — otherwise leaves PAC
|
||||
/// closed for a Core that is still serving, and nothing else would ever reopen it: PAC is
|
||||
/// re-derived only when the Running Mode changes, and that is exactly what did not happen.
|
||||
pub fn core_starting(&self) {
|
||||
self.env.set_pac_available(false);
|
||||
}
|
||||
|
||||
/// The start attempt is over, however it ended: PAC goes back to following the Running Mode.
|
||||
///
|
||||
/// Idempotent and safe on every path, because it re-derives rather than restores. After a
|
||||
/// start that succeeded the mode is already running and this confirms PAC open; after one
|
||||
/// that was abandoned the mode never moved and this reopens PAC for the Core that kept
|
||||
/// serving; after one that failed and stopped the Core the mode says NotRunning and PAC
|
||||
/// stays shut.
|
||||
pub fn core_start_settled(&self) {
|
||||
let running = !matches!(**self.mode.load(), RunningMode::NotRunning);
|
||||
self.env.set_pac_available(running);
|
||||
}
|
||||
|
||||
/// Move to `mode` and re-derive everything that follows from it.
|
||||
///
|
||||
/// PAC availability and the outward mirror are derived here and nowhere else, so they
|
||||
@@ -628,6 +652,33 @@ mod tests {
|
||||
assert!(!settled.op_in_flight);
|
||||
}
|
||||
|
||||
// Multi-threaded on purpose, so operations really do start and finish underneath the reader.
|
||||
// This is a guard, not a reproducer: the window it protects against was narrow enough that
|
||||
// reverting the fix did not fail this test in six runs. What makes the invariant hold is
|
||||
// that `settled` reads the slot once, inside the snapshot it returns; this fails if someone
|
||||
// reintroduces a separate check before it.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_settled_snapshot_never_describes_an_operation_in_flight() {
|
||||
let store = Arc::new(with_env(FakeEnv::new()));
|
||||
store.observe(ServiceHealth::Ready);
|
||||
|
||||
for _ in 0..64 {
|
||||
let claimer = {
|
||||
let store = Arc::clone(&store);
|
||||
tokio::spawn(async move {
|
||||
let guard = store.begin_operation();
|
||||
tokio::task::yield_now().await;
|
||||
drop(guard);
|
||||
})
|
||||
};
|
||||
|
||||
let settled = store.settled().await;
|
||||
assert!(!settled.op_in_flight, "a settled snapshot describes a settled state");
|
||||
|
||||
claimer.await.expect("the claimer should not panic");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn probing_a_ready_service_records_it() {
|
||||
let store = with_env(FakeEnv::new().service_ready());
|
||||
@@ -831,6 +882,48 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_abandoned_start_attempt_reopens_pac_for_the_core_that_kept_running() {
|
||||
// The regression this pins: a proxy-port candidate rejected before anything was
|
||||
// stopped. `core_starting` closed PAC, the Running Mode never moved, and so nothing
|
||||
// would ever re-derive PAC — the Core kept serving while its PAC endpoint stayed shut.
|
||||
for mode in [RunningMode::Service, RunningMode::Sidecar] {
|
||||
let store = with_env(FakeEnv::new());
|
||||
store.core_started(mode);
|
||||
store.core_starting();
|
||||
assert_eq!(store.env.pac_available(), Some(false));
|
||||
|
||||
store.core_start_settled();
|
||||
|
||||
assert_eq!(store.env.pac_available(), Some(true), "{mode} kept serving");
|
||||
assert_eq!(store.state().mode, mode, "an abandoned start is not a mode change");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_settled_start_leaves_pac_shut_when_no_core_is_running() {
|
||||
let store = with_env(FakeEnv::new());
|
||||
store.core_starting();
|
||||
|
||||
store.core_start_settled();
|
||||
|
||||
assert_eq!(store.env.pac_available(), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settling_a_start_is_idempotent_and_never_contradicts_the_mode() {
|
||||
// Callers pair this with `core_starting` via a guard that runs on every path, so it
|
||||
// also runs after a start that already opened PAC itself.
|
||||
let store = with_env(FakeEnv::new());
|
||||
store.core_starting();
|
||||
store.core_started(RunningMode::Service);
|
||||
|
||||
store.core_start_settled();
|
||||
store.core_start_settled();
|
||||
|
||||
assert_eq!(store.env.pac_available(), Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pac_availability_can_never_disagree_with_the_running_mode() {
|
||||
let store = with_env(FakeEnv::new());
|
||||
|
||||
Reference in New Issue
Block a user