1/**
2 * The Forgotten Server - a free and open-source MMORPG server emulator
3 * Copyright (C) 2019 Mark Samman <mark.samman@gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20#include "otpch.h"
21
22#include "outputmessage.h"
23#include "protocol.h"
24#include "lockfree.h"
25#include "scheduler.h"
26
27extern Scheduler g_scheduler;
28
29const uint16_t OUTPUTMESSAGE_FREE_LIST_CAPACITY = 2048;
30const std::chrono::milliseconds OUTPUTMESSAGE_AUTOSEND_DELAY {10};
31
32void OutputMessagePool::scheduleSendAll()
33{
34 auto functor = std::bind(&OutputMessagePool::sendAll, this);
35 g_scheduler.addEvent(createSchedulerTask(OUTPUTMESSAGE_AUTOSEND_DELAY.count(), functor));
36}
37
38void OutputMessagePool::sendAll()
39{
40 //dispatcher thread
41 for (auto& protocol : bufferedProtocols) {
42 auto& msg = protocol->getCurrentBuffer();
43 if (msg) {
44 protocol->send(std::move(msg));
45 }
46 }
47
48 if (!bufferedProtocols.empty()) {
49 scheduleSendAll();
50 }
51}
52
53void OutputMessagePool::addProtocolToAutosend(Protocol_ptr protocol)
54{
55 //dispatcher thread
56 if (bufferedProtocols.empty()) {
57 scheduleSendAll();
58 }
59 bufferedProtocols.emplace_back(protocol);
60}
61
62void OutputMessagePool::removeProtocolFromAutosend(const Protocol_ptr& protocol)
63{
64 //dispatcher thread
65 auto it = std::find(bufferedProtocols.begin(), bufferedProtocols.end(), protocol);
66 if (it != bufferedProtocols.end()) {
67 std::swap(*it, bufferedProtocols.back());
68 bufferedProtocols.pop_back();
69 }
70}
71
72OutputMessage_ptr OutputMessagePool::getOutputMessage()
73{
74 // LockfreePoolingAllocator<void,...> will leave (void* allocate) ill-formed because
75 // of sizeof(T), so this guaranatees that only one list will be initialized
76 return std::allocate_shared<OutputMessage>(LockfreePoolingAllocator<void, OUTPUTMESSAGE_FREE_LIST_CAPACITY>());
77}
78