summaryrefslogtreecommitdiffstats
path: root/mqtt-tester/src/command.rs
blob: 8e36b46b7349ffdf30550592753b8d564b330c8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
//
//   This Source Code Form is subject to the terms of the Mozilla Public
//   License, v. 2.0. If a copy of the MPL was not distributed with this
//   file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

use std::sync::Arc;

use bytes::{BufMut, BytesMut};
use miette::IntoDiagnostic;
use mqtt_format::v3::packet::MPacket;
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt},
    process::{ChildStdin, ChildStdout},
};

use crate::packet_invariant::PacketInvariant;

pub struct Command {
    inner: tokio::process::Command,
}

pub trait CheckBytes: Send + Sync + 'static {
    fn check_bytes(self, bytes: &[u8]) -> bool;
}

impl<F> CheckBytes for F
where
    F: FnOnce(&[u8]) -> bool,
    F: Send,
    F: Sync,
    F: 'static,
{
    fn check_bytes(self, bytes: &[u8]) -> bool {
        (self)(bytes)
    }
}

impl Command {
    pub fn new(inner: tokio::process::Command) -> Self {
        Self { inner }
    }

    pub fn spawn(mut self) -> miette::Result<(tokio::process::Child, Input, Output)> {
        let mut client = self.inner.spawn().into_diagnostic()?;
        let to_client = client.stdin.take().unwrap();
        let stdout = client.stdout.take().unwrap();

        Ok((
            client,
            Input(to_client),
            Output {
                stdout,
                attached_invariants: vec![],
            },
        ))
    }
}

pub struct Input(ChildStdin);

impl Input {
    pub async fn send(&mut self, bytes: &[u8]) -> miette::Result<()> {
        self.0.write_all(bytes).await.into_diagnostic()
    }

    pub async fn send_packet<'m, P>(&mut self, packet: P) -> miette::Result<()>
    where
        P: Into<MPacket<'m>>,
    {
        let mut buf = vec![];
        packet
            .into()
            .write_to(std::pin::Pin::new(&mut buf))
            .await
            .into_diagnostic()?;
        self.send(&buf).await
    }
}

pub struct Output {
    stdout: ChildStdout,
    attached_invariants: Vec<Arc<dyn crate::packet_invariant::PacketInvariant>>,
}

static_assertions::assert_impl_all!(Output: Send);

impl Output {
    pub fn with_invariants<I>(&mut self, i: I)
    where
        I: Iterator<Item = Arc<dyn PacketInvariant>>,
    {
        self.attached_invariants.extend(i);
    }

    pub async fn wait_and_check(&mut self, check: impl CheckBytes) -> miette::Result<()> {
        match tokio::time::timeout(std::time::Duration::from_millis(100), async {
            let mut buffer = BytesMut::new();
            buffer.put_u16(self.stdout.read_u16().await.into_diagnostic()?);
            buffer.put_u8(self.stdout.read_u8().await.into_diagnostic()?);

            if buffer[1] & 0b1000_0000 != 0 {
                buffer.put_u8(self.stdout.read_u8().await.into_diagnostic()?);
                if buffer[2] & 0b1000_0000 != 0 {
                    buffer.put_u8(self.stdout.read_u8().await.into_diagnostic()?);
                    if buffer[3] & 0b1000_0000 != 0 {
                        buffer.put_u8(self.stdout.read_u8().await.into_diagnostic()?);
                    }
                }
            }

            let rest_len = buffer[1..].iter().enumerate().fold(0, |val, (exp, len)| {
                val + (*len as u32 & 0b0111_1111) * 128u32.pow(exp as u32)
            });

            let mut rest_buf = buffer.limit(rest_len as usize);
            self.stdout
                .read_buf(&mut rest_buf)
                .await
                .into_diagnostic()?;
            Ok::<_, miette::Error>(rest_buf.into_inner())
        })
        .await
        {
            Ok(Ok(buffer)) => {
                if !check.check_bytes(&buffer) {
                    return Err(miette::miette!("Check failed for Bytes {:?}", buffer));
                }
            }
            Ok(Err(e)) => return Err(e),
            Err(_elapsed) => return Err(miette::miette!("Did not hear from client until timeout")),
        }

        Ok(())
    }
}