use std::fmt;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::time::Duration;
use icedwright_protocol::{FrameKind, HEADER_LEN, WireFrame};
use icedwright_trace::Step;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Headed {
#[default]
Off,
Watch,
Step,
}
impl Headed {
pub(crate) fn parse(value: &str) -> Option<Self> {
match value {
"1" | "on" | "true" => Some(Self::Watch),
"step" => Some(Self::Step),
"0" | "off" | "false" => Some(Self::Off),
_ => None,
}
}
}
#[cfg_attr(test, mockall::automock)]
pub trait HeadedLink {
fn send(&mut self, bytes: &[u8]) -> std::io::Result<()>;
fn receive(&mut self, within: Option<Duration>) -> std::io::Result<Vec<u8>>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Stalled {
pub(crate) after: Duration,
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum Outgoing<'a> {
Hello {
test: &'a str,
step_mode: bool,
slow_mo_ms: Option<u64>,
scale: f32,
},
Paused {
next: Option<&'a str>,
},
Step {
step: &'a Step,
frame: bool,
},
Finished {
failure: Option<&'a str>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum Reply {
Continue,
Run,
Ack,
}
fn encode(message: &Outgoing<'_>, png: Option<&[u8]>) -> std::io::Result<Vec<u8>> {
let json = serde_json::to_vec(message).map_err(std::io::Error::other)?;
let mut bytes = WireFrame::json(json)
.encode()
.map_err(std::io::Error::other)?;
if let Some(png) = png {
let frame = WireFrame::binary(png.to_vec())
.encode()
.map_err(std::io::Error::other)?;
bytes.extend(frame);
}
Ok(bytes)
}
pub(crate) struct HeadedSession {
link: Option<Box<dyn HeadedLink>>,
step_mode: bool,
answer_within: Option<Duration>,
}
impl fmt::Debug for HeadedSession {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HeadedSession")
.field("connected", &self.link.is_some())
.field("step_mode", &self.step_mode)
.field("answer_within", &self.answer_within)
.finish()
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Hello<'a> {
pub(crate) test: &'a str,
pub(crate) mode: Headed,
pub(crate) slow_mo: Option<Duration>,
pub(crate) scale: f32,
pub(crate) answer_within: Option<Duration>,
}
pub(crate) fn answer_within(
window: Option<Duration>,
slow_mo: Option<Duration>,
) -> Option<Duration> {
window.map(|window| window.saturating_add(slow_mo.unwrap_or_default()))
}
impl HeadedSession {
pub(crate) fn start(link: Box<dyn HeadedLink>, hello: Hello<'_>) -> Option<Self> {
if hello.mode == Headed::Off {
return None;
}
let mut session = Self {
link: Some(link),
step_mode: hello.mode == Headed::Step,
answer_within: hello.answer_within,
};
let slow_mo_ms = hello
.slow_mo
.map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX));
session.send(
&Outgoing::Hello {
test: hello.test,
step_mode: session.step_mode,
slow_mo_ms,
scale: hello.scale,
},
None,
);
session.link.is_some().then_some(session)
}
pub(crate) fn connected(&self) -> bool {
self.link.is_some()
}
fn close(&mut self, error: &std::io::Error) {
if self.link.take().is_some() {
eprintln!("icedwright: the headed link to studio closed ({error}); running headless");
}
}
fn send(&mut self, message: &Outgoing<'_>, png: Option<&[u8]>) {
let Some(link) = self.link.as_mut() else {
return;
};
if let Err(error) = encode(message, png).and_then(|bytes| link.send(&bytes)) {
self.close(&error);
}
}
fn wait_for(
&mut self,
wanted: &[Reply],
within: Option<Duration>,
) -> std::io::Result<Option<Reply>> {
loop {
let Some(link) = self.link.as_mut() else {
return Ok(None);
};
let reply = link.receive(within).and_then(|json| {
serde_json::from_slice::<Reply>(&json).map_err(std::io::Error::other)
})?;
if wanted.contains(&reply) {
return Ok(Some(reply));
}
}
}
pub(crate) fn pause(&mut self, next: Option<&str>) -> bool {
if !self.step_mode || self.link.is_none() {
return false;
}
self.send(&Outgoing::Paused { next }, None);
match self.wait_for(&[Reply::Continue, Reply::Run], None) {
Ok(Some(Reply::Run)) => self.step_mode = false,
Ok(_) => {}
Err(error) => self.close(&error),
}
true
}
pub(crate) fn step(&mut self, step: &Step, png: Option<&[u8]>) -> Result<(), Stalled> {
let Some(link) = self.link.as_mut() else {
return Ok(());
};
let message = Outgoing::Step {
step,
frame: png.is_some(),
};
let sent = encode(&message, png).and_then(|bytes| link.send(&bytes));
let answered = sent.and_then(|()| self.wait_for(&[Reply::Ack], self.answer_within));
let Err(error) = answered else {
return Ok(());
};
if error.kind() != ErrorKind::TimedOut {
self.close(&error);
return Ok(());
}
self.link = None;
Err(Stalled {
after: self.answer_within.unwrap_or_default(),
})
}
pub(crate) fn finish(mut self, failure: Option<&str>) {
self.send(&Outgoing::Finished { failure }, None);
}
}
pub(crate) fn socket_in(runtime_dir: &Path) -> PathBuf {
runtime_dir.join("icedwright").join("studio.sock")
}
#[cfg(unix)]
struct UnixLink {
stream: std::os::unix::net::UnixStream,
}
#[cfg(unix)]
fn timed_out(error: std::io::Error) -> std::io::Error {
if error.kind() == ErrorKind::WouldBlock {
return std::io::Error::new(ErrorKind::TimedOut, error);
}
error
}
#[cfg(unix)]
impl HeadedLink for UnixLink {
fn send(&mut self, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
self.stream.write_all(bytes).map_err(timed_out)
}
fn receive(&mut self, within: Option<Duration>) -> std::io::Result<Vec<u8>> {
use std::io::Read as _;
self.stream.set_read_timeout(within)?;
let mut header = [0; HEADER_LEN];
self.stream.read_exact(&mut header).map_err(timed_out)?;
let (kind, length) = WireFrame::decode_header(header).map_err(std::io::Error::other)?;
let mut payload = vec![0; length];
self.stream.read_exact(&mut payload).map_err(timed_out)?;
if kind != FrameKind::Json {
return Err(std::io::Error::other("studio sent a binary frame"));
}
Ok(payload)
}
}
pub(crate) fn connect(path: &Path, send_within: Option<Duration>) -> Option<Box<dyn HeadedLink>> {
#[cfg(unix)]
{
let connected = std::os::unix::net::UnixStream::connect(path).and_then(|stream| {
stream.set_write_timeout(send_within)?;
Ok(stream)
});
match connected {
Ok(stream) => Some(Box::new(UnixLink { stream })),
Err(error) => {
eprintln!(
"icedwright: headed mode found no studio on {} ({error}); start `icedwright-studio headed` first. Running headless",
path.display()
);
None
}
}
}
#[cfg(not(unix))]
{
let _ = send_within;
eprintln!(
"icedwright: headed mode needs a Unix socket, which {} is not on this platform; running headless",
path.display()
);
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use icedwright_trace::{
RealSpan, SourceLocation, StepKind, StepOutcome, TraceConfig, TraceMeta, TraceStart,
TraceWriter,
};
use icedwright_types::{ScaleFactor, VirtualDuration};
use mockall::Sequence;
fn json(reply: &str) -> std::io::Result<Vec<u8>> {
Ok(format!("{{\"type\":\"{reply}\"}}").into_bytes())
}
fn step() -> Step {
let meta = TraceMeta {
test: "t".to_owned(),
crate_name: "c".to_owned(),
iced_version: "0.14".to_owned(),
windows: Vec::new(),
theme: None,
scale_factor: ScaleFactor::ONE,
failure: None,
};
let start = TraceStart {
boot: None,
tree: String::new(),
frame: None,
};
let mut writer = TraceWriter::new(meta, &TraceConfig::new(), start);
let location = SourceLocation {
file: "tests/ui.rs".to_owned(),
line: 3,
column: 5,
};
let kind = StepKind::Advance {
by: VirtualDuration::from_secs(1),
};
let _ = writer
.begin_step(kind, location, VirtualDuration::ZERO)
.end(
StepOutcome::Passed,
VirtualDuration::from_secs(1),
RealSpan {
start: Duration::ZERO,
end: Duration::ZERO,
},
);
writer.last_step().cloned().unwrap()
}
fn hello(mode: Headed) -> Hello<'static> {
Hello {
test: "ui::adds",
mode,
slow_mo: Some(Duration::from_millis(250)),
scale: 1.0,
answer_within: Some(BOUND),
}
}
const BOUND: Duration = Duration::from_secs(120);
fn messages(bytes: &[u8]) -> Vec<serde_json::Value> {
let mut rest = bytes;
let mut out = Vec::new();
while let Some((frame, used)) = WireFrame::decode(rest).unwrap() {
if frame.kind == FrameKind::Json {
out.push(serde_json::from_slice(&frame.payload).unwrap());
}
rest = rest.get(used..).unwrap();
}
out
}
#[test]
fn hello_carries_step_mode_and_slow_motion() {
let mut link = MockHeadedLink::new();
link.expect_send()
.withf(|bytes| {
let sent = messages(bytes);
sent.len() == 1
&& sent[0]["type"] == "hello"
&& sent[0]["test"] == "ui::adds"
&& sent[0]["step_mode"] == true
&& sent[0]["slow_mo_ms"] == 250
})
.times(1)
.returning(|_| Ok(()));
let session = HeadedSession::start(Box::new(link), hello(Headed::Step));
assert!(session.is_some_and(|s| s.connected()));
}
#[test]
fn off_never_touches_the_link() {
let link = MockHeadedLink::new();
assert!(HeadedSession::start(Box::new(link), hello(Headed::Off)).is_none());
}
#[test]
fn step_mode_waits_for_continue_and_run_ends_the_pauses() {
let mut link = MockHeadedLink::new();
let mut order = Sequence::new();
link.expect_send()
.times(1)
.in_sequence(&mut order)
.returning(|_| Ok(()));
link.expect_send()
.withf(|bytes| messages(bytes)[0]["type"] == "paused")
.times(1)
.in_sequence(&mut order)
.returning(|_| Ok(()));
link.expect_receive()
.withf(Option::is_none)
.times(1)
.in_sequence(&mut order)
.returning(|_| json("ack"));
link.expect_receive()
.withf(Option::is_none)
.times(1)
.in_sequence(&mut order)
.returning(|_| json("continue"));
link.expect_send()
.withf(|bytes| messages(bytes)[0]["type"] == "paused")
.times(1)
.in_sequence(&mut order)
.returning(|_| Ok(()));
link.expect_receive()
.withf(Option::is_none)
.times(1)
.in_sequence(&mut order)
.returning(|_| json("run"));
let mut session = HeadedSession::start(Box::new(link), hello(Headed::Step)).unwrap();
assert!(
session.pause(Some("tests/ui.rs:3")),
"the first pause waits"
);
assert!(session.pause(None), "the second pause waits for run");
assert!(!session.pause(None), "after run nothing pauses");
}
#[test]
fn watch_mode_never_pauses() {
let mut link = MockHeadedLink::new();
link.expect_send().times(1).returning(|_| Ok(()));
let mut session = HeadedSession::start(Box::new(link), hello(Headed::Watch)).unwrap();
assert!(!session.pause(None));
}
#[test]
fn a_step_and_its_frame_wait_for_the_acknowledgement() {
let step = step();
let mut link = MockHeadedLink::new();
let mut order = Sequence::new();
link.expect_send()
.times(1)
.in_sequence(&mut order)
.returning(|_| Ok(()));
link.expect_send()
.withf(|bytes| {
let mut kinds = Vec::new();
let mut rest = bytes;
while let Some((frame, used)) = WireFrame::decode(rest).unwrap() {
kinds.push((frame.kind, frame.payload));
rest = rest.get(used..).unwrap();
}
let [(FrameKind::Json, json), (FrameKind::Binary, png)] = kinds.as_slice() else {
return false;
};
let message: serde_json::Value = serde_json::from_slice(json).unwrap();
message["type"] == "step" && message["frame"] == true && png == b"png"
})
.times(1)
.in_sequence(&mut order)
.returning(|_| Ok(()));
link.expect_receive()
.withf(|within| *within == Some(BOUND))
.times(1)
.in_sequence(&mut order)
.returning(|_| json("ack"));
let mut session = HeadedSession::start(Box::new(link), hello(Headed::Watch)).unwrap();
assert_eq!(session.step(&step, Some(b"png")), Ok(()));
assert!(session.connected());
}
#[test]
fn studio_that_never_acknowledges_a_step_fails_it_instead_of_blocking() {
let step = step();
let mut link = MockHeadedLink::new();
link.expect_send().times(2).returning(|_| Ok(()));
link.expect_receive()
.withf(|within| *within == Some(BOUND))
.times(1)
.returning(|_| Err(std::io::Error::from(ErrorKind::TimedOut)));
let mut session = HeadedSession::start(Box::new(link), hello(Headed::Watch)).unwrap();
assert_eq!(
session.step(&step, None),
Err(Stalled { after: BOUND }),
"a stalled studio fails the step"
);
assert!(!session.connected(), "and nothing waits on it again");
assert_eq!(session.step(&step, None), Ok(()));
}
#[test]
fn studio_that_cannot_take_a_step_fails_it_instead_of_blocking() {
let step = step();
let mut link = MockHeadedLink::new();
let mut order = Sequence::new();
link.expect_send()
.times(1)
.in_sequence(&mut order)
.returning(|_| Ok(()));
link.expect_send()
.times(1)
.in_sequence(&mut order)
.returning(|_| Err(std::io::Error::from(ErrorKind::TimedOut)));
let mut session = HeadedSession::start(Box::new(link), hello(Headed::Watch)).unwrap();
assert_eq!(session.step(&step, None), Err(Stalled { after: BOUND }));
assert!(!session.connected());
}
#[test]
fn the_bound_is_the_hang_window_plus_the_slow_motion_hold() {
let window = Some(Duration::from_secs(120));
assert_eq!(
answer_within(window, Some(Duration::from_millis(250))),
Some(Duration::from_millis(120_250))
);
assert_eq!(answer_within(window, None), window);
assert_eq!(answer_within(None, Some(Duration::from_secs(1))), None);
}
#[test]
fn a_closed_link_falls_back_to_headless() {
let step = step();
let mut link = MockHeadedLink::new();
link.expect_send().times(1).returning(|_| Ok(()));
link.expect_send()
.times(1)
.returning(|_| Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe)));
let mut session = HeadedSession::start(Box::new(link), hello(Headed::Step)).unwrap();
assert_eq!(
session.step(&step, None),
Ok(()),
"studio going away is not a failure"
);
assert!(!session.connected());
assert!(!session.pause(None), "a closed link never pauses");
assert_eq!(session.step(&step, None), Ok(()));
session.finish(None);
}
#[test]
fn a_failed_greeting_runs_headless() {
let mut link = MockHeadedLink::new();
link.expect_send()
.returning(|_| Err(std::io::Error::from(std::io::ErrorKind::ConnectionRefused)));
assert!(HeadedSession::start(Box::new(link), hello(Headed::Watch)).is_none());
}
#[test]
fn studio_going_away_while_paused_carries_on() {
let mut link = MockHeadedLink::new();
link.expect_send().returning(|_| Ok(()));
link.expect_receive()
.times(1)
.returning(|_| Err(std::io::Error::from(std::io::ErrorKind::UnexpectedEof)));
let mut session = HeadedSession::start(Box::new(link), hello(Headed::Step)).unwrap();
assert!(session.pause(None));
assert!(!session.connected());
}
#[test]
fn the_environment_names_three_modes() {
assert_eq!(Headed::parse("1"), Some(Headed::Watch));
assert_eq!(Headed::parse("step"), Some(Headed::Step));
assert_eq!(Headed::parse("off"), Some(Headed::Off));
assert_eq!(Headed::parse("sometimes"), None);
}
#[test]
fn the_socket_lives_under_the_runtime_directory() {
assert_eq!(
socket_in(Path::new("/run/user/1000")),
PathBuf::from("/run/user/1000/icedwright/studio.sock")
);
}
}