kino 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.yardopts +5 -0
- data/CHANGELOG.md +286 -0
- data/Cargo.lock +209 -132
- data/README.md +269 -438
- data/doc/README.md +27 -2
- data/doc/architecture.md +862 -43
- data/doc/benchmarks.md +444 -214
- data/doc/configuration.md +215 -0
- data/doc/operations.md +258 -0
- data/doc/rails-on-ractors.md +161 -49
- data/doc/streaming.md +52 -0
- data/doc/websockets.md +469 -0
- data/doc/why-kino.md +6 -6
- data/doc/worker-loop.md +462 -0
- data/ext/kino/Cargo.toml +19 -3
- data/ext/kino/build.rs +32 -1
- data/ext/kino/clippy.toml +10 -0
- data/ext/kino/src/access_log.rs +70 -92
- data/ext/kino/src/control.rs +26 -685
- data/ext/kino/src/counters.rs +132 -0
- data/ext/kino/src/cpus.rs +1 -18
- data/ext/kino/src/dispatch/tests.rs +731 -0
- data/ext/kino/src/dispatch.rs +276 -0
- data/ext/kino/src/doorbell.rs +108 -0
- data/ext/kino/src/env_strings.rs +26 -30
- data/ext/kino/src/framing.rs +110 -0
- data/ext/kino/src/gvl.rs +292 -66
- data/ext/kino/src/hijack/tests.rs +416 -0
- data/ext/kino/src/hijack.rs +471 -0
- data/ext/kino/src/inline/answer.rs +488 -0
- data/ext/kino/src/inline/conn.rs +1124 -0
- data/ext/kino/src/inline/deadline.rs +421 -0
- data/ext/kino/src/inline/encode.rs +119 -0
- data/ext/kino/src/inline/io.rs +487 -0
- data/ext/kino/src/inline/mod.rs +766 -0
- data/ext/kino/src/inline/parity.rs +862 -0
- data/ext/kino/src/inline/parse.rs +131 -0
- data/ext/kino/src/inline/spin.rs +428 -0
- data/ext/kino/src/inline/testing.rs +628 -0
- data/ext/kino/src/io_shards.rs +240 -192
- data/ext/kino/src/lane_room.rs +99 -0
- data/ext/kino/src/lib.rs +139 -77
- data/ext/kino/src/listen.rs +180 -12
- data/ext/kino/src/log.rs +12 -47
- data/ext/kino/src/logsink.rs +3 -9
- data/ext/kino/src/mono.rs +12 -17
- data/ext/kino/src/pin.rs +3 -3
- data/ext/kino/src/queue/mod.rs +54 -0
- data/ext/kino/src/queue/take.rs +503 -0
- data/ext/kino/src/queue/testing.rs +107 -0
- data/ext/kino/src/queue/tests.rs +581 -0
- data/ext/kino/src/queue/worker.rs +501 -0
- data/ext/kino/src/registry.rs +168 -379
- data/ext/kino/src/request.rs +834 -235
- data/ext/kino/src/response.rs +532 -94
- data/ext/kino/src/server/accept.rs +322 -0
- data/ext/kino/src/server/config.rs +138 -0
- data/ext/kino/src/server/handle.rs +247 -0
- data/ext/kino/src/server/intake.rs +217 -0
- data/ext/kino/src/server/mod.rs +157 -0
- data/ext/kino/src/server/natives.rs +223 -0
- data/ext/kino/src/server/serve/intake_tests.rs +458 -0
- data/ext/kino/src/server/serve.rs +436 -0
- data/ext/kino/src/server/tests.rs +532 -0
- data/ext/kino/src/shared_gvl.rs +50 -0
- data/ext/kino/src/slot/lane.rs +138 -0
- data/ext/kino/src/slot/life.rs +111 -0
- data/ext/kino/src/slot/load.rs +193 -0
- data/ext/kino/src/slot/mod.rs +494 -0
- data/ext/kino/src/slot/park.rs +82 -0
- data/ext/kino/src/stats.rs +936 -0
- data/ext/kino/src/symbols.rs +66 -0
- data/ext/kino/src/test_support.rs +24 -14
- data/ext/kino/src/testing.rs +409 -0
- data/ext/kino/src/ticker.rs +87 -0
- data/ext/kino/src/timer.rs +4 -7
- data/ext/kino/src/tls.rs +101 -131
- data/ext/kino/src/typed_data.rs +131 -0
- data/ext/kino/src/upgrade.rs +77 -0
- data/ext/kino/src/ws/codec.rs +470 -0
- data/ext/kino/src/ws/drive.rs +600 -0
- data/ext/kino/src/ws/handshake.rs +267 -0
- data/ext/kino/src/ws/mod.rs +317 -0
- data/ext/kino/src/ws/server_tests.rs +759 -0
- data/ext/kino/src/ws/socket.rs +279 -0
- data/ext/kino/src/ws/stats.rs +88 -0
- data/ext/kino/src/ws/testing.rs +156 -0
- data/ext/kino/src/ws/topics.rs +550 -0
- data/lib/kino/cli.rb +100 -9
- data/lib/kino/configuration.rb +32 -10
- data/lib/kino/crash_backoff.rb +56 -0
- data/lib/kino/input.rb +36 -17
- data/lib/kino/log.rb +8 -1
- data/lib/kino/monitor.rb +1 -1
- data/lib/kino/pool.rb +169 -0
- data/lib/kino/pool_scaler.rb +12 -13
- data/lib/kino/quarantine_monitor.rb +3 -3
- data/lib/kino/ractor_supervisor.rb +201 -161
- data/lib/kino/server.rb +291 -185
- data/lib/kino/slot_bank.rb +21 -9
- data/lib/kino/stream.rb +2 -2
- data/lib/kino/teardown.rb +33 -0
- data/lib/kino/templates/kino.rb.tt +41 -6
- data/lib/kino/threaded_pool.rb +87 -102
- data/lib/kino/version.rb +1 -1
- data/lib/kino/web_socket.rb +125 -0
- data/lib/kino/worker/loop.rb +319 -0
- data/lib/kino/worker.rb +345 -79
- data/lib/kino/worker_hooks.rb +7 -1
- data/lib/kino/worker_row.rb +15 -0
- data/lib/kino.rb +27 -3
- data/lib/rackup/handler/kino.rb +1 -1
- data/sig/kino.rbs +93 -10
- metadata +66 -3
- data/ext/kino/src/queue.rs +0 -333
- data/ext/kino/src/server.rs +0 -1785
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
//! The WebSocket wire format (RFC 6455): the handshake digest, the frames Kino writes, and its
|
|
2
|
+
//! clients' frames, which tungstenite reads into messages.
|
|
3
|
+
|
|
4
|
+
use std::io::{self, Cursor, Read, Write};
|
|
5
|
+
use std::pin::Pin;
|
|
6
|
+
use std::task::{Context, Poll};
|
|
7
|
+
|
|
8
|
+
use bytes::{BufMut, Bytes, BytesMut};
|
|
9
|
+
use tokio::io::{AsyncRead, ReadBuf};
|
|
10
|
+
use tungstenite::error::{Error, ProtocolError};
|
|
11
|
+
use tungstenite::protocol::frame::coding::{CloseCode, OpCode};
|
|
12
|
+
use tungstenite::protocol::frame::FrameHeader;
|
|
13
|
+
use tungstenite::protocol::{CloseFrame, Role, WebSocketConfig, WebSocketContext};
|
|
14
|
+
use tungstenite::Message;
|
|
15
|
+
|
|
16
|
+
use super::stats::Cause;
|
|
17
|
+
|
|
18
|
+
const GUID: &[u8] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
19
|
+
/// What a socket's reader buffers (tungstenite's default is 128 KiB).
|
|
20
|
+
const READ_BUFFER: usize = 4 * 1024;
|
|
21
|
+
const MAX_CONTROL: usize = 125;
|
|
22
|
+
|
|
23
|
+
/// Sec-WebSocket-Accept for a client's Sec-WebSocket-Key.
|
|
24
|
+
pub fn accept_key(key: &[u8]) -> String {
|
|
25
|
+
let mut ctx = ring::digest::Context::new(&ring::digest::SHA1_FOR_LEGACY_USE_ONLY);
|
|
26
|
+
ctx.update(key);
|
|
27
|
+
ctx.update(GUID);
|
|
28
|
+
base64(ctx.finish().as_ref())
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
fn base64(input: &[u8]) -> String {
|
|
32
|
+
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
33
|
+
let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
|
|
34
|
+
for chunk in input.chunks(3) {
|
|
35
|
+
let b = [
|
|
36
|
+
chunk[0],
|
|
37
|
+
*chunk.get(1).unwrap_or(&0),
|
|
38
|
+
*chunk.get(2).unwrap_or(&0),
|
|
39
|
+
];
|
|
40
|
+
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
|
|
41
|
+
for (i, shift) in [18, 12, 6, 0].into_iter().enumerate() {
|
|
42
|
+
if i <= chunk.len() {
|
|
43
|
+
out.push(ALPHABET[(n >> shift) as usize & 63] as char);
|
|
44
|
+
} else {
|
|
45
|
+
out.push('=');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
out
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/// What a frame Kino sends carries.
|
|
53
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
54
|
+
#[repr(u8)]
|
|
55
|
+
pub enum Opcode {
|
|
56
|
+
Text = 0x1,
|
|
57
|
+
Binary = 0x2,
|
|
58
|
+
Close = 0x8,
|
|
59
|
+
Ping = 0x9,
|
|
60
|
+
Pong = 0xA,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/// One server frame: FIN set, unmasked.
|
|
64
|
+
pub fn encode(opcode: Opcode, payload: &[u8]) -> Bytes {
|
|
65
|
+
encode_parts(opcode, &[payload])
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/// One server frame whose payload is `parts` joined, each copied once.
|
|
69
|
+
pub(super) fn encode_parts(opcode: Opcode, parts: &[&[u8]]) -> Bytes {
|
|
70
|
+
let len = parts.iter().map(|part| part.len()).sum::<usize>();
|
|
71
|
+
let mut buf = BytesMut::with_capacity(len + 10);
|
|
72
|
+
buf.put_u8(0x80 | opcode as u8);
|
|
73
|
+
if len < 126 {
|
|
74
|
+
buf.put_u8(len as u8);
|
|
75
|
+
} else if len < 65_536 {
|
|
76
|
+
buf.put_u8(126);
|
|
77
|
+
buf.put_u16(len as u16);
|
|
78
|
+
} else {
|
|
79
|
+
buf.put_u8(127);
|
|
80
|
+
buf.put_u64(len as u64);
|
|
81
|
+
}
|
|
82
|
+
for part in parts {
|
|
83
|
+
buf.put_slice(part);
|
|
84
|
+
}
|
|
85
|
+
buf.freeze()
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
pub fn close_frame(code: u16) -> Bytes {
|
|
89
|
+
encode(Opcode::Close, &code.to_be_bytes())
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/// Codes an endpoint may send (RFC 6455 7.4); 1005, 1006 and 1015 never appear on the wire.
|
|
93
|
+
pub fn valid_close_code(code: u16) -> bool {
|
|
94
|
+
matches!(code, 1000..=1003 | 1007..=1011 | 3000..=4999)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/// The close code Kino answers with (none to a client that is gone), and the cause it ends for.
|
|
98
|
+
#[derive(Debug, PartialEq, Eq)]
|
|
99
|
+
pub(super) struct Ended {
|
|
100
|
+
pub(super) code: Option<u16>,
|
|
101
|
+
pub(super) cause: Cause,
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/// A socket's client frames, read into whole messages by tungstenite: masked, each within
|
|
105
|
+
/// `max_message` however fragmented. Kino answers pings and closes itself.
|
|
106
|
+
pub(super) struct Reader<R> {
|
|
107
|
+
rd: R,
|
|
108
|
+
ws: WebSocketContext,
|
|
109
|
+
fed: Fed,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
impl<R: AsyncRead + Unpin> Reader<R> {
|
|
113
|
+
pub(super) fn new(rd: R, max_message: usize) -> Self {
|
|
114
|
+
let config = WebSocketConfig::default()
|
|
115
|
+
.read_buffer_size(READ_BUFFER)
|
|
116
|
+
.max_message_size(Some(max_message))
|
|
117
|
+
// A declared length past this is refused before its payload
|
|
118
|
+
// is read; a control frame may carry MAX_CONTROL whatever the cap.
|
|
119
|
+
.max_frame_size(Some(max_message.max(MAX_CONTROL)))
|
|
120
|
+
.accept_unmasked_frames(false);
|
|
121
|
+
Reader {
|
|
122
|
+
rd,
|
|
123
|
+
ws: WebSocketContext::new(Role::Server, Some(config)),
|
|
124
|
+
fed: Fed::default(),
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/// The next message, ping or pong; a close or a failure ends reading.
|
|
129
|
+
pub(super) async fn next(&mut self) -> Result<Message, Ended> {
|
|
130
|
+
let read = std::future::poll_fn(|cx| {
|
|
131
|
+
let mut rd = Polled {
|
|
132
|
+
rd: &mut self.rd,
|
|
133
|
+
cx,
|
|
134
|
+
fed: &mut self.fed,
|
|
135
|
+
};
|
|
136
|
+
match self.ws.read(&mut rd) {
|
|
137
|
+
Err(Error::Io(error)) if error.kind() == io::ErrorKind::WouldBlock => Poll::Pending,
|
|
138
|
+
read => Poll::Ready(read),
|
|
139
|
+
}
|
|
140
|
+
})
|
|
141
|
+
.await;
|
|
142
|
+
match read {
|
|
143
|
+
Ok(Message::Close(frame)) => Err(closed(frame)),
|
|
144
|
+
Ok(message) => {
|
|
145
|
+
if self.fed.handed_back() {
|
|
146
|
+
self.ws = WebSocketContext::new(Role::Server, Some(*self.ws.get_config()));
|
|
147
|
+
}
|
|
148
|
+
Ok(message)
|
|
149
|
+
}
|
|
150
|
+
Err(error) => Err(failed(&error)),
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/// What tungstenite has been fed, to tell when it holds none of it: it keeps its buffer as
|
|
156
|
+
/// large as the largest frame, so after one past READ_BUFFER the reader starts afresh once empty.
|
|
157
|
+
#[derive(Default)]
|
|
158
|
+
struct Fed {
|
|
159
|
+
/// A frame head cut short by the end of a read; the longest is
|
|
160
|
+
/// 2 + 8 (length) + 4 (mask) bytes.
|
|
161
|
+
head: [u8; 14],
|
|
162
|
+
have: usize,
|
|
163
|
+
/// The payload still to come of a frame whose head is in.
|
|
164
|
+
rest: u64,
|
|
165
|
+
/// Message-ending frames (FIN set, or control) that tungstenite has yet to hand back.
|
|
166
|
+
unread: usize,
|
|
167
|
+
open: bool,
|
|
168
|
+
/// A data frame past READ_BUFFER came since the last fresh start.
|
|
169
|
+
grown: bool,
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
impl Fed {
|
|
173
|
+
fn feed(&mut self, mut bytes: &[u8]) {
|
|
174
|
+
while !bytes.is_empty() {
|
|
175
|
+
if self.rest == 0 {
|
|
176
|
+
let Some(len) = self.head(&mut bytes) else {
|
|
177
|
+
return;
|
|
178
|
+
};
|
|
179
|
+
self.rest = len;
|
|
180
|
+
}
|
|
181
|
+
let taken = self.rest.min(bytes.len() as u64);
|
|
182
|
+
self.rest -= taken;
|
|
183
|
+
bytes = &bytes[taken as usize..];
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/// Once the head is whole, its payload length, with `bytes` moved past it. None while the
|
|
188
|
+
/// head is cut short; FrameHeader::parse never refuses a whole head.
|
|
189
|
+
fn head(&mut self, bytes: &mut &[u8]) -> Option<u64> {
|
|
190
|
+
let taken = bytes.len().min(self.head.len() - self.have);
|
|
191
|
+
self.head[self.have..][..taken].copy_from_slice(&bytes[..taken]);
|
|
192
|
+
let mut cursor = Cursor::new(&self.head[..self.have + taken]);
|
|
193
|
+
let Ok(Some((head, len))) = FrameHeader::parse(&mut cursor) else {
|
|
194
|
+
self.have += taken;
|
|
195
|
+
return None;
|
|
196
|
+
};
|
|
197
|
+
*bytes = &bytes[cursor.position() as usize - self.have..];
|
|
198
|
+
self.have = 0;
|
|
199
|
+
let control = matches!(head.opcode, OpCode::Control(_));
|
|
200
|
+
self.unread += usize::from(head.is_final || control);
|
|
201
|
+
if !control {
|
|
202
|
+
self.open = !head.is_final;
|
|
203
|
+
self.grown |= len > READ_BUFFER as u64;
|
|
204
|
+
}
|
|
205
|
+
Some(len)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/// True once per large frame, when the message handed back was the last thing tungstenite
|
|
209
|
+
/// holds: no message-ending frame unread, no fragmented message open, no head cut short.
|
|
210
|
+
fn handed_back(&mut self) -> bool {
|
|
211
|
+
self.unread -= 1;
|
|
212
|
+
let empty = self.unread == 0 && self.have == 0 && !self.open;
|
|
213
|
+
empty && std::mem::take(&mut self.grown)
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/// Its own code back (1000 for none), or 1002 for one no endpoint may send: tungstenite hands
|
|
218
|
+
/// those over as its 1002 "Protocol violation", and lets 1012 and 1013 through.
|
|
219
|
+
fn closed(frame: Option<CloseFrame>) -> Ended {
|
|
220
|
+
let code = frame.as_ref().map_or(1000, |frame| u16::from(frame.code));
|
|
221
|
+
let replaced = frame.is_some_and(|frame| {
|
|
222
|
+
frame.code == CloseCode::Protocol && frame.reason == "Protocol violation"
|
|
223
|
+
});
|
|
224
|
+
let (code, cause) = if replaced || !valid_close_code(code) {
|
|
225
|
+
(1002, Cause::Protocol)
|
|
226
|
+
} else {
|
|
227
|
+
(code, Cause::Normal)
|
|
228
|
+
};
|
|
229
|
+
Ended {
|
|
230
|
+
code: Some(code),
|
|
231
|
+
cause,
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/// 1002 for a broken rule, 1007 for text not UTF-8, 1009 past the cap; a gone client hears nothing.
|
|
236
|
+
fn failed(error: &Error) -> Ended {
|
|
237
|
+
let (code, cause) = match error {
|
|
238
|
+
Error::Protocol(ProtocolError::ResetWithoutClosingHandshake) => (None, Cause::ClientGone),
|
|
239
|
+
Error::Protocol(_) => (Some(1002), Cause::Protocol),
|
|
240
|
+
Error::Utf8(_) => (Some(1007), Cause::Protocol),
|
|
241
|
+
Error::Capacity(_) => (Some(1009), Cause::TooBig),
|
|
242
|
+
_ => (None, Cause::ClientGone),
|
|
243
|
+
};
|
|
244
|
+
Ended { code, cause }
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/// A socket's read half as std::io for tungstenite, within one poll:
|
|
248
|
+
/// Pending reads as WouldBlock, and each read is shown to `fed`. What
|
|
249
|
+
/// tungstenite writes (its own pongs and close echoes) goes nowhere.
|
|
250
|
+
struct Polled<'a, 'b, R> {
|
|
251
|
+
rd: &'a mut R,
|
|
252
|
+
cx: &'a mut Context<'b>,
|
|
253
|
+
fed: &'a mut Fed,
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
impl<R: AsyncRead + Unpin> Read for Polled<'_, '_, R> {
|
|
257
|
+
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
|
258
|
+
let mut buf = ReadBuf::new(buf);
|
|
259
|
+
match Pin::new(&mut *self.rd).poll_read(self.cx, &mut buf) {
|
|
260
|
+
Poll::Ready(read) => read.map(|()| {
|
|
261
|
+
self.fed.feed(buf.filled());
|
|
262
|
+
buf.filled().len()
|
|
263
|
+
}),
|
|
264
|
+
Poll::Pending => Err(io::ErrorKind::WouldBlock.into()),
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
impl<R> Write for Polled<'_, '_, R> {
|
|
270
|
+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
|
271
|
+
Ok(buf.len())
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
fn flush(&mut self) -> io::Result<()> {
|
|
275
|
+
Ok(())
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
#[cfg(test)]
|
|
280
|
+
mod tests {
|
|
281
|
+
use tokio::io::AsyncWriteExt;
|
|
282
|
+
|
|
283
|
+
use super::*;
|
|
284
|
+
use crate::ws::testing::client_frame;
|
|
285
|
+
|
|
286
|
+
/// What a Reader capped at `max_message` yields for `wire`, sent by a
|
|
287
|
+
/// client that then hangs up, up to how reading ended. One byte gets
|
|
288
|
+
/// through at a time, so every read waits, and resumes, at each byte.
|
|
289
|
+
async fn read(wire: Vec<u8>, max_message: usize) -> Vec<Result<Message, Ended>> {
|
|
290
|
+
let (mut client, conn) = tokio::io::duplex(1);
|
|
291
|
+
tokio::spawn(async move {
|
|
292
|
+
let _ = client.write_all(&wire).await;
|
|
293
|
+
});
|
|
294
|
+
let mut reader = Reader::new(conn, max_message);
|
|
295
|
+
let mut seen = Vec::new();
|
|
296
|
+
loop {
|
|
297
|
+
let next = reader.next().await;
|
|
298
|
+
let ended = next.is_err();
|
|
299
|
+
seen.push(next);
|
|
300
|
+
if ended {
|
|
301
|
+
return seen;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
fn ended(code: Option<u16>, cause: Cause) -> Result<Message, Ended> {
|
|
307
|
+
Err(Ended { code, cause })
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/// A connection its client reset.
|
|
311
|
+
struct Reset;
|
|
312
|
+
|
|
313
|
+
impl AsyncRead for Reset {
|
|
314
|
+
fn poll_read(
|
|
315
|
+
self: Pin<&mut Self>,
|
|
316
|
+
_: &mut Context,
|
|
317
|
+
_: &mut ReadBuf,
|
|
318
|
+
) -> Poll<io::Result<()>> {
|
|
319
|
+
Poll::Ready(Err(io::ErrorKind::ConnectionReset.into()))
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
#[test]
|
|
324
|
+
fn server_frames_are_unmasked_with_fin_set_and_the_shortest_length_form() {
|
|
325
|
+
// RFC 6455 5.2: up to 125 bytes in the 7 bits, up to 65,535 as 126
|
|
326
|
+
// and 16 bits, past that as 127 and 64 bits.
|
|
327
|
+
let frames: [(Bytes, &[u8]); 5] = [
|
|
328
|
+
(encode(Opcode::Text, b"Hello"), b"\x81\x05Hello"), // RFC 6455 5.7
|
|
329
|
+
(encode(Opcode::Text, &[0; 125]), &[0x81, 125]),
|
|
330
|
+
(encode(Opcode::Text, &[0; 126]), &[0x81, 126, 0, 126]),
|
|
331
|
+
(
|
|
332
|
+
encode(Opcode::Binary, &[0; 65_535]),
|
|
333
|
+
&[0x82, 126, 0xFF, 0xFF],
|
|
334
|
+
),
|
|
335
|
+
(
|
|
336
|
+
encode(Opcode::Binary, &[0; 65_536]),
|
|
337
|
+
&[0x82, 127, 0, 0, 0, 0, 0, 1, 0, 0],
|
|
338
|
+
),
|
|
339
|
+
];
|
|
340
|
+
for (frame, head) in frames {
|
|
341
|
+
assert_eq!(
|
|
342
|
+
&frame[..head.len()],
|
|
343
|
+
head,
|
|
344
|
+
"a frame of {} bytes",
|
|
345
|
+
frame.len()
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
#[tokio::test]
|
|
351
|
+
async fn how_reading_ends_sets_the_close_code_and_the_cause() {
|
|
352
|
+
use Cause::*;
|
|
353
|
+
let close = |code: u16, reason: &[u8]| {
|
|
354
|
+
client_frame(0x88, &[&code.to_be_bytes()[..], reason].concat())
|
|
355
|
+
};
|
|
356
|
+
let mut cut = client_frame(0x81, b"hello");
|
|
357
|
+
cut.truncate(cut.len() - 2);
|
|
358
|
+
// One row per case; rustfmt would split each row field by field.
|
|
359
|
+
#[rustfmt::skip]
|
|
360
|
+
let cases = [
|
|
361
|
+
(cut, None, ClientGone, "a connection lost mid-frame"),
|
|
362
|
+
// RFC 6455 5.1: a client must mask every frame.
|
|
363
|
+
(b"\x81\x02hi".to_vec(), Some(1002), Protocol, "an unmasked frame"),
|
|
364
|
+
(client_frame(0x81, &[0xC3, 0x28]), Some(1007), Protocol, "text not UTF-8"),
|
|
365
|
+
(client_frame(0x82, &[0; 17]), Some(1009), TooBig, "past the cap"),
|
|
366
|
+
(client_frame(0x88, b""), Some(1000), Normal, "a close with no code"),
|
|
367
|
+
(close(4000, b"bye"), Some(4000), Normal, "a close with a code"),
|
|
368
|
+
(close(1005, b""), Some(1002), Protocol, "a code for local use only"),
|
|
369
|
+
(close(1012, b""), Some(1002), Protocol, "a code RFC 6455 does not define"),
|
|
370
|
+
];
|
|
371
|
+
for (wire, code, cause, why) in cases {
|
|
372
|
+
let ended = read(wire, 16).await.pop();
|
|
373
|
+
assert_eq!(ended, Some(Err(Ended { code, cause })), "{why}");
|
|
374
|
+
}
|
|
375
|
+
let reset = Reader::new(Reset, 16).next().await;
|
|
376
|
+
assert_eq!(reset, ended(None, ClientGone), "a connection reset");
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
#[tokio::test]
|
|
380
|
+
async fn the_cap_counts_every_fragment_of_a_message() {
|
|
381
|
+
// A control frame may carry 125 bytes whatever the cap, and counts
|
|
382
|
+
// toward no message.
|
|
383
|
+
let mut wire = client_frame(0x02, &[7; 10]);
|
|
384
|
+
wire.extend(client_frame(0x89, &[9; 125]));
|
|
385
|
+
wire.extend(client_frame(0x80, &[7; 6]));
|
|
386
|
+
wire.extend(client_frame(0x02, &[7; 10]));
|
|
387
|
+
wire.extend(client_frame(0x80, &[7; 7]));
|
|
388
|
+
assert_eq!(
|
|
389
|
+
read(wire, 16).await,
|
|
390
|
+
[
|
|
391
|
+
Ok(Message::Ping(Bytes::from(vec![9; 125]))),
|
|
392
|
+
Ok(Message::Binary(Bytes::from(vec![7; 16]))),
|
|
393
|
+
ended(Some(1009), Cause::TooBig)
|
|
394
|
+
]
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
#[tokio::test]
|
|
399
|
+
async fn a_large_message_is_let_go_of_once_nothing_is_read_past_it() {
|
|
400
|
+
// tungstenite reads a frame whole into its buffer and hands the
|
|
401
|
+
// payload over in place, so a message shares the reader's buffer.
|
|
402
|
+
let large = client_frame(0x82, &vec![7; 512 * 1024]);
|
|
403
|
+
// 200 bytes: a head of 8, its length in 16 bits.
|
|
404
|
+
let small = client_frame(0x82, &[5; 200]);
|
|
405
|
+
let (mut client, conn) = tokio::io::duplex(1 << 20);
|
|
406
|
+
let mut reader = Reader::new(conn, 1 << 20);
|
|
407
|
+
let mut next = async || reader.next().await.expect("a message");
|
|
408
|
+
let binary = |message| match message {
|
|
409
|
+
Message::Binary(data) => data,
|
|
410
|
+
other => panic!("expected a binary message, got {other:?}"),
|
|
411
|
+
};
|
|
412
|
+
|
|
413
|
+
client.write_all(&small).await.unwrap();
|
|
414
|
+
let alone = binary(next().await);
|
|
415
|
+
assert!(
|
|
416
|
+
!alone.is_unique(),
|
|
417
|
+
"with nothing large read, nothing is let go of"
|
|
418
|
+
);
|
|
419
|
+
client.write_all(&large).await.unwrap();
|
|
420
|
+
let alone = binary(next().await);
|
|
421
|
+
assert!(alone.is_unique(), "the reader still holds a large message");
|
|
422
|
+
|
|
423
|
+
// Read past it: a message, a head cut short, a payload cut short.
|
|
424
|
+
for cut in [small.len(), 3, 9] {
|
|
425
|
+
let wire = [&large[..], &small[..cut]].concat();
|
|
426
|
+
client.write_all(&wire).await.unwrap();
|
|
427
|
+
let ahead = binary(next().await);
|
|
428
|
+
assert!(!ahead.is_unique(), "let go of with {cut} bytes past it");
|
|
429
|
+
client.write_all(&small[cut..]).await.unwrap();
|
|
430
|
+
let behind = binary(next().await);
|
|
431
|
+
assert_eq!(behind, &[5; 200][..]);
|
|
432
|
+
assert!(!behind.is_unique(), "a small message is read in place");
|
|
433
|
+
drop(behind);
|
|
434
|
+
assert!(ahead.is_unique(), "the reader still holds a large message");
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// A pong is a message tungstenite hands back too.
|
|
438
|
+
let wire = [large, client_frame(0x8A, b"pong")].concat();
|
|
439
|
+
client.write_all(&wire).await.unwrap();
|
|
440
|
+
let ahead = binary(next().await);
|
|
441
|
+
assert!(!ahead.is_unique(), "let go of with a pong past it");
|
|
442
|
+
assert_eq!(next().await, Message::Pong(Bytes::from_static(b"pong")));
|
|
443
|
+
assert!(ahead.is_unique(), "the reader still holds a large message");
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
#[tokio::test]
|
|
447
|
+
async fn a_ping_between_the_fragments_of_a_large_message_leaves_it_whole() {
|
|
448
|
+
let mut wire = client_frame(0x02, &[7; 8 * 1024]);
|
|
449
|
+
wire.extend(client_frame(0x89, b"ping"));
|
|
450
|
+
wire.extend(client_frame(0x80, &[7; 10]));
|
|
451
|
+
assert_eq!(
|
|
452
|
+
read(wire, 1 << 20).await,
|
|
453
|
+
[
|
|
454
|
+
Ok(Message::Ping(Bytes::from_static(b"ping"))),
|
|
455
|
+
Ok(Message::Binary(Bytes::from(vec![7; 8 * 1024 + 10]))),
|
|
456
|
+
ended(None, Cause::ClientGone)
|
|
457
|
+
]
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
#[tokio::test]
|
|
462
|
+
async fn a_huge_declared_length_is_refused_before_any_payload_is_read() {
|
|
463
|
+
// No payload follows: reading it would find the client gone (or
|
|
464
|
+
// allocate 2^63 bytes).
|
|
465
|
+
let mut wire = vec![0x82, 0x80 | 127];
|
|
466
|
+
wire.extend_from_slice(&(1u64 << 63).to_be_bytes());
|
|
467
|
+
wire.extend_from_slice(&[0; 4]);
|
|
468
|
+
assert_eq!(read(wire, 1024).await, [ended(Some(1009), Cause::TooBig)]);
|
|
469
|
+
}
|
|
470
|
+
}
|