Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/main'
Browse files Browse the repository at this point in the history
  • Loading branch information
luanluciano93 committed May 29, 2024
2 parents 6edfcef + e3fefe8 commit 056995c
Show file tree
Hide file tree
Showing 14 changed files with 98 additions and 119 deletions.
43 changes: 43 additions & 0 deletions .github/workflows/mysql-schema-check.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
name: MySQL Schema Check
on:
workflow_dispatch:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
paths:
- "schema.sql"
merge_group:
push:
paths:
- "schema.sql"
branches:
- main

jobs:
mysql-schema-check:
runs-on: ubuntu-latest
services:
mysql:
image: mysql:8.0
env:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: canary
MYSQL_USER: canary
MYSQL_PASSWORD: canary
ports:
- 3306/tcp
options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3
strategy:
fail-fast: false
name: Check
steps:
- name: Checkout repository
uses: actions/checkout@main
- name: 📌 MySQL Start & init & show db
run: |
sudo /etc/init.d/mysql start
mysql -e 'CREATE DATABASE canary;' -uroot -proot
mysql -e "SHOW DATABASES" -uroot -proot
- name: Import Canary Schema
run: |
mysql -uroot -proot canary < schema.sql
4 changes: 2 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ cmake_minimum_required(VERSION 3.22 FATAL_ERROR)
# VCPKG
# cmake -DCMAKE_TOOLCHAIN_FILE=/opt/workspace/vcpkg/scripts/buildsystems/vcpkg.cmake ..
# Needed libs is in file vcpkg.json
# Windows required libs: .\vcpkg install --triplet x64-windows asio pugixml spdlog curl protobuf parallel-hashmap magic-enum mio luajit libmariadb mpir abseil
# Windows required libs: .\vcpkg install --triplet x64-windows asio pugixml spdlog curl protobuf parallel-hashmap magic-enum mio luajit libmariadb mpir abseil bshoshany-thread-pool
if(DEFINED ENV{VCPKG_ROOT} AND NOT DEFINED CMAKE_TOOLCHAIN_FILE)
set(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
CACHE STRING "")
Expand Down Expand Up @@ -124,4 +124,4 @@ add_subdirectory(src)

if(BUILD_TESTS)
add_subdirectory(tests)
endif()
endif()
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ local config = {
from = Position(33705, 31463, 14),
to = Position(33719, 31477, 14),
},
exit = Position(33609, 31499, 10),
exit = Position(33609, 31495, 10),
}

local lever = BossLever(config)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
local config = {
monsterName = "Preceptor Lazare",
bossPosition = Position(33374, 31338, 3),
range = 5,
range = 50,
}

local preceptorLazare = GlobalEvent("PreceptorLazareRespawn")
Expand Down
4 changes: 2 additions & 2 deletions src/database/databasetasks.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ DatabaseTasks &DatabaseTasks::getInstance() {
}

