userver: userver/utest/port_reservation.hpp Source File
Loading...
Searching...
No Matches
port_reservation.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utest/port_reservation.hpp
4/// @brief @copybrief utest::PortReservation
5
6#include <chrono>
7#include <cstdint>
8#include <optional>
9
10#include <userver/fs/blocking/file_descriptor.hpp>
11
12USERVER_NAMESPACE_BEGIN
13
14namespace utest {
15
16/// Socket settings for a port reservation.
18 /// Address family of the reserved socket.
19 enum class IpVersion : std::uint8_t {
20 kV4, ///< IPv4.
21 kV6, ///< IPv6.
22 };
23
24 /// Transport protocol of the reserved socket.
25 enum class Protocol : std::uint8_t {
26 kTcp, ///< TCP.
27 kUdp, ///< UDP.
28 };
29
30 /// Address family.
32
33 /// Transport protocol.
35
36 /// Nonzero port to reserve. Otherwise the OS assigns a port.
37 /// Parallel test runs in CI are likely to contend for the same fixed port.
38 /// Use this option only as a last resort when the subsystem under test does not support configuring its port.
39 std::optional<std::uint16_t> fixed_port{};
40
41 /// How long to wait for a fixed port.
42 std::chrono::milliseconds timeout{std::chrono::seconds{30}};
43};
44
45/// @ingroup userver_utest
46/// @brief Owns a socket bound to a port on an IPv4 or IPv6 loopback address.
47/// Keep the reservation alive until the consumer has duplicated the descriptor.
48class PortReservation final {
49public:
50 using Options = PortReservationOptions;
51 using IpVersion = Options::IpVersion;
52 using Protocol = Options::Protocol;
53
54 /// Binds the socket without enabling port sharing.
55 /// For a fixed port, this can block the calling thread until the port becomes available.
56 /// @throws std::system_error If binding fails or the fixed port remains busy until the timeout.
57 /// @throws std::invalid_argument If the fixed port is zero.
58 explicit PortReservation(Options options = {});
59
60 PortReservation(const PortReservation&) = delete;
61 PortReservation(PortReservation&&) noexcept = default;
62 PortReservation& operator=(const PortReservation&) = delete;
63 PortReservation& operator=(PortReservation&&) noexcept = default;
64
65 /// Returns whether the reservation still owns its socket.
66 bool IsValid() const noexcept;
67
68 /// Returns a borrowed descriptor. Requires a valid reservation. The caller must not close it.
69 int GetNativeFd() const;
70
71 /// Transfers ownership of the bound descriptor to the caller and invalidates this reservation.
72 /// Requires a valid reservation.
73 [[nodiscard]] int ReleaseNativeFd() &&;
74
75 /// Returns the assigned port. Requires a reservation that still owns its socket.
76 std::uint16_t GetPort() const;
77
78private:
79 fs::blocking::FileDescriptor fd_;
80};
81
82} // namespace utest
83
84USERVER_NAMESPACE_END