aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/http/client/fetch/pool.cpp
blob: f0a142eced7977836e9ff476f9647a7c6c52f585 (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
#include "pool.h"

namespace NHttpFetcher {
    void TSocketPool::Clear() {
        TSocketMap sockets;

        {
            auto g(Guard(Lock_));
            Sockets_.swap(sockets);
        }
    }

    void TSocketPool::Drain(const TDuration timeout) {
        const TInstant now = TInstant::Now();
        TVector<THolder<TSocketHandle>> sockets;

        {
            auto g(Guard(Lock_));
            for (auto si = Sockets_.begin(); si != Sockets_.end();) {
                if (si->second.Touched + timeout < now) {
                    sockets.push_back(std::move(si->second.Socket));
                    Sockets_.erase(si++);
                } else {
                    ++si;
                }
            }
        }
    }

    THolder<TSocketPool::TSocketHandle> TSocketPool::GetSocket(const TString& host, const TIpPort port) {
        THolder<TSocketPool::TSocketHandle> socket;

        {
            auto g(Guard(Lock_));
            auto si = Sockets_.find(std::make_pair(host, port));
            if (si != Sockets_.end()) {
                socket = std::move(si->second.Socket);
                Sockets_.erase(si);
            }
        }

        return socket;
    }

    void TSocketPool::ReturnSocket(const TString& host, const TIpPort port, THolder<TSocketHandle> socket) {
        TConnection conn;

        conn.Socket = std::move(socket);
        conn.Touched = TInstant::Now();

        {
            auto g(Guard(Lock_));
            Sockets_.emplace(std::make_pair(host, port), std::move(conn));
        }
    }

}