pagesift_engine/engine/
cpu.rs1use super::*;
5
6static CPU_CAPACITY: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
7static CPU_GROUPS: std::sync::OnceLock<Vec<pagesift_flow::CpuSet>> = std::sync::OnceLock::new();
8
9pub fn set_cpu_capacity(cpus: usize) {
15 let _ = CPU_CAPACITY.set(cpus.max(1));
16}
17
18pub fn set_cpu_groups(groups: Vec<pagesift_flow::CpuSet>) {
22 let _ = CPU_GROUPS.set(groups);
23}
24
25thread_local! {
26 pub(super) static CONTENT_WORKSPACE: std::cell::RefCell<pagesift_content::ProcessWorkspace> =
29 std::cell::RefCell::new(pagesift_content::ProcessWorkspace::default());
30}
31
32pub fn pool() -> &'static pagesift_flow::Pool {
33 static POOL: std::sync::LazyLock<pagesift_flow::Pool> = std::sync::LazyLock::new(|| {
34 let n = CPU_CAPACITY
35 .get()
36 .copied()
37 .unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get()));
38 let groups = CPU_GROUPS.get().map_or(&[][..], Vec::as_slice);
39 let pin = (groups.len() > 1).then_some(
41 pagesift_policy::topology::pin_current_thread_to_set as fn(&[usize]) -> bool,
42 );
43 pagesift_flow::Pool::with_groups(n, groups, pin).expect("starting CPU workers")
44 });
45 &POOL
46}
47
48pub(super) fn install() {
50 static HOOK: std::sync::Once = std::sync::Once::new();
51 HOOK.call_once(|| {
52 pool();
53 pagesift_net::set_cpu_executor(|job| pool().spawn(job), || pool().round_trip());
54 });
55}
56
57pub(super) async fn cpu_task<T: Send + 'static>(
58 f: impl FnOnce() -> T + Send + 'static,
59) -> Result<T, ApiError> {
60 pool()
61 .run(None, f)
62 .await
63 .map_err(|e| ApiError::new(ErrorCode::Internal, e.to_string()))
64}