summaryrefslogtreecommitdiffstats
path: root/yql/essentials/utils/fetch/fetch.cpp
blob: 4b0777e9feb3a889ec7833d9e0693b1c3dff022a (plain) (blame)
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
#include "fetch.h"

#include <yql/essentials/utils/log/log.h>

#include <library/cpp/openssl/io/stream.h>
#include <library/cpp/http/misc/httpcodes.h>
#include <library/cpp/charset/ci_string.h>

#include <util/network/socket.h>
#include <util/string/cast.h>
#include <util/generic/strbuf.h>

namespace NYql {

namespace {

THttpURL ParseURL(const TStringBuf addr, NUri::TParseFlags features) {
    THttpURL url;
    THttpURL::TParsedState parsedState = url.Parse(addr, features, nullptr, 65536);
    if (THttpURL::ParsedOK != parsedState) {
        ythrow yexception() << "Bad URL: \"" << addr << "\", " << HttpURLParsedStateToString(parsedState);
    }
    return url;
}

class TFetchResultImpl: public IFetchResult {
public:
    TFetchResultImpl(const THttpURL& url, const THttpHeaders& additionalHeaders, TDuration timeout) {
        TString host = url.Get(THttpURL::FieldHost);
        TString path = url.PrintS(THttpURL::FlagPath | THttpURL::FlagQuery);
        const char* p = url.Get(THttpURL::FieldPort);
        ui16 port = 80;
        bool https = false;

        if (url.Get(THttpURL::FieldScheme) == TStringBuf("https")) {
            port = 443;
            https = true;
        }

        if (p) {
            port = FromString<ui16>(p);
        }

        TString req;
        {
            TStringOutput rqs(req);
            TStringBuf userAgent = "User-Agent: Mozilla/5.0 (compatible; YQL/1.0)";

            IOutputStream::TPart request[] = {
                IOutputStream::TPart("GET ", 4),
                IOutputStream::TPart(path.data(), path.size()),
                IOutputStream::TPart(" HTTP/1.1", 9),
                IOutputStream::TPart::CrLf(),
                IOutputStream::TPart("Host: ", 6),
                IOutputStream::TPart(host.data(), host.size()),
                IOutputStream::TPart::CrLf(),
                IOutputStream::TPart(userAgent.data(), userAgent.size()),
                IOutputStream::TPart::CrLf(),
            };
            rqs.Write(request, Y_ARRAY_SIZE(request));
            if (!additionalHeaders.Empty()) {
                additionalHeaders.OutTo(&rqs);
            }
            rqs << "\r\n";
        }

        Socket_.Reset(new TSocket(TNetworkAddress(host, port), timeout));
        SocketInput_.Reset(new TSocketInput(*Socket_));
        SocketOutput_.Reset(new TSocketOutput(*Socket_));

        Socket_->SetSocketTimeout(timeout.Seconds(), timeout.MilliSeconds() % 1000);

        if (https) {
            Ssl_.Reset(new TOpenSslClientIO(SocketInput_.Get(), SocketOutput_.Get()));
        }

        {
            THttpOutput ho(Ssl_ ? (IOutputStream*)Ssl_.Get() : (IOutputStream*)SocketOutput_.Get());
            (ho << req).Finish();
        }
        HttpInput_.Reset(new THttpInput(Ssl_ ? (IInputStream*)Ssl_.Get() : (IInputStream*)SocketInput_.Get()));
    }

    THttpInput& GetStream() override {
        return *HttpInput_;
    }

    unsigned GetRetCode() override {
        return ParseHttpRetCode(HttpInput_->FirstLine());
    }

    THttpURL GetRedirectURL(const THttpURL& baseUrl) override {
        for (auto i = HttpInput_->Headers().Begin(); i != HttpInput_->Headers().End(); ++i) {
            if (0 == TCiString::compare(i->Name(), TStringBuf("location"))) {
                THttpURL target = ParseURL(i->Value(), THttpURL::FeaturesAll | NUri::TFeature::FeatureConvertHostIDN);
                if (!target.IsValidAbs()) {
                    target.Merge(baseUrl);
                }
                return target;
            }
        }
        ythrow yexception() << "Unknown redirect location from " << baseUrl.PrintS();
    }

