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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
//! Serialization for messages send over USB ("serial port").
//!
//! These messages are used for interacting with a running device:
//! getting runtime stats, executing cheats and admin commands, etc.
//!
//! Unlike in multiplayer (which is peer-to-peer), this is asymmetric communication.
//! Clients (desktop app, CLI, etc) send [`Request`]s
//! and the runtime (device or emulator) sends back [`Response`]s.
use serde::{Deserialize, Serialize};

/// Messages that clients send into the runtime.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum Request {
    /// Call the `cheat` callback with the given two arguments.
    ///
    /// It's up to the app how to handle the passed values,
    /// but the most common practice is to treat the first value as the command
    /// to execute (for exmaple, 42 for "noclip") and the second value as
    /// the command argument (for example, 0 for "disable" and 1 for "enable").
    Cheat(i32, i32),

    /// Turn on/off collection and sending of runtime stats.
    Stats(bool),
}

impl Request {
    /// Load request from bytes generated by [`Request::encode`].
    ///
    /// # Errors
    ///
    /// May return an error if the buffer does not contain valid request.
    pub fn decode(s: &[u8]) -> Result<Self, postcard::Error> {
        postcard::from_bytes(s)
    }

    /// Encode the request using the buffer.
    ///
    /// The buffer is required to avoid allocations on the crate side.
    /// Use [`Request::size`] to calculate the required buffer size.
    ///
    /// # Errors
    ///
    /// May return an error if the buffer is not big enough.
    pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b mut [u8], postcard::Error> {
        postcard::to_slice(self, buf)
    }

    /// Calculate the buffer size required to encode the request.
    #[must_use]
    #[allow(clippy::missing_panics_doc)]
    pub fn size(&self) -> usize {
        let flavor = postcard::ser_flavors::Size::default();
        postcard::serialize_with_flavor(self, flavor).unwrap()
    }
}

/// Messages that the runtime sends to connected clients.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum Response {
    /// The value returned by the `cheat` callback.
    Cheat(i32),
    /// Instructions executed by a callback.
    Fuel(Callback, Fuel),
    /// CPU time spent running code vs sleeping.
    CPU(CPU),
    /// Linear memory used by the wasm app.
    Memory(Memory),
}

impl Response {
    /// Load request from bytes generated by [`Response::encode`].
    ///
    /// # Errors
    ///
    /// May return an error if the buffer does not contain valid response.
    pub fn decode(s: &[u8]) -> Result<Self, postcard::Error> {
        postcard::from_bytes(s)
    }

    /// Encode the response using the buffer.
    ///
    /// The buffer is required to avoid allocations on the crate side.
    /// Use [`Response::size`] to calculate the required buffer size.
    ///
    /// # Errors
    ///
    /// May return an error if the buffer is not big enough.
    pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b mut [u8], postcard::Error> {
        postcard::to_slice(self, buf)
    }

    /// Calculate the buffer size required to encode the rsponse.
    #[must_use]
    #[allow(clippy::missing_panics_doc)]
    pub fn size(&self) -> usize {
        let flavor = postcard::ser_flavors::Size::default();
        postcard::serialize_with_flavor(self, flavor).unwrap()
    }
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum Callback {
    /// The `boot` wasm callback.
    Boot,
    /// The `update` wasm callback.
    Update,
    /// The `render` wasm callback.
    Render,
    /// The `render_line` wasm callback.
    RenderLine,
    /// The `cheat` wasm callback.
    Cheat,
}

/// The fuel consumed (wasm instructions executed) by a callback on the observed interval.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Fuel {
    /// The least fuel consumed by a single run.
    pub min: u32,

    /// The most fuel consumed by a single run.
    pub max: u32,

    /// The average number of instructions executed per run.
    pub mean: u32,

    /// Squared standard deviation of individual runs from the average.
    ///
    /// Lower value means more consistent CPU load. Higher values mean
    /// that some runs are fast and some runs are slow.
    ///
    /// Take square root to get stdev.
    pub var: f32,

    /// The number of runs of the given callback on the observed interval.
    pub calls: u32,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Memory {
    /// The number of linear memory pages allocated for the app.
    ///
    /// One page size is 64 KB, as defined by the WebAssembly core specification.
    pub pages: u16,

    /// The address of the last byte that isn't zero.
    ///
    /// This roughly corresponds to the actual memory used in the app,
    /// assuming that the allocator tries to use lower address values
    /// and that most of data structures in use aren't all zeroes.
    pub last_one: u32,

    /// The number of read operations.
    ///
    /// Currently unused. Reserved for future use.
    pub reads: u32,

    /// The number of write operations.
    ///
    /// Currently unused. Reserved for future use.
    pub writes: u32,

    /// The maximum memory that can be allocated.
    ///
    /// Currently unused. Reserved for future use.
    pub max: u32,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct CPU {
    /// The time taken running the app.
    ///
    /// Includes executing wasm callbacks, wasm host functions,
    /// rendering frame buffer on the screen, syncing network code, etc.
    /// Basically, everything except when the main thread is sleeping.
    ///
    /// Lower is better.
    pub busy_ns: u32,

    /// The time over expected limit taken by updates.
    ///
    /// Lower is better. If this value is not zero, the app will be lagging.
    pub lag_ns: u32,

    /// The total duration of the observed interval, in nanoseconds.
    pub total_ns: u32,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_roundtrip_request() {
        let given = Request::Cheat(3, 4);
        let mut buf = vec![0; given.size()];
        let raw = given.encode(&mut buf).unwrap();
        let actual = Request::decode(raw).unwrap();
        assert_eq!(given, actual);
    }

    #[test]
    fn test_roundtrip_response() {
        let given = Response::Cheat(13);
        let mut buf = vec![0; given.size()];
        let raw = given.encode(&mut buf).unwrap();
        let actual = Response::decode(raw).unwrap();
        assert_eq!(given, actual);
    }
}