stream.hpp 17 KB

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