This repository has been archived by the owner on Mar 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
frame.rs
221 lines (182 loc) · 6.54 KB
/
frame.rs
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
use std::io::{self, Cursor, ErrorKind, Read, Write};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use {Error, WireError};
// Frame layout
// id(u64) + len(u64) + payload([u8; len])
// req frame layout
// id(u64) + len(u64) + req_data([u8; len])
// rsp frame layout
// id(u64) + len(u64) + ty(u8) + len1(u64) + rsp_data([u8; len1])
// max frame len
const FRAME_MAX_LEN: u64 = 1024 * 1024;
/// raw frame wrapper, low level protocol
/// TODO: add check sum check
#[derive(Debug)]
pub struct Frame {
/// frame id, req and rsp has the same id
pub id: u64,
/// payload data
data: Vec<u8>,
}
impl Frame {
/// decode a frame from the reader
pub fn decode_from<R: Read>(r: &mut R) -> io::Result<Self> {
let id = r.read_u64::<BigEndian>()?;
info!("decode id = {:?}", id);
let len = r.read_u64::<BigEndian>()? + 16;
info!("decode len = {:?}", len);
if len > FRAME_MAX_LEN {
let s = format!("decode too big frame length. len={}", len);
error!("{}", s);
return Err(io::Error::new(ErrorKind::InvalidInput, s));
}
let mut data = vec![0; len as usize];
r.read_exact(&mut data[16..])?;
// blow can be skipped, we don't need them in the buffer
let mut cursor = Cursor::new(data);
cursor.write_u64::<BigEndian>(id).unwrap();
cursor.write_u64::<BigEndian>(len - 16).unwrap();
let data = cursor.into_inner();
Ok(Frame { id: id, data: data })
}
/// convert self into raw buf that can be re-send as a frame
#[allow(dead_code)]
pub fn finish(self, id: u64) -> Vec<u8> {
let mut cursor = Cursor::new(self.data);
// write from start
cursor.write_u64::<BigEndian>(id).unwrap();
info!("re-encode id = {:?}", id);
cursor.into_inner()
}
/// decode a request from the frame, this would return the req raw bufer
/// you need to deserialized from it into the real type
pub fn decode_req(&self) -> &[u8] {
// skip the frame head
&self.data[16..]
}
/// decode a response from the frame, this would return the rsp raw bufer
/// you need to deserialized from it into the real type
pub fn decode_rsp(&self) -> Result<&[u8], Error> {
use Error::*;
let mut r = Cursor::new(&self.data);
// skip the frame head
r.set_position(16);
let ty = r.read_u8()?;
// we don't need to check len here, frame is checked already
let len = r.read_u64::<BigEndian>()? as usize;
let buf = r.into_inner();
let data = &buf[25..len + 25];
// info!("decode response, ty={}, len={}", ty, len);
match ty {
0 => Ok(data),
1 => Err(ServerDeserialize(unsafe {
String::from_utf8_unchecked(data.into())
})),
2 => Err(ServerSerialize(unsafe {
String::from_utf8_unchecked(data.into())
})),
3 => Err(Status(unsafe { String::from_utf8_unchecked(data.into()) })),
_ => {
let s = format!("invalid response type. ty={}", ty);
error!("{}", s);
Err(ClientDeserialize(s))
}
}
}
}
/// req frame buffer that can be serialized into
pub struct ReqBuf(Cursor<Vec<u8>>);
impl ReqBuf {
pub fn new() -> Self {
let mut buf = Vec::with_capacity(128);
buf.resize(16, 0);
let mut cursor = Cursor::new(buf);
// leave enough space to write id and len
cursor.set_position(16);
ReqBuf(cursor)
}
/// convert self into raw buf that can be send as a frame
pub fn finish(self, id: u64) -> Vec<u8> {
let mut cursor = self.0;
let len = cursor.get_ref().len() as u64;
assert!(len <= FRAME_MAX_LEN);
// write from start
cursor.set_position(0);
cursor.write_u64::<BigEndian>(id).unwrap();
info!("encode id = {:?}", id);
// adjust the data length
cursor.write_u64::<BigEndian>(len - 16).unwrap();
info!("encode len = {:?}", len);
cursor.into_inner()
}
}
impl Write for ReqBuf {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
/// rsp frame buffer that can be serialized into
pub struct RspBuf(Cursor<Vec<u8>>);
pub const SERVER_POLL_ENCODE: u8 = 200;
impl RspBuf {
pub fn new() -> Self {
let mut buf = Vec::with_capacity(64);
// id + len + ty + len + data
buf.resize(25, 0);
let mut cursor = Cursor::new(buf);
// leave enough space to write id and len
cursor.set_position(25);
RspBuf(cursor)
}
/// convert self into raw buf that can be send as a frame
pub fn finish(self, id: u64, ret: Result<(), WireError>) -> Vec<u8> {
let mut cursor = self.0;
let dummy = Vec::new();
let (ty, len, data) = match ret {
Ok(_) => (0, cursor.get_ref().len() - 25, dummy.as_slice()),
Err(ref e) => match *e {
WireError::ServerDeserialize(ref s) => (1, s.len(), s.as_bytes()),
WireError::ServerSerialize(ref s) => (2, s.len(), s.as_bytes()),
WireError::Status(ref s) => (3, s.len(), s.as_bytes()),
WireError::Polling => (SERVER_POLL_ENCODE, 0, dummy.as_slice()),
},
};
let len = len as u64;
assert!(len < FRAME_MAX_LEN);
// write from start
cursor.set_position(0);
cursor.write_u64::<BigEndian>(id).unwrap();
info!("encode id = {:?}", id);
// adjust the data length
cursor.write_u64::<BigEndian>(len + 9).unwrap();
info!("encode len = {:?}", len);
// write the type
cursor.write_u8(ty).unwrap();
// write the len
cursor.write_u64::<BigEndian>(len).unwrap();
// write the data into the writer
match ty {
0 => {} // the normal ret already writed
SERVER_POLL_ENCODE => {
// the server need to poll the client, will be filtered out by multiplex_client
}
1 | 2 | 3 => {
cursor.get_mut().resize(len as usize + 25, 0);
cursor.write_all(data).unwrap();
}
_ => unreachable!("unkown rsp type"),
}
cursor.into_inner()
}
}
impl Write for RspBuf {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}