    static TFetchResultPtr Fetch(const THttpURL& url, const THttpHeaders& additionalHeaders, const TDuration& timeout) {
        return new TFetchResultImpl(url, additionalHeaders, timeout);
    }

private:
    THolder<TSocket> Socket_;
    THolder<TSocketInput> SocketInput_;
    THolder<TSocketOutput> SocketOutput_;
    THolder<TOpenSslClientIO> Ssl_;
    THolder<THttpInput> HttpInput_;
};

inline bool IsRedirectCode(unsigned code) {
    switch (code) {
        case HTTP_MOVED_PERMANENTLY:
        case HTTP_FOUND:
        case HTTP_SEE_OTHER:
        case HTTP_TEMPORARY_REDIRECT:
            return true;
    }
    return false;
}

} // unnamed

ERetryErrorClass DefaultClassifyHttpCode(unsigned code) {
    switch (code) {
        case HTTP_REQUEST_TIME_OUT:             //408
        case HTTP_AUTHENTICATION_TIMEOUT:       //419
            return ERetryErrorClass::ShortRetry;
        case HTTP_TOO_MANY_REQUESTS:            //429
        case HTTP_SERVICE_UNAVAILABLE:          //503
            return ERetryErrorClass::LongRetry;
        default:
            return IsServerError(code)
                ? ERetryErrorClass::ShortRetry  //5xx
                : ERetryErrorClass::NoRetry;
    }
}

IRetryPolicy<unsigned>::TPtr GetDefaultPolicy() {
    static const auto policy = IRetryPolicy<unsigned>::GetExponentialBackoffPolicy(
            /*retryClassFunction=*/DefaultClassifyHttpCode,
            /*minDelay=*/TDuration::Seconds(1),
            /*minLongRetryDelay:*/TDuration::Seconds(5),
            /*maxDelay=*/TDuration::Minutes(1),
            /*maxRetries=*/3,
            /*maxTime=*/TDuration::Minutes(3),
            /*scaleFactor=*/2
    );
    return policy;
}

THttpURL ParseURL(const TStringBuf addr) {
    return ParseURL(addr, THttpURL::FeaturesAll | NUri::TFeature::FeatureConvertHostIDN | NUri::TFeature::FeatureNoRelPath);
}

TFetchResultPtr Fetch(const THttpURL& url, const THttpHeaders& additionalHeaders, const TDuration& timeout, size_t redirects, const IRetryPolicy<unsigned>::TPtr& policy) {
    const auto& actualPolicy = policy ? policy : GetDefaultPolicy();
    THttpURL currentUrl = url;
    for (size_t fetchNum = 0; fetchNum < redirects; ++fetchNum) {
        IRetryPolicy<unsigned>::IRetryState::TPtr state = actualPolicy->CreateRetryState();
        unsigned responseCode = 0;
        TFetchResultPtr fr;
        while (true) {
            std::exception_ptr eptr;
            try {
                fr = TFetchResultImpl::Fetch(currentUrl, additionalHeaders, timeout);
                responseCode = fr->GetRetCode();
            } catch (const TSystemError& ex) {
                if (ex.Status() != ETIMEDOUT) {
                    throw;
                }

                responseCode = HTTP_REQUEST_TIME_OUT;
                eptr = std::current_exception();
            }

            if (auto delay = state->GetNextRetryDelay(responseCode)) {
                YQL_LOG(DEBUG) << "Connection failed. Retry delay: " << *delay;
                Sleep(*delay);
            } else if (eptr != nullptr) {
                std::rethrow_exception(eptr);
            } else {
                break;
            }
        }

        if (responseCode >= 200 && responseCode < 300) {
            return fr;
        }

        if (responseCode == HTTP_NOT_MODIFIED) {
            return fr;
        }

        if (IsRedirectCode(responseCode)) {
            currentUrl = fr->GetRedirectURL(currentUrl);
            YQL_LOG(INFO) << "Got redirect to " << currentUrl.PrintS();
            continue;
        }

        TString errorBody;
        try {
            errorBody = fr->GetStream().ReadAll();
        } catch (...) {
        }

        ythrow yexception() << "Failed to fetch url '" << currentUrl.PrintS() << "' with code " << responseCode << ", body: " << errorBody;
    }
    ythrow yexception() << "Failed to fetch url '" << currentUrl.PrintS() << "': too many redirects";
}

} // NYql