aboutsummaryrefslogtreecommitdiff
path: root/src/common/network/Http/HttpService.h
blob: 1549893576f87c431982f3ac99f86a6b04b7d24b (plain)
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
/*
 * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef TRINITYCORE_HTTP_SERVICE_H
#define TRINITYCORE_HTTP_SERVICE_H

#include "AsioHacksFwd.h"
#include "Concepts.h"
#include "Define.h"
#include "EnumFlag.h"
#include "HttpCommon.h"
#include "HttpSessionState.h"
#include "Optional.h"
#include "SocketMgr.h"
#include <boost/uuid/uuid.hpp>
#include <functional>
#include <map>
#include <set>
#include <shared_mutex>

namespace Trinity::Net::Http
{
class AbstractSocket;

enum class RequestHandlerFlag
{
    None                    = 0x0,
    DoNotLogRequestContent  = 0x1,
    DoNotLogResponseContent = 0x2,
};

DEFINE_ENUM_FLAG(RequestHandlerFlag);

struct RequestHandler
{
    std::function<RequestHandlerResult(std::shared_ptr<AbstractSocket> session, RequestContext& context)> Func;
    EnumFlag<RequestHandlerFlag> Flags = RequestHandlerFlag::None;
};

class TC_NETWORK_API DispatcherService
{
public:
    explicit DispatcherService(std::string_view loggerSuffix) : _logger("server.http.dispatcher.")
    {
        _logger.append(loggerSuffix);
    }

    RequestHandlerResult HandleRequest(std::shared_ptr<AbstractSocket> session, RequestContext& context);

    static RequestHandlerResult HandleBadRequest(std::shared_ptr<AbstractSocket> session, RequestContext& context);
    static RequestHandlerResult HandleUnauthorized(std::shared_ptr<AbstractSocket> session, RequestContext& context);
    static RequestHandlerResult HandlePathNotFound(std::shared_ptr<AbstractSocket> session, RequestContext& context);

protected:
    void RegisterHandler(boost::beast::http::verb method, std::string_view path,
        std::function<RequestHandlerResult(std::shared_ptr<AbstractSocket> session, RequestContext& context)> handler,
        RequestHandlerFlag flags = RequestHandlerFlag::None);

private:
    using HttpMethodHandlerMap = std::map<std::string, RequestHandler, std::less<>>;

    HttpMethodHandlerMap _getHandlers;
    HttpMethodHandlerMap _postHandlers;

    std::string _logger;
};

class TC_NETWORK_API SessionService
{
public:
    explicit SessionService(std::string_view loggerSuffix) : _logger("server.http.session.")
    {
        _logger.append(loggerSuffix);
    }

    void Start(Asio::IoContext& ioContext);
    void Stop();

    std::shared_ptr<SessionState> FindAndRefreshSessionState(std::string_view id, boost::asio::ip::address const& address);
    void MarkSessionInactive(boost::uuids::uuid const& id);

protected:
    void InitAndStoreSessionState(std::shared_ptr<SessionState> state, boost::asio::ip::address const& address);

    void KillInactiveSessions();

private:
    std::shared_mutex _sessionsMutex;
    std::map<boost::uuids::uuid, std::shared_ptr<SessionState>> _sessions;

    std::mutex _inactiveSessionsMutex;
    std::set<boost::uuids::uuid> _inactiveSessions;
    std::unique_ptr<Asio::DeadlineTimer> _inactiveSessionsKillTimer;

    std::string _logger;
};

template<typename Callable, typename SessionImpl>
concept HttpRequestHandler = invocable_r<Callable, RequestHandlerResult, std::shared_ptr<SessionImpl>, RequestContext&>;

template<typename SessionImpl>
class HttpService : public SocketMgr<SessionImpl>, public DispatcherService, public SessionService
{
public:
    HttpService(std::string_view loggerSuffix) : DispatcherService(loggerSuffix), SessionService(loggerSuffix), _ioContext(nullptr), _logger("server.http.")
    {
        _logger.append(loggerSuffix);
    }

    bool StartNetwork(Asio::IoContext& ioContext, std::string const& bindIp, uint16 port, int32 threadCount = 1) override
    {
        if (!SocketMgr<SessionImpl>::StartNetwork(ioContext, bindIp, port, threadCount))
            return false;

        SessionService::Start(ioContext);
        return true;
    }

    void StopNetwork() override
    {
        SessionService::Stop();
        SocketMgr<SessionImpl>::StopNetwork();
    }

    // http handling
    using DispatcherService::RegisterHandler;

    template<HttpRequestHandler<SessionImpl> Callable>
    void RegisterHandler(boost::beast::http::verb method, std::string_view path, Callable handler, RequestHandlerFlag flags = RequestHandlerFlag::None)
    {
        this->DispatcherService::RegisterHandler(method, path, [handler = std::move(handler)](std::shared_ptr<AbstractSocket> session, RequestContext& context) -> RequestHandlerResult
        {
            return handler(std::static_pointer_cast<SessionImpl>(std::move(session)), context);
        }, flags);
    }

    // session tracking
    virtual std::shared_ptr<SessionState> CreateNewSessionState(boost::asio::ip::address const& address)
    {
        std::shared_ptr<SessionState> state = std::make_shared<SessionState>();
        InitAndStoreSessionState(state, address);
        return state;
    }

protected:
    class Thread : public NetworkThread<SessionImpl>
    {
    protected:
        void SocketRemoved(std::shared_ptr<SessionImpl> const& session) override
        {
            if (Optional<boost::uuids::uuid> id = session->GetSessionId())
                _service->MarkSessionInactive(*id);
        }

    private:
        friend HttpService;

        SessionService* _service;
    };

    NetworkThread<SessionImpl>* CreateThreads() const override
    {
        Thread* threads = new Thread[this->GetNetworkThreadCount()];
        for (int32 i = 0; i < this->GetNetworkThreadCount(); ++i)
            threads[i]._service = const_cast<HttpService*>(this);
        return threads;
    }

    Asio::IoContext* _ioContext;
    std::string _logger;
};
}

#endif // TRINITYCORE_HTTP_SERVICE_H