commit ccebe083e389178c4ae6fe7286f813e790271df7 Author: faumaray Date: Sat Jul 11 16:30:05 2026 +0300 New arch Signed-off-by: faumaray diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..2ef59d0 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,42 @@ +cmake_minimum_required(VERSION 4.0.0) +project(EchoionHost VERSION 1.0.0 LANGUAGES CXX) + +CPMAddPackage( + NAME dylib + GITHUB_REPOSITORY martin-olivier/dylib + GIT_TAG "v3.0.1" + OPTIONS "CMAKE_POSITION_INDEPENDENT_CODE ON" +) + +add_library(EchoionHost STATIC + src/CoreLoader.cpp + src/FileWatcher.cpp +) +add_library(Echoion::Host ALIAS EchoionHost) + +target_compile_features(EchoionHost PUBLIC cxx_std_26) +set_target_properties(EchoionHost PROPERTIES POSITION_INDEPENDENT_CODE ON) +target_include_directories(EchoionHost PUBLIC + $ + $ +) +target_link_libraries(EchoionHost + PUBLIC + Echoion::ApiBase + Echoion::ApiConfig + Echoion::ApiPlugin + Echoion::ApiOpaque + Echoion::ApiCoreInterface + dylib + PRIVATE + Echoion::ApiLogger + Void::Data + Void::Log + Void::Stacktrace + Threads::Threads +) + +if(NOT MSVC) + target_compile_options(EchoionHost PRIVATE + -Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wshadow) +endif() diff --git a/include/echoion/host/CoreLoader.hpp b/include/echoion/host/CoreLoader.hpp new file mode 100644 index 0000000..e9c634a --- /dev/null +++ b/include/echoion/host/CoreLoader.hpp @@ -0,0 +1,95 @@ +#pragma once +#include "echoion/host/FileWatcher.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Host +{ + + class CoreLoader + { + public: + + CoreLoader(); + ~CoreLoader(); + + Api::Result load(const std::filesystem::path& libraryPath); + Api::Result unload(); + Api::Result + hotReload(const std::filesystem::path& newLibraryPath); + [[nodiscard]] bool isLoaded() const noexcept; + [[nodiscard]] Api::CoreInterfacePtr getCore() const; + void setConfigPath(const std::filesystem::path& configPath); + [[nodiscard]] std::filesystem::path getConfigPath() const; + [[nodiscard]] bool isHotReloading() const noexcept; + + // Automatic hot reload + void enableAutoReload(); + void disableAutoReload(); + [[nodiscard]] bool isAutoReloadEnabled() const noexcept; + + // Callback for hot reload completion (called after auto-reload + // finishes) + using HotReloadCallback = std::function; + void setHotReloadCallback(HotReloadCallback callback) + { + hotReloadCallback_ = std::move(callback); + } + + private: + + Api::Result + loadLibraryInternal(const std::filesystem::path& path); + Api::Result unloadLibraryInternal(); + [[nodiscard]] Api::SerializedState saveStateInternal(); + [[nodiscard]] Api::Result + restoreStateInternal(const Api::SerializedState& state); + [[nodiscard]] std::filesystem::path + getTempLibraryPath(const std::filesystem::path& original) const; + void cleanupTempFiles(); + + std::unique_ptr library_; + Api::CoreInterfacePtr core_; + std::filesystem::path currentLibraryPath_; + std::filesystem::path tempLibraryPath_; + std::filesystem::path configPath_; + mutable std::mutex mutex_; + std::atomic loaded_{false}; + std::atomic hotReloading_{false}; + + // Auto reload + FileWatcher fileWatcher_; + std::atomic autoReloadEnabled_{false}; + + // Deferred reload - waits for current track to finish + std::thread deferredReloadThread_; + std::atomic hasPendingReload_{false}; + std::atomic stopDeferredReload_{false}; + std::condition_variable deferredReloadCv_; + std::filesystem::path pendingReloadPath_; + std::string pendingTrackId_; // Track ID that was playing when + // reload scheduled + mutable std::mutex pendingReloadMutex_; + + // Hot reload completion callback + HotReloadCallback hotReloadCallback_; + + void onCoreFileChanged(); + void waitForTrackAndReload(const std::filesystem::path& targetPath, + const std::string& trackId); + [[nodiscard]] bool isPlaybackActive() const; + [[nodiscard]] bool + isSameTrackPlaying(const std::string& trackId) const; + }; + +} // namespace Echoion::Host diff --git a/include/echoion/host/FileWatcher.hpp b/include/echoion/host/FileWatcher.hpp new file mode 100644 index 0000000..a3e1af7 --- /dev/null +++ b/include/echoion/host/FileWatcher.hpp @@ -0,0 +1,65 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace Echoion::Host +{ + + /** + * @brief Simple file watcher that monitors a file for changes + * and triggers a callback when the file is modified. + */ + class FileWatcher + { + public: + + using ChangeCallback = std::function; + + FileWatcher(); + ~FileWatcher(); + + // Disable copy + FileWatcher(const FileWatcher&) = delete; + FileWatcher& operator=(const FileWatcher&) = delete; + + /** + * @brief Start watching a file for changes + * @param filePath Path to the file to watch + * @param callback Function to call when file changes + * @param intervalMs Polling interval in milliseconds + */ + void startWatching(const std::filesystem::path& filePath, + ChangeCallback callback, + std::chrono::milliseconds intervalMs = + std::chrono::milliseconds(1000)); + + /** + * @brief Stop watching + */ + void stopWatching(); + + [[nodiscard]] bool isWatching() const noexcept; + + private: + + void watchLoop(); + + std::filesystem::path watchedPath_; + ChangeCallback callback_; + std::chrono::milliseconds intervalMs_{1000}; + std::atomic watching_{false}; + std::atomic stopRequested_{false}; + std::thread watchThread_; + std::mutex mutex_; + + // Store last modification time + std::filesystem::file_time_type lastWriteTime_; + std::uint64_t lastFileSize_ = 0; + }; + +} // namespace Echoion::Host diff --git a/src/CoreLoader.cpp b/src/CoreLoader.cpp new file mode 100644 index 0000000..b11f578 --- /dev/null +++ b/src/CoreLoader.cpp @@ -0,0 +1,517 @@ +#include +#include "dylib.hpp" +#include "echoion/host/CoreLoader.hpp" +#include +#include +#include +#include +#include + +namespace Echoion::Host +{ + + CoreLoader::CoreLoader() { cleanupTempFiles(); } + + void CoreLoader::enableAutoReload() + { + if (autoReloadEnabled_.exchange(true)) { + return; // Already enabled + } + + std::lock_guard lock(mutex_); + if (!currentLibraryPath_.empty() && + std::filesystem::exists(currentLibraryPath_)) { + Void::Log::info("CoreLoader", "{}", std::format("Enabling auto-reload for: {}", + currentLibraryPath_.string())); + + fileWatcher_.startWatching(currentLibraryPath_, + [this]() { onCoreFileChanged(); }); + } + } + + void CoreLoader::disableAutoReload() + { + autoReloadEnabled_ = false; + fileWatcher_.stopWatching(); + Void::Log::info("CoreLoader", "{}", "Auto-reload disabled"); + } + + bool CoreLoader::isAutoReloadEnabled() const noexcept + { + return autoReloadEnabled_.load(); + } + + void CoreLoader::onCoreFileChanged() + { + if (!autoReloadEnabled_.load() || hotReloading_.load()) { + return; + } + + Void::Log::info("CoreLoader", "{}", + "Core file changed, scheduling hot reload after current track..."); + + // Small delay to ensure file write is complete + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + + // Check if playback is active - if so, defer reload + if (isPlaybackActive()) { + std::string currentTrackId; + { + std::lock_guard lock(pendingReloadMutex_); + hasPendingReload_ = true; + pendingReloadPath_ = currentLibraryPath_; + + // Capture current track ID + auto state = core_->getPlaybackSummary(); + if (state && state->currentTrack.has_value()) { + pendingTrackId_ = state->currentTrack->id; + currentTrackId = pendingTrackId_; + } + } + + Void::Log::info("CoreLoader", "{}", + std::format("Playback active (track: {}), deferring reload " + "until track finishes", + currentTrackId)); + + // Start background thread to wait for track end + if (deferredReloadThread_.joinable()) { + deferredReloadThread_.join(); + } + deferredReloadThread_ = std::thread([this, currentTrackId]() { + waitForTrackAndReload(pendingReloadPath_, currentTrackId); + }); + } else { + // No playback, reload immediately + auto result = hotReload(currentLibraryPath_); + if (!result) { + Void::Log::error("CoreLoader", "{}", std::format("Auto hot-reload failed: {}", + result.error().message)); + } else { + Void::Log::info("CoreLoader", "{}", "Auto hot-reload completed successfully"); + // Notify Plugin to re-register callbacks + if (hotReloadCallback_) { + hotReloadCallback_(); + } + } + } + } + + bool CoreLoader::isPlaybackActive() const + { + if (!core_) { + return false; + } + + auto state = core_->getPlaybackSummary(); + if (!state) { + return false; + } + + // Check if currently playing a track + return state->isPlaying && state->currentTrack.has_value(); + } + + bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const + { + if (!core_ || trackId.empty()) { + return false; + } + + auto state = core_->getPlaybackSummary(); + if (!state || !state->currentTrack.has_value()) { + return false; + } + + return state->currentTrack->id == trackId; + } + + void CoreLoader::waitForTrackAndReload( + const std::filesystem::path& targetPath, const std::string& trackId) + { + Void::Log::info("CoreLoader", "{}", std::format( + "Waiting for track {} to finish before reload...", trackId)); + + // Poll every 500ms to check if the specific track finished + // (playback may continue with next track, but we only care about THIS + // track). The wait is interruptible so the destructor can join this + // thread instead of detaching it (detaching risks use-after-free when + // the plugin unloads mid-wait). + while (isSameTrackPlaying(trackId)) { + std::unique_lock lock(pendingReloadMutex_); + if (deferredReloadCv_.wait_for( + lock, std::chrono::milliseconds(500), + [this] { return stopDeferredReload_.load(); })) { + Void::Log::info("CoreLoader", "{}", + "Deferred hot-reload cancelled (loader shutting down)"); + return; + } + } + + if (stopDeferredReload_.load()) { + return; + } + + Void::Log::info("CoreLoader", "{}", "Track finished, starting hot reload"); + + // Clear pending flag + { + std::lock_guard lock(pendingReloadMutex_); + hasPendingReload_ = false; + pendingTrackId_.clear(); + } + + // Now do the reload + auto result = hotReload(targetPath); + if (!result) { + Void::Log::error("CoreLoader", "{}", std::format("Deferred hot-reload failed: {}", + result.error().message)); + } else { + Void::Log::info("CoreLoader", "{}", "Deferred hot-reload completed successfully"); + // Notify Plugin to re-register callbacks + if (hotReloadCallback_) { + hotReloadCallback_(); + } + } + } + + CoreLoader::~CoreLoader() + { + // Signal the deferred reload thread to stop and wait for it. It must + // never outlive this object: it dereferences core_ and this. + stopDeferredReload_ = true; + deferredReloadCv_.notify_all(); + if (deferredReloadThread_.joinable()) { + deferredReloadThread_.join(); + } + if (auto result = unload(); !result) { + Void::Log::warn("CoreLoader", "{}", + std::format("Unload from destructor failed: {}", + result.error().message)); + } + cleanupTempFiles(); + } + + Api::Result CoreLoader::load(const std::filesystem::path& libraryPath) + { + std::lock_guard lock(mutex_); + + if (loaded_) { + return Api::fail(Api::ErrorCode::AlreadyExists, + "Core already loaded"); + } + + if (!std::filesystem::exists(libraryPath)) { + return Api::fail( + Api::ErrorCode::NotFound, + std::format("Library not found: {}", libraryPath.string())); + } + + tempLibraryPath_ = getTempLibraryPath(libraryPath); + + try { + std::filesystem::copy_file( + libraryPath, tempLibraryPath_, + std::filesystem::copy_options::overwrite_existing); + } catch (const std::exception& e) { + return Api::fail( + Api::ErrorCode::UnknownError, + std::format("Failed to copy library to temp: {}", e.what())); + } + + auto result = loadLibraryInternal(tempLibraryPath_); + if (result) { + currentLibraryPath_ = libraryPath; + } else { + std::error_code ec; + std::filesystem::remove(tempLibraryPath_, ec); + } + + return result; + } + + Api::Result CoreLoader::unload() + { + std::lock_guard lock(mutex_); + + auto result = unloadLibraryInternal(); + + if (!tempLibraryPath_.empty()) { + std::error_code ec; + std::filesystem::remove(tempLibraryPath_, ec); + } + + return result; + } + + Api::Result + CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) + { + std::lock_guard lock(mutex_); + + if (!loaded_) { + return Api::fail(Api::ErrorCode::NotFound, + "No core loaded to reload"); + } + + hotReloading_ = true; + + Void::Log::info("CoreLoader", "{}", "Starting hot reload with temp file..."); + + // Step 1: Save state as opaque blob (Plugin doesn't know contents) + Api::StateBlob stateBlob; + if (core_) { + stateBlob = core_->saveState(); + Void::Log::info("CoreLoader", "{}", + std::format("Saved state: version={}, size={} bytes", + stateBlob.version, stateBlob.size())); + } + + auto targetPath = + newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath; + + if (!std::filesystem::exists(targetPath)) { + hotReloading_ = false; + return Api::fail( + Api::ErrorCode::NotFound, + std::format("New library not found: {}", targetPath.string())); + } + + std::filesystem::path newTempPath = getTempLibraryPath(targetPath); + + try { + std::filesystem::copy_file( + targetPath, newTempPath, + std::filesystem::copy_options::overwrite_existing); + } catch (const std::exception& e) { + hotReloading_ = false; + std::error_code ec; + std::filesystem::remove(newTempPath, ec); + return Api::fail(Api::ErrorCode::UnknownError, + std::format("Failed to copy new library to temp: {}", + e.what())); + } + + auto unloadResult = unloadLibraryInternal(); + if (!unloadResult) { + hotReloading_ = false; + std::error_code ec; + std::filesystem::remove(newTempPath, ec); + return unloadResult; + } + + std::error_code ec; + std::filesystem::remove(tempLibraryPath_, ec); + tempLibraryPath_ = newTempPath; + + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + + auto loadResult = loadLibraryInternal(tempLibraryPath_); + if (!loadResult) { + hotReloading_ = false; + return loadResult; + } + + // Step 4: Ask new Core to restore state (it handles migration + // internally) + if (!stateBlob.empty()) { + auto coreVersion = core_->getStateFormatVersion(); + auto stateVersion = stateBlob.version; + + Void::Log::info("CoreLoader", "{}", std::format("Restoring state v{} to Core v{}", + stateVersion, coreVersion)); + + if (core_->canRestoreStateVersion(stateVersion)) { + auto restoreResult = core_->restoreState(stateBlob); + if (!restoreResult) { + Void::Log::error("CoreLoader", "{}", + std::format("Failed to restore state: {}", + restoreResult.error().message)); + + // Check if it's a version issue + if (restoreResult.error().code == + Api::ErrorCode::IncompatibleVersion) { + // Signal user to update/restart + Void::Log::warn("CoreLoader", "{}", "State version incompatible. " + "User needs to update/restart."); + // Optionally: notify through plugin interface + } + + // Continue with empty state - graceful degradation + } else { + Void::Log::info("CoreLoader", "{}", "State restored successfully"); + } + } else { + Void::Log::warn("CoreLoader", "{}", std::format( + "Cannot restore state v{} in Core v{}. " + "Version age exceeds maximum supported ({} versions).", + stateVersion, coreVersion, + Api::MAX_SUPPORTED_STATE_VERSION_AGE)); + // Continue with empty state + } + } + + currentLibraryPath_ = targetPath; + hotReloading_ = false; + + Void::Log::info("CoreLoader", "{}", "Hot reload complete"); + return {}; + } + + bool CoreLoader::isLoaded() const noexcept { return loaded_.load(); } + + Api::CoreInterfacePtr CoreLoader::getCore() const + { + std::lock_guard lock(mutex_); + return core_; + } + + void CoreLoader::setConfigPath(const std::filesystem::path& configPath) + { + std::lock_guard lock(mutex_); + configPath_ = configPath; + } + + std::filesystem::path CoreLoader::getConfigPath() const + { + std::lock_guard lock(mutex_); + return configPath_; + } + + bool CoreLoader::isHotReloading() const noexcept + { + return hotReloading_.load(); + } + + Api::Result + CoreLoader::loadLibraryInternal(const std::filesystem::path& path) + { + try { + + std::cout << std::format("[Echoion] Loading core library: {}", + path.string()) + << '\n'; + // Use no decorations - the path already has the correct extension + // (.ts) + library_ = std::make_unique( + path.string(), dylib::decorations::none()); + + auto createFunc = + library_->get_function("CreateCore"); + auto versionFunc = + library_->get_function("GetApiVersion"); + auto compatibleFunc = + library_->get_function( + "IsApiCompatible"); + + if (!compatibleFunc(Api::VERSION_MAJOR, Api::VERSION_MINOR)) { + library_.reset(); + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("API version mismatch. Expected {}.{}, got {}", + Api::VERSION_MAJOR, Api::VERSION_MINOR, + versionFunc())); + } + + core_ = createFunc(); + if (!core_) { + library_.reset(); + return Api::fail(Api::ErrorCode::UnknownError, + "Failed to create core instance"); + } + + auto initResult = core_->initialize(configPath_); + if (!initResult) { + core_.reset(); + library_.reset(); + return initResult; + } + + loaded_ = true; + + Void::Log::info("CoreLoader", "{}", std::format( + "Core library loaded (API version: {})", versionFunc())); + return {}; + + } catch (const dylib::load_error& e) { + return Api::fail( + Api::ErrorCode::PluginError, + std::format("Failed to load library: {}", e.what())); + } catch (const dylib::symbol_error& e) { + return Api::fail(Api::ErrorCode::PluginError, + std::format("Failed to find symbol: {}", e.what())); + } catch (const std::exception& e) { + return Api::fail(Api::ErrorCode::UnknownError, + std::format("Unexpected error: {}", e.what())); + } + } + + Api::Result CoreLoader::unloadLibraryInternal() + { + if (!loaded_) { + return {}; + } + + Void::Log::info("CoreLoader", "{}", "Unloading core library..."); + + if (core_) { + if (auto result = core_->shutdown(); !result) { + Void::Log::warn( + "CoreLoader", "{}", + std::format("Core shutdown reported failure: {}", + result.error().message)); + } + core_.reset(); + } + + library_.reset(); + + loaded_ = false; + std::cout << "[Echoion] Core library unloaded" << '\n'; + return {}; + } + + std::filesystem::path CoreLoader::getTempLibraryPath( + const std::filesystem::path& original) const + { + auto tempDir = std::filesystem::temp_directory_path(); + auto filename = original.filename().string(); + + auto now = std::chrono::system_clock::now(); + auto ms = std::chrono::duration_cast( + now.time_since_epoch()) + .count(); + +// Use the same extension as the original file (.ts for TeamSpeak plugin) +#ifdef _WIN32 + auto tempName = std::format( + "echoion_{}_{}.dll", ms, + std::hash{}(std::this_thread::get_id())); +#else + auto tempName = std::format( + "echoion_{}_{}.ts", ms, + std::hash{}(std::this_thread::get_id())); +#endif + + return tempDir / tempName; + } + + void CoreLoader::cleanupTempFiles() + { + auto tempDir = std::filesystem::temp_directory_path(); + std::error_code ec; + + for (const auto& entry : + std::filesystem::directory_iterator(tempDir, ec)) { + if (entry.is_regular_file()) { + auto name = entry.path().filename().string(); + if (name.starts_with("echoion_") && + (name.ends_with(".dll") || name.ends_with(".so") || + name.ends_with(".ts"))) { + std::filesystem::remove(entry.path(), ec); + } + } + } + } + +} // namespace Echoion::Host diff --git a/src/FileWatcher.cpp b/src/FileWatcher.cpp new file mode 100644 index 0000000..2c92ace --- /dev/null +++ b/src/FileWatcher.cpp @@ -0,0 +1,98 @@ +#include "echoion/host/FileWatcher.hpp" +#include +#include +#include + +namespace Echoion::Host +{ + + FileWatcher::FileWatcher() = default; + + FileWatcher::~FileWatcher() { stopWatching(); } + + void FileWatcher::startWatching(const std::filesystem::path& filePath, + ChangeCallback callback, + std::chrono::milliseconds intervalMs) + { + + std::lock_guard lock(mutex_); + + if (watching_.load()) { + stopWatching(); + } + + watchedPath_ = filePath; + callback_ = std::move(callback); + intervalMs_ = intervalMs; + stopRequested_ = false; + + // Get initial file state + if (std::filesystem::exists(watchedPath_)) { + lastWriteTime_ = std::filesystem::last_write_time(watchedPath_); + lastFileSize_ = std::filesystem::file_size(watchedPath_); + } + + watching_ = true; + watchThread_ = std::thread(&FileWatcher::watchLoop, this); + } + + void FileWatcher::stopWatching() + { + stopRequested_ = true; + + if (watchThread_.joinable()) { + watchThread_.join(); + } + + watching_ = false; + } + + bool FileWatcher::isWatching() const noexcept { return watching_.load(); } + + void FileWatcher::watchLoop() + { + while (!stopRequested_.load()) { + // Sleep first to avoid checking immediately + std::this_thread::sleep_for(intervalMs_); + + if (stopRequested_.load()) { + break; + } + + std::lock_guard lock(mutex_); + + if (!std::filesystem::exists(watchedPath_)) { + continue; + } + + try { + auto currentWriteTime = + std::filesystem::last_write_time(watchedPath_); + auto currentFileSize = std::filesystem::file_size(watchedPath_); + + // Check if file has changed (time or size) + if (currentWriteTime != lastWriteTime_ || + currentFileSize != lastFileSize_) { + // Update stored values + lastWriteTime_ = currentWriteTime; + lastFileSize_ = currentFileSize; + + // Trigger callback + if (callback_) { + try { + callback_(); + } catch (const std::exception& e) { + std::cerr + << std::format("FileWatcher callback error: {}", + e.what()) + << '\n'; + } + } + } + } catch (const std::exception& e) { + // Ignore errors (file might be locked during write) + } + } + } + +} // namespace Echoion::Host