void DatabaseTasks::execute(const std::string &query, std::function<void(DBResult_ptr, bool)> callback /* nullptr */) {
threadPool.addLoad([this, query, callback]() {
threadPool.detach_task([this, query, callback]() {
bool success = db.executeQuery(query);
if (callback != nullptr) {
g_dispatcher().addEvent([callback, success]() { callback(nullptr, success); }, "DatabaseTasks::execute");
Expand All @@ -32,7 +32,7 @@ void DatabaseTasks::execute(const std::string &query, std::function<void(DBResul
}

void DatabaseTasks::store(const std::string &query, std::function<void(DBResult_ptr, bool)> callback /* nullptr */) {
threadPool.addLoad([this, query, callback]() {
threadPool.detach_task([this, query, callback]() {
DBResult_ptr result = db.storeQuery(query);
if (callback != nullptr) {
g_dispatcher().addEvent([callback, result]() { callback(result, true); }, "DatabaseTasks::store");
Expand Down
6 changes: 3 additions & 3 deletions src/game/scheduling/dispatcher.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ Dispatcher &Dispatcher::getInstance() {
void Dispatcher::init() {
UPDATE_OTSYS_TIME();

threadPool.addLoad([this] {
threadPool.detach_task([this] {
std::unique_lock asyncLock(dummyMutex);

while (!threadPool.getIoContext().stopped()) {
while (!threadPool.isStopped()) {
UPDATE_OTSYS_TIME();

executeEvents();
Expand Down Expand Up @@ -60,7 +60,7 @@ void Dispatcher::executeParallelEvents(std::vector<Task> &tasks, const uint8_t g
std::atomic_bool isTasksCompleted = false;

for (const auto &task : tasks) {
threadPool.addLoad([groupId, &task, &isTasksCompleted, &totalTaskSize] {
threadPool.detach_task([groupId, &task, &isTasksCompleted, &totalTaskSize] {
dispacherContext.type = DispatcherType::AsyncEvent;
dispacherContext.group = static_cast<TaskGroup>(groupId);
dispacherContext.taskName = task.getContext();
Expand Down
2 changes: 1 addition & 1 deletion src/game/scheduling/dispatcher.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ class Dispatcher {
public:
explicit Dispatcher(ThreadPool &threadPool) :
threadPool(threadPool) {
threads.reserve(threadPool.getNumberOfThreads() + 1);
threads.reserve(threadPool.get_thread_count() + 1);
for (uint_fast16_t i = 0; i < threads.capacity(); ++i) {
threads.emplace_back(std::make_unique<ThreadTask>());
}
Expand Down
4 changes: 2 additions & 2 deletions src/game/scheduling/save_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ void SaveManager::scheduleAll() {
return;
}

threadPool.addLoad([this, scheduledAt]() {
threadPool.detach_task([this, scheduledAt]() {
if (m_scheduledAt.load() != scheduledAt) {
logger.warn("Skipping save for server because another save has been scheduled.");
return;
Expand Down Expand Up @@ -69,7 +69,7 @@ void SaveManager::schedulePlayer(std::weak_ptr<Player> playerPtr) {
logger.debug("Scheduling player {} for saving.", playerToSave->getName());
auto scheduledAt = std::chrono::steady_clock::now();
m_playerMap[playerToSave->getGUID()] = scheduledAt;
threadPool.addLoad([this, playerPtr, scheduledAt]() {
threadPool.detach_task([this, playerPtr, scheduledAt]() {
auto player = playerPtr.lock();
if (!player) {
logger.debug("Skipping save for player because player is no longer online.");
Expand Down
2 changes: 1 addition & 1 deletion src/lib/thread/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ int main() {
ThreadPool &pool = inject<ThreadPool>(); // preferrably uses constructor injection or setter injection.

// Post a task to the thread pool
pool.addLoad([]() {
pool.detach_task([]() {
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
});
}
Expand Down
77 changes: 10 additions & 67 deletions src/lib/thread/thread_pool.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,84 +14,27 @@
#include "game/game.hpp"
#include "utils/tools.hpp"

/**
* Regardless of how many cores your computer have, we want at least
* 4 threads because, even though they won't improve processing they
* will make processing non-blocking in some way and that would allow
* single core computers to process things concurrently, but not in parallel.
*/

#ifndef DEFAULT_NUMBER_OF_THREADS
#define DEFAULT_NUMBER_OF_THREADS 4
#endif

ThreadPool::ThreadPool(Logger &logger) :

Check warning on line 28 in src/lib/thread/thread_pool.cpp

View workflow job for this annotation

GitHub Actions / ubuntu-22.04-linux-debug

when initialized here [-Wreorder]
logger(logger) {
logger(logger), BS::thread_pool(std::max<int>(getNumberOfCores(), DEFAULT_NUMBER_OF_THREADS)) {

Check warning on line 29 in src/lib/thread/thread_pool.cpp

View workflow job for this annotation

GitHub Actions / ubuntu-22.04-linux-debug

base ‘BS::thread_pool’ [-Wreorder]
start();
}

void ThreadPool::start() {
logger.info("Setting up thread pool");

/**
* Regardless of how many cores your computer have, we want at least
* 4 threads because, even though they won't improve processing they
* will make processing non-blocking in some way and that would allow
* single core computers to process things concurrently, but not in parallel.
*/
nThreads = std::max<uint16_t>(static_cast<int>(getNumberOfCores()), DEFAULT_NUMBER_OF_THREADS);

for (std::size_t i = 0; i < nThreads; ++i) {
threads.emplace_back([this] { ioService.run(); });
}

logger.info("Running with {} threads.", threads.size());
logger.info("Running with {} threads.", get_thread_count());
}

void ThreadPool::shutdown() {
if (ioService.stopped()) {
return;
}

stopped = true;
logger.info("Shutting down thread pool...");

ioService.stop();

std::vector<std::future<void>> futures;
for (std::size_t i = 0; i < threads.size(); i++) {
logger.debug("Joining thread {}/{}.", i + 1, threads.size());

if (threads[i].joinable()) {
futures.emplace_back(std::async(std::launch::async, [&]() {
threads[i].join();
}));
}
}

std::future_status status = std::future_status::timeout;
auto timeout = std::chrono::seconds(5);
auto start = std::chrono::steady_clock::now();
int tries = 0;
while (status == std::future_status::timeout && std::chrono::steady_clock::now() - start < timeout) {
tries++;
if (tries > 5) {
break;
}
for (auto &future : futures) {
status = future.wait_for(std::chrono::seconds(0));
if (status != std::future_status::timeout) {
break;
}
}
}
}

asio::io_context &ThreadPool::getIoContext() {
return ioService;
}

void ThreadPool::addLoad(const std::function<void(void)> &load) {
asio::post(ioService, [this, load]() {
if (ioService.stopped()) {
if (g_game().getGameState() != GAME_STATE_SHUTDOWN) {
logger.error("Shutting down, cannot execute task.");
}
return;
}

load();
});
}
19 changes: 7 additions & 12 deletions src/lib/thread/thread_pool.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
#pragma once

#include "lib/logging/logger.hpp"
#include "BS_thread_pool.hpp"

class ThreadPool {
class ThreadPool : public BS::thread_pool {
public:
explicit ThreadPool(Logger &logger);

Expand All @@ -20,12 +21,6 @@ class ThreadPool {

void start();
void shutdown();
asio::io_context &getIoContext();
void addLoad(const std::function<void(void)> &load);

uint16_t getNumberOfThreads() const {
return nThreads;
}

static int16_t getThreadId() {
static std::atomic_int16_t lastId = -1;
Expand All @@ -39,11 +34,11 @@ class ThreadPool {
return id;
};

bool isStopped() const {
return stopped;
}

private:
Logger &logger;

Check warning on line 42 in src/lib/thread/thread_pool.hpp

View workflow job for this annotation

GitHub Actions / ubuntu-22.04-linux-debug

‘ThreadPool::logger’ will be initialized after [-Wreorder]
asio::io_context ioService;
std::vector<std::jthread> threads;
asio::io_context::work work { ioService };

uint16_t nThreads = 0;
bool stopped = false;
};
49 changes: 23 additions & 26 deletions src/map/map.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -320,13 +320,22 @@ bool Map::placeCreature(const Position &centerPos, std::shared_ptr<Creature> cre
}

void Map::moveCreature(const std::shared_ptr<Creature> &creature, const std::shared_ptr<Tile> &newTile, bool forceTeleport /* = false*/) {
auto oldTile = creature->getTile();
if (!creature || !newTile) {
return;
}

const auto &oldTile = creature->getTile();

if (!oldTile) {
return;
}

Position oldPos = oldTile->getPosition();
Position newPos = newTile->getPosition();
const auto &oldPos = oldTile->getPosition();
const auto &newPos = newTile->getPosition();

const auto &fromZones = oldTile->getZones();
const auto &toZones = newTile->getZones();

if (auto ret = g_game().beforeCreatureZoneChange(creature, fromZones, toZones); ret != RETURNVALUE_NOERROR) {
return;
}
Expand Down Expand Up @@ -695,29 +704,17 @@ uint32_t Map::clean() {

ItemVector toRemove;
toRemove.reserve(128);
for (const auto &mit : mapSectors) {
for (uint8_t z = 0; z < MAP_MAX_LAYERS; ++z) {
if (const auto &floor = mit.second.getFloor(z)) {
for (auto &tiles : floor->getTiles()) {
for (const auto &[tile, cachedTile] : tiles) {
if (!tile || tile->hasFlag(TILESTATE_PROTECTIONZONE)) {
continue;
}

TileItemVector* itemList = tile->getItemList();
if (!itemList) {
continue;
}

++qntTiles;

for (auto it = ItemVector::const_reverse_iterator(itemList->getEndDownItem()), end = ItemVector::const_reverse_iterator(itemList->getBeginDownItem()); it != end; ++it) {
const auto &item = *it;
if (item->isCleanable()) {
toRemove.push_back(item);
}
}
}

for (const auto &tile : g_game().getTilesToClean()) {
if (!tile) {
continue;
}

if (const auto items = tile->getItemList()) {
++qntTiles;
for (const auto &item : *items) {
if (item->isCleanable()) {
toRemove.emplace_back(item);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/server/network/webhook/webhook.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Webhook &Webhook::getInstance() {
}

void Webhook::run() {
threadPool.addLoad([this] { sendWebhook(); });
threadPool.detach_task([this] { sendWebhook(); });
g_dispatcher().scheduleEvent(
g_configManager().getNumber(DISCORD_WEBHOOK_DELAY_MS, __FUNCTION__), [this] { run(); }, "Webhook::run"
);
Expand Down
1 change: 1 addition & 0 deletions vcpkg.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"pugixml",
"spdlog",
"zlib",
"bshoshany-thread-pool",
{
"name": "libmariadb",
"features": [
Expand Down

0 comments on commit 056995c

Please sign in to comment.