Bump CMake minimum to 4.0 for VoidLibrary toolchain
This commit is contained in:
1 parent
0fa9db4691
commit
05c9f8bc6c
11 files changed
+2524
-2125
No files matched your search
+443
-369
@@ -1,424 +1,498 @@
|
||||
#include "echoion/plugin/CoreLoader.hpp"
|
||||
#include "LoggerInterface.hpp"
|
||||
#include "dylib.hpp"
|
||||
#include <format>
|
||||
#include <thread>
|
||||
#include "echoion/plugin/CoreLoader.hpp"
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Plugin {
|
||||
namespace Echoion::Plugin
|
||||
{
|
||||
|
||||
CoreLoader::CoreLoader() {
|
||||
cleanupTempFiles();
|
||||
}
|
||||
CoreLoader::CoreLoader() { cleanupTempFiles(); }
|
||||
|
||||
void CoreLoader::enableAutoReload() {
|
||||
if (autoReloadEnabled_.exchange(true)) {
|
||||
return; // Already enabled
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!currentLibraryPath_.empty() && std::filesystem::exists(currentLibraryPath_)) {
|
||||
ECHOION_LOG_INFO(std::format("Enabling auto-reload for: {}", currentLibraryPath_.string()));
|
||||
|
||||
// Create weak pointer to avoid circular reference in lambda
|
||||
std::weak_ptr<CoreLoader> weakThis =
|
||||
std::const_pointer_cast<CoreLoader>(
|
||||
std::shared_ptr<const CoreLoader>(this, [](const CoreLoader*){}));
|
||||
|
||||
fileWatcher_.startWatching(currentLibraryPath_, [this]() {
|
||||
onCoreFileChanged();
|
||||
});
|
||||
}
|
||||
}
|
||||
void CoreLoader::enableAutoReload()
|
||||
{
|
||||
if (autoReloadEnabled_.exchange(true)) {
|
||||
return; // Already enabled
|
||||
}
|
||||
|
||||
void CoreLoader::disableAutoReload() {
|
||||
autoReloadEnabled_ = false;
|
||||
fileWatcher_.stopWatching();
|
||||
ECHOION_LOG_INFO("Auto-reload disabled");
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!currentLibraryPath_.empty() &&
|
||||
std::filesystem::exists(currentLibraryPath_)) {
|
||||
ECHOION_LOG_INFO(std::format("Enabling auto-reload for: {}",
|
||||
currentLibraryPath_.string()));
|
||||
|
||||
bool CoreLoader::isAutoReloadEnabled() const noexcept {
|
||||
return autoReloadEnabled_.load();
|
||||
}
|
||||
fileWatcher_.startWatching(currentLibraryPath_,
|
||||
[this]() { onCoreFileChanged(); });
|
||||
}
|
||||
}
|
||||
|
||||
void CoreLoader::onCoreFileChanged() {
|
||||
if (!autoReloadEnabled_.load() || hotReloading_.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO("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<std::mutex> lock(pendingReloadMutex_);
|
||||
hasPendingReload_ = true;
|
||||
pendingReloadPath_ = currentLibraryPath_;
|
||||
|
||||
// Capture current track ID
|
||||
auto state = core_->getPlaybackState();
|
||||
if (state && state->currentTrack.has_value()) {
|
||||
pendingTrackId_ = state->currentTrack->track.id;
|
||||
currentTrackId = pendingTrackId_;
|
||||
}
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO(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) {
|
||||
ECHOION_LOG_ERROR(std::format("Auto hot-reload failed: {}", result.error().message));
|
||||
} else {
|
||||
ECHOION_LOG_INFO("Auto hot-reload completed successfully");
|
||||
// Notify Plugin to re-register callbacks
|
||||
if (hotReloadCallback_) {
|
||||
hotReloadCallback_();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void CoreLoader::disableAutoReload()
|
||||
{
|
||||
autoReloadEnabled_ = false;
|
||||
fileWatcher_.stopWatching();
|
||||
ECHOION_LOG_INFO("Auto-reload disabled");
|
||||
}
|
||||
|
||||
bool CoreLoader::isPlaybackActive() const {
|
||||
if (!core_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto state = core_->getPlaybackState();
|
||||
if (!state) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if currently playing a track
|
||||
return state->isPlaying && state->currentTrack.has_value();
|
||||
}
|
||||
bool CoreLoader::isAutoReloadEnabled() const noexcept
|
||||
{
|
||||
return autoReloadEnabled_.load();
|
||||
}
|
||||
|
||||
bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const {
|
||||
if (!core_ || trackId.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto state = core_->getPlaybackState();
|
||||
if (!state || !state->currentTrack.has_value()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return state->currentTrack->track.id == trackId;
|
||||
}
|
||||
void CoreLoader::onCoreFileChanged()
|
||||
{
|
||||
if (!autoReloadEnabled_.load() || hotReloading_.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
void CoreLoader::waitForTrackAndReload(const std::filesystem::path& targetPath, const std::string& trackId) {
|
||||
ECHOION_LOG_INFO(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)
|
||||
while (isSameTrackPlaying(trackId)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO("Track finished, starting hot reload");
|
||||
|
||||
// Clear pending flag
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
|
||||
hasPendingReload_ = false;
|
||||
pendingTrackId_.clear();
|
||||
}
|
||||
|
||||
// Now do the reload
|
||||
auto result = hotReload(targetPath);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Deferred hot-reload failed: {}", result.error().message));
|
||||
} else {
|
||||
ECHOION_LOG_INFO("Deferred hot-reload completed successfully");
|
||||
// Notify Plugin to re-register callbacks
|
||||
if (hotReloadCallback_) {
|
||||
hotReloadCallback_();
|
||||
}
|
||||
}
|
||||
}
|
||||
ECHOION_LOG_INFO(
|
||||
"Core file changed, scheduling hot reload after current track...");
|
||||
|
||||
CoreLoader::~CoreLoader() {
|
||||
// Stop any deferred reload thread
|
||||
if (deferredReloadThread_.joinable()) {
|
||||
// We can't really stop it gracefully, but we can detach it
|
||||
// to avoid hanging on shutdown
|
||||
deferredReloadThread_.detach();
|
||||
}
|
||||
unload();
|
||||
cleanupTempFiles();
|
||||
}
|
||||
// Small delay to ensure file write is complete
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
|
||||
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (loaded_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "Core already loaded"));
|
||||
}
|
||||
// Check if playback is active - if so, defer reload
|
||||
if (isPlaybackActive()) {
|
||||
std::string currentTrackId;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
|
||||
hasPendingReload_ = true;
|
||||
pendingReloadPath_ = currentLibraryPath_;
|
||||
|
||||
if (!std::filesystem::exists(libraryPath)) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
|
||||
std::format("Library not found: {}", libraryPath.string())));
|
||||
}
|
||||
// Capture current track ID
|
||||
auto state = core_->getPlaybackSummary();
|
||||
if (state && state->currentTrack.has_value()) {
|
||||
pendingTrackId_ = state->currentTrack->id;
|
||||
currentTrackId = pendingTrackId_;
|
||||
}
|
||||
}
|
||||
|
||||
tempLibraryPath_ = getTempLibraryPath(libraryPath);
|
||||
|
||||
try {
|
||||
std::filesystem::copy_file(libraryPath, tempLibraryPath_,
|
||||
std::filesystem::copy_options::overwrite_existing);
|
||||
} catch (const std::exception& e) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::UnknownError,
|
||||
std::format("Failed to copy library to temp: {}", e.what())));
|
||||
}
|
||||
ECHOION_LOG_INFO(
|
||||
std::format("Playback active (track: {}), deferring reload "
|
||||
"until track finishes",
|
||||
currentTrackId));
|
||||
|
||||
auto result = loadLibraryInternal(tempLibraryPath_);
|
||||
if (result) {
|
||||
currentLibraryPath_ = libraryPath;
|
||||
} else {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tempLibraryPath_, ec);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
// 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) {
|
||||
ECHOION_LOG_ERROR(std::format("Auto hot-reload failed: {}",
|
||||
result.error().message));
|
||||
} else {
|
||||
ECHOION_LOG_INFO("Auto hot-reload completed successfully");
|
||||
// Notify Plugin to re-register callbacks
|
||||
if (hotReloadCallback_) {
|
||||
hotReloadCallback_();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::unload() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
auto result = unloadLibraryInternal();
|
||||
|
||||
if (!tempLibraryPath_.empty()) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tempLibraryPath_, ec);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
bool CoreLoader::isPlaybackActive() const
|
||||
{
|
||||
if (!core_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (!loaded_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "No core loaded to reload"));
|
||||
}
|
||||
auto state = core_->getPlaybackSummary();
|
||||
if (!state) {
|
||||
return false;
|
||||
}
|
||||
|
||||
hotReloading_ = true;
|
||||
|
||||
ECHOION_LOG_INFO("Starting hot reload with temp file...");
|
||||
// Check if currently playing a track
|
||||
return state->isPlaying && state->currentTrack.has_value();
|
||||
}
|
||||
|
||||
auto state = saveStateInternal();
|
||||
|
||||
auto targetPath = newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
|
||||
|
||||
if (!std::filesystem::exists(targetPath)) {
|
||||
hotReloading_ = false;
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
|
||||
std::format("New library not found: {}", targetPath.string())));
|
||||
}
|
||||
bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const
|
||||
{
|
||||
if (!core_ || trackId.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
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 std::unexpected(Api::Error(Api::ErrorCode::UnknownError,
|
||||
std::format("Failed to copy new library to temp: {}", e.what())));
|
||||
}
|
||||
auto state = core_->getPlaybackSummary();
|
||||
if (!state || !state->currentTrack.has_value()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto unloadResult = unloadLibraryInternal();
|
||||
if (!unloadResult) {
|
||||
hotReloading_ = false;
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(newTempPath, ec);
|
||||
return unloadResult;
|
||||
}
|
||||
return state->currentTrack->id == trackId;
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tempLibraryPath_, ec);
|
||||
tempLibraryPath_ = newTempPath;
|
||||
void CoreLoader::waitForTrackAndReload(
|
||||
const std::filesystem::path& targetPath, const std::string& trackId)
|
||||
{
|
||||
ECHOION_LOG_INFO(std::format(
|
||||
"Waiting for track {} to finish before reload...", trackId));
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
// Poll every 500ms to check if the specific track finished
|
||||
// (playback may continue with next track, but we only care about THIS
|
||||
// track)
|
||||
while (isSameTrackPlaying(trackId)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
}
|
||||
|
||||
auto loadResult = loadLibraryInternal(tempLibraryPath_);
|
||||
if (!loadResult) {
|
||||
hotReloading_ = false;
|
||||
return loadResult;
|
||||
}
|
||||
ECHOION_LOG_INFO("Track finished, starting hot reload");
|
||||
|
||||
auto restoreResult = restoreStateInternal(state);
|
||||
if (!restoreResult) {
|
||||
ECHOION_LOG_ERROR(std::format("Failed to restore state: {}", restoreResult.error().message));
|
||||
}
|
||||
// Clear pending flag
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
|
||||
hasPendingReload_ = false;
|
||||
pendingTrackId_.clear();
|
||||
}
|
||||
|
||||
currentLibraryPath_ = targetPath;
|
||||
hotReloading_ = false;
|
||||
|
||||
ECHOION_LOG_INFO("Hot reload complete");
|
||||
return {};
|
||||
}
|
||||
// Now do the reload
|
||||
auto result = hotReload(targetPath);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Deferred hot-reload failed: {}",
|
||||
result.error().message));
|
||||
} else {
|
||||
ECHOION_LOG_INFO("Deferred hot-reload completed successfully");
|
||||
// Notify Plugin to re-register callbacks
|
||||
if (hotReloadCallback_) {
|
||||
hotReloadCallback_();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool CoreLoader::isLoaded() const noexcept {
|
||||
return loaded_.load();
|
||||
}
|
||||
CoreLoader::~CoreLoader()
|
||||
{
|
||||
// Stop any deferred reload thread
|
||||
if (deferredReloadThread_.joinable()) {
|
||||
// We can't really stop it gracefully, but we can detach it
|
||||
// to avoid hanging on shutdown
|
||||
deferredReloadThread_.detach();
|
||||
}
|
||||
unload();
|
||||
cleanupTempFiles();
|
||||
}
|
||||
|
||||
Api::CoreInterfacePtr CoreLoader::getCore() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return core_;
|
||||
}
|
||||
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
void CoreLoader::setConfigPath(const std::filesystem::path& configPath) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
configPath_ = configPath;
|
||||
}
|
||||
if (loaded_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists,
|
||||
"Core already loaded"));
|
||||
}
|
||||
|
||||
std::filesystem::path CoreLoader::getConfigPath() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return configPath_;
|
||||
}
|
||||
if (!std::filesystem::exists(libraryPath)) {
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::NotFound,
|
||||
std::format("Library not found: {}", libraryPath.string())));
|
||||
}
|
||||
|
||||
bool CoreLoader::isHotReloading() const noexcept {
|
||||
return hotReloading_.load();
|
||||
}
|
||||
tempLibraryPath_ = getTempLibraryPath(libraryPath);
|
||||
|
||||
Api::Result<void> CoreLoader::loadLibraryInternal(const std::filesystem::path& path) {
|
||||
try {
|
||||
ECHOION_LOG_INFO(std::format("Loading core library: {}", path.string()));
|
||||
// Use no decorations - the path already has the correct extension (.ts)
|
||||
library_ = std::make_unique<dylib::library>(path.string(), dylib::decorations::none());
|
||||
|
||||
auto createFunc = library_->get_function<Api::CoreInterfacePtr()>("CreateCore");
|
||||
auto versionFunc = library_->get_function<const char*()>("GetApiVersion");
|
||||
auto compatibleFunc = library_->get_function<bool(uint32_t, uint32_t)>("IsApiCompatible");
|
||||
try {
|
||||
std::filesystem::copy_file(
|
||||
libraryPath, tempLibraryPath_,
|
||||
std::filesystem::copy_options::overwrite_existing);
|
||||
} catch (const std::exception& e) {
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::UnknownError,
|
||||
std::format("Failed to copy library to temp: {}", e.what())));
|
||||
}
|
||||
|
||||
if (!compatibleFunc(Api::VERSION_MAJOR, Api::VERSION_MINOR)) {
|
||||
library_.reset();
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
|
||||
std::format("API version mismatch. Expected {}.{}, got {}",
|
||||
Api::VERSION_MAJOR, Api::VERSION_MINOR, versionFunc())));
|
||||
}
|
||||
auto result = loadLibraryInternal(tempLibraryPath_);
|
||||
if (result) {
|
||||
currentLibraryPath_ = libraryPath;
|
||||
} else {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tempLibraryPath_, ec);
|
||||
}
|
||||
|
||||
core_ = createFunc();
|
||||
if (!core_) {
|
||||
library_.reset();
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::UnknownError,
|
||||
"Failed to create core instance"));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
auto initResult = core_->initialize(configPath_);
|
||||
if (!initResult) {
|
||||
core_.reset();
|
||||
library_.reset();
|
||||
return initResult;
|
||||
}
|
||||
Api::Result<void> CoreLoader::unload()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
loaded_ = true;
|
||||
auto result = unloadLibraryInternal();
|
||||
|
||||
ECHOION_LOG_INFO(std::format("Core library loaded (API version: {})", versionFunc()));
|
||||
return {};
|
||||
if (!tempLibraryPath_.empty()) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tempLibraryPath_, ec);
|
||||
}
|
||||
|
||||
} catch (const dylib::load_error& e) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::PluginError,
|
||||
std::format("Failed to load library: {}", e.what())));
|
||||
} catch (const dylib::symbol_error& e) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::PluginError,
|
||||
std::format("Failed to find symbol: {}", e.what())));
|
||||
} catch (const std::exception& e) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::UnknownError,
|
||||
std::format("Unexpected error: {}", e.what())));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::unloadLibraryInternal() {
|
||||
if (!loaded_) {
|
||||
return {};
|
||||
}
|
||||
Api::Result<void>
|
||||
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
ECHOION_LOG_INFO("Unloading core library...");
|
||||
if (!loaded_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
|
||||
"No core loaded to reload"));
|
||||
}
|
||||
|
||||
if (core_) {
|
||||
core_->shutdown();
|
||||
core_.reset();
|
||||
}
|
||||
hotReloading_ = true;
|
||||
|
||||
library_.reset();
|
||||
ECHOION_LOG_INFO("Starting hot reload with temp file...");
|
||||
|
||||
loaded_ = false;
|
||||
ECHOION_LOG_INFO("Core library unloaded");
|
||||
return {};
|
||||
}
|
||||
// Step 1: Save state as opaque blob (Plugin doesn't know contents)
|
||||
Api::StateBlob stateBlob;
|
||||
if (core_) {
|
||||
stateBlob = core_->saveState();
|
||||
ECHOION_LOG_INFO(
|
||||
std::format("Saved state: version={}, size={} bytes",
|
||||
stateBlob.version, stateBlob.size()));
|
||||
}
|
||||
|
||||
Api::HotReloadState CoreLoader::saveStateInternal() {
|
||||
if (!core_) {
|
||||
return Api::HotReloadState{};
|
||||
}
|
||||
auto targetPath =
|
||||
newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
|
||||
|
||||
auto state = core_->prepareForHotReload();
|
||||
if (state) {
|
||||
return *state;
|
||||
}
|
||||
if (!std::filesystem::exists(targetPath)) {
|
||||
hotReloading_ = false;
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::NotFound,
|
||||
std::format("New library not found: {}", targetPath.string())));
|
||||
}
|
||||
|
||||
ECHOION_LOG_WARNING("Failed to save state for hot reload");
|
||||
return Api::HotReloadState{};
|
||||
}
|
||||
std::filesystem::path newTempPath = getTempLibraryPath(targetPath);
|
||||
|
||||
Api::Result<void> CoreLoader::restoreStateInternal(const Api::HotReloadState& state) {
|
||||
if (!core_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"Core not available for state restore"));
|
||||
}
|
||||
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 std::unexpected(
|
||||
Api::Error(Api::ErrorCode::UnknownError,
|
||||
std::format("Failed to copy new library to temp: {}",
|
||||
e.what())));
|
||||
}
|
||||
|
||||
return core_->restoreAfterHotReload(state);
|
||||
}
|
||||
auto unloadResult = unloadLibraryInternal();
|
||||
if (!unloadResult) {
|
||||
hotReloading_ = false;
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(newTempPath, ec);
|
||||
return unloadResult;
|
||||
}
|
||||
|
||||
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<std::chrono::milliseconds>(
|
||||
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::thread::id>{}(std::this_thread::get_id()));
|
||||
#else
|
||||
auto tempName = std::format("echoion_{}_{}.ts", ms,
|
||||
std::hash<std::thread::id>{}(std::this_thread::get_id()));
|
||||
#endif
|
||||
|
||||
return tempDir / tempName;
|
||||
}
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tempLibraryPath_, ec);
|
||||
tempLibraryPath_ = newTempPath;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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;
|
||||
|
||||
ECHOION_LOG_INFO(std::format("Restoring state v{} to Core v{}",
|
||||
stateVersion, coreVersion));
|
||||
|
||||
if (core_->canRestoreStateVersion(stateVersion)) {
|
||||
auto restoreResult = core_->restoreState(stateBlob);
|
||||
if (!restoreResult) {
|
||||
ECHOION_LOG_ERROR(
|
||||
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
|
||||
ECHOION_LOG_WARNING("State version incompatible. "
|
||||
"User needs to update/restart.");
|
||||
// Optionally: notify through plugin interface
|
||||
}
|
||||
|
||||
// Continue with empty state - graceful degradation
|
||||
} else {
|
||||
ECHOION_LOG_INFO("State restored successfully");
|
||||
}
|
||||
} else {
|
||||
ECHOION_LOG_WARNING(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;
|
||||
|
||||
ECHOION_LOG_INFO("Hot reload complete");
|
||||
return {};
|
||||
}
|
||||
|
||||
bool CoreLoader::isLoaded() const noexcept { return loaded_.load(); }
|
||||
|
||||
Api::CoreInterfacePtr CoreLoader::getCore() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return core_;
|
||||
}
|
||||
|
||||
void CoreLoader::setConfigPath(const std::filesystem::path& configPath)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
configPath_ = configPath;
|
||||
}
|
||||
|
||||
std::filesystem::path CoreLoader::getConfigPath() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return configPath_;
|
||||
}
|
||||
|
||||
bool CoreLoader::isHotReloading() const noexcept
|
||||
{
|
||||
return hotReloading_.load();
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
CoreLoader::loadLibraryInternal(const std::filesystem::path& path)
|
||||
{
|
||||
try {
|
||||
|
||||
std::cout << std::format("[Echoion] Loading core library: {}",
|
||||
path.string())
|
||||
<< std::endl;
|
||||
// Use no decorations - the path already has the correct extension
|
||||
// (.ts)
|
||||
library_ = std::make_unique<dylib::library>(
|
||||
path.string(), dylib::decorations::none());
|
||||
|
||||
auto createFunc =
|
||||
library_->get_function<Api::CoreInterfacePtr()>("CreateCore");
|
||||
auto versionFunc =
|
||||
library_->get_function<const char*()>("GetApiVersion");
|
||||
auto compatibleFunc =
|
||||
library_->get_function<bool(uint32_t, uint32_t)>(
|
||||
"IsApiCompatible");
|
||||
|
||||
if (!compatibleFunc(Api::VERSION_MAJOR, Api::VERSION_MINOR)) {
|
||||
library_.reset();
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::InvalidArgument,
|
||||
std::format("API version mismatch. Expected {}.{}, got {}",
|
||||
Api::VERSION_MAJOR, Api::VERSION_MINOR,
|
||||
versionFunc())));
|
||||
}
|
||||
|
||||
core_ = createFunc();
|
||||
if (!core_) {
|
||||
library_.reset();
|
||||
return std::unexpected(
|
||||
Api::Error(Api::ErrorCode::UnknownError,
|
||||
"Failed to create core instance"));
|
||||
}
|
||||
|
||||
auto initResult = core_->initialize(configPath_);
|
||||
if (!initResult) {
|
||||
core_.reset();
|
||||
library_.reset();
|
||||
return initResult;
|
||||
}
|
||||
|
||||
loaded_ = true;
|
||||
|
||||
ECHOION_LOG_INFO(std::format(
|
||||
"Core library loaded (API version: {})", versionFunc()));
|
||||
return {};
|
||||
|
||||
} catch (const dylib::load_error& e) {
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::PluginError,
|
||||
std::format("Failed to load library: {}", e.what())));
|
||||
} catch (const dylib::symbol_error& e) {
|
||||
return std::unexpected(
|
||||
Api::Error(Api::ErrorCode::PluginError,
|
||||
std::format("Failed to find symbol: {}", e.what())));
|
||||
} catch (const std::exception& e) {
|
||||
return std::unexpected(
|
||||
Api::Error(Api::ErrorCode::UnknownError,
|
||||
std::format("Unexpected error: {}", e.what())));
|
||||
}
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::unloadLibraryInternal()
|
||||
{
|
||||
if (!loaded_) {
|
||||
return {};
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO("Unloading core library...");
|
||||
|
||||
if (core_) {
|
||||
core_->shutdown();
|
||||
core_.reset();
|
||||
}
|
||||
|
||||
library_.reset();
|
||||
|
||||
loaded_ = false;
|
||||
std::cout << "[Echoion] Core library unloaded" << std::endl;
|
||||
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<std::chrono::milliseconds>(
|
||||
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::thread::id>{}(std::this_thread::get_id()));
|
||||
#else
|
||||
auto tempName = std::format(
|
||||
"echoion_{}_{}.ts", ms,
|
||||
std::hash<std::thread::id>{}(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::Plugin
|
||||
Reference in new issue
Block a user