| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Process services that an engine incarnation can observe. |
| 4 | //! |
| 5 | //! Production installs one service set. A deterministic domain installs one |
| 6 | //! set per simulated node, so co-hosted incarnations do not share counters or |
| 7 | //! host measurements. |
| 8 | |
| 9 | use crate::ownership_store::LiveLoad; |
| 10 | use std::sync::{Arc, Mutex, OnceLock}; |
| 11 | |
| 12 | /// One resource observation used by the pressure path. |
| 13 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 14 | pub struct HostMetricsSample { |
| 15 | pub cpu_percent_x100: u64, |
| 16 | pub rss_bytes: u64, |
| 17 | pub in_use_bytes: u64, |
| 18 | pub cgroup_working_set_bytes: Option<u64>, |
| 19 | pub cgroup_current_bytes: Option<u64>, |
| 20 | } |
| 21 | |
| 22 | enum MetricsBackend { |
| 23 | Production(Mutex<ProcessLoadSampler>), |
| 24 | #[cfg(celld_internal_tests)] |
| 25 | Scripted(Mutex<HostMetricsSample>), |
| 26 | } |
| 27 | |
| 28 | /// All process-like services owned by one execution domain. |
| 29 | pub struct HostServices { |
| 30 | domain: OnceLock<crate::asyncrt::DomainToken>, |
| 31 | node_load: OnceLock<Arc<LiveLoad>>, |
| 32 | wake_entry: crate::js::WakeEntryService, |
| 33 | websockets: crate::js::WebSocketService, |
| 34 | http_streams: Arc<crate::js::HttpStreamService>, |
| 35 | metrics: MetricsBackend, |
| 36 | #[cfg(all(test, celld_internal_tests))] |
| 37 | handoff_transport: Mutex<Option<Arc<dyn crate::actor::HandoffTransportForTest>>>, |
| 38 | } |
| 39 | |
| 40 | impl HostServices { |
| 41 | pub(crate) fn production() -> Self { |
| 42 | Self { |
| 43 | domain: OnceLock::new(), |
| 44 | node_load: OnceLock::new(), |
| 45 | wake_entry: crate::js::WakeEntryService::default(), |
| 46 | websockets: crate::js::WebSocketService::default(), |
| 47 | http_streams: Arc::new(crate::js::HttpStreamService::default()), |
| 48 | metrics: MetricsBackend::Production(Mutex::new(ProcessLoadSampler::default())), |
| 49 | #[cfg(all(test, celld_internal_tests))] |
| 50 | handoff_transport: Mutex::new(None), |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | #[cfg(celld_internal_tests)] |
| 55 | pub fn scripted() -> Self { |
| 56 | Self { |
| 57 | domain: OnceLock::new(), |
| 58 | node_load: OnceLock::new(), |
| 59 | wake_entry: crate::js::WakeEntryService::default(), |
| 60 | websockets: crate::js::WebSocketService::default(), |
| 61 | http_streams: Arc::new(crate::js::HttpStreamService::default()), |
| 62 | metrics: MetricsBackend::Scripted(Mutex::new(HostMetricsSample::default())), |
| 63 | #[cfg(all(test, celld_internal_tests))] |
| 64 | handoff_transport: Mutex::new(None), |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | pub fn set_node_load(&self, load: Arc<LiveLoad>) { |
| 69 | let _ = self.node_load.set(load); |
| 70 | } |
| 71 | |
| 72 | #[cfg(all(test, celld_internal_tests))] |
| 73 | pub(crate) fn set_handoff_transport_for_test( |
| 74 | &self, |
| 75 | transport: Arc<dyn crate::actor::HandoffTransportForTest>, |
| 76 | ) { |
| 77 | let mut slot = self.handoff_transport.lock().unwrap(); |
| 78 | assert!(slot.is_none(), "the handoff transport is already installed"); |
| 79 | *slot = Some(transport); |
| 80 | } |
| 81 | |
| 82 | #[cfg(all(test, celld_internal_tests))] |
| 83 | pub(crate) fn handoff_transport_for_test( |
| 84 | &self, |
| 85 | ) -> Option<Arc<dyn crate::actor::HandoffTransportForTest>> { |
| 86 | self.handoff_transport.lock().unwrap().clone() |
| 87 | } |
| 88 | |
| 89 | pub(crate) fn bind_domain(&self, domain: crate::asyncrt::DomainToken) { |
| 90 | if let Err(candidate) = self.domain.set(domain) { |
| 91 | assert!( |
| 92 | self.domain |
| 93 | .get() |
| 94 | .is_some_and(|bound| bound.same_owner(&candidate)), |
| 95 | "HostServices cannot belong to more than one execution domain" |
| 96 | ); |
| 97 | } |
| 98 | self.http_streams.bind_domain( |
| 99 | self.domain |
| 100 | .get() |
| 101 | .expect("a HostServices domain was just installed") |
| 102 | .clone(), |
| 103 | ); |
| 104 | } |
| 105 | |
| 106 | pub(crate) fn domain_token(&self) -> Option<crate::asyncrt::DomainToken> { |
| 107 | self.domain.get().cloned() |
| 108 | } |
| 109 | |
| 110 | pub fn node_load(&self) -> Option<Arc<LiveLoad>> { |
| 111 | self.node_load.get().cloned() |
| 112 | } |
| 113 | |
| 114 | pub(crate) fn wake_entry(&self) -> &crate::js::WakeEntryService { |
| 115 | &self.wake_entry |
| 116 | } |
| 117 | |
| 118 | pub(crate) fn websockets(&self) -> &crate::js::WebSocketService { |
| 119 | &self.websockets |
| 120 | } |
| 121 | |
| 122 | pub(crate) fn http_streams(&self) -> Arc<crate::js::HttpStreamService> { |
| 123 | if let Some(domain) = self.domain_token() { |
| 124 | self.http_streams.bind_domain(domain); |
| 125 | } |
| 126 | self.http_streams.clone() |
| 127 | } |
| 128 | |
| 129 | #[cfg(all(test, celld_internal_tests))] |
| 130 | pub(crate) fn quarantine_http_streams(&self) { |
| 131 | self.http_streams.quarantine(); |
| 132 | } |
| 133 | |
| 134 | #[cfg(all(test, celld_internal_tests))] |
| 135 | pub(crate) fn close_http_streams(&self) { |
| 136 | self.http_streams.close(); |
| 137 | } |
| 138 | |
| 139 | pub fn sample_metrics(&self) -> HostMetricsSample { |
| 140 | match &self.metrics { |
| 141 | MetricsBackend::Production(sampler) => { |
| 142 | let mut sampler = sampler.lock().unwrap(); |
| 143 | let memory = crate::memory::sample(); |
| 144 | HostMetricsSample { |
| 145 | cpu_percent_x100: sampler.sample_cpu_percent_x100(), |
| 146 | rss_bytes: memory.rss_bytes, |
| 147 | in_use_bytes: memory.in_use_bytes, |
| 148 | cgroup_working_set_bytes: memory.cgroup_working_set_bytes, |
| 149 | cgroup_current_bytes: memory.cgroup_current_bytes, |
| 150 | } |
| 151 | } |
| 152 | #[cfg(celld_internal_tests)] |
| 153 | MetricsBackend::Scripted(sample) => *sample.lock().unwrap(), |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | #[cfg(celld_internal_tests)] |
| 158 | pub fn set_scripted_metrics(&self, sample: HostMetricsSample) { |
| 159 | let MetricsBackend::Scripted(current) = &self.metrics else { |
| 160 | panic!("scripted metrics require a simulation HostServices instance"); |
| 161 | }; |
| 162 | *current.lock().unwrap() = sample; |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | #[derive(Default)] |
| 167 | struct ProcessLoadSampler { |
| 168 | previous_cpu_ticks: Option<u64>, |
| 169 | previous_sample: Option<std::time::Instant>, |
| 170 | } |
| 171 | |
| 172 | impl ProcessLoadSampler { |
| 173 | // This is the production metrics arm. A simulation HostServices returns a |
| 174 | // scripted sample and never calls this host-clock sampler. |
| 175 | #[allow(clippy::disallowed_methods)] |
| 176 | fn sample_cpu_percent_x100(&mut self) -> u64 { |
| 177 | let Some(ticks) = process_cpu_ticks() else { |
| 178 | return 0; |
| 179 | }; |
| 180 | let now = std::time::Instant::now(); |
| 181 | let value = match (self.previous_cpu_ticks, self.previous_sample) { |
| 182 | (Some(previous_ticks), Some(previous_sample)) => { |
| 183 | let elapsed = previous_sample.elapsed().as_secs_f64(); |
| 184 | let ticks_per_second = clock_ticks_per_second() as f64; |
| 185 | if elapsed > 0.0 && ticks_per_second > 0.0 { |
| 186 | (((ticks.saturating_sub(previous_ticks)) as f64 / ticks_per_second / elapsed) |
| 187 | * 10_000.0) as u64 |
| 188 | } else { |
| 189 | 0 |
| 190 | } |
| 191 | } |
| 192 | _ => 0, |
| 193 | }; |
| 194 | self.previous_cpu_ticks = Some(ticks); |
| 195 | self.previous_sample = Some(now); |
| 196 | value |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | #[cfg(target_os = "linux")] |
| 201 | #[allow(clippy::disallowed_methods)] // `/proc` is host telemetry, not node storage. |
| 202 | fn process_cpu_ticks() -> Option<u64> { |
| 203 | let stat = std::fs::read_to_string("/proc/self/stat").ok()?; |
| 204 | let fields = stat |
| 205 | .get(stat.rfind(')')? + 2..)? |
| 206 | .split_whitespace() |
| 207 | .collect::<Vec<_>>(); |
| 208 | Some(fields.get(11)?.parse::<u64>().ok()? + fields.get(12)?.parse::<u64>().ok()?) |
| 209 | } |
| 210 | |
| 211 | #[cfg(not(target_os = "linux"))] |
| 212 | fn process_cpu_ticks() -> Option<u64> { |
| 213 | None |
| 214 | } |
| 215 | |
| 216 | #[cfg(unix)] |
| 217 | fn clock_ticks_per_second() -> u64 { |
| 218 | let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }; |
| 219 | u64::try_from(ticks) |
| 220 | .ok() |
| 221 | .filter(|ticks| *ticks > 0) |
| 222 | .unwrap_or(100) |
| 223 | } |
| 224 | |
| 225 | #[cfg(not(unix))] |
| 226 | fn clock_ticks_per_second() -> u64 { |
| 227 | 100 |
| 228 | } |