File: pending_writes_manager.cpp

package info (click to toggle)
warzone2100 4.6.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 660,320 kB
  • sloc: cpp: 676,209; ansic: 391,201; javascript: 78,238; python: 16,632; php: 4,294; sh: 4,094; makefile: 2,629; lisp: 1,492; cs: 489; xml: 404; perl: 224; ruby: 156; java: 89
file content (270 lines) | stat: -rw-r--r-- 7,701 bytes parent folder | download
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
// SPDX-License-Identifier: GPL-2.0-or-later

/*
	This file is part of Warzone 2100.
	Copyright (C) 2025  Warzone 2100 Project

	Warzone 2100 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.

	Warzone 2100 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 Warzone 2100; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include "pending_writes_manager.h"

#include "lib/framework/frame.h" // for ASSERT
#include "lib/netplay/descriptor_set.h"
#include "lib/netplay/client_connection.h"
#include "lib/netplay/wz_connection_provider.h"
#include "lib/netplay/error_categories.h"

#include <system_error>

PendingWritesManager::~PendingWritesManager()
{
	deinitialize();
}

void PendingWritesManager::deinitialize()
{
	if (thread_ == nullptr)
	{
		// No-op in case of a repeated `deinitialize()` call
		return;
	}
	wzMutexLock(mtx_);
	stopRequested_ = true;
	pendingWrites_.clear();
	writableSet_.reset();
	wzMutexUnlock(mtx_);
	wzSemaphorePost(sema_);  // Wake up the thread, so it can quit.
	wzThreadJoin(thread_);
	wzMutexDestroy(mtx_);
	wzSemaphoreDestroy(sema_);
	thread_ = nullptr;
	mtx_ = nullptr;
	sema_ = nullptr;
}

void PendingWritesManager::initialize(WzConnectionProvider& connProvider)
{
	if (thread_ != nullptr)
	{
		// No-op in case of a repeated `initialize()` call
		return;
	}
	writableSet_ = connProvider.newDescriptorSet(PollEventType::WRITABLE);
	stopRequested_ = false;
	mtx_ = wzMutexCreate();
	sema_ = wzSemaphoreCreate(0);
	thread_ = wzThreadCreate(pendingWritesThreadFunction, reinterpret_cast<void*>(this), "WzPendingWrites");
	wzThreadStart(thread_);
}

net::result<int> PendingWritesManager::checkConnectionsWritable(IDescriptorSet& writableSet, std::chrono::milliseconds timeout)
{
	if (writableSet.empty())
	{
		return 0;
	}

	wzMutexUnlock(mtx_);
	const auto pollRes = writableSet.poll(timeout);
	wzMutexLock(mtx_);

	if (!pollRes.has_value())
	{
		const auto msg = pollRes.error().message();
		debug(LOG_ERROR, "poll failed: %s", msg.c_str());
		return pollRes;
	}

	if (pollRes.value() == 0)
	{
		debug(LOG_WARNING, "poll timed out after waiting for %u milliseconds", static_cast<unsigned int>(timeout.count()));
		return 0;
	}

	return pollRes.value();
}

void PendingWritesManager::populateWritableSet(IDescriptorSet& writableSet)
{
	for (auto it = pendingWrites_.begin(); it != pendingWrites_.end();)
	{
		const auto& pendingConnWrite = *it;
		if (!pendingConnWrite.second.empty())
		{
			writableSet.add(pendingConnWrite.first);
			++it;
		}
		else
		{
			ASSERT(false, "Empty buffer for pending socket writes"); // This shouldn't happen!
			IClientConnection* conn = pendingConnWrite.first;
			it = pendingWrites_.erase(it);
			if (conn->deleteLaterRequested())
			{
				delete conn;
			}
		}
	}
}

void PendingWritesManager::threadImplFunction()
{
	wzMutexLock(mtx_);
	while (!stopRequested_)
	{
		static constexpr std::chrono::milliseconds WRITABLE_CHECK_TIMEOUT{ 50 };
		// Check if we can write to some connections.
		writableSet_->clear();
		populateWritableSet(*writableSet_);
		ASSERT(!writableSet_->empty() || pendingWrites_.empty(), "writableSet must not be empty if there are pending writes.");

		const auto checkWritableRes = checkConnectionsWritable(*writableSet_, WRITABLE_CHECK_TIMEOUT);

		if (checkWritableRes.has_value() && checkWritableRes.value() != 0)
		{
			for (auto connIt = pendingWrites_.begin(); connIt != pendingWrites_.end();)
			{
				auto currentIt = connIt;
				++connIt;

				IClientConnection* conn = currentIt->first;
				ConnectionWriteQueue& writeQueue = currentIt->second;
				ASSERT(!writeQueue.empty(), "writeQueue[sock] must not be empty.");

				auto isSetResult = writableSet_->isSet(conn);
				if (!isSetResult.has_value())
				{
					// Poll returned some fatal error state for the connection
					switch (isSetResult.error())
					{
					case IDescriptorSet::ErroredState::InvalidConn:
						// Connection is somehow invalid?
						debug(LOG_ERROR, "Socket error: PollInvalidConn?");
						conn->setWriteErrorCode(make_network_error_code(EBADF));
						break;
					case IDescriptorSet::ErroredState::Error:
						debug(LOG_INFO, "Socket error: PollError");
						conn->setWriteErrorCode(make_network_error_code(EBADF));
						break;
					case IDescriptorSet::ErroredState::HangUp:
						debug(LOG_NET, "Socket error: PollHangUp");
						conn->setWriteErrorCode(make_network_error_code(ECONNRESET));
						break;
					}

					pendingWrites_.erase(currentIt);  // Connection broken, don't try writing to it again.
					if (conn->deleteLaterRequested())
					{
						delete conn;
					}
					continue;
				}

				if (!isSetResult.value() || writeQueue.empty())
				{
					continue;  // This connection is not ready for writing, or we don't have anything to write.
				}

				// Write data.
				const auto retSent = conn->sendImpl(writeQueue);
				if (retSent.has_value())
				{
					// Erase as much data as written.
					writeQueue.erase(writeQueue.begin(), writeQueue.begin() + retSent.value());
					if (writeQueue.empty())
					{
						pendingWrites_.erase(currentIt);  // Nothing left to write, delete from pending list.
						if (conn->deleteLaterRequested())
						{
							delete conn;
						}
					}
				}
				else
				{
					if (retSent.error() == std::errc::interrupted)
					{
						// Not an actual error, just try to send again later
						continue;
					}
					const auto connStatus = conn->connectionStatus();
					if (!conn->isValid() || !connStatus.has_value()) // Check if the connection is still open
					{
						if (!connStatus.has_value())
						{
							const auto errMsg = connStatus.error().message();
							debug(LOG_NET, "Socket error: %s", errMsg.c_str());
							conn->setWriteErrorCode(connStatus.error());
						}
						else
						{
							debug(LOG_NET, "Socket error: connection is not valid");
							conn->setWriteErrorCode(make_network_error_code(ECONNRESET));
						}
						pendingWrites_.erase(currentIt);  // Connection broken, don't try writing to it again.
						if (conn->deleteLaterRequested())
						{
							delete conn;
						}
					}
				}
			}
		}
		if (pendingWrites_.empty())
		{
			// Nothing to do, expect to wait.
			wzMutexUnlock(mtx_);
			wzSemaphoreWait(sema_);
			wzMutexLock(mtx_);
		}
	}
	wzMutexUnlock(mtx_);
}

void PendingWritesManager::safeDispose(IClientConnection* conn)
{
	executeUnderLock([this, conn]
	{
		// Need a `const_cast` to make the `unordered_map` work with `const` key type.
		if (pendingWrites_.count(const_cast<IClientConnection*>(conn)) != 0)
		{
			// Wait until the data is written, then delete the socket.
			conn->requestDeleteLater();
		}
		else
		{
			// Notify the owning connection provider to properly dispose of the connection object.
			if (auto connProvider = conn->connProvider_.lock())
			{
				connProvider->disposeConnection(conn);
			}
			else
			{
				ASSERT(false, "IClientConnection::connProvider_ has gone away before safeDispose!");
			}
			// Delete the socket and destroy the connection right away.
			delete conn;
		}
	});
}

int pendingWritesThreadFunction(void* data)
{
	PendingWritesManager* inst = reinterpret_cast<PendingWritesManager*>(data);
	inst->threadImplFunction();
	// Return value ignored
	return 0;
}