userver: userver/server/http/http_response.hpp Source File
Loading...
Searching...
No Matches
http_response.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/server/http/http_response.hpp
4/// @brief @copybrief server::http::HttpResponse
5
6#include <chrono>
7#include <limits>
8#include <memory>
9#include <string>
10#include <string_view>
11#include <variant>
12
13#include <userver/engine/single_consumer_event.hpp>
14#include <userver/http/content_type.hpp>
15#include <userver/http/header_map.hpp>
16#include <userver/server/http/http_response_cookie.hpp>
17#include <userver/utils/impl/projecting_view.hpp>
18#include <userver/utils/str_icase.hpp>
19
20#include "http_status.hpp"
21
22USERVER_NAMESPACE_BEGIN
23
24namespace server::request {
25class ResponseDataAccounter;
26} // namespace server::request
27
28namespace server::http {
29
30// RFC 9110 states that in case of missing Content-Type it may be assumed to be
31// application/octet-stream.
32//
33// text/plain was our first guess, but we should provide an encoding with that
34// type, which we do not know for sure. "application/octet-stream" has no
35// charset https://www.iana.org/assignments/media-types/application/octet-stream
36inline constexpr std::string_view kDefaultContentType = "application/octet-stream";
37
38class Http2ResponseWriter;
39class HttpResponseImpl;
40
41namespace impl {
42
43class ChunkStorage final {
44public:
45 ChunkStorage() = default;
46 explicit ChunkStorage(std::string data);
47 explicit ChunkStorage(std::shared_ptr<const std::string> data);
48
49 ChunkStorage(const ChunkStorage&) = delete;
50 ChunkStorage(ChunkStorage&&) noexcept = default;
51 ChunkStorage& operator=(const ChunkStorage&) = delete;
52 ChunkStorage& operator=(ChunkStorage&&) noexcept = default;
53
54 bool Empty() const noexcept;
55 std::size_t Size() const noexcept;
56 std::string_view View() const noexcept;
57 const std::string& AsString() const;
58
59private:
60 std::variant<std::string, std::shared_ptr<const std::string>> storage_{};
61};
62
63} // namespace impl
64
65class HttpRequest;
66
67/// @brief HTTP Response data
69public:
70 HttpResponse(const HttpResponse&) = delete;
71 HttpResponse(HttpResponse&&) = delete;
72
73 using HeadersMap = USERVER_NAMESPACE::http::headers::HeaderMap;
74
75 using HeadersMapKeys = decltype(utils::impl::MakeKeysView(HeadersMap()));
76
77 using CookiesMap = Cookie::CookiesMap;
78
79 using CookiesMapKeys = decltype(utils::impl::MakeKeysView(CookiesMap()));
80
81 void SetData(std::string data);
82 /// @brief Sets response body without copying, keeping @a data alive.
83 /// Useful for serving cached static content.
84 void SetSharedData(std::shared_ptr<const std::string> data);
85 const std::string& GetData() const;
86
87 /// @brief Add a new response header or rewrite an existing one.
88 /// @returns true if the header was set. Returns false if headers
89 /// were already sent for stream'ed response and the new header was not set,
90 /// or the header overrides system header.
91 bool SetHeader(std::string name, std::string value);
92
93 /// @brief Add a new response header or rewrite an existing one.
94 /// @returns true if the header was set. Returns false if headers
95 /// were already sent for stream'ed response and the new header was not set,
96 /// or the header overrides system header.
97 bool SetHeader(std::string_view name, std::string value);
98
99 /// @overload
100 bool SetHeader(const USERVER_NAMESPACE::http::headers::PredefinedHeader& header, std::string value);
101
102 /// @brief Add or rewrite the Content-Type header.
103 void SetContentType(const USERVER_NAMESPACE::http::ContentType& type);
104
105 /// @brief Add or rewrite the Content-Encoding header.
106 void SetContentEncoding(std::string encoding);
107
108 /// @brief Set the HTTP response status code.
109 /// @returns true if the status was set. Returns false if headers
110 /// were already sent for stream'ed response and the new status was not set.
111 bool SetStatus(HttpStatus status) noexcept;
112
113 /// @brief Set the throttle reason in tracing and try to set the response headers.
114 /// The `X-YaTaxi-Ratelimited-By` header is controlled by the server's
115 /// `allow-set-response-ratelimited-by` static option and is disabled by default.
116 /// Set the option to true to enable the header. The option does not affect
117 /// the `X-YaTaxi-Ratelimit-Reason` header.
118 /// Header updates follow the restrictions of @ref server::http::HttpResponse::SetHeader.
119 /// After headers are committed, they remain unchanged, but the current span,
120 /// if any, is still tagged with the throttle reason.
121 void SetThrottleReason(std::string log_reason, std::string http_header_reason);
122
123 /// @brief Remove all headers from response, except system headers.
124 /// @returns true if the headers were cleared. Returns false if headers
125 /// were already sent for stream'ed response and the headers were not cleared.
127
128 /// @brief Sets a cookie if it was not set before.
129 void SetCookie(Cookie cookie);
130
131 /// @brief Remove all cookies from response.
133
134 /// @return HTTP response status
135 HttpStatus GetStatus() const noexcept { return status_; }
136
137 /// @return List of HTTP system headers names.
138 HeadersMapKeys GetSystemHeaderNames() const;
139
140 /// @return List of HTTP user headers names.
141 HeadersMapKeys GetUserHeaderNames() const;
142
143 /// @return Value of the header with case insensitive name header_name, or an
144 /// empty string if no such header.
145 const std::string& GetHeader(std::string_view header_name) const;
146 /// @overload
147 const std::string& GetHeader(const USERVER_NAMESPACE::http::headers::PredefinedHeader& header_name) const;
148
149 /// @return true if header with case insensitive name header_name exists,
150 /// false otherwise.
151 bool HasHeader(std::string_view header_name) const;
152 /// @overload
153 bool HasHeader(const USERVER_NAMESPACE::http::headers::PredefinedHeader& header_name) const;
154
155 /// @return List of cookies names.
156 CookiesMapKeys GetCookieNames() const;
157
158 /// @return Value of the cookie with case sensitive name cookie_name, or an
159 /// empty string if no such cookie exists.
160 const Cookie& GetCookie(std::string_view cookie_name) const;
161
162 void SetStatusServiceUnavailable() { SetStatus(HttpStatus::kServiceUnavailable); }
163 void SetStatusOk() { SetStatus(HttpStatus::kOk); }
164 void SetStatusNotFound() { SetStatus(HttpStatus::kNotFound); }
165
166 bool WaitForHeadersEnd();
167 void SetHeadersEnd();
168
169 /// @returns true if response headers were committed and cannot be changed.
170 [[nodiscard]] bool IsHeadersEnd() const noexcept { return headers_end_.IsReady(); }
171
172 [[nodiscard]] bool IsBodyStreamed() const noexcept { return is_stream_body_; }
173
174 [[nodiscard]] bool IsSent() const noexcept { return is_sent_; }
175
176protected:
177 HttpResponse(const HttpRequest& request, request::ResponseDataAccounter& data_accounter);
178 HttpResponse(
179 const HttpRequest& request,
180 request::ResponseDataAccounter& data_accounter,
181 std::chrono::steady_clock::time_point now,
182 utils::StrCaseHash hasher
183 );
184 ~HttpResponse() noexcept;
185
186private:
187 friend class HttpResponseImpl;
188 friend class Http2ResponseWriter;
189
190 void StoreData(impl::ChunkStorage data);
191
192 [[nodiscard]] bool IsHeadersMutable() const noexcept { return !headers_end_.IsReady(); }
193
194 static constexpr auto kUnset = std::chrono::steady_clock::time_point::min();
195
196 request::ResponseDataAccounter& accounter_;
197 impl::ChunkStorage data_;
198 std::chrono::steady_clock::time_point create_time_;
199 std::chrono::steady_clock::time_point ready_time_{kUnset};
200 std::size_t accounted_size_ = 0;
201 std::size_t bytes_sent_ = 0;
202 bool is_sent_ = false;
203
204 bool is_final_;
205 bool is_head_request_;
206 std::uint8_t http_major_;
207 std::uint8_t http_minor_;
208 HttpStatus status_ = HttpStatus::kOk;
209 HeadersMap system_headers_;
210 HeadersMap user_headers_;
211 CookiesMap cookies_;
212
213 bool is_stream_body_{false};
214 bool system_headers_ended_ = false;
215 bool allow_set_response_ratelimited_by_ = false;
216 engine::SingleConsumerEvent headers_end_{engine::SingleConsumerEvent::NoAutoReset()};
217};
218
219/// @brief Compatibility wrapper for @ref server::http::HttpResponse::SetThrottleReason.
220[[deprecated("Use HttpResponse::SetThrottleReason instead")]]
221void SetThrottleReason(http::HttpResponse& http_response, std::string log_reason, std::string http_header_reason);
222
223} // namespace server::http
224
225USERVER_NAMESPACE_END