nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
database.cc
Go to the documentation of this file.
1#include "server/database.h"
2
3#include <errmsg.h>
4#include <mysqld_error.h>
5
6#include <array>
7#include <chrono>
8#include <cstddef>
9#include <functional>
10#include <memory>
11#include <string>
12#include <string_view>
13#include <type_traits>
14#include <utility>
15#include <vector>
16
17#include "absl/memory/memory.h"
18#include "absl/strings/numbers.h"
19#include "absl/strings/str_cat.h"
20#include "absl/strings/str_split.h"
21#include "server/tracing.h"
22
23namespace nanommo {
24
25namespace {
26
27// Room for the longest value we read back, a password hash.
28constexpr int kValueSize = 256;
29
30// The C API's own type for a length, whatever it is on this system.
31using Length = std::remove_pointer_t<decltype(MYSQL_BIND::length)>;
32
33struct Value {
34 std::array<char, kValueSize> bytes;
35 Length length = 0;
36 bool null = false;
37};
38
39absl::Status Error(unsigned int code, const char* message) {
40 if (code == ER_DUP_ENTRY) {
41 return absl::AlreadyExistsError(message);
42 }
43 // Another transaction held what this one needed for too long, or the two
44 // waited for each other: it's worth trying again.
45 if (code == ER_LOCK_WAIT_TIMEOUT || code == ER_LOCK_DEADLOCK) {
46 return absl::AbortedError(absl::StrCat("MySQL gave up: ", message));
47 }
48 if (code == CR_SERVER_GONE_ERROR || code == CR_SERVER_LOST ||
49 code == ER_CLIENT_INTERACTION_TIMEOUT) {
50 return absl::UnavailableError(
51 absl::StrCat("lost the connection to MySQL: ", message));
52 }
53 return absl::InternalError(absl::StrCat("MySQL error ", code, ": ", message));
54}
55
56absl::Status StatementError(MYSQL_STMT* statement) {
57 return Error(mysql_stmt_errno(statement), mysql_stmt_error(statement));
58}
59
60// A statement, as a span under the request it's run for, named by what it does
61// and to which table, such as SELECT players. Its SQL has a ? for each value,
62// so the values stay out of it.
63Span StartStatement(std::string_view sql) {
64 if (!InTrace()) {
65 return Span();
66 }
67 std::string_view operation;
68 std::string_view table;
69 bool table_next = false;
70 for (const std::string_view word :
71 absl::StrSplit(sql, absl::ByAnyChar(" (),\n"), absl::SkipEmpty())) {
72 if (operation.empty()) {
73 operation = word;
74 table_next = operation == "UPDATE";
75 } else if (table_next && word != "SELECT") {
76 table = word;
77 break;
78 } else {
79 table_next = word == "FROM" || word == "INTO";
80 }
81 }
82 Span span = StartChildSpan(absl::StrCat("mysql ", operation, " ", table),
84 span.SetAttribute("db.system", "mysql");
85 span.SetAttribute("db.operation", operation);
86 span.SetAttribute("db.sql.table", table);
87 // The saver's statements run to thousands of ?, so a few hundred characters
88 // say which one it is.
89 span.SetAttribute("db.statement", sql.substr(0, 300));
90 return span;
91}
92
93absl::StatusOr<Statement> Prepare(MYSQL* mysql, std::string_view sql) {
94 Statement statement(mysql_stmt_init(mysql));
95 if (!statement) {
96 return Error(mysql_errno(mysql), mysql_error(mysql));
97 }
98 if (mysql_stmt_prepare(statement.get(), sql.data(), sql.size()) != 0) {
99 return StatementError(statement.get());
100 }
101 return statement;
102}
103
104} // namespace
105
106absl::StatusOr<std::unique_ptr<Database>> Database::Create(
107 const std::string& host, const std::string& user,
108 const std::string& password, const std::string& name,
109 MysqlTimeouts timeouts) {
110 std::unique_ptr<Database> database =
111 absl::WrapUnique(new Database(host, user, password, name, timeouts));
112 const absl::Status connected = database->Connect();
113 if (!connected.ok()) {
114 return connected;
115 }
116 return database;
117}
118
119absl::Status Database::Connect() {
120 MYSQL* mysql = mysql_init(nullptr);
121 if (mysql == nullptr) {
122 return absl::ResourceExhaustedError("out of memory");
123 }
124 mysql_options(mysql, MYSQL_SET_CHARSET_NAME, "utf8mb4");
125 const auto connect = static_cast<unsigned int>(timeouts_.connect.count());
126 const auto answer = static_cast<unsigned int>(timeouts_.answer.count());
127 mysql_options(mysql, MYSQL_OPT_CONNECT_TIMEOUT, &connect);
128 mysql_options(mysql, MYSQL_OPT_READ_TIMEOUT, &answer);
129 mysql_options(mysql, MYSQL_OPT_WRITE_TIMEOUT, &answer);
130 // A host can name its port, as host:port, or it's MySQL's.
131 const std::vector<std::string> host = absl::StrSplit(host_, ':');
132 unsigned int port = 0;
133 if (host.size() == 2 && !absl::SimpleAtoi(host[1], &port)) {
134 mysql_close(mysql);
135 return absl::InvalidArgumentError(
136 absl::StrCat("a MySQL host's port that isn't a number: ", host_));
137 }
138 if (mysql_real_connect(mysql, host[0].c_str(), user_.c_str(),
139 password_.c_str(), name_.c_str(), port, nullptr,
140 0) == nullptr) {
141 const absl::Status status = absl::UnavailableError(
142 absl::StrCat("couldn't connect to MySQL: ", mysql_error(mysql)));
143 mysql_close(mysql);
144 failing_until_ = std::chrono::steady_clock::now() + timeouts_.fail_fast;
145 return status;
146 }
147 // A world's tick waits for what it asks of MySQL, so a statement waits two
148 // seconds at most for a lock another transaction holds, not MySQL's fifty.
149 if (mysql_query(mysql, "SET SESSION innodb_lock_wait_timeout = 2") != 0) {
150 const absl::Status status = Error(mysql_errno(mysql), mysql_error(mysql));
151 mysql_close(mysql);
152 return status;
153 }
154 // The old connection goes once the new one works, and the statements
155 // prepared on it with it.
156 reads_.clear();
157 mysql_close(mysql_);
158 mysql_ = mysql;
159 return absl::OkStatus();
160}
161
163 reads_.clear();
164 mysql_close(mysql_);
165}
166
167absl::Status Database::Ready() const {
168 if (std::chrono::steady_clock::now() < failing_until_) {
169 return absl::UnavailableError(
170 "MySQL didn't answer a moment ago, so it isn't asked yet");
171 }
172 return absl::OkStatus();
173}
174
175bool Database::TimedOut(std::chrono::steady_clock::time_point start) const {
176 return std::chrono::steady_clock::now() - start >= timeouts_.answer;
177}
178
179void Database::Notice(const absl::Status& status,
180 std::chrono::steady_clock::time_point start) {
181 if (absl::IsUnavailable(status) && TimedOut(start)) {
182 failing_until_ = std::chrono::steady_clock::now() + timeouts_.fail_fast;
183 }
184}
185
186absl::StatusOr<Result> Database::Run(std::string_view sql,
187 const std::vector<std::string>& values) {
188 const Span span = StartStatement(sql);
189 if (const absl::Status ready = Ready(); !ready.ok()) {
190 return ready;
191 }
192 const auto start = std::chrono::steady_clock::now();
193 absl::StatusOr<Result> result = RunOnce(sql, values, start);
194 Notice(result.status(), start);
195 return result;
196}
197
198absl::StatusOr<Result> Database::RunOnce(
199 std::string_view sql, const std::vector<std::string>& values,
200 std::chrono::steady_clock::time_point start) {
201 if (const auto kept = reads_.find(sql); kept != reads_.end()) {
202 absl::StatusOr<Result> result = Execute(kept->second.get(), values);
203 if (result.ok()) {
204 return result;
205 }
206 // It's prepared again next time.
207 reads_.erase(kept);
208 // A connection that's gone stale since it was prepared fails as it runs.
209 // A read changed nothing, so it runs again, on a new connection, unless
210 // we're in a transaction, which went with the old one. One that waited
211 // out its timeout found MySQL not answering, and asking again would wait
212 // as long again.
213 if (!absl::IsUnavailable(result.status()) || in_transaction_ ||
214 TimedOut(start)) {
215 return result;
216 }
217 }
218 absl::StatusOr<Statement> prepared = Prepare(mysql_, sql);
219 // MySQL drops a connection that sits idle for eight hours, and a restart
220 // drops them all. Nothing has run yet, so we connect again and retry,
221 // unless we're in a transaction, which went with the connection, or MySQL
222 // didn't answer in time.
223 if (absl::IsUnavailable(prepared.status()) && !in_transaction_ &&
224 !TimedOut(start)) {
225 const absl::Status connected = Connect();
226 if (!connected.ok()) {
227 return connected;
228 }
229 prepared = Prepare(mysql_, sql);
230 }
231 if (!prepared.ok()) {
232 return prepared.status();
233 }
234 Statement statement = *std::move(prepared);
235 absl::StatusOr<Result> result = Execute(statement.get(), values);
236 if (result.ok() && sql.starts_with("SELECT") && reads_.size() < kMostReads) {
237 reads_.emplace(sql, std::move(statement));
238 }
239 return result;
240}
241
242absl::StatusOr<Result> Database::Execute(
243 MYSQL_STMT* statement, const std::vector<std::string>& values) {
244 if (mysql_stmt_param_count(statement) != values.size()) {
245 return absl::InvalidArgumentError(
246 "the statement needs a different number of values");
247 }
248
249 // Each value goes in as text, and MySQL converts it to its column's type.
250 std::vector<MYSQL_BIND> params(values.size());
251 for (std::size_t i = 0; i < values.size(); ++i) {
252 params[i].buffer_type = MYSQL_TYPE_STRING;
253 params[i].buffer = const_cast<char*>(values[i].data());
254 params[i].buffer_length = values[i].size();
255 }
256 if ((!params.empty() &&
257 mysql_stmt_bind_param(statement, params.data()) != 0) ||
258 mysql_stmt_execute(statement) != 0) {
259 return StatementError(statement);
260 }
261
262 Result result;
263 result.insert_id = mysql_stmt_insert_id(statement);
264 result.affected_rows = mysql_stmt_affected_rows(statement);
265 const unsigned int columns = mysql_stmt_field_count(statement);
266 if (columns == 0) {
267 return result;
268 }
269
270 std::vector<Value> row(columns);
271 std::vector<MYSQL_BIND> bound(columns);
272 for (unsigned int i = 0; i < columns; ++i) {
273 bound[i].buffer_type = MYSQL_TYPE_STRING;
274 bound[i].buffer = row[i].bytes.data();
275 bound[i].buffer_length = kValueSize;
276 bound[i].length = &row[i].length;
277 bound[i].is_null = &row[i].null;
278 }
279 if (mysql_stmt_bind_result(statement, bound.data()) != 0) {
280 return StatementError(statement);
281 }
282 int status = 0;
283 while ((status = mysql_stmt_fetch(statement)) == 0) {
284 std::vector<std::string>& copy = result.rows.emplace_back();
285 for (const Value& value : row) {
286 copy.emplace_back(value.bytes.data(), value.null ? 0 : value.length);
287 }
288 }
289 if (status == MYSQL_DATA_TRUNCATED) {
290 return absl::OutOfRangeError(
291 absl::StrCat("a value didn't fit in ", kValueSize, " bytes"));
292 }
293 if (status != MYSQL_NO_DATA) {
294 return StatementError(statement);
295 }
296 return result;
297}
298
300 const std::function<absl::Status()>& statements) {
301 // Its statements' spans go under it, and the commit's time is its own.
302 const Span span = StartChildSpan("mysql transaction", SpanKind::kInternal);
303 if (const absl::Status ready = Ready(); !ready.ok()) {
304 return ready;
305 }
306 const auto start = std::chrono::steady_clock::now();
307 // Turning autocommit off is the first thing to reach MySQL, so a connection
308 // that's gone stale fails there, before anything has run, and we connect
309 // again.
310 if (mysql_autocommit(mysql_, false) != 0) {
311 const absl::Status connected =
312 TimedOut(start) ? absl::UnavailableError("MySQL didn't answer in time")
313 : Connect();
314 if (!connected.ok()) {
315 Notice(connected, start);
316 return connected;
317 }
318 if (mysql_autocommit(mysql_, false) != 0) {
319 return Error(mysql_errno(mysql_), mysql_error(mysql_));
320 }
321 }
322 in_transaction_ = true;
323 absl::Status status = statements();
324 in_transaction_ = false;
325 if (status.ok() && mysql_commit(mysql_) != 0) {
326 status = Error(mysql_errno(mysql_), mysql_error(mysql_));
327 }
328 if (!status.ok()) {
329 mysql_rollback(mysql_);
330 }
331 mysql_autocommit(mysql_, true);
332 Notice(status, start);
333 return status;
334}
335
336} // namespace nanommo
Database(const Database &)=delete
static absl::StatusOr< std::unique_ptr< Database > > Create(const std::string &host, const std::string &user, const std::string &password, const std::string &name, MysqlTimeouts timeouts={})
Definition database.cc:106
absl::Status Transaction(const std::function< absl::Status()> &statements)
Definition database.cc:299
static constexpr std::size_t kMostReads
The most reads a connection keeps prepared.
Definition database.h:64
absl::StatusOr< Result > Run(std::string_view sql, const std::vector< std::string > &values={})
Definition database.cc:186
Definition chat.cc:9
std::unique_ptr< MYSQL_STMT, CloseStatement > Statement
Definition database.h:26
bool InTrace()
Definition tracing.cc:402
Span StartChildSpan(std::string_view name, SpanKind kind)
Definition tracing.cc:404
std::chrono::seconds answer
Definition database.h:44
std::chrono::seconds connect
For connecting.
Definition database.h:40