icedwright-probe 0.1.3

What an iced app links for icedwright: semantic annotations, typed test ids and named tasks, all pass-through unless a feature turns them on
Documentation
//! The socket threads: one accepting connections, and per connection one reading requests
//! into the app's inbox and one writing replies from its [`Outbox`].

use std::fmt;
use std::io;
use std::sync::mpsc;
use std::thread;

use icedwright_protocol::{FrameKind, RequestId, WireFrame};
use serde_json::Value;

use super::dispatch::ClientId;
use super::tasks::TaskEvent;
use super::transport::{Listener, Socket};

/// What the socket threads and the task controller hand to the app's `update`.
#[derive(Debug)]
pub enum Inbound {
    /// A client connected and passed the peer check.
    Opened {
        /// The client.
        client: ClientId,
        /// Where its replies go.
        outbox: Outbox,
    },
    /// A request.
    Call {
        /// The client.
        client: ClientId,
        /// Its id.
        id: RequestId,
        /// Its method.
        method: String,
        /// Its params.
        params: Value,
    },
    /// A frame that was not a request.
    Malformed {
        /// The client.
        client: ClientId,
        /// The request id, when it could be read.
        id: Option<RequestId>,
        /// What was wrong.
        message: String,
    },
    /// The connection closed.
    Closed {
        /// The client.
        client: ClientId,
    },
    /// A named task changed.
    Task(TaskEvent),
}

/// Sends frames to one client's writer thread.
#[derive(Clone)]
pub struct Outbox(mpsc::Sender<WireFrame>);

impl fmt::Debug for Outbox {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Outbox")
    }
}

impl Outbox {
    /// An outbox whose frames arrive on `receiver`.
    #[must_use]
    pub fn channel() -> (Self, mpsc::Receiver<WireFrame>) {
        let (sender, receiver) = mpsc::channel();
        (Self(sender), receiver)
    }

    /// Queues frames in order. Fails once the client has gone.
    #[must_use]
    pub fn send(&self, frames: Vec<WireFrame>) -> bool {
        frames.into_iter().all(|frame| self.0.send(frame).is_ok())
    }

    fn spawn(mut writer: Box<dyn Socket>) -> io::Result<Self> {
        let (outbox, frames) = Self::channel();
        thread::Builder::new()
            .name("icedwright-remote-writer".to_owned())
            .spawn(move || {
                for frame in frames {
                    if writer.write_frame(&frame).is_err() {
                        break;
                    }
                }
            })?;
        Ok(outbox)
    }
}

/// Serves one connection until it closes. A peer running as another user is closed without a
/// reply and never reaches the app.
pub fn serve(
    socket: &mut dyn Socket,
    client: ClientId,
    sink: &dyn Fn(Inbound) -> bool,
) -> io::Result<()> {
    if !socket.peer_is_same_user()? {
        return Ok(());
    }
    let outbox = Outbox::spawn(socket.try_clone()?)?;
    if !sink(Inbound::Opened { client, outbox }) {
        return Ok(());
    }
    let end = loop {
        let frame = match socket.read_frame() {
            Ok(frame) => frame,
            Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => break Ok(()),
            Err(error) => break Err(error),
        };
        if !sink(parse(client, &frame)) {
            break Ok(());
        }
    };
    sink(Inbound::Closed { client });
    end
}

fn parse(client: ClientId, frame: &WireFrame) -> Inbound {
    let malformed = |id, message: String| Inbound::Malformed {
        client,
        id,
        message,
    };
    if frame.kind != FrameKind::Json {
        return malformed(None, "the client sent a binary frame".to_owned());
    }
    let value: Value = match serde_json::from_slice(&frame.payload) {
        Ok(value) => value,
        Err(error) => return malformed(None, format!("not JSON: {error}")),
    };
    let id = value.get("id").and_then(Value::as_u64).map(RequestId);
    let Some(id) = id else {
        return malformed(None, "a request needs a numeric `id`".to_owned());
    };
    let Some(method) = value.get("method").and_then(Value::as_str) else {
        return malformed(Some(id), "a request needs a `method`".to_owned());
    };
    let params = value.get("params").cloned().unwrap_or(Value::Null);
    Inbound::Call {
        client,
        id,
        method: method.to_owned(),
        params,
    }
}

