1 parent
ccebe083e3
commit
7a1c817f90
5 files changed
+222
-414
No files matched your search
+2
-9
@@ -1,16 +1,8 @@
|
|||||||
cmake_minimum_required(VERSION 4.0.0)
|
cmake_minimum_required(VERSION 4.0.0)
|
||||||
project(EchoionHost VERSION 1.0.0 LANGUAGES CXX)
|
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
|
add_library(EchoionHost STATIC
|
||||||
src/CoreLoader.cpp
|
src/CoreLoader.cpp
|
||||||
src/FileWatcher.cpp
|
|
||||||
)
|
)
|
||||||
add_library(Echoion::Host ALIAS EchoionHost)
|
add_library(Echoion::Host ALIAS EchoionHost)
|
||||||
|
|
||||||
@@ -27,11 +19,12 @@ target_link_libraries(EchoionHost
|
|||||||
Echoion::ApiPlugin
|
Echoion::ApiPlugin
|
||||||
Echoion::ApiOpaque
|
Echoion::ApiOpaque
|
||||||
Echoion::ApiCoreInterface
|
Echoion::ApiCoreInterface
|
||||||
dylib
|
|
||||||
PRIVATE
|
PRIVATE
|
||||||
Echoion::ApiLogger
|
Echoion::ApiLogger
|
||||||
Void::Data
|
Void::Data
|
||||||
Void::Log
|
Void::Log
|
||||||
|
Void::Plugin
|
||||||
|
Void::System
|
||||||
Void::Stacktrace
|
Void::Stacktrace
|
||||||
Threads::Threads
|
Threads::Threads
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include "echoion/host/FileWatcher.hpp"
|
#include <Void/System/FileWatcher.hpp>
|
||||||
|
#include <Void/Plugin/Manager.hpp>
|
||||||
#include <CoreInterface.hpp>
|
#include <CoreInterface.hpp>
|
||||||
#include <PluginTypes.hpp>
|
#include <PluginTypes.hpp>
|
||||||
#include <Types.hpp>
|
#include <Types.hpp>
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
#include <dylib.hpp>
|
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
@@ -32,6 +32,10 @@ namespace Echoion::Host
|
|||||||
void setConfigPath(const std::filesystem::path& configPath);
|
void setConfigPath(const std::filesystem::path& configPath);
|
||||||
[[nodiscard]] std::filesystem::path getConfigPath() const;
|
[[nodiscard]] std::filesystem::path getConfigPath() const;
|
||||||
[[nodiscard]] bool isHotReloading() const noexcept;
|
[[nodiscard]] bool isHotReloading() const noexcept;
|
||||||
|
Api::Result<void>
|
||||||
|
checkpoint(const std::filesystem::path& destination);
|
||||||
|
Api::Result<void>
|
||||||
|
restoreCheckpoint(const std::filesystem::path& source);
|
||||||
|
|
||||||
// Automatic hot reload
|
// Automatic hot reload
|
||||||
void enableAutoReload();
|
void enableAutoReload();
|
||||||
@@ -41,6 +45,11 @@ namespace Echoion::Host
|
|||||||
// Callback for hot reload completion (called after auto-reload
|
// Callback for hot reload completion (called after auto-reload
|
||||||
// finishes)
|
// finishes)
|
||||||
using HotReloadCallback = std::function<void()>;
|
using HotReloadCallback = std::function<void()>;
|
||||||
|
using HotReloadPrepareCallback = std::function<void()>;
|
||||||
|
void setHotReloadPrepareCallback(HotReloadPrepareCallback callback)
|
||||||
|
{
|
||||||
|
hotReloadPrepareCallback_ = std::move(callback);
|
||||||
|
}
|
||||||
void setHotReloadCallback(HotReloadCallback callback)
|
void setHotReloadCallback(HotReloadCallback callback)
|
||||||
{
|
{
|
||||||
hotReloadCallback_ = std::move(callback);
|
hotReloadCallback_ = std::move(callback);
|
||||||
@@ -51,24 +60,19 @@ namespace Echoion::Host
|
|||||||
Api::Result<void>
|
Api::Result<void>
|
||||||
loadLibraryInternal(const std::filesystem::path& path);
|
loadLibraryInternal(const std::filesystem::path& path);
|
||||||
Api::Result<void> unloadLibraryInternal();
|
Api::Result<void> unloadLibraryInternal();
|
||||||
[[nodiscard]] Api::SerializedState saveStateInternal();
|
[[nodiscard]] Api::Result<void> refreshCoreHandle();
|
||||||
[[nodiscard]] Api::Result<void>
|
|
||||||
restoreStateInternal(const Api::SerializedState& state);
|
|
||||||
[[nodiscard]] std::filesystem::path
|
|
||||||
getTempLibraryPath(const std::filesystem::path& original) const;
|
|
||||||
void cleanupTempFiles();
|
|
||||||
|
|
||||||
std::unique_ptr<dylib::library> library_;
|
Void::Plugin::PluginManager pluginManager_;
|
||||||
|
std::string pluginName_;
|
||||||
Api::CoreInterfacePtr core_;
|
Api::CoreInterfacePtr core_;
|
||||||
std::filesystem::path currentLibraryPath_;
|
std::filesystem::path currentLibraryPath_;
|
||||||
std::filesystem::path tempLibraryPath_;
|
|
||||||
std::filesystem::path configPath_;
|
std::filesystem::path configPath_;
|
||||||
mutable std::mutex mutex_;
|
mutable std::mutex mutex_;
|
||||||
std::atomic<bool> loaded_{false};
|
std::atomic<bool> loaded_{false};
|
||||||
std::atomic<bool> hotReloading_{false};
|
std::atomic<bool> hotReloading_{false};
|
||||||
|
|
||||||
// Auto reload
|
// Auto reload
|
||||||
FileWatcher fileWatcher_;
|
Void::FileSystem::FileWatcher fileWatcher_;
|
||||||
std::atomic<bool> autoReloadEnabled_{false};
|
std::atomic<bool> autoReloadEnabled_{false};
|
||||||
|
|
||||||
// Deferred reload - waits for current track to finish
|
// Deferred reload - waits for current track to finish
|
||||||
@@ -82,6 +86,7 @@ namespace Echoion::Host
|
|||||||
mutable std::mutex pendingReloadMutex_;
|
mutable std::mutex pendingReloadMutex_;
|
||||||
|
|
||||||
// Hot reload completion callback
|
// Hot reload completion callback
|
||||||
|
HotReloadPrepareCallback hotReloadPrepareCallback_;
|
||||||
HotReloadCallback hotReloadCallback_;
|
HotReloadCallback hotReloadCallback_;
|
||||||
|
|
||||||
void onCoreFileChanged();
|
void onCoreFileChanged();
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <atomic>
|
|
||||||
#include <chrono>
|
|
||||||
#include <filesystem>
|
|
||||||
#include <functional>
|
|
||||||
#include <mutex>
|
|
||||||
#include <thread>
|
|
||||||
|
|
||||||
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<void()>;
|
|
||||||
|
|
||||||
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<bool> watching_{false};
|
|
||||||
std::atomic<bool> 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
|
|
||||||
+204
-231
@@ -1,5 +1,6 @@
|
|||||||
#include <Void/Log/Log.hpp>
|
#include <Void/Log/Log.hpp>
|
||||||
#include "dylib.hpp"
|
#include <Void/Plugin/Loader.hpp>
|
||||||
|
#include <Void/System/Path.hpp>
|
||||||
#include "echoion/host/CoreLoader.hpp"
|
#include "echoion/host/CoreLoader.hpp"
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <format>
|
#include <format>
|
||||||
@@ -10,7 +11,19 @@
|
|||||||
namespace Echoion::Host
|
namespace Echoion::Host
|
||||||
{
|
{
|
||||||
|
|
||||||
CoreLoader::CoreLoader() { cleanupTempFiles(); }
|
CoreLoader::CoreLoader()
|
||||||
|
: pluginManager_(Void::Plugin::PluginManager::Options{
|
||||||
|
.dlclose_on_swap = false,
|
||||||
|
.copy_on_load = true,
|
||||||
|
.config_provider = [this](std::string_view) {
|
||||||
|
return configPath_.string();
|
||||||
|
},
|
||||||
|
.instance_validator = [](Void::Plugin::IPlugin& plugin,
|
||||||
|
const Void::Plugin::PluginInfo&) {
|
||||||
|
return dynamic_cast<Api::ICoreInterface*>(&plugin) != nullptr;
|
||||||
|
}})
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
void CoreLoader::enableAutoReload()
|
void CoreLoader::enableAutoReload()
|
||||||
{
|
{
|
||||||
@@ -24,15 +37,21 @@ namespace Echoion::Host
|
|||||||
Void::Log::info("CoreLoader", "{}", std::format("Enabling auto-reload for: {}",
|
Void::Log::info("CoreLoader", "{}", std::format("Enabling auto-reload for: {}",
|
||||||
currentLibraryPath_.string()));
|
currentLibraryPath_.string()));
|
||||||
|
|
||||||
fileWatcher_.startWatching(currentLibraryPath_,
|
fileWatcher_.watch(currentLibraryPath_,
|
||||||
[this]() { onCoreFileChanged(); });
|
[this](const Void::FileSystem::FileWatcher::Event& event) {
|
||||||
|
if (event.exists) {
|
||||||
|
onCoreFileChanged();
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void CoreLoader::disableAutoReload()
|
void CoreLoader::disableAutoReload()
|
||||||
{
|
{
|
||||||
autoReloadEnabled_ = false;
|
autoReloadEnabled_ = false;
|
||||||
fileWatcher_.stopWatching();
|
if (!currentLibraryPath_.empty()) {
|
||||||
|
fileWatcher_.unwatch(currentLibraryPath_);
|
||||||
|
}
|
||||||
Void::Log::info("CoreLoader", "{}", "Auto-reload disabled");
|
Void::Log::info("CoreLoader", "{}", "Auto-reload disabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,10 +108,6 @@ namespace Echoion::Host
|
|||||||
result.error().message));
|
result.error().message));
|
||||||
} else {
|
} else {
|
||||||
Void::Log::info("CoreLoader", "{}", "Auto hot-reload completed successfully");
|
Void::Log::info("CoreLoader", "{}", "Auto hot-reload completed successfully");
|
||||||
// Notify Plugin to re-register callbacks
|
|
||||||
if (hotReloadCallback_) {
|
|
||||||
hotReloadCallback_();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -168,15 +183,14 @@ namespace Echoion::Host
|
|||||||
result.error().message));
|
result.error().message));
|
||||||
} else {
|
} else {
|
||||||
Void::Log::info("CoreLoader", "{}", "Deferred hot-reload completed successfully");
|
Void::Log::info("CoreLoader", "{}", "Deferred hot-reload completed successfully");
|
||||||
// Notify Plugin to re-register callbacks
|
|
||||||
if (hotReloadCallback_) {
|
|
||||||
hotReloadCallback_();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
CoreLoader::~CoreLoader()
|
CoreLoader::~CoreLoader()
|
||||||
{
|
{
|
||||||
|
if (autoReloadEnabled_.load()) {
|
||||||
|
disableAutoReload();
|
||||||
|
}
|
||||||
// Signal the deferred reload thread to stop and wait for it. It must
|
// Signal the deferred reload thread to stop and wait for it. It must
|
||||||
// never outlive this object: it dereferences core_ and this.
|
// never outlive this object: it dereferences core_ and this.
|
||||||
stopDeferredReload_ = true;
|
stopDeferredReload_ = true;
|
||||||
@@ -189,12 +203,11 @@ namespace Echoion::Host
|
|||||||
std::format("Unload from destructor failed: {}",
|
std::format("Unload from destructor failed: {}",
|
||||||
result.error().message));
|
result.error().message));
|
||||||
}
|
}
|
||||||
cleanupTempFiles();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath)
|
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath)
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
std::unique_lock<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
if (loaded_) {
|
if (loaded_) {
|
||||||
return Api::fail(Api::ErrorCode::AlreadyExists,
|
return Api::fail(Api::ErrorCode::AlreadyExists,
|
||||||
@@ -207,24 +220,9 @@ namespace Echoion::Host
|
|||||||
std::format("Library not found: {}", libraryPath.string()));
|
std::format("Library not found: {}", libraryPath.string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
tempLibraryPath_ = getTempLibraryPath(libraryPath);
|
auto result = loadLibraryInternal(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) {
|
if (result) {
|
||||||
currentLibraryPath_ = libraryPath;
|
currentLibraryPath_ = libraryPath;
|
||||||
} else {
|
|
||||||
std::error_code ec;
|
|
||||||
std::filesystem::remove(tempLibraryPath_, ec);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@@ -234,127 +232,105 @@ namespace Echoion::Host
|
|||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
auto result = unloadLibraryInternal();
|
return unloadLibraryInternal();
|
||||||
|
|
||||||
if (!tempLibraryPath_.empty()) {
|
|
||||||
std::error_code ec;
|
|
||||||
std::filesystem::remove(tempLibraryPath_, ec);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Api::Result<void>
|
Api::Result<void>
|
||||||
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
|
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(mutex_);
|
std::unique_lock<std::mutex> lock(mutex_);
|
||||||
|
|
||||||
if (!loaded_) {
|
if (!loaded_) {
|
||||||
return Api::fail(Api::ErrorCode::NotFound,
|
return Api::fail(Api::ErrorCode::NotFound,
|
||||||
"No core loaded to reload");
|
"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 =
|
auto targetPath =
|
||||||
newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
|
newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
|
||||||
|
|
||||||
if (!std::filesystem::exists(targetPath)) {
|
if (!std::filesystem::exists(targetPath)) {
|
||||||
hotReloading_ = false;
|
|
||||||
return Api::fail(
|
return Api::fail(
|
||||||
Api::ErrorCode::NotFound,
|
Api::ErrorCode::NotFound,
|
||||||
std::format("New library not found: {}", targetPath.string()));
|
std::format("New library not found: {}", targetPath.string()));
|
||||||
}
|
}
|
||||||
|
if (targetPath != currentLibraryPath_) {
|
||||||
std::filesystem::path newTempPath = getTempLibraryPath(targetPath);
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||||
|
"in-process Core reload must use the loaded path; release bundles "
|
||||||
try {
|
"with a new path are applied through daemon re-exec");
|
||||||
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();
|
hotReloading_ = true;
|
||||||
if (!unloadResult) {
|
Void::Log::info("CoreLoader", "{}", "Starting transactional hot reload...");
|
||||||
hotReloading_ = false;
|
|
||||||
std::error_code ec;
|
// No callback may execute code from the old shared object after this
|
||||||
std::filesystem::remove(newTempPath, ec);
|
// barrier returns. State capture and dlclose are safe only after event
|
||||||
return unloadResult;
|
// producers have been drained.
|
||||||
|
if (hotReloadPrepareCallback_) {
|
||||||
|
hotReloadPrepareCallback_();
|
||||||
}
|
}
|
||||||
|
|
||||||
std::error_code ec;
|
// Core owns exclusive process resources (HTTP/RPC listeners), so its
|
||||||
std::filesystem::remove(tempLibraryPath_, ec);
|
// two generations cannot both be initialized during an RCU swap.
|
||||||
tempLibraryPath_ = newTempPath;
|
// Capture state first, then stop the old services while its plugin
|
||||||
|
// instance remains pinned for rollback.
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
Api::StateBlob state;
|
||||||
|
if (core_) {
|
||||||
auto loadResult = loadLibraryInternal(tempLibraryPath_);
|
state = core_->saveState();
|
||||||
if (!loadResult) {
|
if (auto stopped = core_->shutdown(); !stopped) {
|
||||||
hotReloading_ = false;
|
hotReloading_ = false;
|
||||||
return loadResult;
|
lock.unlock();
|
||||||
}
|
if (hotReloadCallback_) {
|
||||||
|
hotReloadCallback_();
|
||||||
// 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 {
|
return stopped;
|
||||||
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;
|
const auto reloadResult = pluginManager_.reload(pluginName_);
|
||||||
|
if (!reloadResult) {
|
||||||
|
hotReloading_ = false;
|
||||||
|
auto message = std::format(
|
||||||
|
"new Core rejected; running Core retained: {}",
|
||||||
|
Void::Plugin::to_string(reloadResult.error()));
|
||||||
|
if (core_) {
|
||||||
|
if (auto initialized = core_->initialize(configPath_); !initialized) {
|
||||||
|
message += std::format("; retained Core reactivation failed: {}",
|
||||||
|
initialized.error().message);
|
||||||
|
} else if (!state.empty()) {
|
||||||
|
if (auto restored = core_->restoreState(state); !restored) {
|
||||||
|
message += std::format(
|
||||||
|
"; retained Core state restore failed: {}",
|
||||||
|
restored.error().message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Void::Log::warn("CoreLoader", "{}", message);
|
||||||
|
lock.unlock();
|
||||||
|
// The prepare callback removed the event route. Restore it against
|
||||||
|
// the still-current Core even though no swap occurred.
|
||||||
|
if (hotReloadCallback_) {
|
||||||
|
hotReloadCallback_();
|
||||||
|
}
|
||||||
|
return Api::fail(Api::ErrorCode::PluginError, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (auto refreshed = refreshCoreHandle(); !refreshed) {
|
||||||
|
hotReloading_ = false;
|
||||||
|
return refreshed;
|
||||||
|
}
|
||||||
|
if (!state.empty()) {
|
||||||
|
if (auto restored = core_->restoreState(state); !restored) {
|
||||||
|
Void::Log::warn("CoreLoader", "new Core state restore failed: {}",
|
||||||
|
restored.error().message);
|
||||||
|
}
|
||||||
|
}
|
||||||
hotReloading_ = false;
|
hotReloading_ = false;
|
||||||
|
|
||||||
Void::Log::info("CoreLoader", "{}", "Hot reload complete");
|
Void::Log::info("CoreLoader", "{}", "Hot reload complete");
|
||||||
|
lock.unlock();
|
||||||
|
if (hotReloadCallback_) {
|
||||||
|
hotReloadCallback_();
|
||||||
|
}
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -383,67 +359,109 @@ namespace Echoion::Host
|
|||||||
return hotReloading_.load();
|
return hotReloading_.load();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Api::Result<void>
|
||||||
|
CoreLoader::checkpoint(const std::filesystem::path& destination)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
if (!core_) {
|
||||||
|
return Api::fail(Api::ErrorCode::NotInitialized,
|
||||||
|
"cannot checkpoint without a loaded Core");
|
||||||
|
}
|
||||||
|
const auto state = core_->saveState();
|
||||||
|
std::string bytes;
|
||||||
|
bytes.reserve(8 + state.timestamp.size() + state.data.size());
|
||||||
|
auto appendU32 = [&bytes](uint32_t value) {
|
||||||
|
for (int shift : {24, 16, 8, 0}) {
|
||||||
|
bytes.push_back(static_cast<char>((value >> shift) & 0xffU));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
appendU32(state.version);
|
||||||
|
appendU32(static_cast<uint32_t>(state.timestamp.size()));
|
||||||
|
bytes.append(state.timestamp);
|
||||||
|
bytes.append(reinterpret_cast<const char*>(state.data.data()),
|
||||||
|
state.data.size());
|
||||||
|
if (auto result = Void::FileSystem::atomic_write(destination, bytes);
|
||||||
|
!result) {
|
||||||
|
return Api::fail(Api::ErrorCode::PluginError,
|
||||||
|
result.error().message());
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Api::Result<void>
|
||||||
|
CoreLoader::restoreCheckpoint(const std::filesystem::path& source)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(mutex_);
|
||||||
|
if (!core_) {
|
||||||
|
return Api::fail(Api::ErrorCode::NotInitialized,
|
||||||
|
"cannot restore without a loaded Core");
|
||||||
|
}
|
||||||
|
auto contents = Void::FileSystem::read_file(source);
|
||||||
|
if (!contents) {
|
||||||
|
return Api::fail(Api::ErrorCode::NotFound,
|
||||||
|
contents.error().message());
|
||||||
|
}
|
||||||
|
if (contents->size() < 8) {
|
||||||
|
return Api::fail(Api::ErrorCode::ParseError,
|
||||||
|
"checkpoint header is truncated");
|
||||||
|
}
|
||||||
|
auto readU32 = [&contents](std::size_t offset) {
|
||||||
|
uint32_t value = 0;
|
||||||
|
for (std::size_t index = 0; index < 4; ++index) {
|
||||||
|
value = (value << 8U) |
|
||||||
|
static_cast<unsigned char>((*contents)[offset + index]);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
Api::StateBlob state;
|
||||||
|
state.version = readU32(0);
|
||||||
|
const auto timestampSize = readU32(4);
|
||||||
|
if (timestampSize > contents->size() - 8) {
|
||||||
|
return Api::fail(Api::ErrorCode::ParseError,
|
||||||
|
"checkpoint timestamp is truncated");
|
||||||
|
}
|
||||||
|
state.timestamp = contents->substr(8, timestampSize);
|
||||||
|
const auto dataOffset = 8 + timestampSize;
|
||||||
|
state.data.assign(contents->begin() +
|
||||||
|
static_cast<std::ptrdiff_t>(dataOffset), contents->end());
|
||||||
|
return core_->restoreState(state);
|
||||||
|
}
|
||||||
|
|
||||||
Api::Result<void>
|
Api::Result<void>
|
||||||
CoreLoader::loadLibraryInternal(const std::filesystem::path& path)
|
CoreLoader::loadLibraryInternal(const std::filesystem::path& path)
|
||||||
{
|
{
|
||||||
try {
|
auto result = pluginManager_.load(path);
|
||||||
|
if (!result) {
|
||||||
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<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 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,
|
return Api::fail(Api::ErrorCode::PluginError,
|
||||||
std::format("Failed to find symbol: {}", e.what()));
|
std::format("failed to load Core plugin: {}",
|
||||||
} catch (const std::exception& e) {
|
Void::Plugin::to_string(result.error())));
|
||||||
return Api::fail(Api::ErrorCode::UnknownError,
|
|
||||||
std::format("Unexpected error: {}", e.what()));
|
|
||||||
}
|
}
|
||||||
|
pluginName_ = std::move(*result);
|
||||||
|
if (auto refreshed = refreshCoreHandle(); !refreshed) {
|
||||||
|
std::ignore = pluginManager_.unload(pluginName_);
|
||||||
|
pluginName_.clear();
|
||||||
|
return refreshed;
|
||||||
|
}
|
||||||
|
loaded_ = true;
|
||||||
|
Void::Log::info("CoreLoader", "Core plugin '{}' loaded", pluginName_);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Api::Result<void> CoreLoader::refreshCoreHandle()
|
||||||
|
{
|
||||||
|
auto pin = std::make_shared<Void::Plugin::PluginHandle>(
|
||||||
|
pluginManager_.acquire(pluginName_));
|
||||||
|
if (!*pin) {
|
||||||
|
return Api::fail(Api::ErrorCode::PluginError,
|
||||||
|
"Core plugin disappeared from the registry");
|
||||||
|
}
|
||||||
|
auto* interface = dynamic_cast<Api::ICoreInterface*>(pin->get());
|
||||||
|
if (interface == nullptr) {
|
||||||
|
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||||
|
"Void plugin does not implement Echoion Core interface");
|
||||||
|
}
|
||||||
|
core_ = Api::CoreInterfacePtr{std::move(pin), interface};
|
||||||
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
Api::Result<void> CoreLoader::unloadLibraryInternal()
|
Api::Result<void> CoreLoader::unloadLibraryInternal()
|
||||||
@@ -454,64 +472,19 @@ namespace Echoion::Host
|
|||||||
|
|
||||||
Void::Log::info("CoreLoader", "{}", "Unloading core library...");
|
Void::Log::info("CoreLoader", "{}", "Unloading core library...");
|
||||||
|
|
||||||
if (core_) {
|
core_.reset();
|
||||||
if (auto result = core_->shutdown(); !result) {
|
if (!pluginName_.empty()) {
|
||||||
Void::Log::warn(
|
if (auto result = pluginManager_.unload(pluginName_); !result) {
|
||||||
"CoreLoader", "{}",
|
return Api::fail(Api::ErrorCode::PluginError,
|
||||||
std::format("Core shutdown reported failure: {}",
|
std::format("failed to unload Core plugin: {}",
|
||||||
result.error().message));
|
Void::Plugin::to_string(result.error())));
|
||||||
}
|
}
|
||||||
core_.reset();
|
pluginName_.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
library_.reset();
|
|
||||||
|
|
||||||
loaded_ = false;
|
loaded_ = false;
|
||||||
std::cout << "[Echoion] Core library unloaded" << '\n';
|
std::cout << "[Echoion] Core library unloaded" << '\n';
|
||||||
return {};
|
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::Host
|
} // namespace Echoion::Host
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
#include "echoion/host/FileWatcher.hpp"
|
|
||||||
#include <chrono>
|
|
||||||
#include <format>
|
|
||||||
#include <iostream>
|
|
||||||
|
|
||||||
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<std::mutex> 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<std::mutex> 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
|
|
||||||
Reference in new issue
Block a user