Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

chore(curl): add opt-in WebSocket owner diagnostics

ldm0d9ce1e216ba2
diff --git a/Cargo.lock b/Cargo.lock
index fdaa7cb9c..cd6c416b6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2475,6 +2475,7 @@ dependencies = [
"tokio",
"tokio-tungstenite",
"tracing",
+ "tracing-subscriber",
"url",
]
diff --git a/moli-curl/Cargo.toml b/moli-curl/Cargo.toml
index 594742f27..4bed4413c 100644
--- a/moli-curl/Cargo.toml
+++ b/moli-curl/Cargo.toml
@@ -20,6 +20,7 @@ rcgen = { version = "0.13", default-features = false, features = ["aws_lc_rs", "
rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs", "std", "tls12"] }
tokio = { version = "1.51.0", features = ["macros", "rt", "time"] }
tokio-tungstenite = { version = "0.28.0", default-features = false, features = ["handshake"] }
+tracing-subscriber = { version = "0.3.19", features = ["fmt"] }
[lints]
workspace = true
diff --git a/moli-curl/README.md b/moli-curl/README.md
new file mode 100644
index 000000000..e51f4222a
--- /dev/null
+++ b/moli-curl/README.md
@@ -0,0 +1,79 @@
+# Native WebSocket owner diagnostics
+
+`moli-curl` owns native connections and frame I/O. Browser message assembly,
+UTF-8 checks, command admission and the close handshake live in `moli-websocket`.
+The native owner keeps reads and writes independent and parks I/O after AGAIN
+until the corresponding socket is signalled. It shares one spare receive Vec;
+successful reads transfer that Vec to the event consumer.
+
+## Enable counters
+
+Set `MOLI_CURL_WEBSOCKET_DIAGNOSTICS=1` before creating the runtime and enable
+INFO logging for the `moli_curl_websocket` tracing target. The owner emits an
+aggregate about once per second and a final partial window when it exits.
+Diagnostics are disabled by default; disabled diagnostics do not request
+per-turn or per-poll timestamps. Counters are maintained on the owner thread.
+
+| Fields | Meaning |
+| --- | --- |
+| `owner_thread` | Identifies the owner when more than one runtime emits reports |
+| `turns`, `progressed_turns` | Owner rounds and rounds with native WebSocket I/O progress |
+| `sessions` | Attached sessions, including opening handshakes |
+| `read_bytes`, `written_bytes` | Payload bytes returned by receive / consumed by native send |
+| `read_frames`, `written_frames` | Completed native frames; a fragmented browser message has multiple frames |
+| `read_again`, `write_again` | Native operations that returned AGAIN |
+| `receive_allocations` | Allocations of the owner's receive buffer |
+| `polls`, `zero_timeout_polls` | All poll calls and calls explicitly requested with zero timeout |
+| `requested_wait_ns`, `actual_wait_ns`, `max_wait_ns` | Sum of requested waits, sum of actual poll durations, maximum actual duration |
+| `fast_no_io_polls`, `max_fast_no_io_streak` | Positive-timeout polls returning in less than 100 microseconds after a round without WebSocket I/O progress; total and longest consecutive streak |
+
+Zero-timeout polls are expected while draining buffered work. A long sequence
+of fast positive-timeout polls together with AGAIN and no byte/frame progress
+is useful evidence for investigating a busy loop. Command and handshake
+wakeups can also return early, so this counter is a diagnostic hint rather
+than an automatic failure condition. Streaks carry over between log windows.
+Actual poll duration includes time executing the poll call and time descheduled;
+it is not a measurement of sleeping time alone. Compare it with owner CPU time.
+
+Logs contain aggregate counts, with no URLs, request headers or payloads.
+The current binding does not expose a TLS operation's actual cross-direction
+wait. Ordinary WSS/backpressure coverage does not prove that all TLS wait
+directions have been exercised.
+
+## Local workload
+
+Build the standalone probe once:
+
+```sh
+cargo build --release -p moli-curl --example websocket_owner_probe
+```
+
+Run individual workloads using the same duration:
+
+```sh
+target/release/examples/websocket_owner_probe --scenario idle --idle 128 --seconds 3
+target/release/examples/websocket_owner_probe --scenario active --idle 1 --seconds 3
+target/release/examples/websocket_owner_probe --scenario active --idle 32 --seconds 3
+target/release/examples/websocket_owner_probe --scenario active --idle 128 --seconds 3
+target/release/examples/websocket_owner_probe --scenario slow-read --idle 0 --seconds 3
+target/release/examples/websocket_owner_probe --scenario wss --idle 0 --seconds 3
+MOLI_CURL_WEBSOCKET_DIAGNOSTICS=1 target/release/examples/websocket_owner_probe --scenario active --idle 128 --seconds 3
+```
+
+`--idle` counts quiet connections; active scenarios add one connection. The
+total must be between 1 and 255. The peer and owner run in separate threads
+inside the probe. `slow-read` spaces peer reads by 2 ms to create send
+backpressure. `wss` pauses native reading for 100 ms during the measured window,
+then resumes it; its generated certificate is used only for the local fixture.
+
+The probe validates payload content and reports elapsed time, transferred
+payload bytes, MiB/s and owner-thread CPU time. On Linux, CPU time comes from
+the owner's `/proc/self/task/*/schedstat`; on other platforms it is unavailable.
+It excludes a fixed warmup and connection teardown. Native send completion
+counts local consumption, not acknowledgement by the peer.
+
+For comparisons, alternate binaries/configurations under the same conditions
+and record several runs. Avoid concurrent builds or test suites while measuring.
+CPU/throughput measurements are observations, not CI pass thresholds. Deterministic
+CI regressions cover idle receive attempts, buffer allocation counts, retained
+Chunk contents, WSS recovery, peer EOF and send progress under backpressure.
diff --git a/moli-curl/examples/websocket_owner_probe.rs b/moli-curl/examples/websocket_owner_probe.rs
new file mode 100644
index 000000000..081181730
--- /dev/null
+++ b/moli-curl/examples/websocket_owner_probe.rs
@@ -0,0 +1,260 @@
+//! Local, repeatable owner workload. See moli-curl/README.md for commands.
+use anyhow::{Context, Result, bail};
+use moli_curl::websocket::{
+ CurlWebSocketConnection, CurlWebSocketEvent, CurlWebSocketRequest, CurlWebSocketRuntime,
+ CurlWebSocketSend, MAX_SEND_FRAME_BYTES, WsFlags,
+};
+use std::{
+ io::{Read, Write},
+ net::TcpListener,
+ sync::Arc,
+ thread,
+ time::{Duration, Instant},
+};
+use tokio_tungstenite::tungstenite::{self, Message};
+
+struct Options {
+ scenario: String,
+ idle: usize,
+ duration: Duration,
+}
+
+fn options() -> Result<Options> {
+ let mut options = Options {
+ scenario: "active".into(),
+ idle: 32,
+ duration: Duration::from_secs(3),
+ };
+ let mut args = std::env::args().skip(1);
+ while let Some(arg) = args.next() {
+ let value = args
+ .next()
+ .context("expected a value after --scenario, --idle or --seconds")?;
+ match arg.as_str() {
+ "--scenario" => options.scenario = value,
+ "--idle" => options.idle = value.parse()?,
+ "--seconds" => options.duration = Duration::try_from_secs_f64(value.parse()?)?,
+ _ => bail!("unknown option: {arg}"),
+ }
+ }
+ if !matches!(
+ options.scenario.as_str(),
+ "idle" | "active" | "slow-read" | "wss"
+ ) {
+ bail!("scenario must be idle, active, slow-read or wss");
+ }
+ let count = options
+ .idle
+ .checked_add(usize::from(options.scenario != "idle"))
+ .context("too many connections")?;
+ if !(1..=255).contains(&count) || options.duration.is_zero() {
+ bail!("use 1..255 total connections and a positive duration");
+ }
+ Ok(options)
+}
+
+fn serve<S: Read + Write>(stream: S, scenario: &str) -> Result<()> {
+ let mut socket = tungstenite::accept(stream)
+ .map_err(|error| anyhow::anyhow!("server handshake: {error}"))?;
+ if matches!(scenario, "active" | "wss") {
+ let message = Message::Binary(vec![7; MAX_SEND_FRAME_BYTES].into());
+ while socket.send(message.clone()).is_ok() {}
+ } else {
+ loop {
+ if scenario == "slow-read" {
+ // This delay defines the benchmark peer's receive rate.
+ thread::sleep(Duration::from_millis(2));
+ }
+ match socket.read() {
+ Ok(Message::Binary(data)) => {
+ if data.len() != MAX_SEND_FRAME_BYTES || data.iter().any(|byte| *byte != 7) {
+ bail!("unexpected outgoing payload");
+ }
+ }
+ Ok(Message::Close(_)) | Err(_) => break,
+ Ok(_) => {}
+ }
+ }
+ }
+ Ok(())
+}
+
+fn peer(
+ scenario: String,
+ tls: Option<Arc<rustls::ServerConfig>>,
+) -> Result<(String, thread::JoinHandle<Result<()>>)> {
+ let listener = TcpListener::bind("127.0.0.1:0")?;
+ let scheme = if tls.is_some() { "wss" } else { "ws" };
+ let url = format!("{scheme}://{}/probe", listener.local_addr()?);
+ let task = thread::spawn(move || {
+ let (stream, _) = listener.accept()?;
+ stream.set_write_timeout(Some(Duration::from_secs(10)))?;
+ if let Some(tls) = tls {
+ serve(
+ rustls::StreamOwned::new(rustls::ServerConnection::new(tls)?, stream),
+ &scenario,
+ )
+ } else {
+ serve(stream, &scenario)
+ }
+ });
+ Ok((url, task))
+}
+
+fn tls_config() -> Result<Arc<rustls::ServerConfig>> {
+ use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
+ let certificate = rcgen::generate_simple_self_signed(vec!["localhost".into()])?;
+ Ok(Arc::new(
+ rustls::ServerConfig::builder()
+ .with_no_client_auth()
+ .with_single_cert(
+ vec![CertificateDer::from(certificate.cert.der().to_vec())],
+ PrivateKeyDer::from(PrivatePkcs8KeyDer::from(
+ certificate.key_pair.serialize_der(),
+ )),
+ )?,
+ ))
+}
+
+// Linux exposes scheduled CPU nanoseconds per thread. Other platforms still
+// report workload throughput; no process-wide CPU is substituted for the owner.
+fn owner_cpu_ns() -> Option<u64> {
+ for task in std::fs::read_dir("/proc/self/task").ok()? {
+ let path = task.ok()?.path();
+ if std::fs::read_to_string(path.join("comm"))
+ .ok()?
+ .starts_with("moli-curl-web")
+ {
+ return std::fs::read_to_string(path.join("schedstat"))
+ .ok()?
+ .split_whitespace()
+ .next()?
+ .parse()
+ .ok();
+ }
+ }
+ None
+}
+
+async fn incoming(
+ connection: &mut CurlWebSocketConnection,
+ end: tokio::time::Instant,
+) -> Result<u64> {
+ let mut bytes = 0;
+ while tokio::time::Instant::now() < end {
+ let Ok(event) = tokio::time::timeout_at(end, connection.recv()).await else {
+ break;
+ };
+ match event {
+ Some(CurlWebSocketEvent::Chunk { data, .. }) => {
+ if data.iter().any(|byte| *byte != 7) {
+ bail!("unexpected incoming payload");
+ }
+ bytes += data.len() as u64;
+ }
+ unexpected => bail!("connection ended during probe: {unexpected:?}"),
+ }
+ }
+ Ok(bytes)
+}
+
+#[tokio::main(flavor = "current_thread")]
+async fn main() -> Result<()> {
+ let options = options()?;
+ tracing_subscriber::fmt()
+ .with_max_level(tracing::Level::INFO)
+ .with_ansi(false)
+ .with_writer(std::io::stderr)
+ .init();
+ let runtime = CurlWebSocketRuntime::new()?;
+ let tls = (options.scenario == "wss").then(tls_config).transpose()?;
+ let mut peers = Vec::new();
+ let mut connections = Vec::new();
+ let active = options.scenario != "idle";
+ for index in 0..options.idle + usize::from(active) {
+ let scenario = if index < options.idle {
+ "idle"
+ } else {
+ &options.scenario
+ };
+ let (url, task) = peer(scenario.into(), tls.clone())?;
+ peers.push(task);
+ let mut request = CurlWebSocketRequest::new(url);
+ // The WSS fixture owns this locally generated certificate.
+ request.tls.verify = tls.is_none();
+ let mut connection = runtime.connect(request)?;
+ match tokio::time::timeout(Duration::from_secs(10), connection.recv()).await? {
+ Some(CurlWebSocketEvent::Handshake { result, .. }) => {
+ result.map_err(anyhow::Error::msg)?
+ }
+ unexpected => bail!("expected handshake, got {unexpected:?}"),
+ }
+ connection.sender().set_reading(true);
+ connections.push(connection);
+ }
+ // A fixed warmup is part of the workload, not a correctness assertion.
+ if active && matches!(options.scenario.as_str(), "active" | "wss") {
+ incoming(
+ connections.last_mut().unwrap(),
+ tokio::time::Instant::now() + Duration::from_millis(200),
+ )
+ .await?;
+ } else {
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ let cpu_before = owner_cpu_ns();
+ let started = Instant::now();
+ let end = tokio::time::Instant::now() + options.duration;
+ let bytes = match options.scenario.as_str() {
+ "idle" => {
+ tokio::time::sleep_until(end).await;
+ 0
+ }
+ "slow-read" => {
+ let sender = connections.last().unwrap().sender();
+ let mut bytes = 0;
+ while tokio::time::Instant::now() < end {
+ let frame = CurlWebSocketSend {
+ flags: WsFlags::BINARY,
+ data: vec![7; MAX_SEND_FRAME_BYTES],
+ };
+ match tokio::time::timeout_at(end, sender.send_frame(frame)).await {
+ Ok(result) => bytes += result? as u64,
+ Err(_) => break,
+ }
+ }
+ bytes
+ }
+ _ => {
+ let connection = connections.last_mut().unwrap();
+ if options.scenario == "wss" {
+ connection.sender().set_reading(false);
+ tokio::time::sleep_until(
+ end.min(tokio::time::Instant::now() + Duration::from_millis(100)),
+ )
+ .await;
+ connection.sender().set_reading(true);
+ }
+ incoming(connection, end).await?
+ }
+ };
+ let elapsed = started.elapsed();
+ let cpu_ms = cpu_before
+ .zip(owner_cpu_ns())
+ .map(|(before, after)| after.saturating_sub(before) as f64 / 1_000_000.0);
+ println!(
+ "scenario={} idle={} elapsed_s={:.3} bytes={} mib_per_s={:.3} owner_cpu_ms={cpu_ms:?}",
+ options.scenario,
+ options.idle,
+ elapsed.as_secs_f64(),
+ bytes,
+ bytes as f64 / 1_048_576.0 / elapsed.as_secs_f64()
+ );
+ drop(connections);
+ drop(runtime);
+ for task in peers {
+ task.join()
+ .map_err(|_| anyhow::anyhow!("peer panicked"))??;
+ }
+ Ok(())
+}
diff --git a/moli-curl/src/websocket.rs b/moli-curl/src/websocket.rs
index f4ad2bc4d..cadb5406c 100644
--- a/moli-curl/src/websocket.rs
+++ b/moli-curl/src/websocket.rs
@@ -10,6 +10,7 @@
//! AGAIN parks that I/O until its socket is signalled. Application wakeups only
//! resume paused work, such as a new frame or restored receive capacity.
+mod diagnostics;
mod owner;
mod request;
mod scheduling;
diff --git a/moli-curl/src/websocket/diagnostics.rs b/moli-curl/src/websocket/diagnostics.rs
new file mode 100644
index 000000000..23c2dcb39
--- /dev/null
+++ b/moli-curl/src/websocket/diagnostics.rs
@@ -0,0 +1,194 @@
+//! Optional owner-thread counters. Disabled diagnostics do not read the clock
+//! per turn or per poll. Reports contain counts only, never connection contents.
+use std::time::{Duration, Instant};
+
+#[derive(Default, Debug)]
+pub(super) struct Counters {
+ pub turns: u64,
+ pub progressed_turns: u64,
+ pub read_bytes: u64,
+ pub written_bytes: u64,
+ pub read_frames: u64,
+ pub written_frames: u64,
+ pub read_again: u64,
+ pub write_again: u64,
+ pub receive_allocations: u64,
+ pub polls: u64,
+ pub zero_timeout_polls: u64,
+ pub requested_wait_ns: u128,
+ pub actual_wait_ns: u128,
+ pub max_wait_ns: u128,
+ pub fast_no_io_polls: u64,
+ fast_no_io_streak: u64,
+ pub max_fast_no_io_streak: u64,
+}
+
+impl Counters {
+ fn polled(&mut self, requested: Duration, actual: Duration, progressed: bool) {
+ self.polls += 1;
+ self.zero_timeout_polls += u64::from(requested.is_zero());
+ self.requested_wait_ns += requested.as_nanos();
+ self.actual_wait_ns += actual.as_nanos();
+ self.max_wait_ns = self.max_wait_ns.max(actual.as_nanos());
+ // This is a diagnostic hint, not a spin detector: command/handshake
+ // wakeups can legitimately return early without WebSocket I/O progress.
+ if !progressed && !requested.is_zero() && actual < Duration::from_micros(100) {
+ self.fast_no_io_polls += 1;
+ self.fast_no_io_streak += 1;
+ self.max_fast_no_io_streak = self.max_fast_no_io_streak.max(self.fast_no_io_streak);
+ } else {
+ self.fast_no_io_streak = 0;
+ }
+ }
+}
+
+struct Window {
+ started: Instant,
+ counters: Counters,
+}
+
+pub(super) struct Diagnostics(Option<Window>);
+
+impl Diagnostics {
+ pub(super) fn from_env() -> Self {
+ Self::new(
+ std::env::var("MOLI_CURL_WEBSOCKET_DIAGNOSTICS").is_ok_and(|value| {
+ let value = value.trim();
+ !value.is_empty() && value != "0" && !value.eq_ignore_ascii_case("false")
+ }),
+ )
+ }
+
+ fn new(enabled: bool) -> Self {
+ Self(enabled.then(|| Window {
+ started: Instant::now(),
+ counters: Counters::default(),
+ }))
+ }
+
+ pub(super) fn counters(&mut self) -> Option<&mut Counters> {
+ self.0.as_mut().map(|window| &mut window.counters)
+ }
+
+ pub(super) fn poll_start(&self) -> Option<Instant> {
+ self.0.as_ref().map(|_| Instant::now())
+ }
+
+ pub(super) fn polled(&mut self, start: Option<Instant>, timeout: Duration, progressed: bool) {
+ if let Some(start) = start {
+ self.0
+ .as_mut()
+ .expect("enabled poll measurement")
+ .counters
+ .polled(timeout, start.elapsed(), progressed);
+ }
+ }
+
+ pub(super) fn report(&mut self, sessions: usize, finished: bool) {
+ let Some(window) = &mut self.0 else {
+ return;
+ };
+ let now = Instant::now();
+ let elapsed = now.duration_since(window.started);
+ if !finished && elapsed < Duration::from_secs(1) {
+ return;
+ }
+ let c = &window.counters;
+ tracing::info!(
+ target: "moli_curl_websocket",
+ owner_thread = ?std::thread::current().id(),
+ window_ms = elapsed.as_millis(), sessions, finished,
+ turns = c.turns, progressed_turns = c.progressed_turns,
+ read_bytes = c.read_bytes, written_bytes = c.written_bytes,
+ read_frames = c.read_frames, written_frames = c.written_frames,
+ read_again = c.read_again, write_again = c.write_again,
+ receive_allocations = c.receive_allocations,
+ polls = c.polls, zero_timeout_polls = c.zero_timeout_polls,
+ requested_wait_ns = c.requested_wait_ns, actual_wait_ns = c.actual_wait_ns,
+ max_wait_ns = c.max_wait_ns, fast_no_io_polls = c.fast_no_io_polls,
+ max_fast_no_io_streak = c.max_fast_no_io_streak,
+ "WebSocket owner work"
+ );
+ let streak = c.fast_no_io_streak;
+ window.counters = Counters {
+ fast_no_io_streak: streak,
+ max_fast_no_io_streak: streak,
+ ..Counters::default()
+ };
+ window.started = now;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn productive_zero_timeout_polls_are_distinct_from_fast_no_io_wakeups() {
+ let mut counts = Counters::default();
+ counts.polled(Duration::ZERO, Duration::ZERO, true);
+ counts.polled(Duration::ZERO, Duration::ZERO, false);
+ assert_eq!(counts.zero_timeout_polls, 2);
+ assert_eq!(counts.fast_no_io_polls, 0);
+ for _ in 0..3 {
+ counts.polled(Duration::from_secs(1), Duration::from_micros(10), false);
+ }
+ assert_eq!(counts.fast_no_io_polls, 3);
+ assert_eq!(counts.max_fast_no_io_streak, 3);
+ counts.polled(Duration::from_secs(1), Duration::from_secs(1), false);
+ counts.polled(Duration::from_secs(1), Duration::ZERO, false);
+ assert_eq!(counts.fast_no_io_streak, 1);
+ assert_eq!(counts.max_fast_no_io_streak, 3);
+ assert_eq!(counts.polls, 7);
+ assert_eq!(counts.requested_wait_ns, 5_000_000_000);
+ assert_eq!(counts.actual_wait_ns, 1_000_030_000);
+ }
+
+ #[test]
+ fn reports_reset_window_totals_but_preserve_a_consecutive_streak() {
+ use parking_lot::Mutex;
+ use std::{io::Write, sync::Arc};
+ struct Writer(Arc<Mutex<Vec<u8>>>);
+ impl Write for Writer {
+ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().extend_from_slice(bytes);
+ Ok(bytes.len())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+ let output = Arc::new(Mutex::new(Vec::new()));
+ let writer = output.clone();
+ let subscriber = tracing_subscriber::fmt()
+ .with_ansi(false)
+ .without_time()
+ .with_max_level(tracing::Level::INFO)
+ .with_writer(move || Writer(writer.clone()))
+ .finish();
+ tracing::subscriber::with_default(subscriber, || {
+ let mut diagnostics = Diagnostics::new(true);
+ let counts = diagnostics.counters().unwrap();
+ counts.turns = 4;
+ counts.read_bytes = 17;
+ for _ in 0..2 {
+ counts.polled(Duration::from_secs(1), Duration::ZERO, false);
+ }
+ diagnostics.report(3, true);
+ let counts = diagnostics.counters().unwrap();
+ assert_eq!((counts.turns, counts.read_bytes, counts.polls), (0, 0, 0));
+ counts.polled(Duration::from_secs(1), Duration::ZERO, false);
+ assert_eq!(counts.max_fast_no_io_streak, 3);
+ diagnostics.report(0, true);
+ // A disabled owner produces neither counters nor reports.
+ let mut disabled = Diagnostics::new(false);
+ assert!(disabled.poll_start().is_none());
+ disabled.report(100, true);
+ });
+ let output = String::from_utf8(output.lock().clone()).unwrap();
+ assert_eq!(output.lines().count(), 2);
+ assert!(output.contains("turns=4"));
+ assert!(output.contains("read_bytes=17"));
+ assert!(output.contains("max_fast_no_io_streak=3"));
+ }
+}
diff --git a/moli-curl/src/websocket/owner.rs b/moli-curl/src/websocket/owner.rs
index ee18175bf..569e0d219 100644
--- a/moli-curl/src/websocket/owner.rs
+++ b/moli-curl/src/websocket/owner.rs
@@ -17,6 +17,7 @@ use curl::{
use super::{
SessionIo, Submission,
+ diagnostics::Diagnostics,
request::{self, Handshake},
scheduling::SocketPoll,
session::{Session, Step},
@@ -39,6 +40,7 @@ struct Owner {
dns: CurlDnsOwnerResidence<CurlTransferId, Pending>,
poll: SocketPoll,
receive: Vec<u8>,
+ diagnostics: Diagnostics,
}
pub(super) fn run(
@@ -52,6 +54,7 @@ pub(super) fn run(
dns: CurlDnsOwnerResidence::default(),
poll: SocketPoll::default(),
receive: Vec::new(),
+ diagnostics: Diagnostics::from_env(),
};
let _ = waker_tx.send(owner.multi.waker());
while !shutdown.load(Ordering::Acquire) {
@@ -59,6 +62,10 @@ pub(super) fn run(
owner.resolve_dns();
owner.advance_handshakes();
let progressed = owner.advance_sessions();
+ if let Some(counters) = owner.diagnostics.counters() {
+ counters.turns += 1;
+ counters.progressed_turns += u64::from(progressed);
+ }
owner.wait_for_work(progressed);
}
owner.fail_sessions("curl WebSocket runtime shut down");
@@ -67,6 +74,7 @@ pub(super) fn run(
.io
.finish(Err("curl WebSocket runtime shut down".to_owned()));
}
+ owner.diagnostics.report(0, true);
}
impl Owner {
@@ -171,7 +179,7 @@ impl Owner {
let mut retired = Vec::new();
let mut progressed = false;
for (id, session) in &mut self.sessions {
- match session.advance(&mut self.receive) {
+ match session.advance(&mut self.receive, &mut self.diagnostics) {
Ok(Step::Progress) => progressed = true,
Ok(Step::Idle) => {}
terminal => retired.push((*id, terminal)),
@@ -214,9 +222,16 @@ impl Owner {
})
.unwrap_or(IDLE_WAIT)
};
- if let Err(error) = self.poll.wait(&self.multi, &mut self.sessions, timeout) {
+ if let Err(error) = self.poll.wait(
+ &self.multi,
+ &mut self.sessions,
+ timeout,
+ progressed,
+ &mut self.diagnostics,
+ ) {
self.fail_sessions(&error.to_string());
}
+ self.diagnostics.report(self.sessions.len(), false);
}
fn fail_sessions(&mut self, error: &str) {
diff --git a/moli-curl/src/websocket/scheduling.rs b/moli-curl/src/websocket/scheduling.rs
index 6a3eccaf7..9ae4f008c 100644
--- a/moli-curl/src/websocket/scheduling.rs
+++ b/moli-curl/src/websocket/scheduling.rs
@@ -6,7 +6,7 @@ use std::{collections::HashMap, time::Duration};
use curl::multi::{Multi, WaitFd};
-use super::session::Session;
+use super::{diagnostics::Diagnostics, session::Session};
use crate::CurlTransferId;
#[derive(Default, PartialEq, Eq)]
@@ -60,6 +60,8 @@ impl SocketPoll {
multi: &Multi,
sessions: &mut HashMap<CurlTransferId, Session>,
timeout: Duration,
+ progressed: bool,
+ diagnostics: &mut Diagnostics,
) -> Result<(), curl::MultiError> {
self.ids.clear();
self.fds.clear();
@@ -69,7 +71,10 @@ impl SocketPoll {
self.fds.push(fd);
}
}
- multi.poll(&mut self.fds, timeout)?;
+ let started = diagnostics.poll_start();
+ let result = multi.poll(&mut self.fds, timeout);
+ diagnostics.polled(started, timeout, progressed);
+ result?;
for (id, fd) in self.ids.iter().zip(&self.fds) {
if fd.received_read() || fd.received_write() {
// A socket event permits a retry, not guaranteed progress.
diff --git a/moli-curl/src/websocket/session.rs b/moli-curl/src/websocket/session.rs
index 28c38f43d..cc8ded67d 100644
--- a/moli-curl/src/websocket/session.rs
+++ b/moli-curl/src/websocket/session.rs
@@ -8,6 +8,7 @@ use curl::{
multi::{Easy2Handle, Multi, WaitFd},
};
+use super::diagnostics::Diagnostics;
use super::{CurlWebSocketEvent, SessionIo, WsFlags, request::Handshake, scheduling::IoState};
use crate::CurlTransferId;
@@ -113,7 +114,11 @@ impl Session {
Ok(Step::Idle)
}
- pub(super) fn advance(&mut self, receive: &mut Vec<u8>) -> Result<Step, String> {
+ pub(super) fn advance(
+ &mut self,
+ receive: &mut Vec<u8>,
+ diagnostics: &mut Diagnostics,
+ ) -> Result<Step, String> {
if self.io.cancelled() {
return Ok(Step::Closed);
}
@@ -130,8 +135,8 @@ impl Session {
return Ok(Step::Closed);
}
// Receive delivery must never hold up a pending write.
- progressed |= self.write_pending()?;
- match self.read_chunk(receive)? {
+ progressed |= self.write_pending(diagnostics)?;
+ match self.read_chunk(receive, diagnostics)? {
Step::Progress => progressed = true,
Step::Idle => break,
Step::Closed => return Ok(Step::Closed),
@@ -144,7 +149,7 @@ impl Session {
})
}
- fn write_pending(&mut self) -> Result<bool, String> {
+ fn write_pending(&mut self, diagnostics: &mut Diagnostics) -> Result<bool, String> {
// Keep the single frame resident across partial nonblocking writes.
let mut pending = self.io.control.send.lock();
if !self.writing.can_run(pending.is_some()) {
@@ -159,7 +164,12 @@ impl Session {
{
Ok(count) => {
send.offset += count;
- if send.offset == send.frame.data.len() {
+ let completed = send.offset == send.frame.data.len();
+ if let Some(counters) = diagnostics.counters() {
+ counters.written_bytes += count as u64;
+ counters.written_frames += u64::from(completed);
+ }
+ if completed {
let send = pending.take().expect("completed frame");
self.writing.pause();
let _ = send.completed.send(send.offset);
@@ -168,6 +178,9 @@ impl Session {
}
Err(error) if error.is_again() => {
self.writing.would_block();
+ if let Some(counters) = diagnostics.counters() {
+ counters.write_again += 1;
+ }
#[cfg(test)]
self.io.control.write_blocked.notify_one();
Ok(false)
@@ -180,7 +193,11 @@ impl Session {
matches!(self.phase, Phase::Open) && self.io.control.reading.load(Ordering::Acquire)
}
- fn read_chunk(&mut self, receive: &mut Vec<u8>) -> Result<Step, String> {
+ fn read_chunk(
+ &mut self,
+ receive: &mut Vec<u8>,
+ diagnostics: &mut Diagnostics,
+ ) -> Result<Step, String> {
if !self.reading.can_run(self.reading_enabled()) {
return Ok(Step::Idle);
}
@@ -196,14 +213,17 @@ impl Session {
};
// The owner lends one spare buffer across connections. AGAIN keeps it;
// success transfers ownership to the event without copying the payload.
- #[cfg(test)]
- if receive.capacity() < CHUNK_BYTES {
+ if receive.is_empty() {
+ *receive = vec![0; CHUNK_BYTES];
+ if let Some(counters) = diagnostics.counters() {
+ counters.receive_allocations += 1;
+ }
+ #[cfg(test)]
self.io
.control
.receive_allocations
.fetch_add(1, Ordering::Relaxed);
}
- receive.resize(CHUNK_BYTES, 0);
#[cfg(test)]
self.io
.control
@@ -213,6 +233,10 @@ impl Session {
Ok((count, frame)) => {
let mut data = std::mem::take(receive);
data.truncate(count);
+ if let Some(counters) = diagnostics.counters() {
+ counters.read_bytes += count as u64;
+ counters.read_frames += u64::from(frame.bytes_left() == 0);
+ }
// Let the caller answer Close before probing EOF. A peer can
// half-close TCP in the same packet as its Close frame.
if frame.flags().contains(WsFlags::CLOSE) && frame.bytes_left() == 0 {
@@ -223,6 +247,9 @@ impl Session {
}
Err(error) if error.is_again() => {
self.reading.would_block();
+ if let Some(counters) = diagnostics.counters() {
+ counters.read_again += 1;
+ }
#[cfg(test)]
self.io.control.read_waiting.notify_one();
Ok(Step::Idle)