/// Accepts connections on a thread of its own, serving each on another.
pub fn spawn_acceptor(
    mut listener: Box<dyn Listener>,
    sink: impl Fn(Inbound) -> bool + Clone + Send + 'static,
) -> io::Result<()> {
    thread::Builder::new()
        .name("icedwright-remote-accept".to_owned())
        .spawn(move || {
            let mut next = 0;
            while let Ok(mut socket) = listener.accept() {
                next += 1;
                let client = ClientId(next);
                let sink = sink.clone();
                let spawned = thread::Builder::new()
                    .name("icedwright-remote-reader".to_owned())
                    .spawn(move || {
                        let _ = serve(socket.as_mut(), client, &sink);
                    });
                if spawned.is_err() {
                    break;
                }
            }
        })?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};

    use super::super::transport::MockSocket;
    use super::*;

    fn collect() -> (Arc<Mutex<Vec<Inbound>>>, impl Fn(Inbound) -> bool) {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let sink = {
            let seen = Arc::clone(&seen);
            move |inbound| seen.lock().map(|mut seen| seen.push(inbound)).is_ok()
        };
        (seen, sink)
    }

    #[test]
    fn a_peer_running_as_another_user_is_closed_without_a_reply() -> io::Result<()> {
        let mut socket = MockSocket::new();
        socket
            .expect_peer_is_same_user()
            .times(1)
            .returning(|| Ok(false));
        socket.expect_try_clone().never();
        socket.expect_read_frame().never();
        socket.expect_write_frame().never();
        let (seen, sink) = collect();
        serve(&mut socket, ClientId(1), &sink)?;
        assert!(seen.lock().map(|s| s.is_empty()).unwrap_or(false));
        Ok(())
    }

    #[test]
    fn requests_reach_the_app_and_closing_is_reported() -> io::Result<()> {
        let mut socket = MockSocket::new();
        socket.expect_peer_is_same_user().returning(|| Ok(true));
        socket.expect_try_clone().times(1).returning(|| {
            let mut writer = MockSocket::new();
            writer.expect_write_frame().returning(|_| Ok(()));
            Ok(Box::new(writer))
        });
        let mut frames = vec![
            Err(io::Error::from(io::ErrorKind::UnexpectedEof)),
            Ok(WireFrame::binary(vec![1])),
            Ok(WireFrame::json(br#"{"id":4}"#.to_vec())),
            Ok(WireFrame::json(
                br#"{"id":3,"method":"windows","params":null}"#.to_vec(),
            )),
        ];
        socket.expect_read_frame().times(4).returning(move || {
            frames
                .pop()
                .unwrap_or_else(|| Err(io::ErrorKind::Other.into()))
        });
        let (seen, sink) = collect();
        serve(&mut socket, ClientId(9), &sink)?;
        let seen = seen.lock().map_err(|_| io::Error::other("poisoned"))?;
        assert!(matches!(
            seen[0],
            Inbound::Opened {
                client: ClientId(9),
                ..
            }
        ));
        assert!(matches!(
            &seen[1],
            Inbound::Call { id: RequestId(3), method, .. } if method == "windows"
        ));
        assert!(matches!(
            seen[2],
            Inbound::Malformed {
                id: Some(RequestId(4)),
                ..
            }
        ));
        assert!(matches!(seen[3], Inbound::Malformed { id: None, .. }));
        assert!(matches!(
            seen[4],
            Inbound::Closed {
                client: ClientId(9)
            }
        ));
        assert_eq!(seen.len(), 5);
        Ok(())
    }

    #[test]
    fn a_failing_peer_check_is_an_error_and_reaches_nothing() {
        let mut socket = MockSocket::new();
        socket
            .expect_peer_is_same_user()
            .returning(|| Err(io::ErrorKind::PermissionDenied.into()));
        let (seen, sink) = collect();
        assert!(serve(&mut socket, ClientId(1), &sink).is_err());
        assert!(seen.lock().map(|s| s.is_empty()).unwrap_or(false));
    }
}