aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/http/http_proxy_outgoing.cpp
blob: b1f27c2c5a1eb1a5859394bf289d7fdf5f430d49 (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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#include "http_proxy.h"
#include "http_proxy_sock_impl.h"

namespace NHttp {

template <typename TSocketImpl>
class TOutgoingConnectionActor : public NActors::TActor<TOutgoingConnectionActor<TSocketImpl>>, public TSocketImpl, virtual public THttpConfig {
public:
    using TBase = NActors::TActor<TOutgoingConnectionActor<TSocketImpl>>;
    using TSelf = TOutgoingConnectionActor<TSocketImpl>;
    const TActorId Owner;
    const TActorId Poller;
    SocketAddressType Address;
    TActorId RequestOwner;
    THttpOutgoingRequestPtr Request;
    THttpIncomingResponsePtr Response;
    TInstant LastActivity;
    TDuration ConnectionTimeout = CONNECTION_TIMEOUT;
    NActors::TPollerToken::TPtr PollerToken;

    TOutgoingConnectionActor(const TActorId& owner, const TActorId& poller)
        : TBase(&TSelf::StateWaiting)
        , Owner(owner)
        , Poller(poller)
    {
    }

    static constexpr char ActorName[] = "OUT_CONNECTION_ACTOR";

    void Die(const NActors::TActorContext& ctx) override {
        ctx.Send(Owner, new TEvHttpProxy::TEvHttpConnectionClosed(ctx.SelfID));
        TSocketImpl::Shutdown(); // to avoid errors when connection already closed
        TBase::Die(ctx);
    }

    TString GetSocketName() {
        TStringBuilder builder;
        if (TSocketImpl::Socket) {
            builder << "(#" << TSocketImpl::GetRawSocket();
            if (Address && Address->SockAddr()->sa_family) {
                builder << "," << Address;
            }
            builder << ") ";
        }
        return builder;
    }

    void ReplyAndDie(const NActors::TActorContext& ctx) {
        LOG_DEBUG_S(ctx, HttpLog, GetSocketName() << "-> (" << Response->Status << " " << Response->Message << ")");
        ctx.Send(RequestOwner, new TEvHttpProxy::TEvHttpIncomingResponse(Request, Response));
        RequestOwner = TActorId();
        THolder<TEvHttpProxy::TEvReportSensors> sensors(BuildOutgoingRequestSensors(Request, Response));
        ctx.Send(Owner, sensors.Release());
        LOG_DEBUG_S(ctx, HttpLog, GetSocketName() << "connection closed");
        Die(ctx);
    }

    void ReplyErrorAndDie(const NActors::TActorContext& ctx, const TString& error) {
        LOG_ERROR_S(ctx, HttpLog, GetSocketName() << "connection closed with error: " << error);
        if (RequestOwner) {
            ctx.Send(RequestOwner, new TEvHttpProxy::TEvHttpIncomingResponse(Request, Response, error));
            RequestOwner = TActorId();
            THolder<TEvHttpProxy::TEvReportSensors> sensors(BuildOutgoingRequestSensors(Request, Response));
            ctx.Send(Owner, sensors.Release());
            Die(ctx);
        }
    }

protected:
    void FailConnection(const NActors::TActorContext& ctx, const TString& error) {
        if (Request) {
            return ReplyErrorAndDie(ctx, error);
        }
        return TBase::Become(&TOutgoingConnectionActor::StateFailed);
    }

    void Connect(const NActors::TActorContext& ctx) {
        LOG_DEBUG_S(ctx, HttpLog, GetSocketName() << "connecting");
        TSocketImpl::Create(Address->SockAddr()->sa_family);
        TSocketImpl::SetNonBlock();
        TSocketImpl::SetTimeout(ConnectionTimeout);
        int res = TSocketImpl::Connect(Address);
        RegisterPoller(ctx);
        switch (-res) {
        case 0:
            return OnConnect(ctx);
        case EINPROGRESS:
        case EAGAIN:
            return TBase::Become(&TOutgoingConnectionActor::StateConnecting);
        default:
            return ReplyErrorAndDie(ctx, strerror(-res));
        }
    }

    void FlushOutput(const NActors::TActorContext& ctx) {
        if (Request != nullptr) {
            Request->Finish();
            while (auto size = Request->Size()) {
                bool read = false, write = false;
                ssize_t res = TSocketImpl::Send(Request->Data(), size, read, write);
                if (res > 0) {
                   Request->ChopHead(res);
                } else if (-res == EINTR) {
                    continue;
                } else if (-res == EAGAIN || -res == EWOULDBLOCK) {
                    if (PollerToken) {
                        if (!read && !write) {
                            write = true;
                        }
                        if (PollerToken->RequestNotificationAfterWouldBlock(read, write)) {
                            continue;
                        }
                    }
                    break;
                } else {
                    if (!res) {
                        ReplyAndDie(ctx);
                    } else {
                        ReplyErrorAndDie(ctx, strerror(-res));
                    }
                    break;
                }
            }
        }
    }

    void PullInput(const NActors::TActorContext& ctx) {
        for (;;) {
            if (Response == nullptr) {
                Response = new THttpIncomingResponse(Request);
            }
            if (!Response->EnsureEnoughSpaceAvailable()) {
                return ReplyErrorAndDie(ctx, "Not enough space in socket buffer");
            }
            bool read = false, write = false;
            ssize_t res = TSocketImpl::Recv(Response->Pos(), Response->Avail(), read, write);
            if (res > 0) {
                Response->Advance(res);
                if (Response->IsDone() && Response->IsReady()) {
                    return ReplyAndDie(ctx);
                }
            } else if (-res == EINTR) {
                continue;
            } else if (-res == EAGAIN || -res == EWOULDBLOCK) {
                if (PollerToken) {
                    if (!read && !write) {
                        read = true;
                    }
                    if (PollerToken->RequestNotificationAfterWouldBlock(read, write)) {
                        continue;
                    }
                }
                return;
            } else {
                if (!res) {
                    Response->ConnectionClosed();
                }
                if (Response->IsDone() && Response->IsReady()) {
                    return ReplyAndDie(ctx);
                }
                return ReplyErrorAndDie(ctx, strerror(-res));
            }
        }
    }

    void RegisterPoller(const NActors::TActorContext& ctx) {
        ctx.Send(Poller, new NActors::TEvPollerRegister(TSocketImpl::Socket, ctx.SelfID, ctx.SelfID));
    }

    void OnConnect(const NActors::TActorContext& ctx) {
        bool read = false, write = false;
        if (int res = TSocketImpl::OnConnect(read, write); res != 1) {
            if (-res == EAGAIN) {
                if (PollerToken) {
                    PollerToken->Request(read, write);
                }
                return;
            } else {
                return ReplyErrorAndDie(ctx, strerror(-res));
            }
        }
        LOG_DEBUG_S(ctx, HttpLog, GetSocketName() << "outgoing connection opened");
        TBase::Become(&TOutgoingConnectionActor::StateConnected);
        LOG_DEBUG_S(ctx, HttpLog, GetSocketName() << "<- (" << Request->Method << " " << Request->URL << ")");
        ctx.Send(ctx.SelfID, new NActors::TEvPollerReady(nullptr, true, true));
    }

    static int GetPort(SocketAddressType address) {
        switch (address->SockAddr()->sa_family) {
            case AF_INET:
                return ntohs(reinterpret_cast<sockaddr_in*>(address->SockAddr())->sin_port);
            case AF_INET6:
                return ntohs(reinterpret_cast<sockaddr_in6*>(address->SockAddr())->sin6_port);
        }
        return {};
    }

    static void SetPort(SocketAddressType address, int port) {
        switch (address->SockAddr()->sa_family) {
            case AF_INET:
                reinterpret_cast<sockaddr_in*>(address->SockAddr())->sin_port = htons(port);
                break;
            case AF_INET6:
                reinterpret_cast<sockaddr_in6*>(address->SockAddr())->sin6_port = htons(port);
                break;
        }
    }

    void HandleResolving(TEvHttpProxy::TEvResolveHostResponse::TPtr event, const NActors::TActorContext& ctx) {
        LastActivity = ctx.Now();
        if (!event->Get()->Error.empty()) {
            return FailConnection(ctx, event->Get()->Error);
        }
        Address = event->Get()->Address;
        if (GetPort(Address) == 0) {
            SetPort(Address, Request->Secure ? 443 : 80);
        }
        Connect(ctx);
    }

    void HandleConnecting(NActors::TEvPollerReady::TPtr, const NActors::TActorContext& ctx) {
        LastActivity = ctx.Now();
        int res = TSocketImpl::GetError();
        if (res == 0) {
            OnConnect(ctx);
        } else {
            FailConnection(ctx, TStringBuilder() << strerror(res));
        }
    }

    void HandleConnecting(NActors::TEvPollerRegisterResult::TPtr ev, const NActors::TActorContext& ctx) {
        PollerToken = std::move(ev->Get()->PollerToken);
        LastActivity = ctx.Now();
        int res = TSocketImpl::GetError();
        if (res == 0) {
            OnConnect(ctx);
        } else {
            FailConnection(ctx, TStringBuilder() << strerror(res));
        }
    }

    void HandleWaiting(TEvHttpProxy::TEvHttpOutgoingRequest::TPtr event, const NActors::TActorContext& ctx) {
        LastActivity = ctx.Now();
        Request = std::move(event->Get()->Request);
        TSocketImpl::SetHost(TString(Request->Host));
        LOG_DEBUG_S(ctx, HttpLog, GetSocketName() << "resolving " << TSocketImpl::Host);
        Request->Timer.Reset();
        RequestOwner = event->Sender;
        ctx.Send(Owner, new TEvHttpProxy::TEvResolveHostRequest(TSocketImpl::Host));
        if (event->Get()->Timeout) {
            ConnectionTimeout = event->Get()->Timeout;
        }
        ctx.Schedule(ConnectionTimeout, new NActors::TEvents::TEvWakeup());
        LastActivity = ctx.Now();
        TBase::Become(&TOutgoingConnectionActor::StateResolving);
    }

    void HandleConnected(NActors::TEvPollerReady::TPtr event, const NActors::TActorContext& ctx) {
        LastActivity = ctx.Now();
        if (event->Get()->Write && RequestOwner) {
            FlushOutput(ctx);
        }
        if (event->Get()->Read && RequestOwner) {
            PullInput(ctx);
        }
    }

    void HandleConnected(NActors::TEvPollerRegisterResult::TPtr ev, const NActors::TActorContext& ctx) {
        PollerToken = std::move(ev->Get()->PollerToken);
        LastActivity = ctx.Now();
        PullInput(ctx);
        FlushOutput(ctx);
    }

    void HandleFailed(TEvHttpProxy::TEvHttpOutgoingRequest::TPtr event, const NActors::TActorContext& ctx) {
        Request = std::move(event->Get()->Request);
        RequestOwner = event->Sender;
        ReplyErrorAndDie(ctx, "Failed");
    }

    void HandleTimeout(const NActors::TActorContext& ctx) {
        TDuration inactivityTime = ctx.Now() - LastActivity;
        if (inactivityTime >= ConnectionTimeout) {
            FailConnection(ctx, "Connection timed out");
        } else {
            ctx.Schedule(Min(ConnectionTimeout - inactivityTime, TDuration::MilliSeconds(100)), new NActors::TEvents::TEvWakeup());
        }
    }

    STFUNC(StateWaiting) {
        switch (ev->GetTypeRewrite()) {
            HFunc(TEvHttpProxy::TEvHttpOutgoingRequest, HandleWaiting);
            CFunc(NActors::TEvents::TEvWakeup::EventType, HandleTimeout);
        }
    }

    STFUNC(StateResolving) {
        switch (ev->GetTypeRewrite()) {
            HFunc(TEvHttpProxy::TEvResolveHostResponse, HandleResolving);
            CFunc(NActors::TEvents::TEvWakeup::EventType, HandleTimeout);
        }
    }

    STFUNC(StateConnecting) {
        switch (ev->GetTypeRewrite()) {
            HFunc(NActors::TEvPollerReady, HandleConnecting);
            CFunc(NActors::TEvents::TEvWakeup::EventType, HandleTimeout);
            HFunc(NActors::TEvPollerRegisterResult, HandleConnecting);
        }
    }

    STFUNC(StateConnected) {
        switch (ev->GetTypeRewrite()) {
            HFunc(NActors::TEvPollerReady, HandleConnected);
            CFunc(NActors::TEvents::TEvWakeup::EventType, HandleTimeout);
            HFunc(NActors::TEvPollerRegisterResult, HandleConnected);
        }
    }

    STFUNC(StateFailed) {
        switch (ev->GetTypeRewrite()) {
            HFunc(TEvHttpProxy::TEvHttpOutgoingRequest, HandleFailed);
        }
    }
};

NActors::IActor* CreateOutgoingConnectionActor(const TActorId& owner, bool secure, const TActorId& poller) {
    if (secure) {
        return new TOutgoingConnectionActor<TSecureSocketImpl>(owner, poller);
    } else {
        return new TOutgoingConnectionActor<TPlainSocketImpl>(owner, poller);
    }
}

}