flat_stream.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. #ifndef BHO_BEAST_CORE_FLAT_STREAM_HPP
  10. #define BHO_BEAST_CORE_FLAT_STREAM_HPP
  11. #include <asio2/bho/beast/core/detail/config.hpp>
  12. #include <asio2/bho/beast/core/error.hpp>
  13. #include <asio2/bho/beast/core/flat_buffer.hpp>
  14. #include <asio2/bho/beast/core/stream_traits.hpp>
  15. #include <asio2/bho/beast/core/detail/flat_stream.hpp>
  16. #include <asio/async_result.hpp>
  17. #include <cstdlib>
  18. #include <utility>
  19. namespace bho {
  20. namespace beast {
  21. /** Stream wrapper to improve write performance.
  22. This wrapper flattens writes for buffer sequences having length
  23. greater than 1 and total size below a predefined amount, using
  24. a dynamic memory allocation. It is primarily designed to overcome
  25. a performance limitation of the current version of `net::ssl::stream`,
  26. which does not use OpenSSL's scatter/gather interface for its
  27. low-level read some and write some operations.
  28. It is normally not necessary to use this class directly if you
  29. are already using @ref ssl_stream. The following examples shows
  30. how to use this class with the ssl stream that comes with
  31. networking:
  32. @par Example
  33. To use the @ref flat_stream template with SSL streams, declare
  34. a variable of the correct type. Parameters passed to the constructor
  35. will be forwarded to the next layer's constructor:
  36. @code
  37. flat_stream<net::ssl::stream<ip::tcp::socket>> fs{ioc, ctx};
  38. @endcode
  39. Alternatively you can write
  40. @code
  41. ssl::stream<ip::tcp::socket> ss{ioc, ctx};
  42. flat_stream<net::ssl::stream<ip::tcp::socket>&> fs{ss};
  43. @endcode
  44. The resulting stream may be passed to any stream algorithms which
  45. operate on synchronous or asynchronous read or write streams,
  46. examples include:
  47. @li `net::read`, `net::async_read`
  48. @li `net::write`, `net::async_write`
  49. @li `net::read_until`, `net::async_read_until`
  50. The stream may also be used as a template parameter in other
  51. stream wrappers, such as for websocket:
  52. @code
  53. websocket::stream<flat_stream<net::ssl::stream<ip::tcp::socket>>> ws{ioc, ctx};
  54. @endcode
  55. @tparam NextLayer The type representing the next layer, to which
  56. data will be read and written during operations. For synchronous
  57. operations, the type must support the @b SyncStream concept. For
  58. asynchronous operations, the type must support the @b AsyncStream
  59. concept. This type will usually be some variation of
  60. `net::ssl::stream`.
  61. @par Concepts
  62. @li SyncStream
  63. @li AsyncStream
  64. @see
  65. @li https://github.com/boostorg/asio/issues/100
  66. @li https://github.com/boostorg/beast/issues/1108
  67. @li https://stackoverflow.com/questions/38198638/openssl-ssl-write-from-multiple-buffers-ssl-writev
  68. @li https://stackoverflow.com/questions/50026167/performance-drop-on-port-from-beast-1-0-0-b66-to-boost-1-67-0-beast
  69. */
  70. template<class NextLayer>
  71. class flat_stream
  72. #if ! BHO_BEAST_DOXYGEN
  73. : private detail::flat_stream_base
  74. #endif
  75. {
  76. NextLayer stream_;
  77. flat_buffer buffer_;
  78. BHO_STATIC_ASSERT(has_get_executor<NextLayer>::value);
  79. struct ops;
  80. template<class ConstBufferSequence>
  81. std::size_t
  82. stack_write_some(
  83. std::size_t size,
  84. ConstBufferSequence const& buffers,
  85. error_code& ec);
  86. public:
  87. /// The type of the next layer.
  88. using next_layer_type =
  89. typename std::remove_reference<NextLayer>::type;
  90. /// The type of the executor associated with the object.
  91. using executor_type = beast::executor_type<next_layer_type>;
  92. flat_stream(flat_stream&&) = default;
  93. flat_stream(flat_stream const&) = default;
  94. flat_stream& operator=(flat_stream&&) = default;
  95. flat_stream& operator=(flat_stream const&) = default;
  96. /** Destructor
  97. The treatment of pending operations will be the same as that
  98. of the next layer.
  99. */
  100. ~flat_stream() = default;
  101. /** Constructor
  102. Arguments, if any, are forwarded to the next layer's constructor.
  103. */
  104. template<class... Args>
  105. explicit
  106. flat_stream(Args&&... args);
  107. //--------------------------------------------------------------------------
  108. /** Get the executor associated with the object.
  109. This function may be used to obtain the executor object that the
  110. stream uses to dispatch handlers for asynchronous operations.
  111. @return A copy of the executor that stream will use to dispatch handlers.
  112. */
  113. executor_type
  114. get_executor() noexcept
  115. {
  116. return stream_.get_executor();
  117. }
  118. /** Get a reference to the next layer
  119. This function returns a reference to the next layer
  120. in a stack of stream layers.
  121. @return A reference to the next layer in the stack of
  122. stream layers.
  123. */
  124. next_layer_type&
  125. next_layer() noexcept
  126. {
  127. return stream_;
  128. }
  129. /** Get a reference to the next layer
  130. This function returns a reference to the next layer in a
  131. stack of stream layers.
  132. @return A reference to the next layer in the stack of
  133. stream layers.
  134. */
  135. next_layer_type const&
  136. next_layer() const noexcept
  137. {
  138. return stream_;
  139. }
  140. //--------------------------------------------------------------------------
  141. /** Read some data from the stream.
  142. This function is used to read data from the stream. The function call will
  143. block until one or more bytes of data has been read successfully, or until
  144. an error occurs.
  145. @param buffers The buffers into which the data will be read.
  146. @returns The number of bytes read.
  147. @throws asio::system_error Thrown on failure.
  148. @note The `read_some` operation may not read all of the requested number of
  149. bytes. Consider using the function `net::read` if you need to ensure
  150. that the requested amount of data is read before the blocking operation
  151. completes.
  152. */
  153. template<class MutableBufferSequence>
  154. std::size_t
  155. read_some(MutableBufferSequence const& buffers);
  156. /** Read some data from the stream.
  157. This function is used to read data from the stream. The function call will
  158. block until one or more bytes of data has been read successfully, or until
  159. an error occurs.
  160. @param buffers The buffers into which the data will be read.
  161. @param ec Set to indicate what error occurred, if any.
  162. @returns The number of bytes read.
  163. @note The `read_some` operation may not read all of the requested number of
  164. bytes. Consider using the function `net::read` if you need to ensure
  165. that the requested amount of data is read before the blocking operation
  166. completes.
  167. */
  168. template<class MutableBufferSequence>
  169. std::size_t
  170. read_some(
  171. MutableBufferSequence const& buffers,
  172. error_code& ec);
  173. /** Start an asynchronous read.
  174. This function is used to asynchronously read one or more bytes of data from
  175. the stream. The function call always returns immediately.
  176. @param buffers The buffers into which the data will be read. Although the
  177. buffers object may be copied as necessary, ownership of the underlying
  178. buffers is retained by the caller, which must guarantee that they remain
  179. valid until the handler is called.
  180. @param handler The completion handler to invoke when the operation
  181. completes. The implementation takes ownership of the handler by
  182. performing a decay-copy. The equivalent function signature of
  183. the handler must be:
  184. @code
  185. void handler(
  186. error_code const& error, // Result of operation.
  187. std::size_t bytes_transferred // Number of bytes read.
  188. );
  189. @endcode
  190. If the handler has an associated immediate executor,
  191. an immediate completion will be dispatched to it.
  192. Otherwise, the handler will not be invoked from within
  193. this function. Invocation of the handler will be performed
  194. by dispatching to the immediate executor. If no
  195. immediate executor is specified, this is equivalent
  196. to using `net::post`.
  197. @note The `read_some` operation may not read all of the requested number of
  198. bytes. Consider using the function `net::async_read` if you need
  199. to ensure that the requested amount of data is read before the asynchronous
  200. operation completes.
  201. */
  202. template<
  203. class MutableBufferSequence,
  204. BHO_BEAST_ASYNC_TPARAM2 ReadHandler =
  205. net::default_completion_token_t<executor_type>>
  206. BHO_BEAST_ASYNC_RESULT2(ReadHandler)
  207. async_read_some(
  208. MutableBufferSequence const& buffers,
  209. ReadHandler&& handler =
  210. net::default_completion_token_t<executor_type>{});
  211. /** Write some data to the stream.
  212. This function is used to write data on the stream. The function call will
  213. block until one or more bytes of data has been written successfully, or
  214. until an error occurs.
  215. @param buffers The data to be written.
  216. @returns The number of bytes written.
  217. @throws asio::system_error Thrown on failure.
  218. @note The `write_some` operation may not transmit all of the data to the
  219. peer. Consider using the function `net::write` if you need to
  220. ensure that all data is written before the blocking operation completes.
  221. */
  222. template<class ConstBufferSequence>
  223. std::size_t
  224. write_some(ConstBufferSequence const& buffers);
  225. /** Write some data to the stream.
  226. This function is used to write data on the stream. The function call will
  227. block until one or more bytes of data has been written successfully, or
  228. until an error occurs.
  229. @param buffers The data to be written.
  230. @param ec Set to indicate what error occurred, if any.
  231. @returns The number of bytes written.
  232. @note The `write_some` operation may not transmit all of the data to the
  233. peer. Consider using the function `net::write` if you need to
  234. ensure that all data is written before the blocking operation completes.
  235. */
  236. template<class ConstBufferSequence>
  237. std::size_t
  238. write_some(
  239. ConstBufferSequence const& buffers,
  240. error_code& ec);
  241. /** Start an asynchronous write.
  242. This function is used to asynchronously write one or more bytes of data to
  243. the stream. The function call always returns immediately.
  244. @param buffers The data to be written to the stream. Although the buffers
  245. object may be copied as necessary, ownership of the underlying buffers is
  246. retained by the caller, which must guarantee that they remain valid until
  247. the handler is called.
  248. @param handler The completion handler to invoke when the operation
  249. completes. The implementation takes ownership of the handler by
  250. performing a decay-copy. The equivalent function signature of
  251. the handler must be:
  252. @code
  253. void handler(
  254. error_code const& ec, // Result of operation.
  255. std::size_t bytes_transferred // Number of bytes written.
  256. );
  257. @endcode
  258. If the handler has an associated immediate executor,
  259. an immediate completion will be dispatched to it.
  260. Otherwise, the handler will not be invoked from within
  261. this function. Invocation of the handler will be performed
  262. by dispatching to the immediate executor. If no
  263. immediate executor is specified, this is equivalent
  264. to using `net::post`.
  265. @note The `async_write_some` operation may not transmit all of the data to
  266. the peer. Consider using the function `net::async_write` if you need
  267. to ensure that all data is written before the asynchronous operation completes.
  268. */
  269. template<
  270. class ConstBufferSequence,
  271. BHO_BEAST_ASYNC_TPARAM2 WriteHandler =
  272. net::default_completion_token_t<executor_type>>
  273. BHO_BEAST_ASYNC_RESULT2(WriteHandler)
  274. async_write_some(
  275. ConstBufferSequence const& buffers,
  276. WriteHandler&& handler =
  277. net::default_completion_token_t<executor_type>{});
  278. };
  279. } // beast
  280. } // bho
  281. #include <asio2/bho/beast/core/impl/flat_stream.hpp>
  282. #endif