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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
|
//! Protocol v5: bounded frames and the request/reply/event envelope.
//!
//! Every packet is `[u32 length][UTF-8 payload]`. The length is big-endian and
//! capped, so a peer cannot make the reader allocate without bound. Inside a
//! frame the payload is text:
//!
//! ```text
//! REQ <id> [idem=<token>] <command>
//! RES <id> <body>
//! EVT <seq> <body>
//! ```
//!
//! The command and body grammar is the same text protocol the games already
//! use (`HELLO`, `PLAY_START`, `GAME_RESULT`, ...). The envelope only adds
//! correlation, event numbering and a hard size limit.
use std::fmt;
use std::io::{self, Read, Write};
/// Largest payload a peer may send in one frame. A game message is a few
/// hundred bytes; 64 KiB is generous and still bounds the reader.
pub const MAX_FRAME_LEN: usize = 64 * 1024;
/// How many request ids a connection remembers for idempotent retries.
pub const REPLAY_CACHE_LEN: usize = 256;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameError {
/// The declared payload length exceeds [`MAX_FRAME_LEN`].
TooLarge(usize),
/// The payload was not valid UTF-8.
InvalidUtf8,
}
impl fmt::Display for FrameError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FrameError::TooLarge(length) => {
write!(
f,
"frame of {length} bytes exceeds the {MAX_FRAME_LEN}-byte limit"
)
}
FrameError::InvalidUtf8 => write!(f, "frame payload is not valid UTF-8"),
}
}
}
impl std::error::Error for FrameError {}
/// A bounded frame decoder. Feed it bytes from a socket, take whole frames.
#[derive(Debug, Default)]
pub struct FrameBuffer {
buffer: Vec<u8>,
}
impl FrameBuffer {
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, bytes: &[u8]) {
self.buffer.extend_from_slice(bytes);
}
/// Return the next complete frame, if the buffer holds one.
///
/// A declared length above the limit is reported immediately instead of
/// waiting for bytes that will never be accepted; the caller should close
/// the connection.
pub fn next_frame(&mut self) -> Option<Result<String, FrameError>> {
if self.buffer.len() < 4 {
return None;
}
let length = u32::from_be_bytes([
self.buffer[0],
self.buffer[1],
self.buffer[2],
self.buffer[3],
]) as usize;
if length > MAX_FRAME_LEN {
self.buffer.clear();
return Some(Err(FrameError::TooLarge(length)));
}
if self.buffer.len() < 4 + length {
return None;
}
let payload: Vec<u8> = self.buffer[4..4 + length].to_vec();
self.buffer.drain(..4 + length);
match String::from_utf8(payload) {
Ok(text) => Some(Ok(text)),
Err(_) => Some(Err(FrameError::InvalidUtf8)),
}
}
/// Read one frame from a blocking reader, preserving leftover bytes.
/// `None` means EOF with no complete frame buffered.
pub fn read_frame<R: Read>(&mut self, reader: &mut R) -> io::Result<Option<String>> {
loop {
match self.next_frame() {
Some(Ok(frame)) => return Ok(Some(frame)),
Some(Err(error)) => return Err(io::Error::new(io::ErrorKind::InvalidData, error)),
None => {}
}
let mut chunk = [0u8; 4096];
match reader.read(&mut chunk) {
Ok(0) => return Ok(None),
Ok(n) => self.push(&chunk[..n]),
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
}
}
}
/// True when a partial frame is buffered (used by tests and diagnostics).
pub fn is_empty(&self) -> bool {
self.buffer.is_empty()
}
}
/// Encode one payload as a length-prefixed frame.
pub fn encode_frame(payload: &str) -> Vec<u8> {
let length = payload.len() as u32;
let mut bytes = Vec::with_capacity(4 + payload.len());
bytes.extend_from_slice(&length.to_be_bytes());
bytes.extend_from_slice(payload.as_bytes());
bytes
}
/// Write one payload as a length-prefixed frame.
pub fn write_frame<W: Write>(writer: &mut W, payload: &str) -> io::Result<()> {
writer.write_all(&encode_frame(payload))?;
writer.flush()
}
/// One client request. `id` is the correlation key; `idem` is optional
/// metadata for logs and a future cross-connection cache.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request {
pub id: u64,
pub idem: Option<String>,
pub payload: String,
}
/// A frame received by a client.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Packet {
Reply { id: u64, body: String },
Event { seq: u64, body: String },
}
pub fn request_line(id: u64, idem: Option<&str>, payload: &str) -> String {
match idem {
Some(idem) if !idem.is_empty() => format!("REQ {id} idem={idem} {payload}"),
_ => format!("REQ {id} {payload}"),
}
}
pub fn reply_line(id: u64, body: &str) -> String {
format!("RES {id} {body}")
}
pub fn event_line(seq: u64, body: &str) -> String {
format!("EVT {seq} {body}")
}
/// Parse a `REQ` payload. Errors are safe to return to the peer.
pub fn parse_request(frame: &str) -> Result<Request, String> {
let frame = frame.trim_end();
let rest = frame
.strip_prefix("REQ ")
.ok_or_else(|| "Malformed request: expected REQ".to_string())?;
let (id_token, mut rest) = split_token(rest);
let id: u64 = id_token
.parse()
.map_err(|_| "Malformed request id".to_string())?;
let mut idem = None;
let (next, after) = split_token(rest);
if let Some(value) = next.strip_prefix("idem=") {
if value.is_empty() {
return Err("Malformed idempotency key".to_string());
}
idem = Some(value.to_string());
rest = after;
}
Ok(Request {
id,
idem,
payload: rest.to_string(),
})
}
/// Parse a `RES` or `EVT` payload on the client side.
pub fn parse_packet(frame: &str) -> Result<Packet, String> {
let frame = frame.trim_end();
if let Some(rest) = frame.strip_prefix("RES ") {
let (id_token, body) = split_token(rest);
let id: u64 = id_token
.parse()
.map_err(|_| "Malformed reply id".to_string())?;
return Ok(Packet::Reply {
id,
body: body.to_string(),
});
}
if let Some(rest) = frame.strip_prefix("EVT ") {
let (seq_token, body) = split_token(rest);
let seq: u64 = seq_token
.parse()
.map_err(|_| "Malformed event sequence".to_string())?;
return Ok(Packet::Event {
seq,
body: body.to_string(),
});
}
Err(format!("Unexpected packet: {frame}"))
}
fn split_token(rest: &str) -> (&str, &str) {
let rest = rest.trim_start();
match rest.find(' ') {
Some(index) => (&rest[..index], rest[index + 1..].trim_start()),
None => (rest, ""),
}
}
/// A stable, user-facing message for a failed request.
pub fn io_failure_message(error: &io::Error) -> &'static str {
match error.kind() {
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock => "ERROR Request timed out",
_ => "ERROR Connection lost",
}
}
|