agentmux_srv_core/backend/sampler/thread.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sampler's own thread. The sampler used to be a task on srv's runtime, so
5//! when the runtime stopped running tasks (the log's `runtime-stall:` lines), the
6//! tick that measures the machine waited with everything else, and the CPU chart
7//! showed a hole exactly when the machine was busiest. On its own OS thread, with
8//! a runtime of its own that holds nothing else, the tick is only as late as the
9//! operating system is.
10
11use std::io;
12use std::sync::atomic::AtomicBool;
13use std::sync::Arc;
14use std::thread::JoinHandle;
15
16use crate::backend::mps::Broker;
17use crate::backend::sampler::panes::PaneSampler;
18use crate::backend::sysinfo::run_sysinfo_loop;
19use crate::backend::wconfig::ConfigState;
20
21/// Starts the sampling loop on a thread of its own. It runs until `stop` is set
22/// (within one interval), which only a test does.
23pub fn spawn(
24 broker: Arc<Broker>,
25 config: Arc<ConfigState>,
26 conn_name: String,
27 panes: PaneSampler,
28 stop: Arc<AtomicBool>,
29) -> io::Result<JoinHandle<()>> {
30 std::thread::Builder::new().name("sysinfo-sampler".into()).spawn(move || {
31 // Timers only: the loop reads the OS directly and publishes through the broker's own lock.
32 let rt = tokio::runtime::Builder::new_current_thread()
33 .enable_time()
34 .build()
35 .expect("the sampler's runtime");
36 rt.block_on(run_sysinfo_loop(broker, config, conn_name, panes, stop));
37 })
38}