aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/coroutine/engine/helper.cpp
blob: bffe208dc890be339d79e36ae9f9a0dc1dd8345a (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
#include "helper.h"

#include "impl.h"
#include "network.h"

namespace NCoro {

    bool TryConnect(const TString& host, ui16 port, TDuration timeout) {
        bool connected = false;

        auto f = [&connected, &host, port, timeout](TCont* c) {
            TSocketHolder socket;
            TNetworkAddress address(host, port);
            connected = (0 == NCoro::ConnectT(c, socket, address, timeout));
        };

        TContExecutor e(128 * 1024);
        e.Create(f, "try_connect");
        e.Execute();
        return connected;
    }

    bool WaitUntilConnectable(const TString& host, ui16 port, TDuration timeout) {
        const TInstant deadline = timeout.ToDeadLine();

        for (size_t i = 1; Now() < deadline; ++i) {
            const TDuration waitTime = TDuration::MilliSeconds(100) * i * i;
            SleepUntil(Min(Now() + waitTime, deadline));

            if (TryConnect(host, port, waitTime)) {
                return true;
            }
        }

        return false;
    }
}