blob: 7e0f8b6c3c3f422936597c1b34420e6f226c5b0f [file] [log] [blame]
Allen George8b96bfb2016-11-02 08:01:08 -04001// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
Allen George8b96bfb2016-11-02 08:01:08 -040019use std::cmp;
20use std::io;
Allen Georgeb7084cb2017-12-13 07:34:49 -050021use std::io::{Read, Write};
Allen George8b96bfb2016-11-02 08:01:08 -040022
Allen George0e22c362017-01-30 07:15:00 -050023use super::{TReadTransport, TReadTransportFactory, TWriteTransport, TWriteTransportFactory};
Allen George8b96bfb2016-11-02 08:01:08 -040024
25/// Default capacity of the read buffer in bytes.
Allen George0e22c362017-01-30 07:15:00 -050026const READ_CAPACITY: usize = 4096;
Allen George8b96bfb2016-11-02 08:01:08 -040027
Allen George0e22c362017-01-30 07:15:00 -050028/// Default capacity of the write buffer in bytes.
29const WRITE_CAPACITY: usize = 4096;
Allen George8b96bfb2016-11-02 08:01:08 -040030
Allen George0e22c362017-01-30 07:15:00 -050031/// Transport that reads framed messages.
Allen George8b96bfb2016-11-02 08:01:08 -040032///
Allen George0e22c362017-01-30 07:15:00 -050033/// A `TFramedReadTransport` maintains a fixed-size internal read buffer.
34/// On a call to `TFramedReadTransport::read(...)` one full message - both
35/// fixed-length header and bytes - is read from the wrapped channel and
36/// buffered. Subsequent read calls are serviced from the internal buffer
37/// until it is exhausted, at which point the next full message is read
38/// from the wrapped channel.
Allen George8b96bfb2016-11-02 08:01:08 -040039///
40/// # Examples
41///
Allen George0e22c362017-01-30 07:15:00 -050042/// Create and use a `TFramedReadTransport`.
Allen George8b96bfb2016-11-02 08:01:08 -040043///
44/// ```no_run
Allen George0e22c362017-01-30 07:15:00 -050045/// use std::io::Read;
46/// use thrift::transport::{TFramedReadTransport, TTcpChannel};
Allen George8b96bfb2016-11-02 08:01:08 -040047///
Allen George0e22c362017-01-30 07:15:00 -050048/// let mut c = TTcpChannel::new();
49/// c.open("localhost:9090").unwrap();
Allen George8b96bfb2016-11-02 08:01:08 -040050///
Allen George0e22c362017-01-30 07:15:00 -050051/// let mut t = TFramedReadTransport::new(c);
Allen George8b96bfb2016-11-02 08:01:08 -040052///
Allen George8b96bfb2016-11-02 08:01:08 -040053/// t.read(&mut vec![0u8; 1]).unwrap();
Allen George8b96bfb2016-11-02 08:01:08 -040054/// ```
Allen George0e22c362017-01-30 07:15:00 -050055#[derive(Debug)]
56pub struct TFramedReadTransport<C>
57where
58 C: Read,
59{
Allen Georgeb7084cb2017-12-13 07:34:49 -050060 buf: Vec<u8>,
Allen George0e22c362017-01-30 07:15:00 -050061 pos: usize,
62 cap: usize,
63 chan: C,
Allen George8b96bfb2016-11-02 08:01:08 -040064}
65
Allen George0e22c362017-01-30 07:15:00 -050066impl<C> TFramedReadTransport<C>
67where
68 C: Read,
69{
Allen Georgeb7084cb2017-12-13 07:34:49 -050070 /// Create a `TFramedReadTransport` with a default-sized
71 /// internal read buffer that wraps the given `TIoChannel`.
Allen George0e22c362017-01-30 07:15:00 -050072 pub fn new(channel: C) -> TFramedReadTransport<C> {
73 TFramedReadTransport::with_capacity(READ_CAPACITY, channel)
Allen George8b96bfb2016-11-02 08:01:08 -040074 }
75
Allen Georgeb7084cb2017-12-13 07:34:49 -050076 /// Create a `TFramedTransport` with an internal read buffer
77 /// of size `read_capacity` that wraps the given `TIoChannel`.
Allen George0e22c362017-01-30 07:15:00 -050078 pub fn with_capacity(read_capacity: usize, channel: C) -> TFramedReadTransport<C> {
79 TFramedReadTransport {
Allen Georgeb7084cb2017-12-13 07:34:49 -050080 buf: vec![0; read_capacity], // FIXME: do I actually have to do this?
Allen George0e22c362017-01-30 07:15:00 -050081 pos: 0,
82 cap: 0,
83 chan: channel,
Allen George8b96bfb2016-11-02 08:01:08 -040084 }
85 }
86}
87
Allen George0e22c362017-01-30 07:15:00 -050088impl<C> Read for TFramedReadTransport<C>
89where
90 C: Read,
91{
Allen George8b96bfb2016-11-02 08:01:08 -040092 fn read(&mut self, b: &mut [u8]) -> io::Result<usize> {
Allen George0e22c362017-01-30 07:15:00 -050093 if self.cap - self.pos == 0 {
94 let message_size = self.chan.read_i32::<BigEndian>()? as usize;
Allen Georgeb7084cb2017-12-13 07:34:49 -050095
96 let buf_capacity = cmp::max(message_size, READ_CAPACITY);
97 self.buf.resize(buf_capacity, 0);
98
Allen George0e22c362017-01-30 07:15:00 -050099 self.chan.read_exact(&mut self.buf[..message_size])?;
Allen George0e22c362017-01-30 07:15:00 -0500100 self.cap = message_size as usize;
Allen Georgeb7084cb2017-12-13 07:34:49 -0500101 self.pos = 0;
Allen George8b96bfb2016-11-02 08:01:08 -0400102 }
103
Allen George0e22c362017-01-30 07:15:00 -0500104 let nread = cmp::min(b.len(), self.cap - self.pos);
105 b[..nread].clone_from_slice(&self.buf[self.pos..self.pos + nread]);
106 self.pos += nread;
Allen George8b96bfb2016-11-02 08:01:08 -0400107
108 Ok(nread)
109 }
110}
111
Allen George0e22c362017-01-30 07:15:00 -0500112/// Factory for creating instances of `TFramedReadTransport`.
113#[derive(Default)]
114pub struct TFramedReadTransportFactory;
115
116impl TFramedReadTransportFactory {
117 pub fn new() -> TFramedReadTransportFactory {
118 TFramedReadTransportFactory {}
119 }
120}
121
122impl TReadTransportFactory for TFramedReadTransportFactory {
123 /// Create a `TFramedReadTransport`.
124 fn create(&self, channel: Box<Read + Send>) -> Box<TReadTransport + Send> {
125 Box::new(TFramedReadTransport::new(channel))
126 }
127}
128
129/// Transport that writes framed messages.
130///
131/// A `TFramedWriteTransport` maintains a fixed-size internal write buffer. All
132/// writes are made to this buffer and are sent to the wrapped channel only
133/// when `TFramedWriteTransport::flush()` is called. On a flush a fixed-length
134/// header with a count of the buffered bytes is written, followed by the bytes
135/// themselves.
136///
137/// # Examples
138///
139/// Create and use a `TFramedWriteTransport`.
140///
141/// ```no_run
142/// use std::io::Write;
143/// use thrift::transport::{TFramedWriteTransport, TTcpChannel};
144///
145/// let mut c = TTcpChannel::new();
146/// c.open("localhost:9090").unwrap();
147///
148/// let mut t = TFramedWriteTransport::new(c);
149///
150/// t.write(&[0x00]).unwrap();
151/// t.flush().unwrap();
152/// ```
153#[derive(Debug)]
154pub struct TFramedWriteTransport<C>
155where
156 C: Write,
157{
Allen Georgeb7084cb2017-12-13 07:34:49 -0500158 buf: Vec<u8>,
Allen George0e22c362017-01-30 07:15:00 -0500159 channel: C,
160}
161
162impl<C> TFramedWriteTransport<C>
163where
164 C: Write,
165{
Allen Georgeb7084cb2017-12-13 07:34:49 -0500166 /// Create a `TFramedWriteTransport` with default-sized internal
167 /// write buffer that wraps the given `TIoChannel`.
Allen George0e22c362017-01-30 07:15:00 -0500168 pub fn new(channel: C) -> TFramedWriteTransport<C> {
169 TFramedWriteTransport::with_capacity(WRITE_CAPACITY, channel)
170 }
171
Allen Georgeb7084cb2017-12-13 07:34:49 -0500172 /// Create a `TFramedWriteTransport` with an internal write buffer
173 /// of size `write_capacity` that wraps the given `TIoChannel`.
Allen George0e22c362017-01-30 07:15:00 -0500174 pub fn with_capacity(write_capacity: usize, channel: C) -> TFramedWriteTransport<C> {
175 TFramedWriteTransport {
Allen Georgeb7084cb2017-12-13 07:34:49 -0500176 buf: Vec::with_capacity(write_capacity),
177 channel,
Allen George0e22c362017-01-30 07:15:00 -0500178 }
179 }
180}
181
182impl<C> Write for TFramedWriteTransport<C>
183where
184 C: Write,
185{
Allen George8b96bfb2016-11-02 08:01:08 -0400186 fn write(&mut self, b: &[u8]) -> io::Result<usize> {
Allen Georgeb7084cb2017-12-13 07:34:49 -0500187 let current_capacity = self.buf.capacity();
188 let available_space = current_capacity - self.buf.len();
189 if b.len() > available_space {
190 let additional_space = cmp::max(b.len() - available_space, current_capacity);
191 self.buf.reserve(additional_space);
Allen George8b96bfb2016-11-02 08:01:08 -0400192 }
193
Allen Georgeb7084cb2017-12-13 07:34:49 -0500194 self.buf.extend_from_slice(b);
195 Ok(b.len())
Allen George8b96bfb2016-11-02 08:01:08 -0400196 }
197
198 fn flush(&mut self) -> io::Result<()> {
Allen Georgeb7084cb2017-12-13 07:34:49 -0500199 let message_size = self.buf.len();
Allen George8b96bfb2016-11-02 08:01:08 -0400200
201 if let 0 = message_size {
202 return Ok(());
203 } else {
Allen George0e22c362017-01-30 07:15:00 -0500204 self.channel
205 .write_i32::<BigEndian>(message_size as i32)?;
Allen George8b96bfb2016-11-02 08:01:08 -0400206 }
207
Allen Georgeb7084cb2017-12-13 07:34:49 -0500208 // will spin if the underlying channel can't be written to
Allen George8b96bfb2016-11-02 08:01:08 -0400209 let mut byte_index = 0;
Allen Georgeb7084cb2017-12-13 07:34:49 -0500210 while byte_index < message_size {
211 let nwrite = self.channel.write(&self.buf[byte_index..message_size])?;
212 byte_index = cmp::min(byte_index + nwrite, message_size);
Allen George8b96bfb2016-11-02 08:01:08 -0400213 }
214
Allen Georgeb7084cb2017-12-13 07:34:49 -0500215 let buf_capacity = cmp::min(self.buf.capacity(), WRITE_CAPACITY);
216 self.buf.resize(buf_capacity, 0);
217 self.buf.clear();
218
Allen George0e22c362017-01-30 07:15:00 -0500219 self.channel.flush()
Allen George8b96bfb2016-11-02 08:01:08 -0400220 }
221}
222
Allen George0e22c362017-01-30 07:15:00 -0500223/// Factory for creating instances of `TFramedWriteTransport`.
Allen George8b96bfb2016-11-02 08:01:08 -0400224#[derive(Default)]
Allen George0e22c362017-01-30 07:15:00 -0500225pub struct TFramedWriteTransportFactory;
Allen George8b96bfb2016-11-02 08:01:08 -0400226
Allen George0e22c362017-01-30 07:15:00 -0500227impl TFramedWriteTransportFactory {
228 pub fn new() -> TFramedWriteTransportFactory {
229 TFramedWriteTransportFactory {}
Allen George8b96bfb2016-11-02 08:01:08 -0400230 }
231}
232
Allen George0e22c362017-01-30 07:15:00 -0500233impl TWriteTransportFactory for TFramedWriteTransportFactory {
234 /// Create a `TFramedWriteTransport`.
235 fn create(&self, channel: Box<Write + Send>) -> Box<TWriteTransport + Send> {
236 Box::new(TFramedWriteTransport::new(channel))
Allen George8b96bfb2016-11-02 08:01:08 -0400237 }
238}
239
240#[cfg(test)]
241mod tests {
Allen Georgeb7084cb2017-12-13 07:34:49 -0500242 use super::*;
243 use ::transport::mem::TBufferChannel;
244
245 // FIXME: test a forced reserve
246
247 #[test]
248 fn must_read_message_smaller_than_initial_buffer_size() {
249 let c = TBufferChannel::with_capacity(10, 10);
250 let mut t = TFramedReadTransport::with_capacity(8, c);
251
252 t.chan.set_readable_bytes(
253 &[
254 0x00, 0x00, 0x00, 0x04, /* message size */
255 0x00, 0x01, 0x02, 0x03 /* message body */
256 ]
257 );
258
259 let mut buf = vec![0; 8];
260
261 // we've read exactly 4 bytes
262 assert_eq!(t.read(&mut buf).unwrap(), 4);
263 assert_eq!(&buf[..4], &[0x00, 0x01, 0x02, 0x03]);
264 }
265
266 #[test]
267 fn must_read_message_greater_than_initial_buffer_size() {
268 let c = TBufferChannel::with_capacity(10, 10);
269 let mut t = TFramedReadTransport::with_capacity(2, c);
270
271 t.chan.set_readable_bytes(
272 &[
273 0x00, 0x00, 0x00, 0x04, /* message size */
274 0x00, 0x01, 0x02, 0x03 /* message body */
275 ]
276 );
277
278 let mut buf = vec![0; 8];
279
280 // we've read exactly 4 bytes
281 assert_eq!(t.read(&mut buf).unwrap(), 4);
282 assert_eq!(&buf[..4], &[0x00, 0x01, 0x02, 0x03]);
283 }
284
285 #[test]
286 fn must_read_multiple_messages_in_sequence_correctly() {
287 let c = TBufferChannel::with_capacity(10, 10);
288 let mut t = TFramedReadTransport::with_capacity(2, c);
289
290 //
291 // 1st message
292 //
293
294 t.chan.set_readable_bytes(
295 &[
296 0x00, 0x00, 0x00, 0x04, /* message size */
297 0x00, 0x01, 0x02, 0x03 /* message body */
298 ]
299 );
300
301 let mut buf = vec![0; 8];
302
303 // we've read exactly 4 bytes
304 assert_eq!(t.read(&mut buf).unwrap(), 4);
305 assert_eq!(&buf, &[0x00, 0x01, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00]);
306
307 //
308 // 2nd message
309 //
310
311 t.chan.set_readable_bytes(
312 &[
313 0x00, 0x00, 0x00, 0x01, /* message size */
314 0x04 /* message body */
315 ]
316 );
317
318 let mut buf = vec![0; 8];
319
320 // we've read exactly 1 byte
321 assert_eq!(t.read(&mut buf).unwrap(), 1);
322 assert_eq!(&buf, &[0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
323 }
324
325 #[test]
326 fn must_write_message_smaller_than_buffer_size() {
327 let mem = TBufferChannel::with_capacity(0, 0);
328 let mut t = TFramedWriteTransport::with_capacity(20, mem);
329
330 let b = vec![0; 10];
331
332 // should have written 10 bytes
333 assert_eq!(t.write(&b).unwrap(), 10);
334 }
335
336 #[test]
337 fn must_return_zero_if_caller_calls_write_with_empty_buffer() {
338 let mem = TBufferChannel::with_capacity(0, 10);
339 let mut t = TFramedWriteTransport::with_capacity(10, mem);
340
341 let expected: [u8; 0] = [];
342
343 assert_eq!(t.write(&[]).unwrap(), 0);
344 assert_eq_transport_written_bytes!(t, expected);
345 }
346
347 #[test]
348 fn must_write_to_inner_transport_on_flush() {
349 let mem = TBufferChannel::with_capacity(10, 10);
350 let mut t = TFramedWriteTransport::new(mem);
351
352 let b: [u8; 5] = [0x00, 0x01, 0x02, 0x03, 0x04];
353 assert_eq!(t.write(&b).unwrap(), 5);
354 assert_eq_transport_num_written_bytes!(t, 0);
355
356 assert!(t.flush().is_ok());
357
358 let expected_bytes = [
359 0x00, 0x00, 0x00, 0x05, /* message size */
360 0x00, 0x01, 0x02, 0x03, 0x04 /* message body */
361 ];
362
363 assert_eq_transport_written_bytes!(t, expected_bytes);
364 }
365
366 #[test]
367 fn must_write_message_greater_than_buffer_size_00() {
368 let mem = TBufferChannel::with_capacity(0, 10);
369
370 // IMPORTANT: DO **NOT** CHANGE THE WRITE_CAPACITY OR THE NUMBER OF BYTES TO BE WRITTEN!
371 // these lengths were chosen to be just long enough
372 // that doubling the capacity is a **worse** choice than
373 // simply resizing the buffer to b.len()
374
375 let mut t = TFramedWriteTransport::with_capacity(1, mem);
376 let b = [0x00, 0x01, 0x02];
377
378 // should have written 3 bytes
379 assert_eq!(t.write(&b).unwrap(), 3);
380 assert_eq_transport_num_written_bytes!(t, 0);
381
382 assert!(t.flush().is_ok());
383
384 let expected_bytes = [
385 0x00, 0x00, 0x00, 0x03, /* message size */
386 0x00, 0x01, 0x02 /* message body */
387 ];
388
389 assert_eq_transport_written_bytes!(t, expected_bytes);
390 }
391
392 #[test]
393 fn must_write_message_greater_than_buffer_size_01() {
394 let mem = TBufferChannel::with_capacity(0, 10);
395
396 // IMPORTANT: DO **NOT** CHANGE THE WRITE_CAPACITY OR THE NUMBER OF BYTES TO BE WRITTEN!
397 // these lengths were chosen to be just long enough
398 // that doubling the capacity is a **better** choice than
399 // simply resizing the buffer to b.len()
400
401 let mut t = TFramedWriteTransport::with_capacity(2, mem);
402 let b = [0x00, 0x01, 0x02];
403
404 // should have written 3 bytes
405 assert_eq!(t.write(&b).unwrap(), 3);
406 assert_eq_transport_num_written_bytes!(t, 0);
407
408 assert!(t.flush().is_ok());
409
410 let expected_bytes = [
411 0x00, 0x00, 0x00, 0x03, /* message size */
412 0x00, 0x01, 0x02 /* message body */
413 ];
414
415 assert_eq_transport_written_bytes!(t, expected_bytes);
416 }
417
418 #[test]
419 fn must_return_error_if_nothing_can_be_written_to_inner_transport_on_flush() {
420 let mem = TBufferChannel::with_capacity(0, 0);
421 let mut t = TFramedWriteTransport::with_capacity(1, mem);
422
423 let b = vec![0; 10];
424
425 // should have written 10 bytes
426 assert_eq!(t.write(&b).unwrap(), 10);
427
428 // let's flush
429 let r = t.flush();
430
431 // this time we'll error out because the flush can't write to the underlying channel
432 assert!(r.is_err());
433 }
434
435 #[test]
436 fn must_write_successfully_after_flush() {
437 // IMPORTANT: write capacity *MUST* be greater
438 // than message sizes used in this test + 4-byte frame header
439 let mem = TBufferChannel::with_capacity(0, 10);
440 let mut t = TFramedWriteTransport::with_capacity(5, mem);
441
442 // write and flush
443 let first_message: [u8; 5] = [0x00, 0x01, 0x02, 0x03, 0x04];
444 assert_eq!(t.write(&first_message).unwrap(), 5);
445 assert!(t.flush().is_ok());
446
447 let mut expected = Vec::new();
448 expected.write_all(&[0x00, 0x00, 0x00, 0x05]).unwrap(); // message size
449 expected.extend_from_slice(&first_message);
450
451 // check the flushed bytes
452 assert_eq!(t.channel.write_bytes(), expected);
453
454 // reset our underlying transport
455 t.channel.empty_write_buffer();
456
457 let second_message: [u8; 3] = [0x05, 0x06, 0x07];
458 assert_eq!(t.write(&second_message).unwrap(), 3);
459 assert!(t.flush().is_ok());
460
461 expected.clear();
462 expected.write_all(&[0x00, 0x00, 0x00, 0x03]).unwrap(); // message size
463 expected.extend_from_slice(&second_message);
464
465 // check the flushed bytes
466 assert_eq!(t.channel.write_bytes(), expected);
467 }
Allen George8b96bfb2016-11-02 08:01:08 -0400468}