stream.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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 BOOST_BEAST_TEST_STREAM_HPP
  10. #define BOOST_BEAST_TEST_STREAM_HPP
  11. #include <boost/beast/core/detail/config.hpp>
  12. #include <boost/beast/core/bind_handler.hpp>
  13. #include <boost/beast/core/flat_buffer.hpp>
  14. #include <boost/beast/core/role.hpp>
  15. #include <boost/beast/core/string.hpp>
  16. #include <boost/beast/_experimental/test/fail_count.hpp>
  17. #include <boost/asio/async_result.hpp>
  18. #include <boost/asio/buffer.hpp>
  19. #include <boost/asio/error.hpp>
  20. #include <boost/asio/executor_work_guard.hpp>
  21. #include <boost/asio/io_context.hpp>
  22. #include <boost/asio/post.hpp>
  23. #include <boost/assert.hpp>
  24. #include <boost/shared_ptr.hpp>
  25. #include <boost/weak_ptr.hpp>
  26. #include <boost/throw_exception.hpp>
  27. #include <condition_variable>
  28. #include <limits>
  29. #include <memory>
  30. #include <mutex>
  31. #include <utility>
  32. #if ! BOOST_BEAST_DOXYGEN
  33. namespace boost {
  34. namespace asio {
  35. namespace ssl {
  36. template<typename> class stream;
  37. } // ssl
  38. } // asio
  39. } // boost
  40. #endif
  41. namespace boost {
  42. namespace beast {
  43. namespace test {
  44. /** A two-way socket useful for unit testing
  45. An instance of this class simulates a traditional socket,
  46. while also providing features useful for unit testing.
  47. Each endpoint maintains an independent buffer called
  48. the input area. Writes from one endpoint append data
  49. to the peer's pending input area. When an endpoint performs
  50. a read and data is present in the input area, the data is
  51. delivered to the blocking or asynchronous operation. Otherwise
  52. the operation is blocked or deferred until data is made
  53. available, or until the endpoints become disconnected.
  54. These streams may be used anywhere an algorithm accepts a
  55. reference to a synchronous or asynchronous read or write
  56. stream. It is possible to use a test stream in a call to
  57. `net::read_until`, or in a call to
  58. @ref boost::beast::http::async_write for example.
  59. As with Boost.Asio I/O objects, a @ref stream constructs
  60. with a reference to the `net::io_context` to use for
  61. handling asynchronous I/O. For asynchronous operations, the
  62. stream follows the same rules as a traditional asio socket
  63. with respect to how completion handlers for asynchronous
  64. operations are performed.
  65. To facilitate testing, these streams support some additional
  66. features:
  67. @li The input area, represented by a @ref beast::basic_flat_buffer,
  68. may be directly accessed by the caller to inspect the contents
  69. before or after the remote endpoint writes data. This allows
  70. a unit test to verify that the received data matches.
  71. @li Data may be manually appended to the input area. This data
  72. will delivered in the next call to
  73. @ref stream::read_some or @ref stream::async_read_some.
  74. This allows predefined test vectors to be set up for testing
  75. read algorithms.
  76. @li The stream may be constructed with a fail count. The
  77. stream will eventually fail with a predefined error after a
  78. certain number of operations, where the number of operations
  79. is controlled by the test. When a test loops over a range of
  80. operation counts, it is possible to exercise every possible
  81. point of failure in the algorithm being tested. When used
  82. correctly the technique allows the tests to reach a high
  83. percentage of code coverage.
  84. @par Thread Safety
  85. @e Distinct @e objects: Safe.@n
  86. @e Shared @e objects: Unsafe.
  87. The application must also ensure that all asynchronous
  88. operations are performed within the same implicit or explicit strand.
  89. @par Concepts
  90. @li <em>SyncReadStream</em>
  91. @li <em>SyncWriteStream</em>
  92. @li <em>AsyncReadStream</em>
  93. @li <em>AsyncWriteStream</em>
  94. */
  95. class stream
  96. {
  97. struct state;
  98. boost::shared_ptr<state> in_;
  99. boost::weak_ptr<state> out_;
  100. enum class status
  101. {
  102. ok,
  103. eof,
  104. };
  105. class service;
  106. struct service_impl;
  107. struct read_op_base
  108. {
  109. virtual ~read_op_base() = default;
  110. virtual void operator()(error_code ec) = 0;
  111. };
  112. struct state
  113. {
  114. friend class stream;
  115. net::io_context& ioc;
  116. boost::weak_ptr<service_impl> wp;
  117. std::mutex m;
  118. flat_buffer b;
  119. std::condition_variable cv;
  120. std::unique_ptr<read_op_base> op;
  121. status code = status::ok;
  122. fail_count* fc = nullptr;
  123. std::size_t nread = 0;
  124. std::size_t nwrite = 0;
  125. std::size_t read_max =
  126. (std::numeric_limits<std::size_t>::max)();
  127. std::size_t write_max =
  128. (std::numeric_limits<std::size_t>::max)();
  129. BOOST_BEAST_DECL
  130. state(
  131. net::io_context& ioc_,
  132. boost::weak_ptr<service_impl> wp_,
  133. fail_count* fc_);
  134. BOOST_BEAST_DECL
  135. ~state();
  136. BOOST_BEAST_DECL
  137. void
  138. remove() noexcept;
  139. BOOST_BEAST_DECL
  140. void
  141. notify_read();
  142. BOOST_BEAST_DECL
  143. void
  144. cancel_read();
  145. };
  146. template<class Handler, class Buffers>
  147. class read_op;
  148. struct run_read_op;
  149. struct run_write_op;
  150. BOOST_BEAST_DECL
  151. static
  152. void
  153. initiate_read(
  154. boost::shared_ptr<state> const& in,
  155. std::unique_ptr<read_op_base>&& op,
  156. std::size_t buf_size);
  157. #if ! BOOST_BEAST_DOXYGEN
  158. // boost::asio::ssl::stream needs these
  159. // DEPRECATED
  160. template<class>
  161. friend class boost::asio::ssl::stream;
  162. // DEPRECATED
  163. using lowest_layer_type = stream;
  164. // DEPRECATED
  165. lowest_layer_type&
  166. lowest_layer() noexcept
  167. {
  168. return *this;
  169. }
  170. // DEPRECATED
  171. lowest_layer_type const&
  172. lowest_layer() const noexcept
  173. {
  174. return *this;
  175. }
  176. #endif
  177. public:
  178. using buffer_type = flat_buffer;
  179. /** Destructor
  180. If an asynchronous read operation is pending, it will
  181. simply be discarded with no notification to the completion
  182. handler.
  183. If a connection is established while the stream is destroyed,
  184. the peer will see the error `net::error::connection_reset`
  185. when performing any reads or writes.
  186. */
  187. BOOST_BEAST_DECL
  188. ~stream();
  189. /** Move Constructor
  190. Moving the stream while asynchronous operations are pending
  191. results in undefined behavior.
  192. */
  193. BOOST_BEAST_DECL
  194. stream(stream&& other);
  195. /** Move Assignment
  196. Moving the stream while asynchronous operations are pending
  197. results in undefined behavior.
  198. */
  199. BOOST_BEAST_DECL
  200. stream&
  201. operator=(stream&& other);
  202. /** Construct a stream
  203. The stream will be created in a disconnected state.
  204. @param ioc The `io_context` object that the stream will use to
  205. dispatch handlers for any asynchronous operations.
  206. */
  207. BOOST_BEAST_DECL
  208. explicit
  209. stream(net::io_context& ioc);
  210. /** Construct a stream
  211. The stream will be created in a disconnected state.
  212. @param ioc The `io_context` object that the stream will use to
  213. dispatch handlers for any asynchronous operations.
  214. @param fc The @ref fail_count to associate with the stream.
  215. Each I/O operation performed on the stream will increment the
  216. fail count. When the fail count reaches its internal limit,
  217. a simulated failure error will be raised.
  218. */
  219. BOOST_BEAST_DECL
  220. stream(
  221. net::io_context& ioc,
  222. fail_count& fc);
  223. /** Construct a stream
  224. The stream will be created in a disconnected state.
  225. @param ioc The `io_context` object that the stream will use to
  226. dispatch handlers for any asynchronous operations.
  227. @param s A string which will be appended to the input area, not
  228. including the null terminator.
  229. */
  230. BOOST_BEAST_DECL
  231. stream(
  232. net::io_context& ioc,
  233. string_view s);
  234. /** Construct a stream
  235. The stream will be created in a disconnected state.
  236. @param ioc The `io_context` object that the stream will use to
  237. dispatch handlers for any asynchronous operations.
  238. @param fc The @ref fail_count to associate with the stream.
  239. Each I/O operation performed on the stream will increment the
  240. fail count. When the fail count reaches its internal limit,
  241. a simulated failure error will be raised.
  242. @param s A string which will be appended to the input area, not
  243. including the null terminator.
  244. */
  245. BOOST_BEAST_DECL
  246. stream(
  247. net::io_context& ioc,
  248. fail_count& fc,
  249. string_view s);
  250. /// Establish a connection
  251. BOOST_BEAST_DECL
  252. void
  253. connect(stream& remote);
  254. /// The type of the executor associated with the object.
  255. using executor_type =
  256. net::io_context::executor_type;
  257. /// Return the executor associated with the object.
  258. executor_type
  259. get_executor() noexcept
  260. {
  261. return in_->ioc.get_executor();
  262. };
  263. /// Set the maximum number of bytes returned by read_some
  264. void
  265. read_size(std::size_t n) noexcept
  266. {
  267. in_->read_max = n;
  268. }
  269. /// Set the maximum number of bytes returned by write_some
  270. void
  271. write_size(std::size_t n) noexcept
  272. {
  273. in_->write_max = n;
  274. }
  275. /// Direct input buffer access
  276. buffer_type&
  277. buffer() noexcept
  278. {
  279. return in_->b;
  280. }
  281. /// Returns a string view representing the pending input data
  282. BOOST_BEAST_DECL
  283. string_view
  284. str() const;
  285. /// Appends a string to the pending input data
  286. BOOST_BEAST_DECL
  287. void
  288. append(string_view s);
  289. /// Clear the pending input area
  290. BOOST_BEAST_DECL
  291. void
  292. clear();
  293. /// Return the number of reads
  294. std::size_t
  295. nread() const noexcept
  296. {
  297. return in_->nread;
  298. }
  299. /// Return the number of writes
  300. std::size_t
  301. nwrite() const noexcept
  302. {
  303. return in_->nwrite;
  304. }
  305. /** Close the stream.
  306. The other end of the connection will see
  307. `error::eof` after reading all the remaining data.
  308. */
  309. BOOST_BEAST_DECL
  310. void
  311. close();
  312. /** Close the other end of the stream.
  313. This end of the connection will see
  314. `error::eof` after reading all the remaining data.
  315. */
  316. BOOST_BEAST_DECL
  317. void
  318. close_remote();
  319. /** Read some data from the stream.
  320. This function is used to read data from the stream. The function call will
  321. block until one or more bytes of data has been read successfully, or until
  322. an error occurs.
  323. @param buffers The buffers into which the data will be read.
  324. @returns The number of bytes read.
  325. @throws boost::system::system_error Thrown on failure.
  326. @note The `read_some` operation may not read all of the requested number of
  327. bytes. Consider using the function `net::read` if you need to ensure
  328. that the requested amount of data is read before the blocking operation
  329. completes.
  330. */
  331. template<class MutableBufferSequence>
  332. std::size_t
  333. read_some(MutableBufferSequence const& buffers);
  334. /** Read some data from the stream.
  335. This function is used to read data from the stream. The function call will
  336. block until one or more bytes of data has been read successfully, or until
  337. an error occurs.
  338. @param buffers The buffers into which the data will be read.
  339. @param ec Set to indicate what error occurred, if any.
  340. @returns The number of bytes read.
  341. @note The `read_some` operation may not read all of the requested number of
  342. bytes. Consider using the function `net::read` if you need to ensure
  343. that the requested amount of data is read before the blocking operation
  344. completes.
  345. */
  346. template<class MutableBufferSequence>
  347. std::size_t
  348. read_some(MutableBufferSequence const& buffers,
  349. error_code& ec);
  350. /** Start an asynchronous read.
  351. This function is used to asynchronously read one or more bytes of data from
  352. the stream. The function call always returns immediately.
  353. @param buffers The buffers into which the data will be read. Although the
  354. buffers object may be copied as necessary, ownership of the underlying
  355. buffers is retained by the caller, which must guarantee that they remain
  356. valid until the handler is called.
  357. @param handler The completion handler to invoke when the operation
  358. completes. The implementation takes ownership of the handler by
  359. performing a decay-copy. The equivalent function signature of
  360. the handler must be:
  361. @code
  362. void handler(
  363. error_code const& ec, // Result of operation.
  364. std::size_t bytes_transferred // Number of bytes read.
  365. );
  366. @endcode
  367. Regardless of whether the asynchronous operation completes
  368. immediately or not, the handler will not be invoked from within
  369. this function. Invocation of the handler will be performed in a
  370. manner equivalent to using `net::post`.
  371. @note The `async_read_some` operation may not read all of the requested number of
  372. bytes. Consider using the function `net::async_read` if you need
  373. to ensure that the requested amount of data is read before the asynchronous
  374. operation completes.
  375. */
  376. template<class MutableBufferSequence, class ReadHandler>
  377. BOOST_BEAST_ASYNC_RESULT2(ReadHandler)
  378. async_read_some(MutableBufferSequence const& buffers,
  379. ReadHandler&& handler);
  380. /** Write some data to the stream.
  381. This function is used to write data on the stream. The function call will
  382. block until one or more bytes of data has been written successfully, or
  383. until an error occurs.
  384. @param buffers The data to be written.
  385. @returns The number of bytes written.
  386. @throws boost::system::system_error Thrown on failure.
  387. @note The `write_some` operation may not transmit all of the data to the
  388. peer. Consider using the function `net::write` if you need to
  389. ensure that all data is written before the blocking operation completes.
  390. */
  391. template<class ConstBufferSequence>
  392. std::size_t
  393. write_some(ConstBufferSequence const& buffers);
  394. /** Write some data to the stream.
  395. This function is used to write data on the stream. The function call will
  396. block until one or more bytes of data has been written successfully, or
  397. until an error occurs.
  398. @param buffers The data to be written.
  399. @param ec Set to indicate what error occurred, if any.
  400. @returns The number of bytes written.
  401. @note The `write_some` operation may not transmit all of the data to the
  402. peer. Consider using the function `net::write` if you need to
  403. ensure that all data is written before the blocking operation completes.
  404. */
  405. template<class ConstBufferSequence>
  406. std::size_t
  407. write_some(
  408. ConstBufferSequence const& buffers, error_code& ec);
  409. /** Start an asynchronous write.
  410. This function is used to asynchronously write one or more bytes of data to
  411. the stream. The function call always returns immediately.
  412. @param buffers The data to be written to the stream. Although the buffers
  413. object may be copied as necessary, ownership of the underlying buffers is
  414. retained by the caller, which must guarantee that they remain valid until
  415. the handler is called.
  416. @param handler The completion handler to invoke when the operation
  417. completes. The implementation takes ownership of the handler by
  418. performing a decay-copy. The equivalent function signature of
  419. the handler must be:
  420. @code
  421. void handler(
  422. error_code const& ec, // Result of operation.
  423. std::size_t bytes_transferred // Number of bytes written.
  424. );
  425. @endcode
  426. Regardless of whether the asynchronous operation completes
  427. immediately or not, the handler will not be invoked from within
  428. this function. Invocation of the handler will be performed in a
  429. manner equivalent to using `net::post`.
  430. @note The `async_write_some` operation may not transmit all of the data to
  431. the peer. Consider using the function `net::async_write` if you need
  432. to ensure that all data is written before the asynchronous operation completes.
  433. */
  434. template<class ConstBufferSequence, class WriteHandler>
  435. BOOST_BEAST_ASYNC_RESULT2(WriteHandler)
  436. async_write_some(ConstBufferSequence const& buffers,
  437. WriteHandler&& handler);
  438. #if ! BOOST_BEAST_DOXYGEN
  439. friend
  440. BOOST_BEAST_DECL
  441. void
  442. teardown(
  443. role_type,
  444. stream& s,
  445. boost::system::error_code& ec);
  446. template<class TeardownHandler>
  447. friend
  448. BOOST_BEAST_DECL
  449. void
  450. async_teardown(
  451. role_type role,
  452. stream& s,
  453. TeardownHandler&& handler);
  454. #endif
  455. };
  456. #if ! BOOST_BEAST_DOXYGEN
  457. inline
  458. void
  459. beast_close_socket(stream& s)
  460. {
  461. s.close();
  462. }
  463. #endif
  464. #if BOOST_BEAST_DOXYGEN
  465. /** Return a new stream connected to the given stream
  466. @param to The stream to connect to.
  467. @param args Optional arguments forwarded to the new stream's constructor.
  468. @return The new, connected stream.
  469. */
  470. template<class... Args>
  471. stream
  472. connect(stream& to, Args&&... args);
  473. #else
  474. BOOST_BEAST_DECL
  475. stream
  476. connect(stream& to);
  477. BOOST_BEAST_DECL
  478. void
  479. connect(stream& s1, stream& s2);
  480. template<class Arg1, class... ArgN>
  481. stream
  482. connect(stream& to, Arg1&& arg1, ArgN&&... argn);
  483. #endif
  484. } // test
  485. } // beast
  486. } // boost
  487. #include <boost/beast/_experimental/test/impl/stream.hpp>
  488. #ifdef BOOST_BEAST_HEADER_ONLY
  489. #include <boost/beast/_experimental/test/impl/stream.ipp>
  490. #endif
  491. #endif