diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index a8cd5913..59fb5427 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -16,12 +16,19 @@ CollectAndAddSourceFiles( common ${CMAKE_CURRENT_SOURCE_DIR} EXCLUDE + ${CMAKE_CURRENT_SOURCE_DIR}/Threading/Coro ${CMAKE_CURRENT_SOURCE_DIR}/Debugging/Windows ${CMAKE_CURRENT_SOURCE_DIR}/Platform ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders ${CMAKE_CURRENT_SOURCE_DIR}/mmaps_common ${CMAKE_CURRENT_SOURCE_DIR}/network) +CollectAndAddSourceFiles( + common + ${CMAKE_CURRENT_SOURCE_DIR}/Threading/Coro + BASE_DIR ${CMAKE_CURRENT_SOURCE_DIR} + NO_INCLUDE_SUBDIRECTORIES) + if(WIN32) CollectAndAddSourceFiles( common diff --git a/src/common/Threading/Coro/AllOf.h b/src/common/Threading/Coro/AllOf.h new file mode 100644 index 00000000..1e9ff5ce --- /dev/null +++ b/src/common/Threading/Coro/AllOf.h @@ -0,0 +1,117 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_ALL_OF_H +#define TRINITYCORE_CORO_ALL_OF_H + +#include "./Awaitable.h" +#include "./CoroutineExecutionContext.h" +#include "./CoroutineFwd.h" +#include "Memory.h" +#include "Types.h" +#include "advstd.h" +#include + +namespace Trinity::Coro +{ +namespace Impl +{ +template +class AllOfAwaitable +{ +public: + template + using return_type_element = std::conditional_t, + std::add_lvalue_reference_t::return_type>, + std::remove_reference_t::return_type>>; + + explicit AllOfAwaitable(Awaitables&&... awaitables) + : _awaitables(AllOfAwaitable::AwaitableWrapper(this, std::forward(awaitables))...) { } + + bool await_ready() const noexcept { return _context && !_context->Handle.done(); } + + template promise_type> + void await_suspend(std::coroutine_handle coroutine) noexcept + { + _context = &coroutine.promise(); + auto startCoro = [](CoroutineExecutionContext* context, auto&& awaitable) + { + auto& promise = awaitable.promise(); + promise.CurrentExecutor = context->CurrentExecutor; + promise.QueueCompletion(); + }; + std::apply([&](auto&&... awaitables) { (startCoro(_context, awaitables), ...); }, _awaitables); + } + + auto await_resume() + { + using InputTuple = std::tuple; + + // call .get_result() on void returning awaitables to rethrow their exceptions + auto voidsSequence = Trinity::filter_index_sequence(std::index_sequence_for{}, + [](std::index_sequence) constexpr { return std::is_void_v>>; }); + [&](std::index_sequence) + { + (std::get(_awaitables).promise().get_result(), ...); + }(voidsSequence); + + auto valuesSequence = Trinity::filter_index_sequence(std::index_sequence_for{}, + [](std::index_sequence) constexpr { return !std::is_void_v>>; }); + + // return values from all awaitables + // tuple element types are transformed like this + // * if input awaitable was lvalue ref then tuple element is also lvalue ref + // * if input awaitable was a rvalue ref or a value then tuple element is a value + // * awaitables returning void are skipped in result tuple + return [&](std::index_sequence) + { + return std::tuple>...>( + advstd::forward_like>>(std::get(_awaitables).promise()).get_result()... + ); + }(valuesSequence); + } + +private: + // this class takes ownership of rvalue awaitables by passing them by value to wrapper coroutine + template + static Awaitable> AwaitableWrapper(AllOfAwaitable* allOf, + std::conditional_t, WrappedAwaitable, std::remove_reference_t> awaitable) + { + auto completionGuard = Trinity::make_unique_ptr_with_deleter<&AllOfAwaitable::OnChildComplete>(allOf); + co_return co_await awaitable; + } + + void OnChildComplete() + { + if (_pending.fetch_sub(1, std::memory_order::acq_rel) == 1) + _context->QueueCompletion(); + } + + std::tuple>...> _awaitables; + std::atomic _pending = sizeof...(Awaitables); + CoroutineExecutionContext* _context = nullptr; +}; +} + +template +inline auto AllOf(Awaitables&&... awaitables) -> Impl::AllOfAwaitable +{ + return Impl::AllOfAwaitable(std::forward(awaitables)...); +} +} + +#endif // TRINITYCORE_CORO_ALL_OF_H diff --git a/src/common/Threading/Coro/Allocator.cpp b/src/common/Threading/Coro/Allocator.cpp new file mode 100644 index 00000000..030125be --- /dev/null +++ b/src/common/Threading/Coro/Allocator.cpp @@ -0,0 +1,50 @@ +/* + * 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 . + */ + +#include "./Allocator.h" +#include "./AllocatorImpl.h" + +namespace Trinity::Coro::Impl +{ +namespace CurrentAllocator +{ +namespace +{ +thread_local Allocator* Instance; +} + +Allocator* Get() +{ + return Instance; +} + +void Set(Allocator* allocator) +{ + Instance = allocator; +} + +void* Allocate(std::size_t size) +{ + return Instance->allocate(size); +} + +void Free(void* data, std::size_t size) +{ + Instance->deallocate(data, size); +} +} +} diff --git a/src/common/Threading/Coro/Allocator.h b/src/common/Threading/Coro/Allocator.h new file mode 100644 index 00000000..1cb896fa --- /dev/null +++ b/src/common/Threading/Coro/Allocator.h @@ -0,0 +1,38 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_ALLOCATOR_H +#define TRINITYCORE_CORO_ALLOCATOR_H + +#include "./CoroutineFwd.h" +#include "Define.h" + +namespace Trinity::Coro::Impl +{ +struct Allocator; + +namespace CurrentAllocator +{ +TC_COMMON_API Allocator* Get(); +TC_COMMON_API void Set(Allocator* allocator); + +TC_COMMON_API void* Allocate(std::size_t size); +TC_COMMON_API void Free(void* data, std::size_t size); +} +} + +#endif // TRINITYCORE_CORO_ALLOCATOR_H diff --git a/src/common/Threading/Coro/AllocatorImpl.h b/src/common/Threading/Coro/AllocatorImpl.h new file mode 100644 index 00000000..2202297a --- /dev/null +++ b/src/common/Threading/Coro/AllocatorImpl.h @@ -0,0 +1,32 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_ALLOCATOR_IMPL_H +#define TRINITYCORE_CORO_ALLOCATOR_IMPL_H + +#include "./CoroutineFwd.h" +#include + +namespace Trinity::Coro::Impl +{ +struct Allocator final : std::pmr::unsynchronized_pool_resource +{ + using unsynchronized_pool_resource::unsynchronized_pool_resource; +}; +} + +#endif // TRINITYCORE_CORO_ALLOCATOR_IMPL_H diff --git a/src/common/Threading/Coro/AsioExecutorAdapter.h b/src/common/Threading/Coro/AsioExecutorAdapter.h new file mode 100644 index 00000000..c69b61e4 --- /dev/null +++ b/src/common/Threading/Coro/AsioExecutorAdapter.h @@ -0,0 +1,38 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_ASIO_EXECUTOR_ADAPTER_H +#define TRINITYCORE_CORO_ASIO_EXECUTOR_ADAPTER_H + +#include "./Executor.h" +#include "AsioHacksFwd.h" + +namespace Trinity::Coro +{ +class TC_COMMON_API AsioExecutorAdapter final : public Executor +{ +public: + explicit AsioExecutorAdapter(Asio::IoContext& ioContext) : _ioContext(ioContext) { } + + void QueueCompletion(CoroutineExecutionContext* context) override; + +private: + Asio::IoContext& _ioContext; +}; +} + +#endif // TRINITYCORE_CORO_ASIO_EXECUTOR_ADAPTER_H diff --git a/src/common/Threading/Coro/Awaitable.h b/src/common/Threading/Coro/Awaitable.h new file mode 100644 index 00000000..704b9e12 --- /dev/null +++ b/src/common/Threading/Coro/Awaitable.h @@ -0,0 +1,223 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_AWAITABLE_H +#define TRINITYCORE_CORO_AWAITABLE_H + +#include "./Allocator.h" +#include "./CoroutineExecutionContext.h" +#include "./CoroutineFwd.h" +#include "./ResultValue.h" +#include +#include +#include +#include + +namespace Trinity::Coro +{ +namespace Impl +{ +class PromiseBase : public CoroutineExecutionContext +{ +public: + explicit PromiseBase(std::coroutine_handle<> handle) : CoroutineExecutionContext(handle) { } + + struct FinalAwaitable + { + bool await_ready() const noexcept { return false; } + + template promise_type> + std::coroutine_handle<> await_suspend(std::coroutine_handle coroutine) noexcept + { + promise_type& promise = coroutine.promise(); + return promise.Next ? promise.Next : std::noop_coroutine(); + } + + void await_resume() noexcept { } + }; + + template promise_type> + void set_next(std::coroutine_handle next) + { + Next = next; + CurrentExecutor = next.promise().CurrentExecutor; + } + +protected: + std::coroutine_handle<> Next; +}; + +template +class Promise : public PromiseBase +{ +public: + Promise() : PromiseBase(std::coroutine_handle::from_promise(*this)) { } + + Awaitable get_return_object() noexcept; + + std::suspend_always initial_suspend() noexcept { return { }; } + + FinalAwaitable final_suspend() noexcept { return { }; } + + template ::value_holder> V> + void return_value(V&& value) { _resultValue.set_value(std::forward(value)); } + + void unhandled_exception() { _resultValue.set_exception(std::current_exception()); } + + T& get_result() & { return _resultValue.get(); } + + T&& get_result() && { return std::move(_resultValue).get(); } + + bool has_result() const { return _resultValue.has_value_or_exception(); } + + void* operator new(std::size_t size) + { + return CurrentAllocator::Allocate(size); + } + + void operator delete(void* ptr, std::size_t size) noexcept + { + CurrentAllocator::Free(ptr, size); + } + +private: + ResultValue _resultValue; +}; + +template <> +class Promise : public PromiseBase +{ +public: + Promise() : PromiseBase(std::coroutine_handle::from_promise(*this)) { } + + Awaitable get_return_object() noexcept; + + std::suspend_always initial_suspend() noexcept { return { }; } + + FinalAwaitable final_suspend() noexcept { return { }; } + + void return_void() { _resultValue.set_value(); } + + void unhandled_exception() { _resultValue.set_exception(std::current_exception()); } + + void get_result() { return _resultValue.get(); } + + bool has_result() const { return _resultValue.has_value_or_exception(); } + + void* operator new(std::size_t size) + { + return CurrentAllocator::Allocate(size); + } + + void operator delete(void* ptr, std::size_t size) noexcept + { + CurrentAllocator::Free(ptr, size); + } + +private: + ResultValue _resultValue; +}; + +template Promise> +class AwaiterBase +{ +public: + explicit AwaiterBase(std::coroutine_handle coroutine) noexcept : _coroutine(coroutine) { } + + bool await_ready() const noexcept { return !_coroutine || _coroutine.done(); } + + template promise_type> + std::coroutine_handle<> await_suspend(std::coroutine_handle next) noexcept + { + Promise& promise = _coroutine.promise(); + promise.set_next(next); + return _coroutine; + } + +protected: + std::coroutine_handle _coroutine; +}; + +template Promise, bool RValue> +class Awaiter : public AwaiterBase +{ +public: + using AwaiterBase::AwaiterBase; + + decltype(auto) await_resume() + { + if constexpr (RValue) + return std::move(this->_coroutine.promise()).get_result(); + else + return this->_coroutine.promise().get_result(); + } +}; +} + +template +class Awaitable +{ +public: + using promise_type = Impl::Promise; + using return_type = T; + + Awaitable() noexcept = default; + + explicit Awaitable(std::coroutine_handle coroutine) : _coroutine(coroutine) { } + + Awaitable(Awaitable const&) = delete; + Awaitable(Awaitable&& other) noexcept : _coroutine(std::exchange(other._coroutine, nullptr)) { } + + Awaitable& operator=(Awaitable const&) = delete; + Awaitable& operator=(Awaitable&& right) noexcept + { + if (this != &right) + { + if (_coroutine) + _coroutine.destroy(); + + _coroutine = std::exchange(right._coroutine, nullptr); + } + + return *this; + } + + ~Awaitable() + { + if (_coroutine) + _coroutine.destroy(); + } + + Impl::Awaiter operator co_await() const & noexcept { return Impl::Awaiter(_coroutine); } + Impl::Awaiter operator co_await() const && noexcept { return Impl::Awaiter(_coroutine); } + + promise_type& promise() const { return _coroutine.promise(); } + +private: + std::coroutine_handle _coroutine; +}; + +namespace Impl +{ +template +inline Awaitable Promise::get_return_object() noexcept { return Awaitable(std::coroutine_handle::from_promise(*this)); } + +inline Awaitable Promise::get_return_object() noexcept { return Awaitable(std::coroutine_handle::from_promise(*this)); } +} +} + +#endif // TRINITYCORE_CORO_AWAITABLE_H diff --git a/src/common/Threading/Coro/AwaitableValue.cpp b/src/common/Threading/Coro/AwaitableValue.cpp new file mode 100644 index 00000000..06ecf6b8 --- /dev/null +++ b/src/common/Threading/Coro/AwaitableValue.cpp @@ -0,0 +1,68 @@ +/* + * 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 . + */ + +#include "./AwaitableValue.h" +#include "./CoroutineExecutionContext.h" + +namespace Trinity::Coro::Impl +{ +namespace +{ + constexpr AwaitableValueAwaiterData READY_MARKER; +} + +bool AwaitableValueAwaiterBase::await_ready() const noexcept +{ + return Value._waitQueue.load(std::memory_order::acquire) == &READY_MARKER; +} + +bool AwaitableValueAwaiterBase::handle_suspend(CoroutineExecutionContext* coroutine) noexcept +{ + Coroutine = coroutine; + + AwaitableValueAwaiterData const* old = Value._waitQueue.load(std::memory_order::acquire); + do + { + if (old == &READY_MARKER) + return false; // value is now ready, don't suspend + + Next = old; + } while (!Value._waitQueue.compare_exchange_weak(old, this, std::memory_order::release, std::memory_order::acquire)); + + return true; +} + +void AwaitableValueBase::notify_waiters() +{ + AwaitableValueAwaiterData const* waiter = _waitQueue.exchange(&READY_MARKER, std::memory_order::acq_rel); + if (waiter != &READY_MARKER) + { + while (waiter) + { + AwaitableValueAwaiterData const* next = waiter->Next; + waiter->Coroutine->QueueCompletion(); + waiter = next; + } + } +} + +bool AwaitableValueBase::reset_waiters() +{ + AwaitableValueAwaiterData const* old = &READY_MARKER; + return _waitQueue.compare_exchange_strong(old, nullptr, std::memory_order::acquire); +} +} diff --git a/src/common/Threading/Coro/AwaitableValue.h b/src/common/Threading/Coro/AwaitableValue.h new file mode 100644 index 00000000..19d27574 --- /dev/null +++ b/src/common/Threading/Coro/AwaitableValue.h @@ -0,0 +1,127 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_AWAITABLE_VALUE_H +#define TRINITYCORE_CORO_AWAITABLE_VALUE_H + +#include "./CoroutineFwd.h" +#include "./ResultValue.h" +#include "Define.h" +#include +#include +#include + +namespace Trinity::Coro +{ +namespace Impl +{ +class AwaitableValueBase; + +struct AwaitableValueAwaiterData +{ + AwaitableValueAwaiterData const* Next = nullptr; + CoroutineExecutionContext* Coroutine = nullptr; +}; + +struct TC_COMMON_API AwaitableValueAwaiterBase : AwaitableValueAwaiterData +{ + explicit AwaitableValueAwaiterBase(AwaitableValueBase& value) noexcept : Value(value) { } + + bool await_ready() const noexcept; + + template promise_type> + bool await_suspend(std::coroutine_handle coroutine) noexcept + { + return this->handle_suspend(&coroutine.promise()); + } + +private: + bool handle_suspend(CoroutineExecutionContext* coroutine) noexcept; + +protected: + AwaitableValueBase& Value; +}; + +class TC_COMMON_API AwaitableValueBase +{ +protected: + void notify_waiters(); + + bool reset_waiters(); + + friend AwaitableValueAwaiterBase; + std::atomic _waitQueue; +}; +} + +template +class AwaitableValue : public Impl::AwaitableValueBase +{ +public: + template + struct Awaiter : Impl::AwaitableValueAwaiterBase + { + explicit Awaiter(AwaitableValue& value) noexcept : AwaitableValueAwaiterBase(value) { } + + decltype(auto) await_resume() + { + if constexpr (RValue) + return std::move(static_cast(Value)._resultValue).get(); + else + return static_cast(Value)._resultValue.get(); + } + }; + + explicit AwaitableValue() noexcept = default; + AwaitableValue(AwaitableValue const&) = delete; + AwaitableValue(AwaitableValue&&) = delete; + AwaitableValue& operator=(AwaitableValue const&) = delete; + AwaitableValue& operator=(AwaitableValue&&) = delete; + ~AwaitableValue() = default; + + template ::value_holder> V> + void set_value(V&& value) requires (!std::same_as) + { + _resultValue.set_value(std::forward(value)); + + this->notify_waiters(); + } + + void set_value() requires (std::same_as) + { + _resultValue.set_value(); + + this->notify_waiters(); + } + + void reset() noexcept + { + if (this->reset_waiters()) + _resultValue.reset(); + } + + Awaiter operator co_await() & noexcept { return Awaiter(*this); } + Awaiter operator co_await() && noexcept { return Awaiter(*this); } + +private: + template + friend struct Awaiter; + ResultValue _resultValue; +}; +} + +#endif // TRINITYCORE_CORO_AWAITABLE_VALUE_H diff --git a/src/common/Threading/Coro/CoroutineExecutionContext.h b/src/common/Threading/Coro/CoroutineExecutionContext.h new file mode 100644 index 00000000..e3c8fd1b --- /dev/null +++ b/src/common/Threading/Coro/CoroutineExecutionContext.h @@ -0,0 +1,43 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_EXECUTION_CONTEXT_H +#define TRINITYCORE_CORO_EXECUTION_CONTEXT_H + +#include "./Allocator.h" +#include "./CoroutineFwd.h" +#include "UniqueTrackablePtr.h" +#include +#include + +namespace Trinity::Coro +{ +struct CoroutineExecutionContext +{ + explicit CoroutineExecutionContext(std::coroutine_handle<> handle) noexcept : Handle(handle) { } + + TC_COMMON_API void Resume() noexcept; + TC_COMMON_API void QueueCompletion() noexcept; + + std::atomic QueueLink; + std::coroutine_handle<> Handle; + unique_weak_ptr CurrentExecutor; + Impl::Allocator* CurrentAllocator = Impl::CurrentAllocator::Get(); +}; +} + +#endif // TRINITYCORE_CORO_EXECUTION_CONTEXT_H diff --git a/src/common/Threading/Coro/CoroutineFwd.h b/src/common/Threading/Coro/CoroutineFwd.h new file mode 100644 index 00000000..125066ba --- /dev/null +++ b/src/common/Threading/Coro/CoroutineFwd.h @@ -0,0 +1,40 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_COROUTINE_FWD_H +#define TRINITYCORE_COROUTINE_FWD_H + +namespace Trinity::Coro +{ +template +class Awaitable; + +struct CoroutineExecutionContext; + +class Executor; +class AsioExecutorAdapter; +class MultiThreadedExecutor; +class SingleThreadedExecutor; + +template +class ResultValue; + +template +class AwaitableValue; +} + +#endif // TRINITYCORE_COROUTINE_FWD_H diff --git a/src/common/Threading/Coro/CurrentCoroutine.h b/src/common/Threading/Coro/CurrentCoroutine.h new file mode 100644 index 00000000..0a658d24 --- /dev/null +++ b/src/common/Threading/Coro/CurrentCoroutine.h @@ -0,0 +1,54 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CURRENT_COROUTINE_H +#define TRINITYCORE_CURRENT_COROUTINE_H + +#include "./CoroutineExecutionContext.h" +#include "./CoroutineFwd.h" + +namespace Trinity::Coro +{ +namespace Impl +{ +struct CurrentCoroutineBaseAwaiter +{ + bool await_ready() const noexcept { return false; } + + template promise_type> + bool await_suspend(std::coroutine_handle coroutine) noexcept + { + Context = &coroutine.promise(); + return false; + } + + CoroutineExecutionContext* Context = nullptr; +}; + +struct CurrentExecutorAwaiter : CurrentCoroutineBaseAwaiter +{ + unique_weak_ptr await_resume() const noexcept { return Context->CurrentExecutor; } +}; +} + +struct CurrentExecutorAwaitable +{ + Impl::CurrentExecutorAwaiter operator co_await() const noexcept { return { }; } +} inline constexpr CurrentExecutor; +} + +#endif // TRINITYCORE_CURRENT_COROUTINE_H diff --git a/src/common/Threading/Coro/Executor.cpp b/src/common/Threading/Coro/Executor.cpp new file mode 100644 index 00000000..b7829392 --- /dev/null +++ b/src/common/Threading/Coro/Executor.cpp @@ -0,0 +1,154 @@ +/* + * 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 . + */ + +#include "./Executor.h" +#include "./Allocator.h" +#include "./AsioExecutorAdapter.h" +#include "./MultiThreadedExecutor.h" +#include "./SingleThreadedExecutor.h" +#include "IoContext.h" + +namespace Trinity::Coro +{ +void CoroutineExecutionContext::Resume() noexcept +{ + Impl::CurrentAllocator::Set(CurrentAllocator); + Handle.resume(); +} + +void CoroutineExecutionContext::QueueCompletion() noexcept +{ + if (unique_strong_ref_ptr executor = CurrentExecutor.lock()) + executor->QueueCompletion(this); + else + Handle.destroy(); +} + +void Executor::QueueCompletion(CoroutineExecutionContext* context) +{ + context->CurrentExecutor = weak_from_this(); +} + +void AsioExecutorAdapter::QueueCompletion(CoroutineExecutionContext* context) +{ + Executor::QueueCompletion(context); + + Trinity::Asio::post(_ioContext, [context] + { + context->Resume(); + }); +} + +void MultiThreadedExecutor::QueueCompletion(CoroutineExecutionContext* context) +{ + Executor::QueueCompletion(context); + + std::scoped_lock lock(_mutex); + + _resumeQueue.push_back(*context); + + _condition.notify_one(); +} + +void MultiThreadedExecutor::ResumeReadyCoroutines() +{ + do + { + CoroutineExecutionContext* coroutine; + { + std::scoped_lock lock(_mutex); + if (_resumeQueue.empty()) + break; + + coroutine = &_resumeQueue.front(); + _resumeQueue.pop_front(); + } + + coroutine->Resume(); + + } while (true); +} + +void MultiThreadedExecutor::WaitForReadyCoroutinesAndResume() +{ + do + { + CoroutineExecutionContext* coroutine; + { + std::unique_lock lock(_mutex); + + _condition.wait(lock, [&] { return !_resumeQueue.empty() || _stopped.test(std::memory_order::relaxed); }); + if (_resumeQueue.empty()) + break; + + coroutine = &_resumeQueue.front(); + _resumeQueue.pop_front(); + } + + coroutine->Resume(); + + } while (true); +} + +bool MultiThreadedExecutor::WaitForReadyCoroutinesAndResume(Milliseconds timeout) +{ + do + { + CoroutineExecutionContext* coroutine; + { + std::unique_lock lock(_mutex); + + if (!_condition.wait_for(lock, timeout, [&] { return !_resumeQueue.empty() || _stopped.test(std::memory_order::relaxed); })) + return false; + + if (_resumeQueue.empty()) + break; + + coroutine = &_resumeQueue.front(); + _resumeQueue.pop_front(); + } + + coroutine->Resume(); + + } while (true); + + return true; +} + +void MultiThreadedExecutor::StopWaiting() +{ + std::scoped_lock lock(_mutex); + + _stopped.test_and_set(std::memory_order::relaxed); + + _condition.notify_all(); +} + +void SingleThreadedExecutor::QueueCompletion(CoroutineExecutionContext* context) +{ + Executor::QueueCompletion(context); + + _resumeQueue.Enqueue(context); +} + +void SingleThreadedExecutor::ResumeReadyCoroutines() +{ + CoroutineExecutionContext* context = nullptr; + while (_resumeQueue.Dequeue(context)) + context->Resume(); +} +} diff --git a/src/common/Threading/Coro/Executor.h b/src/common/Threading/Coro/Executor.h new file mode 100644 index 00000000..a0935b16 --- /dev/null +++ b/src/common/Threading/Coro/Executor.h @@ -0,0 +1,41 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_EXECUTOR_H +#define TRINITYCORE_CORO_EXECUTOR_H + +#include "./CoroutineFwd.h" +#include "Define.h" +#include "UniqueTrackablePtr.h" + +namespace Trinity::Coro +{ +class TC_COMMON_API Executor : public enable_unique_weak_from_this +{ +public: + Executor() = default; + Executor(Executor const& other) = delete; + Executor(Executor&& other) noexcept = delete; + Executor& operator=(Executor const& other) = delete; + Executor& operator=(Executor&& other) noexcept = delete; + virtual ~Executor() = default; + + virtual void QueueCompletion(CoroutineExecutionContext* context) = 0; +}; +} + +#endif // TRINITYCORE_CORO_EXECUTOR_H diff --git a/src/common/Threading/Coro/MultiThreadedExecutor.h b/src/common/Threading/Coro/MultiThreadedExecutor.h new file mode 100644 index 00000000..bc56d025 --- /dev/null +++ b/src/common/Threading/Coro/MultiThreadedExecutor.h @@ -0,0 +1,52 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_MULTITHREADED_EXECUTOR_H +#define TRINITYCORE_CORO_MULTITHREADED_EXECUTOR_H + +#include "./CoroutineExecutionContext.h" +#include "./CoroutineFwd.h" +#include "./Executor.h" +#include "Duration.h" +#include "IntrusiveForwardList.h" +#include +#include + +namespace Trinity::Coro +{ +class TC_COMMON_API MultiThreadedExecutor final : public Executor +{ +public: + void QueueCompletion(CoroutineExecutionContext* context) override; + + void ResumeReadyCoroutines(); + + void WaitForReadyCoroutinesAndResume(); + + bool WaitForReadyCoroutinesAndResume(Milliseconds timeout); + + void StopWaiting(); + +private: + std::mutex _mutex; + Containers::IntrusiveForwardList<&CoroutineExecutionContext::QueueLink> _resumeQueue; + std::condition_variable _condition; + std::atomic_flag _stopped; +}; +} + +#endif // TRINITYCORE_CORO_MULTITHREADED_EXECUTOR_H diff --git a/src/common/Threading/Coro/ResultValue.cpp b/src/common/Threading/Coro/ResultValue.cpp new file mode 100644 index 00000000..e88e0ddd --- /dev/null +++ b/src/common/Threading/Coro/ResultValue.cpp @@ -0,0 +1,27 @@ +/* + * 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 . + */ + +#include "./ResultValue.h" +#include + +void Trinity::Coro::Impl::ThrowNoValueException(std::exception_ptr exception) +{ + if (exception) + std::rethrow_exception(exception); + else + throw std::logic_error("No value or exception result for coroutine"); +} diff --git a/src/common/Threading/Coro/ResultValue.h b/src/common/Threading/Coro/ResultValue.h new file mode 100644 index 00000000..8766f62f --- /dev/null +++ b/src/common/Threading/Coro/ResultValue.h @@ -0,0 +1,97 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_RESULT_VALUE_H +#define TRINITYCORE_CORO_RESULT_VALUE_H + +#include "./CoroutineFwd.h" +#include "Define.h" +#include +#include +#include + +namespace Trinity::Coro +{ +namespace Impl +{ +[[noreturn]] TC_COMMON_API void ThrowNoValueException(std::exception_ptr exception); +} + +template +class ResultValue +{ +public: + using value_holder = std::conditional_t, std::reference_wrapper>, std::remove_const_t>; + + bool has_value_or_exception() const { return !std::holds_alternative(_result); } + + template V> + void set_value(V&& value) { _result.template emplace(std::forward(value)); } + + void set_exception(std::exception_ptr exception) { _result.template emplace(std::move(exception)); } + + T& get() & + { + if (std::holds_alternative(_result)) + return std::get(_result); + + Impl::ThrowNoValueException(std::holds_alternative(_result) + ? std::get(std::move(_result)) : nullptr); + } + + T&& get() && + { + if (std::holds_alternative(_result)) + return std::get(std::move(_result)); + + Impl::ThrowNoValueException(std::holds_alternative(_result) + ? std::get(std::move(_result)) : nullptr); + } + + void reset() { _result.template emplace(); } + +private: + std::variant _result; +}; + +template <> +class ResultValue +{ +public: + bool has_value_or_exception() const { return !std::holds_alternative(_result); } + + void set_value() { _result.emplace(true); } + + void set_exception(std::exception_ptr exception) { _result.emplace(std::move(exception)); } + + void get() + { + if (std::holds_alternative(_result)) + return; + + Impl::ThrowNoValueException(std::holds_alternative(_result) + ? std::get(std::move(_result)) : nullptr); + } + + void reset() { _result.emplace(); } + +private: + std::variant _result; +}; +} + +#endif // TRINITYCORE_CORO_RESULT_VALUE_H diff --git a/src/common/Threading/Coro/SingleThreadedExecutor.h b/src/common/Threading/Coro/SingleThreadedExecutor.h new file mode 100644 index 00000000..bf4881ad --- /dev/null +++ b/src/common/Threading/Coro/SingleThreadedExecutor.h @@ -0,0 +1,40 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_SINGLE_THREADED_EXECUTOR_H +#define TRINITYCORE_CORO_SINGLE_THREADED_EXECUTOR_H + +#include "./CoroutineExecutionContext.h" +#include "./CoroutineFwd.h" +#include "./Executor.h" +#include "MPSCQueue.h" + +namespace Trinity::Coro +{ +class TC_COMMON_API SingleThreadedExecutor final : public Executor +{ +public: + void QueueCompletion(CoroutineExecutionContext* context) override; + + void ResumeReadyCoroutines(); + +private: + MPSCQueue _resumeQueue; +}; +} + +#endif // TRINITYCORE_CORO_SINGLE_THREADED_EXECUTOR_H diff --git a/src/common/Threading/Coro/Sleep.cpp b/src/common/Threading/Coro/Sleep.cpp new file mode 100644 index 00000000..74ed1e51 --- /dev/null +++ b/src/common/Threading/Coro/Sleep.cpp @@ -0,0 +1,51 @@ +/* + * 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 . + */ + +#include "./Sleep.h" +#include "DeadlineTimer.h" +#include "IoContext.h" + +namespace Trinity::Coro +{ +namespace Impl +{ +namespace +{ +Asio::IoContext* TimerExecutor; +} + +void SleepAwaiter::handle_suspend(CoroutineExecutionContext* coroutine) noexcept +{ + Asio::DeadlineTimer* timer = new Asio::DeadlineTimer(*TimerExecutor, Expiry); + timer->async_wait([coroutine, timer = std::unique_ptr(timer)](boost::system::error_code const& error) + { + if (!error) + coroutine->QueueCompletion(); + }); +} +} + +void InitializeTimerExecutor(Asio::IoContext* executor) +{ + Impl::TimerExecutor = executor; +} + +void ShutdownTimerExecutor() +{ + Impl::TimerExecutor = nullptr; +} +} diff --git a/src/common/Threading/Coro/Sleep.h b/src/common/Threading/Coro/Sleep.h new file mode 100644 index 00000000..23af83b4 --- /dev/null +++ b/src/common/Threading/Coro/Sleep.h @@ -0,0 +1,72 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_SLEEP_H +#define TRINITYCORE_CORO_SLEEP_H + +#include "./CoroutineExecutionContext.h" +#include "./CoroutineFwd.h" +#include "AsioHacksFwd.h" +#include "Define.h" +#include "Duration.h" + +namespace Trinity::Coro +{ +namespace Impl +{ +struct SleepAwaiter +{ + bool await_ready() const noexcept { return Now >= Expiry; } + + template promise_type> + void await_suspend(std::coroutine_handle coroutine) noexcept + { + this->handle_suspend(&coroutine.promise()); + } + + void await_resume() const noexcept { } + + TC_COMMON_API void handle_suspend(CoroutineExecutionContext* coroutine) noexcept; + + TimePoint Now; + TimePoint Expiry; +}; + +class SleepAwaitable +{ +public: + explicit SleepAwaitable(TimePoint expiry) : _now(TimePoint::clock::now()), _expiry(expiry) { } + explicit SleepAwaitable(TimePoint::duration duration) : _now(TimePoint::clock::now()), _expiry(_now + duration) { } + + SleepAwaiter operator co_await() const { return { .Now = _now, .Expiry = _expiry }; } + +private: + TimePoint _now; + TimePoint _expiry; +}; +} + +// Initializes the global asio executor that handles all timers +// This function must be called before using Coro::SleepFor and Coro::SleepUntil +TC_COMMON_API void InitializeTimerExecutor(Asio::IoContext* executor); +TC_COMMON_API void ShutdownTimerExecutor(); + +inline Impl::SleepAwaitable SleepFor(TimePoint::duration duration) { return Impl::SleepAwaitable(duration); } +inline Impl::SleepAwaitable SleepUntil(TimePoint expiry) { return Impl::SleepAwaitable(expiry); } +} + +#endif // TRINITYCORE_CORO_SLEEP_H diff --git a/src/common/Threading/Coro/Start.cpp b/src/common/Threading/Coro/Start.cpp new file mode 100644 index 00000000..d72f55e4 --- /dev/null +++ b/src/common/Threading/Coro/Start.cpp @@ -0,0 +1,58 @@ +/* + * 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 . + */ + +#include "./Start.h" +#include "./Allocator.h" +#include "./AllocatorImpl.h" +#include "./Executor.h" +#include "Errors.h" +#include "Memory.h" +#include + +namespace Trinity::Coro::Impl +{ +void CoroutineEntryPoint::promise_type::unhandled_exception() noexcept +try +{ + std::rethrow_exception(std::current_exception()); +} +catch (std::exception const& e) +{ + ABORT_MSG("Unhandled coroutine exception: %s", e.what()); +} +catch (...) +{ + ABORT_MSG("Unhandled coroutine exception: UNKNOWN"); +} + +void CoroutineEntryPoint::Start(Executor& executor) +{ + Context->CurrentExecutor = executor.weak_from_this(); + Context->QueueCompletion(); +} + +CoroutineEntryPoint Start(std::function()> awaitableSource) noexcept +{ + Allocator allocator; + CurrentAllocator::Set(&allocator); + auto allocatorGuard = Trinity::make_unique_ptr_with_deleter<[](void*){ CurrentAllocator::Set(nullptr); }>(&allocator); + + Awaitable awaitable = awaitableSource(); + + co_await awaitable; +} +} diff --git a/src/common/Threading/Coro/Start.h b/src/common/Threading/Coro/Start.h new file mode 100644 index 00000000..e7ba0d54 --- /dev/null +++ b/src/common/Threading/Coro/Start.h @@ -0,0 +1,73 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_START_H +#define TRINITYCORE_CORO_START_H + +#include "./Awaitable.h" +#include "./CoroutineExecutionContext.h" +#include "./CoroutineFwd.h" +#include "Concepts.h" +#include "Define.h" +#include + +namespace Trinity::Coro +{ +namespace Impl +{ +struct CoroutineEntryPoint +{ + struct promise_type : CoroutineExecutionContext + { + promise_type() : CoroutineExecutionContext(std::coroutine_handle::from_promise(*this)) { } + + CoroutineEntryPoint get_return_object() noexcept; + + std::suspend_always initial_suspend() noexcept { return { }; } + + std::suspend_never final_suspend() noexcept { return { }; } + + void return_void() noexcept { } + + [[noreturn]] TC_COMMON_API void unhandled_exception() noexcept; + }; + + TC_COMMON_API void Start(Executor& executor); + + CoroutineExecutionContext* Context = nullptr; +}; + +inline CoroutineEntryPoint CoroutineEntryPoint::promise_type::get_return_object() noexcept +{ + return { .Context = this }; +} + +TC_COMMON_API CoroutineEntryPoint Start(std::function()> awaitableSource) noexcept; +} + +template +requires (invocable_r> + && std::is_rvalue_reference_v + && !std::is_const_v>) +void Start(Executor& executor, CoroutineInitFunc&& coroutineInit) +{ + Impl::CoroutineEntryPoint entryPoint = Impl::Start(std::forward(coroutineInit)); + entryPoint.Start(executor); +} +} + +#endif // TRINITYCORE_CORO_START_H diff --git a/src/common/Threading/Coro/SwitchExecutor.cpp b/src/common/Threading/Coro/SwitchExecutor.cpp new file mode 100644 index 00000000..ef97cc26 --- /dev/null +++ b/src/common/Threading/Coro/SwitchExecutor.cpp @@ -0,0 +1,41 @@ +/* + * 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 . + */ + +#include "./SwitchExecutor.h" +#include "./CoroutineExecutionContext.h" +#include "./Executor.h" +#include + +namespace Trinity::Coro +{ +namespace Impl +{ +void SwitchToExecutorAwaiter::handle_suspend(CoroutineExecutionContext* coroutine) +{ + OldExecutor = coroutine->CurrentExecutor; + NewExecutor.QueueCompletion(coroutine); +} +} + +Executor& SwitchToExecutor::resolve_executor(unique_weak_ptr const& executorRef) +{ + if (unique_strong_ref_ptr::element_type> executor = executorRef.lock()) + return *executor; + + throw std::invalid_argument("Expired executor"); +} +} diff --git a/src/common/Threading/Coro/SwitchExecutor.h b/src/common/Threading/Coro/SwitchExecutor.h new file mode 100644 index 00000000..11972abb --- /dev/null +++ b/src/common/Threading/Coro/SwitchExecutor.h @@ -0,0 +1,64 @@ +/* + * 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 . + */ + +#ifndef TRINITYCORE_CORO_SWITCH_EXECUTOR_H +#define TRINITYCORE_CORO_SWITCH_EXECUTOR_H + +#include "./CoroutineFwd.h" +#include "Define.h" +#include "UniqueTrackablePtr.h" +#include + +namespace Trinity::Coro +{ +namespace Impl +{ +struct TC_COMMON_API SwitchToExecutorAwaiter +{ + bool await_ready() const noexcept { return false; } + + template promise_type> + void await_suspend(std::coroutine_handle coroutine) noexcept + { + this->handle_suspend(&coroutine.promise()); + } + + void handle_suspend(CoroutineExecutionContext* coroutine); + + unique_weak_ptr&& await_resume() noexcept { return std::move(OldExecutor); } + + Coro::Executor& NewExecutor; + unique_weak_ptr OldExecutor; +}; +} + +class SwitchToExecutor +{ +public: + explicit SwitchToExecutor(Executor& executor) : _executor(executor) { } + explicit SwitchToExecutor(unique_weak_ptr const& executor) : _executor(resolve_executor(executor)) { } + + Impl::SwitchToExecutorAwaiter operator co_await() const && noexcept { return { .NewExecutor = _executor }; } + +private: + TC_COMMON_API static Executor& resolve_executor(unique_weak_ptr const& executorRef); + + Executor& _executor; +}; +} + +#endif // TRINITYCORE_CORO_SWITCH_EXECUTOR_H diff --git a/tests/common/Coroutine.cpp b/tests/common/Coroutine.cpp new file mode 100644 index 00000000..d470bc4e --- /dev/null +++ b/tests/common/Coroutine.cpp @@ -0,0 +1,282 @@ +/* + * 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 . + */ + +#include "tc_catch2.h" + +#include "Common.h" +#include "Coro/AllOf.h" +#include "Coro/AllocatorImpl.h" +#include "Coro/Awaitable.h" +#include "Coro/AwaitableValue.h" +#include "Coro/CurrentCoroutine.h" +#include "Coro/MultiThreadedExecutor.h" +#include "Coro/Sleep.h" +#include "Coro/Start.h" +#include "Coro/SwitchExecutor.h" +#include "Duration.h" +#include "IoContext.h" +#include + +class CoroutineFixture +{ +public: + Trinity::unique_trackable_ptr executor = Trinity::make_unique_trackable(); + std::variant testCoroutineStatus = false; + Trinity::Asio::IoContext timerContext; + boost::asio::executor_work_guard timerWorkGuard = boost::asio::make_work_guard(timerContext); + std::thread timerThread; + + CoroutineFixture() + { + Trinity::Coro::InitializeTimerExecutor(&timerContext); + timerThread = std::thread([this] { timerContext.run(); }); + } + + ~CoroutineFixture() noexcept(false) + { + bool timedOut = !executor->WaitForReadyCoroutinesAndResume(30s); + + timerWorkGuard.reset(); + timerThread.join(); + Trinity::Coro::ShutdownTimerExecutor(); + + if (timedOut) + FAIL("executor->WaitForReadyCoroutinesAndResume(30s) timed out"); + + if (std::holds_alternative(testCoroutineStatus)) + std::rethrow_exception(std::get(testCoroutineStatus)); + + if (!std::get(testCoroutineStatus)) + FAIL("Test coroutine not finished"); + } + + CoroutineFixture(CoroutineFixture const& other) = delete; + CoroutineFixture(CoroutineFixture&& other) noexcept = delete; + CoroutineFixture& operator=(CoroutineFixture const& other) = delete; + CoroutineFixture& operator=(CoroutineFixture&& other) noexcept = delete; +}; + +template TestFixture> +struct std::coroutine_traits +{ + struct promise_type : Trinity::Coro::CoroutineExecutionContext + { + promise_type(TestFixture& fixture) : CoroutineExecutionContext(std::coroutine_handle::from_promise(*this)), + _testFixture(fixture) + { + CurrentExecutor = fixture.executor->weak_from_this(); + CurrentAllocator = &_allocator; + Trinity::Coro::Impl::CurrentAllocator::Set(CurrentAllocator); + } + + ~promise_type() + { + Trinity::Coro::Impl::CurrentAllocator::Set(nullptr); + } + + void get_return_object() noexcept { } + + std::suspend_never initial_suspend() noexcept { return { }; } + + std::suspend_never final_suspend() noexcept { return { }; } + + void return_void() noexcept + { + _testFixture.testCoroutineStatus = true; + _testFixture.executor->StopWaiting(); + } + + void unhandled_exception() noexcept + { + _testFixture.testCoroutineStatus = std::current_exception(); + _testFixture.executor->StopWaiting(); + } + + TestFixture& _testFixture; + Trinity::Coro::Impl::Allocator _allocator; + + promise_type(promise_type const& other) = delete; + promise_type(promise_type&& other) noexcept = delete; + promise_type& operator=(promise_type const& other) = delete; + promise_type& operator=(promise_type&& other) noexcept = delete; + }; +}; + +Trinity::Coro::Awaitable TestCoro1() +{ + co_return 1; +} + +TEST_CASE_METHOD(CoroutineFixture, "Coro::Allocator is available to nested coroutines", "[Coroutine][Allocator]") +{ + // test failure is a segfault + REQUIRE(co_await TestCoro1() == 1); +} + +TEST_CASE_METHOD(CoroutineFixture, "Coro::AwaitableValue resumes coroutine after obtaining value", "[Coroutine][AwaitableValue]") +{ + Trinity::Coro::AwaitableValue asyncValue; + + std::thread thrd([&asyncValue] + { + std::this_thread::sleep_for(0.5s); + asyncValue.set_value(1); + }); + + int32 result = co_await asyncValue; + + thrd.join(); + + REQUIRE(result == 1); +} + +TEST_CASE_METHOD(CoroutineFixture, "Coro::AwaitableValue doesn't suspend coroutine when value is ready before co_await", "[Coroutine][AwaitableValue]") +{ + Trinity::Coro::AwaitableValue asyncValue; + + asyncValue.set_value(1); + + int32 result = co_await asyncValue; + + REQUIRE(result == 1); +} + +TEST_CASE_METHOD(CoroutineFixture, "Coro::CurrentExecutor returns current executor associated with coroutine", "[Coroutine][AwaitableValue]") +{ + Trinity::unique_weak_ptr result = co_await Trinity::Coro::CurrentExecutor; + + REQUIRE(result.lock().get() == executor.get()); +} + +TEST_CASE("Coro::Start starts a new coroutine", "[Coroutine][Start]") +{ + Trinity::unique_trackable_ptr executor = Trinity::make_unique_trackable(); + bool executed = false; + + Trinity::Coro::Start(*executor, [&executor, &executed]() -> Trinity::Coro::Awaitable + { + executed = true; + executor->StopWaiting(); + co_return; + }); + + REQUIRE(executor->WaitForReadyCoroutinesAndResume(30s)); + REQUIRE(executed); +} + +TEST_CASE_METHOD(CoroutineFixture, "Coro::SwitchToExecutor changes executor associated with coroutine", "[Coroutine][SwitchToExecutor]") +{ + Trinity::unique_trackable_ptr otherExecutor = Trinity::make_unique_trackable(); + std::thread otherExecutorThread([&otherExecutor] { otherExecutor->WaitForReadyCoroutinesAndResume(30s); }); + + co_await Trinity::Coro::SwitchToExecutor(*otherExecutor); + + auto current = co_await Trinity::Coro::CurrentExecutor; + + REQUIRE(current.lock().get() == otherExecutor.get()); + + co_await Trinity::Coro::SwitchToExecutor(*executor); + + current = co_await Trinity::Coro::CurrentExecutor; + + REQUIRE(current.lock().get() == executor.get()); + + otherExecutor->StopWaiting(); + otherExecutorThread.join(); +} + +TEST_CASE_METHOD(CoroutineFixture, "Coro::SleepFor delays coroutine", "[Coroutine][Sleep]") +{ + Seconds sleepDuration = 1s; + + TimePoint start = TimePoint::clock::now(); + + co_await Trinity::Coro::SleepFor(sleepDuration); + + TimePoint now = TimePoint::clock::now(); + + REQUIRE(now >= start + sleepDuration); +} + +TEST_CASE_METHOD(CoroutineFixture, "Coro::SleepUntil delays coroutine", "[Coroutine][Sleep]") +{ + Seconds sleepDuration = 1s; + + TimePoint expiry = TimePoint::clock::now() + sleepDuration; + + co_await Trinity::Coro::SleepUntil(expiry); + + TimePoint now = TimePoint::clock::now(); + + REQUIRE(now >= expiry); +} + +TEST_CASE_METHOD(CoroutineFixture, "Coro::AllOf starts all awaitables at the same time and finishes when all are done", "[Coroutine][AllOf]") +{ + bool startedFlags[3] = { }; + + auto testCoro = [&](std::size_t flagIndex, std::type_identity) -> Trinity::Coro::Awaitable + { + startedFlags[flagIndex] = true; + co_await Trinity::Coro::SleepFor(100ms); + REQUIRE(advstd::ranges::contains(startedFlags, false) == false); + + if constexpr (std::is_same_v) + co_return; + else + co_return static_cast(flagIndex); + }; + + Trinity::Coro::Awaitable coro1 = testCoro(0, std::type_identity()); + Trinity::Coro::Awaitable coro2 = testCoro(1, std::type_identity()); + Trinity::Coro::Awaitable coro3 = testCoro(2, std::type_identity()); + + auto allOf = co_await Trinity::Coro::AllOf(coro1, std::move(coro2), coro3); + + using AllResultOfTuple = decltype(allOf); + STATIC_REQUIRE(std::tuple_size_v == 2); + STATIC_REQUIRE(std::is_lvalue_reference_v>); + STATIC_REQUIRE(std::is_reference_v> == false); + REQUIRE(std::get<0>(allOf) == 0); + REQUIRE(std::get<1>(allOf) == 1); +} + +TEST_CASE_METHOD(CoroutineFixture, "Coro::AllOf rethrows exception from one of its nested awaitables", "[Coroutine][AllOf]") +{ + bool startedFlags[3] = { }; + + auto testCoro = [&](std::size_t flagIndex, std::type_identity, bool throws = false) -> Trinity::Coro::Awaitable + { + startedFlags[flagIndex] = true; + co_await Trinity::Coro::SleepFor(100ms); + REQUIRE(advstd::ranges::contains(startedFlags, false) == false); + + if (throws) + throw std::runtime_error("Controlled failure"); + + if constexpr (std::is_same_v) + co_return; + else + co_return flagIndex; + }; + + Trinity::Coro::Awaitable coro1 = testCoro(0, std::type_identity()); + Trinity::Coro::Awaitable coro2 = testCoro(1, std::type_identity()); + Trinity::Coro::Awaitable coro3 = testCoro(2, std::type_identity(), true); + + REQUIRE_THROWS_WITH(co_await Trinity::Coro::AllOf(coro1, std::move(coro2), coro3), Catch::Matchers::ContainsSubstring("Controlled failure")); +}