1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
|
#include "request.h"
#include <library/cpp/http/client/fetch/codes.h>
#include <library/cpp/uri/location.h>
#include <util/string/ascii.h>
namespace NHttp {
static const ui64 URI_PARSE_FLAGS =
(NUri::TFeature::FeaturesRecommended | NUri::TFeature::FeatureConvertHostIDN | NUri::TFeature::FeatureEncodeExtendedDelim | NUri::TFeature::FeatureEncodePercent) & ~NUri::TFeature::FeatureHashBangToEscapedFragment;
/// Generates sequence of unique identifiers of requests.
static TAtomic RequestCounter = 0;
TFetchRequest::TRedirects::TRedirects(bool parseCookie) {
if (parseCookie) {
CookieStore.Reset(new NHttp::TCookieStore);
}
}
size_t TFetchRequest::TRedirects::Level() const {
return this->size();
}
void TFetchRequest::TRedirects::ParseCookies(const TString& url,
const THttpHeaders& headers) {
if (CookieStore) {
NUri::TUri uri;
if (uri.Parse(url, URI_PARSE_FLAGS) != NUri::TUri::ParsedOK) {
return;
}
if (!uri.IsValidGlobal()) {
return;
}
for (THttpHeaders::TConstIterator it = headers.Begin(); it != headers.End(); it++) {
if (AsciiEqualsIgnoreCase(it->Name(), TStringBuf("Set-Cookie"))) {
CookieStore->SetCookie(uri, it->Value());
}
}
}
}
TFetchRequest::TFetchRequest(const TString& url, const TFetchOptions& options)
: Url_(url)
, Options_(options)
, Id_(AtomicIncrement(RequestCounter))
, RetryAttempts_(options.RetryCount)
, RetryDelay_(options.RetryDelay)
, Cancel_(false)
, CurrentUrl_(url)
{
}
TFetchRequest::TFetchRequest(const TString& url, TVector<TString> headers, const TFetchOptions& options)
: TFetchRequest(url, options)
{
Headers_ = std::move(headers);
}
void TFetchRequest::Cancel() {
AtomicSet(Cancel_, 1);
}
NHttpFetcher::TRequestRef TFetchRequest::GetRequestImpl() const {
NHttpFetcher::TRequestRef req(new NHttpFetcher::TRequest(CurrentUrl_));
req->UnixSocketPath = Options_.UnixSocketPath;
req->Login = Options_.Login;
req->Password = Options_.Password;
req->OAuthToken = Options_.OAuthToken;
req->OnlyHeaders = Options_.OnlyHeaders;
req->CustomHost = Options_.CustomHost;
req->Method = Options_.Method;
req->OAuthToken = Options_.OAuthToken;
req->ContentType = Options_.ContentType;
req->PostData = Options_.PostData;
req->UserAgent = Options_.UserAgent;
req->ExtraHeaders.assign(Headers_.begin(), Headers_.end());
req->NeedDataCallback = OnPartialRead_;
req->Deadline = TInstant::Now() + Options_.Timeout;
if (Options_.ConnectTimeout) {
req->ConnectTimeout = Options_.ConnectTimeout;
}
if (Options_.MaxHeaderSize) {
req->MaxHeaderSize = Options_.MaxHeaderSize.GetRef();
}
if (Options_.MaxBodySize) {
req->MaxBodySize = Options_.MaxBodySize.GetRef();
}
if (Redirects_ && Redirects_->CookieStore) {
NUri::TUri uri;
if (uri.Parse(CurrentUrl_, URI_PARSE_FLAGS) == NUri::TUri::ParsedOK) {
if (TString cookies = Redirects_->CookieStore->GetCookieString(uri)) {
req->ExtraHeaders.push_back("Cookie: " + cookies + "\r\n");
}
}
}
return req;
}
bool TFetchRequest::IsValid() const {
auto g(Guard(Lock_));
return IsValidNoLock();
}
bool TFetchRequest::IsCancelled() const {
return AtomicGet(Cancel_);
}
bool TFetchRequest::GetForceReconnect() const {
return Options_.ForceReconnect;
}
NHttpFetcher::TResultRef TFetchRequest::MakeResult() const {
if (Exception_) {
std::rethrow_exception(Exception_);
}
return Result_;
}
void TFetchRequest::SetException(std::exception_ptr ptr) {
Exception_ = ptr;
}
void TFetchRequest::SetCallback(NHttpFetcher::TCallBack cb) {
Cb_ = cb;
}
void TFetchRequest::SetOnFail(TOnFail cb) {
OnFail_ = cb;
}
void TFetchRequest::SetOnRedirect(TOnRedirect cb) {
OnRedirect_ = cb;
}
void TFetchRequest::SetOnPartialRead(NHttpFetcher::TNeedDataCallback cb) {
OnPartialRead_ = cb;
}
bool TFetchRequest::WaitT(TDuration timeout) {
TCondVar c;
{
auto g(Guard(Lock_));
if (IsValidNoLock()) {
THolder<TWaitState> state(new TWaitState(&c));
Awaitings_.PushBack(state.Get());
if (!c.WaitT(Lock_, timeout)) {
AtomicSet(Cancel_, 1);
// Удаляем элемент из очереди ожидания в случае, если
// истёк установленный период времени.
state->Unlink();
return false;
}
}
}
return true;
}
bool TFetchRequest::IsValidNoLock() const {
return !Result_ && !Exception_ && !AtomicGet(Cancel_);
}
void TFetchRequest::Reply(NHttpFetcher::TResultRef result) {
NHttpFetcher::TCallBack cb;
{
auto g(Guard(Lock_));
cb.swap(Cb_);
Result_.Swap(result);
if (Redirects_) {
Result_->Redirects.assign(Redirects_->begin(), Redirects_->end());
}
}
if (cb) {
try {
cb(Result_);
} catch (...) {
SetException(std::current_exception());
}
}
{
auto g(Guard(Lock_));
while (!Awaitings_.Empty()) {
Awaitings_.PopFront()->Signal();
}
}
}
TDuration TFetchRequest::OnResponse(NHttpFetcher::TResultRef result) {
if (AtomicGet(Cancel_)) {
goto finish;
}
if (NHttpFetcher::IsRedirectCode(result->Code)) {
auto location = NUri::ResolveRedirectLocation(CurrentUrl_, result->Location);
if (!Redirects_) {
Redirects_.Reset(new TRedirects(true));
}
result->ResolvedUrl = location;
Redirects_->push_back(result);
if (Options_.UseCookie) {
Redirects_->ParseCookies(CurrentUrl_, result->Headers);
}
if (Redirects_->Level() < Options_.RedirectDepth) {
if (OnRedirect_) {
if (!OnRedirect_(CurrentUrl_, location)) {
goto finish;
}
}
CurrentUrl_ = location;
return TDuration::Zero();
}
} else if (!NHttpFetcher::IsSuccessCode(result->Code)) {
bool again = RetryAttempts_ > 0;
if (OnFail_ && !OnFail_(result)) {
again = false;
}
if (again) {
RetryAttempts_--;
return RetryDelay_;
}
}
finish:
Reply(result);
return TDuration::Zero();
}
}
|