feat: schedule nonblocking Windows HIP patch checks

This commit is contained in:
Kevin Yue committed 2026-11-18 13:56:12 +08:00
1 parent bde11186f8
commit 5e7e343def
13 files changed
+318 -19

No files matched your search

+29 -15
View File
@@ -85,7 +85,7 @@ impl HipPreviews {
})
.await;
let result = match generated {
Ok(Ok(xml)) => preview_result(&registry, session_id, xml),
Ok(Ok(report)) => preview_result(&registry, session_id, report),
Ok(Err(error)) => {
log::warn!("HIP preview failed: {error:#}");
ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed")
@@ -132,17 +132,20 @@ impl HipPreviews {
}
}
fn preview_result(registry: &SessionRegistry, session_id: Uuid, xml: String) -> ServiceResult {
let result = registry.store_hip_preview(session_id, xml).and_then(|preview_id| {
registry
.hip_preview_chunk(session_id, preview_id, 0)
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
preview_id: preview_id.to_string(),
offset: 0,
xml,
complete,
})
});
fn preview_result(registry: &SessionRegistry, session_id: Uuid, report: gpapi::hip::HipReport) -> ServiceResult {
let result = registry
.store_hip_preview(session_id, report.xml)
.and_then(|preview_id| {
registry
.hip_preview_chunk(session_id, preview_id, 0)
.map(|(xml, complete)| ServiceResult::HipPreviewChunk {
preview_id: preview_id.to_string(),
offset: 0,
xml,
complete,
windows_updates: report.windows_updates,
})
});
result.unwrap_or_else(|_| ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"))
}
@@ -152,7 +155,7 @@ fn generate(
desktop_uid: Option<u32>,
identity: HostIdentity,
cancellation: CancellationToken,
) -> anyhow::Result<String> {
) -> anyhow::Result<gpapi::hip::HipReport> {
ensure!(request.client_version.len() <= 64, "Invalid HIP client version");
ensure!(
request.host_id.as_ref().is_none_or(|id| id.len() <= 256),
@@ -188,7 +191,15 @@ fn generate(
};
let xml = match &request.source {
HipSource::Disabled => bail!("HIP is disabled"),
HipSource::Generated => crate::hip_source::generate(&profile, None, &input, &check, true)?,
HipSource::Generated => {
return gphip::generate_report_details(
&gphip::ReportInput {
profile,
context: gphip::ReportContext::Preview,
},
&check,
);
}
HipSource::Edited { .. } => {
let xml = edited_report.context("Edited HIP report is unavailable")?;
crate::hip_source::generate(&profile, Some(&xml), &input, &check, true)?
@@ -204,7 +215,10 @@ fn generate(
}
};
check()?;
Ok(xml)
Ok(gpapi::hip::HipReport {
xml,
windows_updates: None,
})
}
#[cfg(test)]
+2
View File
@@ -22,6 +22,8 @@ mod runtime_user;
mod session_registry;
mod vpn_script;
mod vpn_task;
#[cfg(windows)]
mod windows_patches;
mod ws_connection;
mod ws_server;
+7 -1
View File
@@ -70,6 +70,10 @@ pub struct RequestDispatcher {
}
impl RequestDispatcher {
#[cfg(windows)]
pub(crate) fn patch_checks(&self) -> Arc<crate::windows_patches::PatchChecks> {
self.lifecycle.patch_checks.clone()
}
pub fn subscribe_tunnel(&self) -> tokio::sync::watch::Receiver<crate::vpn_task::TunnelBinding> {
self.lifecycle.subscribe_tunnel()
}
@@ -262,7 +266,9 @@ impl RequestDispatcher {
| WsRequest::GetHipApprovalStatus { .. }
| WsRequest::ReadHipPreviewChunk(_)
| WsRequest::GetLastSubmittedHipReport
| WsRequest::SetTunnelStatisticsEnabled { .. } => {
| WsRequest::SetTunnelStatisticsEnabled { .. }
| WsRequest::SetWindowsPatchInterest { .. }
| WsRequest::RefreshWindowsPatches { .. } => {
unreachable!("session-bound request was already dispatched")
}
}
+4
View File
@@ -31,6 +31,8 @@ mod script_tun;
#[derive(Clone)]
pub(crate) struct LifecycleHandle {
#[cfg(windows)]
pub(crate) patch_checks: Arc<crate::windows_patches::PatchChecks>,
events: mpsc::Sender<LifecycleEvent>,
admissions: Arc<Mutex<Admissions>>,
tunnel: watch::Sender<TunnelBinding>,
@@ -462,6 +464,8 @@ impl VpnTask {
) -> (Self, LifecycleHandle) {
let (events_tx, events) = mpsc::channel(4);
let lifecycle = LifecycleHandle {
#[cfg(windows)]
patch_checks: crate::windows_patches::PatchChecks::new(),
events: events_tx,
admissions: Arc::new(Mutex::new(Admissions::default())),
tunnel: watch::channel(TunnelBinding::default()).0,
+17
View File
@@ -50,6 +50,23 @@ pub(super) fn spawn(
) -> JoinHandle<()> {
tokio::spawn(async move {
let attempt = input.attempt;
#[cfg(windows)]
let _patch_interest = {
let args = input.connection.request.args();
let profile = &input.connection.resources.profile;
(matches!(args.hip_source(), gpapi::hip::HipSource::Generated)
&& profile.is_native()
&& profile.client_os() == gpapi::os_profile::ClientOs::Windows
&& (input.connection.request.plan().policy().collect_hip_data()
|| input
.connection
.request
.plan()
.members()
.iter()
.any(|member| member.authentication.mode() == SessionMode::Tunnel)))
.then(|| input.lifecycle.patch_checks.consumer())
};
let mut failure = None;
let mut approval = None;
if !cancellation.is_cancelled() {
+159
View File
@@ -0,0 +1,159 @@
//! One service-owned local patch search, independent of report generation.
use gpapi::{
collection::{CollectionBudget, CollectionControl},
process::collection::CollectorCommands,
};
use std::{
collections::HashSet,
sync::{Arc, Mutex},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
const INTERVAL: Duration = Duration::from_secs(15 * 60);
const SEARCH_TIMEOUT: Duration = Duration::from_secs(60);
enum Command {
Interest(Uuid, bool),
CheckIfDue,
Refresh(Option<u64>, oneshot::Sender<bool>),
}
pub(crate) struct PatchChecks {
tx: mpsc::UnboundedSender<Command>,
rx: Mutex<Option<mpsc::UnboundedReceiver<Command>>>,
}
pub(crate) struct Consumer {
checks: Arc<PatchChecks>,
id: Uuid,
}
impl Drop for Consumer {
fn drop(&mut self) {
self.checks.set_interest(self.id, false);
}
}
impl PatchChecks {
pub(crate) fn new() -> Arc<Self> {
let (tx, rx) = mpsc::unbounded_channel();
Arc::new(Self {
tx,
rx: Mutex::new(Some(rx)),
})
}
pub(crate) fn set_interest(&self, id: Uuid, enabled: bool) {
let _ = self.tx.send(Command::Interest(id, enabled));
}
pub(crate) fn check_if_due(&self) {
let _ = self.tx.send(Command::CheckIfDue);
}
pub(crate) fn consumer(self: &Arc<Self>) -> Consumer {
let id = Uuid::new_v4();
self.set_interest(id, true);
Consumer {
checks: self.clone(),
id,
}
}
pub(crate) async fn refresh(&self, after: Option<u64>) -> bool {
let (tx, rx) = oneshot::channel();
if self.tx.send(Command::Refresh(after, tx)).is_err() {
return false;
}
rx.await.unwrap_or(false)
}
pub(crate) async fn run(&self, stop: CancellationToken) {
let Some(mut commands) = self.rx.lock().unwrap().take() else {
return;
};
let mut consumers = HashSet::new();
let mut waiters = Vec::<oneshot::Sender<bool>>::new();
let mut worker = None;
// Reading status never searches Windows Update. Missing/unreadable data is due immediately.
let status = tokio::task::spawn_blocking({
let stop = stop.clone();
move || helper("--patch-status", None, stop)
})
.await;
let mut next = match status {
Ok(Ok(Some(checked))) => checked.saturating_add(INTERVAL.as_secs()),
_ => 0,
};
loop {
tokio::select! {
_ = stop.cancelled() => break,
command = commands.recv() => {
match command {
Some(Command::Interest(id, enabled)) => {
if enabled { consumers.insert(id); } else { consumers.remove(&id); }
}
Some(Command::CheckIfDue) => {
if worker.is_none() && now() >= next { worker = Some(start(None, stop.clone())); }
}
Some(Command::Refresh(after, reply)) => {
waiters.push(reply);
if worker.is_none() { worker = Some(start(after, stop.clone())); }
}
None => break,
}
}
result = async { match &mut worker { Some(task) => task.await, None => std::future::pending().await } } => {
worker = None;
let success = matches!(&result, Ok(Ok(Some(_))));
if !success { log::warn!("Local Windows patch check failed: {result:?}"); }
for reply in waiters.drain(..) { let _ = reply.send(success); }
next = match result {
Ok(Ok(Some(checked))) => checked.saturating_add(INTERVAL.as_secs()),
_ => now().saturating_add(INTERVAL.as_secs()),
};
}
_ = tokio::time::sleep(Duration::from_secs(next.saturating_sub(now()).min(30))),
if worker.is_none() && !consumers.is_empty() => {
if now() >= next { worker = Some(start(None, stop.clone())); }
}
}
}
if let Some(task) = worker {
let _ = task.await;
}
for reply in waiters {
let _ = reply.send(false);
}
}
}
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
fn start(after: Option<u64>, stop: CancellationToken) -> tokio::task::JoinHandle<anyhow::Result<Option<u64>>> {
tokio::task::spawn_blocking(move || helper("--refresh-patches", after, stop))
}
fn helper(command: &str, after: Option<u64>, stop: CancellationToken) -> anyhow::Result<Option<u64>> {
let budget = CollectionBudget::new(SEARCH_TIMEOUT);
let check = || {
if stop.is_cancelled() {
return Err(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"Patch check cancelled",
));
}
budget.check()
};
let path = std::env::current_exe()?.with_file_name("gp-posture.exe");
let after = after.map(|after| after.to_string());
let mut args = vec![command];
if let Some(after) = &after {
args.push(after);
}
let output = CollectorCommands::new(&check)
.run_executable(&path, &args)?
.ok_or_else(|| anyhow::anyhow!("Windows posture helper is unavailable"))?;
anyhow::ensure!(output.status.success(), "Windows posture helper failed");
Ok(serde_json::from_slice(&output.stdout)?)
}
+48
View File
@@ -410,6 +410,48 @@ async fn handle_client_message(
return Ok(());
}
if let WsRequest::SetWindowsPatchInterest { enabled } = &request {
#[cfg(windows)]
ctx.patch_checks.set_interest(control.connection_id(), *enabled);
#[cfg(not(windows))]
let _ = enabled;
control
.send(ConnectionCommand::Reply {
id,
result: ServiceResult::Accepted,
})
.map_err(|_| ())?;
return Ok(());
}
if let WsRequest::RefreshWindowsPatches { after } = &request {
#[cfg(windows)]
{
let checks = ctx.patch_checks.clone();
let control = control.clone();
let after = Some(after.unwrap_or(0));
tokio::spawn(async move {
let success = checks.refresh(after).await;
let result = if success {
ServiceResult::Accepted
} else {
ServiceResult::rejected(ServiceErrorCode::Internal, "Couldn’t check local updates.")
};
let _ = control.send(ConnectionCommand::Reply { id, result });
});
}
#[cfg(not(windows))]
{
let _ = after;
control
.send(ConnectionCommand::Reply {
id,
result: ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Windows patch checks are unavailable"),
})
.map_err(|_| ())?;
}
return Ok(());
}
if let WsRequest::StoreEditedHipReportChunk(report) = request {
let upload_id = report.upload_id.as_deref().and_then(|id| Uuid::parse_str(id).ok());
let result = if report.upload_id.is_some() && upload_id.is_none() {
@@ -451,6 +493,7 @@ async fn handle_client_message(
offset: chunk.offset,
xml,
complete,
windows_updates: None,
})
})
.unwrap_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP preview is unavailable"));
@@ -467,6 +510,7 @@ async fn handle_client_message(
offset: 0,
xml,
complete,
windows_updates: None,
},
Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"),
},
@@ -501,6 +545,10 @@ async fn handle_client_message(
}
if let WsRequest::PreviewHipReport(preview) = request {
#[cfg(windows)]
if preview.client_os == gpapi::os_profile::ClientOs::Windows && matches!(preview.source, HipSource::Generated) {
ctx.patch_checks.check_if_due();
}
let edited_report = if let HipSource::Edited { report_id } = &preview.source {
let report_id = match Uuid::parse_str(report_id) {
Ok(id) => id,
+15
View File
@@ -63,6 +63,8 @@ pub(crate) struct WsServerContext {
state: Mutex<ServiceState>,
handshake_slots: Arc<Semaphore>,
pub(crate) hip_previews: crate::hip_preview::HipPreviews,
#[cfg(windows)]
pub(crate) patch_checks: Arc<crate::windows_patches::PatchChecks>,
}
impl WsServerContext {
@@ -75,6 +77,8 @@ impl WsServerContext {
Self {
product_version,
registry,
#[cfg(windows)]
patch_checks: dispatcher.patch_checks(),
dispatcher,
state: Mutex::new(ServiceState {
revision: 0,
@@ -183,6 +187,8 @@ impl WsServerContext {
pub async fn remove_connection(&self, connection_id: Uuid, session_id: Uuid, generation: u64) {
self.registry.disconnect_if_current(session_id, generation);
#[cfg(windows)]
self.patch_checks.set_interest(connection_id, false);
let mut state = self.state.lock().await;
state.connections.remove(&connection_id);
state.refresh_demand();
@@ -364,6 +370,12 @@ impl WsServer {
};
let _ = ready_tx.send(());
#[cfg(windows)]
let patch_task = {
let checks = self.ctx.patch_checks.clone();
let stop = self.cancel_token.clone();
tokio::spawn(async move { checks.run(stop).await })
};
tokio::select! {
_ = watch_vpn_state(self.vpn_state_rx.clone(), Arc::clone(&self.ctx)) => {
info!("VPN state watch task completed");
@@ -378,6 +390,9 @@ impl WsServer {
info!("WS server cancelled");
}
}
self.cancel_token.cancel();
#[cfg(windows)]
let _ = patch_task.await;
self.ctx.hip_previews.shutdown().await;
let _ = shutdown_tx.send(()).await;
}