Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-16 19:59:57 +03:00
1 parent 7a1c817f90
commit 2e0f15af59
1 file changed
+156 -59
+156 -59
View File
@@ -1,43 +1,114 @@
#include "echoion/host/CoreLoader.hpp"
#include <Void/Log/Log.hpp> #include <Void/Log/Log.hpp>
#include <Void/Plugin/Loader.hpp> #include <Void/Plugin/Loader.hpp>
#include <Void/System/Path.hpp> #include <Void/System/Path.hpp>
#include "echoion/host/CoreLoader.hpp" #include <algorithm>
#include <chrono> #include <chrono>
#include <format> #include <format>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <thread> #include <thread>
#include <vector>
#ifndef _WIN32
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Echoion::Host namespace Echoion::Host
{ {
namespace
{
bool canCreateHotReloadCopy(const std::filesystem::path& libraryPath)
{
const auto directory = libraryPath.parent_path();
#ifdef _WIN32
std::error_code error;
const auto status = std::filesystem::status(directory, error);
if (error || !std::filesystem::is_directory(status)) {
return false;
}
constexpr auto writable = std::filesystem::perms::owner_write |
std::filesystem::perms::group_write |
std::filesystem::perms::others_write;
return (status.permissions() & writable) !=
std::filesystem::perms::none;
#else
struct stat metadata{};
if (::stat(directory.c_str(), &metadata) != 0 ||
!S_ISDIR(metadata.st_mode)) {
return false;
}
const auto effectiveUser = ::geteuid();
const auto effectiveGroup = ::getegid();
bool usesDirectoryGroup = effectiveGroup == metadata.st_gid;
if (!usesDirectoryGroup) {
const int count = ::getgroups(0, nullptr);
if (count > 0) {
std::vector<gid_t> groups(static_cast<std::size_t>(count));
if (::getgroups(count, groups.data()) == count) {
usesDirectoryGroup =
std::ranges::contains(groups, metadata.st_gid);
}
}
}
mode_t required{};
if (effectiveUser == metadata.st_uid) {
required = S_IWUSR | S_IXUSR;
} else if (usesDirectoryGroup) {
required = S_IWGRP | S_IXGRP;
} else {
required = S_IWOTH | S_IXOTH;
}
return (metadata.st_mode & required) == required &&
::access(directory.c_str(), W_OK | X_OK) == 0;
#endif
}
} // namespace
CoreLoader::CoreLoader() CoreLoader::CoreLoader()
: pluginManager_(Void::Plugin::PluginManager::Options{ : pluginManager_(Void::Plugin::PluginManager::Options{
.dlclose_on_swap = false, .dlclose_on_swap = false,
.copy_on_load = true, // Packaged Core libraries live in an immutable, service-readable
.config_provider = [this](std::string_view) { // directory. Initial load must never create a hotswap sibling
return configPath_.string(); // there.
}, .copy_on_load = false,
.instance_validator = [](Void::Plugin::IPlugin& plugin, .config_provider =
const Void::Plugin::PluginInfo&) { [this](std::string_view) { return configPath_.string(); },
return dynamic_cast<Api::ICoreInterface*>(&plugin) != nullptr; .instance_validator =
}}) [](Void::Plugin::IPlugin& plugin,
const Void::Plugin::PluginInfo&) {
return dynamic_cast<Api::ICoreInterface*>(&plugin) !=
nullptr;
}})
{ {
} }
void CoreLoader::enableAutoReload() void CoreLoader::enableAutoReload()
{ {
if (autoReloadEnabled_.exchange(true)) {
return; // Already enabled
}
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
if (autoReloadEnabled_.load()) {
return;
}
if (!currentLibraryPath_.empty() && if (!currentLibraryPath_.empty() &&
std::filesystem::exists(currentLibraryPath_)) { std::filesystem::exists(currentLibraryPath_)) {
Void::Log::info("CoreLoader", "{}", std::format("Enabling auto-reload for: {}", if (!canCreateHotReloadCopy(currentLibraryPath_)) {
currentLibraryPath_.string())); Void::Log::info(
"CoreLoader", "{}",
std::format(
"Auto-reload disabled for read-only Core directory: {}",
currentLibraryPath_.parent_path().string()));
return;
}
autoReloadEnabled_ = true;
Void::Log::info("CoreLoader", "{}",
std::format("Enabling auto-reload for: {}",
currentLibraryPath_.string()));
fileWatcher_.watch(currentLibraryPath_, fileWatcher_.watch(
currentLibraryPath_,
[this](const Void::FileSystem::FileWatcher::Event& event) { [this](const Void::FileSystem::FileWatcher::Event& event) {
if (event.exists) { if (event.exists) {
onCoreFileChanged(); onCoreFileChanged();
@@ -66,7 +137,8 @@ namespace Echoion::Host
return; return;
} }
Void::Log::info("CoreLoader", "{}", Void::Log::info(
"CoreLoader", "{}",
"Core file changed, scheduling hot reload after current track..."); "Core file changed, scheduling hot reload after current track...");
// Small delay to ensure file write is complete // Small delay to ensure file write is complete
@@ -88,7 +160,8 @@ namespace Echoion::Host
} }
} }
Void::Log::info("CoreLoader", "{}", Void::Log::info(
"CoreLoader", "{}",
std::format("Playback active (track: {}), deferring reload " std::format("Playback active (track: {}), deferring reload "
"until track finishes", "until track finishes",
currentTrackId)); currentTrackId));
@@ -104,10 +177,12 @@ namespace Echoion::Host
// No playback, reload immediately // No playback, reload immediately
auto result = hotReload(currentLibraryPath_); auto result = hotReload(currentLibraryPath_);
if (!result) { if (!result) {
Void::Log::error("CoreLoader", "{}", std::format("Auto hot-reload failed: {}", Void::Log::error("CoreLoader", "{}",
result.error().message)); std::format("Auto hot-reload failed: {}",
result.error().message));
} else { } else {
Void::Log::info("CoreLoader", "{}", "Auto hot-reload completed successfully"); Void::Log::info("CoreLoader", "{}",
"Auto hot-reload completed successfully");
} }
} }
} }
@@ -144,8 +219,10 @@ namespace Echoion::Host
void CoreLoader::waitForTrackAndReload( void CoreLoader::waitForTrackAndReload(
const std::filesystem::path& targetPath, const std::string& trackId) const std::filesystem::path& targetPath, const std::string& trackId)
{ {
Void::Log::info("CoreLoader", "{}", std::format( Void::Log::info(
"Waiting for track {} to finish before reload...", trackId)); "CoreLoader", "{}",
std::format("Waiting for track {} to finish before reload...",
trackId));
// Poll every 500ms to check if the specific track finished // Poll every 500ms to check if the specific track finished
// (playback may continue with next track, but we only care about THIS // (playback may continue with next track, but we only care about THIS
@@ -157,7 +234,8 @@ namespace Echoion::Host
if (deferredReloadCv_.wait_for( if (deferredReloadCv_.wait_for(
lock, std::chrono::milliseconds(500), lock, std::chrono::milliseconds(500),
[this] { return stopDeferredReload_.load(); })) { [this] { return stopDeferredReload_.load(); })) {
Void::Log::info("CoreLoader", "{}", Void::Log::info(
"CoreLoader", "{}",
"Deferred hot-reload cancelled (loader shutting down)"); "Deferred hot-reload cancelled (loader shutting down)");
return; return;
} }
@@ -167,7 +245,8 @@ namespace Echoion::Host
return; return;
} }
Void::Log::info("CoreLoader", "{}", "Track finished, starting hot reload"); Void::Log::info("CoreLoader", "{}",
"Track finished, starting hot reload");
// Clear pending flag // Clear pending flag
{ {
@@ -179,10 +258,12 @@ namespace Echoion::Host
// Now do the reload // Now do the reload
auto result = hotReload(targetPath); auto result = hotReload(targetPath);
if (!result) { if (!result) {
Void::Log::error("CoreLoader", "{}", std::format("Deferred hot-reload failed: {}", Void::Log::error("CoreLoader", "{}",
result.error().message)); std::format("Deferred hot-reload failed: {}",
result.error().message));
} else { } else {
Void::Log::info("CoreLoader", "{}", "Deferred hot-reload completed successfully"); Void::Log::info("CoreLoader", "{}",
"Deferred hot-reload completed successfully");
} }
} }
@@ -211,7 +292,7 @@ namespace Echoion::Host
if (loaded_) { if (loaded_) {
return Api::fail(Api::ErrorCode::AlreadyExists, return Api::fail(Api::ErrorCode::AlreadyExists,
"Core already loaded"); "Core already loaded");
} }
if (!std::filesystem::exists(libraryPath)) { if (!std::filesystem::exists(libraryPath)) {
@@ -236,13 +317,13 @@ namespace Echoion::Host
} }
Api::Result<void> Api::Result<void>
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
{ {
std::unique_lock<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");
} }
auto targetPath = auto targetPath =
@@ -254,13 +335,22 @@ namespace Echoion::Host
std::format("New library not found: {}", targetPath.string())); std::format("New library not found: {}", targetPath.string()));
} }
if (targetPath != currentLibraryPath_) { if (targetPath != currentLibraryPath_) {
return Api::fail(Api::ErrorCode::InvalidArgument, return Api::fail(
"in-process Core reload must use the loaded path; release bundles " Api::ErrorCode::InvalidArgument,
"in-process Core reload must use the loaded path; release "
"bundles "
"with a new path are applied through daemon re-exec"); "with a new path are applied through daemon re-exec");
} }
if (!canCreateHotReloadCopy(targetPath)) {
return Api::fail(
Api::ErrorCode::PermissionDenied,
"in-process Core reload requires a writable library directory; "
"immutable releases are applied through daemon re-exec");
}
hotReloading_ = true; hotReloading_ = true;
Void::Log::info("CoreLoader", "{}", "Starting transactional hot reload..."); Void::Log::info("CoreLoader", "{}",
"Starting transactional hot reload...");
// No callback may execute code from the old shared object after this // No callback may execute code from the old shared object after this
// barrier returns. State capture and dlclose are safe only after event // barrier returns. State capture and dlclose are safe only after event
@@ -289,13 +379,15 @@ namespace Echoion::Host
const auto reloadResult = pluginManager_.reload(pluginName_); const auto reloadResult = pluginManager_.reload(pluginName_);
if (!reloadResult) { if (!reloadResult) {
hotReloading_ = false; hotReloading_ = false;
auto message = std::format( auto message =
"new Core rejected; running Core retained: {}", std::format("new Core rejected; running Core retained: {}",
Void::Plugin::to_string(reloadResult.error())); Void::Plugin::to_string(reloadResult.error()));
if (core_) { if (core_) {
if (auto initialized = core_->initialize(configPath_); !initialized) { if (auto initialized = core_->initialize(configPath_);
message += std::format("; retained Core reactivation failed: {}", !initialized) {
initialized.error().message); message +=
std::format("; retained Core reactivation failed: {}",
initialized.error().message);
} else if (!state.empty()) { } else if (!state.empty()) {
if (auto restored = core_->restoreState(state); !restored) { if (auto restored = core_->restoreState(state); !restored) {
message += std::format( message += std::format(
@@ -320,8 +412,9 @@ namespace Echoion::Host
} }
if (!state.empty()) { if (!state.empty()) {
if (auto restored = core_->restoreState(state); !restored) { if (auto restored = core_->restoreState(state); !restored) {
Void::Log::warn("CoreLoader", "new Core state restore failed: {}", Void::Log::warn("CoreLoader",
restored.error().message); "new Core state restore failed: {}",
restored.error().message);
} }
} }
hotReloading_ = false; hotReloading_ = false;
@@ -360,12 +453,12 @@ namespace Echoion::Host
} }
Api::Result<void> Api::Result<void>
CoreLoader::checkpoint(const std::filesystem::path& destination) CoreLoader::checkpoint(const std::filesystem::path& destination)
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
if (!core_) { if (!core_) {
return Api::fail(Api::ErrorCode::NotInitialized, return Api::fail(Api::ErrorCode::NotInitialized,
"cannot checkpoint without a loaded Core"); "cannot checkpoint without a loaded Core");
} }
const auto state = core_->saveState(); const auto state = core_->saveState();
std::string bytes; std::string bytes;
@@ -379,37 +472,37 @@ namespace Echoion::Host
appendU32(static_cast<uint32_t>(state.timestamp.size())); appendU32(static_cast<uint32_t>(state.timestamp.size()));
bytes.append(state.timestamp); bytes.append(state.timestamp);
bytes.append(reinterpret_cast<const char*>(state.data.data()), bytes.append(reinterpret_cast<const char*>(state.data.data()),
state.data.size()); state.data.size());
if (auto result = Void::FileSystem::atomic_write(destination, bytes); if (auto result = Void::FileSystem::atomic_write(destination, bytes);
!result) { !result) {
return Api::fail(Api::ErrorCode::PluginError, return Api::fail(Api::ErrorCode::PluginError,
result.error().message()); result.error().message());
} }
return {}; return {};
} }
Api::Result<void> Api::Result<void>
CoreLoader::restoreCheckpoint(const std::filesystem::path& source) CoreLoader::restoreCheckpoint(const std::filesystem::path& source)
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
if (!core_) { if (!core_) {
return Api::fail(Api::ErrorCode::NotInitialized, return Api::fail(Api::ErrorCode::NotInitialized,
"cannot restore without a loaded Core"); "cannot restore without a loaded Core");
} }
auto contents = Void::FileSystem::read_file(source); auto contents = Void::FileSystem::read_file(source);
if (!contents) { if (!contents) {
return Api::fail(Api::ErrorCode::NotFound, return Api::fail(Api::ErrorCode::NotFound,
contents.error().message()); contents.error().message());
} }
if (contents->size() < 8) { if (contents->size() < 8) {
return Api::fail(Api::ErrorCode::ParseError, return Api::fail(Api::ErrorCode::ParseError,
"checkpoint header is truncated"); "checkpoint header is truncated");
} }
auto readU32 = [&contents](std::size_t offset) { auto readU32 = [&contents](std::size_t offset) {
uint32_t value = 0; uint32_t value = 0;
for (std::size_t index = 0; index < 4; ++index) { for (std::size_t index = 0; index < 4; ++index) {
value = (value << 8U) | value = (value << 8U) |
static_cast<unsigned char>((*contents)[offset + index]); static_cast<unsigned char>((*contents)[offset + index]);
} }
return value; return value;
}; };
@@ -418,12 +511,13 @@ namespace Echoion::Host
const auto timestampSize = readU32(4); const auto timestampSize = readU32(4);
if (timestampSize > contents->size() - 8) { if (timestampSize > contents->size() - 8) {
return Api::fail(Api::ErrorCode::ParseError, return Api::fail(Api::ErrorCode::ParseError,
"checkpoint timestamp is truncated"); "checkpoint timestamp is truncated");
} }
state.timestamp = contents->substr(8, timestampSize); state.timestamp = contents->substr(8, timestampSize);
const auto dataOffset = 8 + timestampSize; const auto dataOffset = 8 + timestampSize;
state.data.assign(contents->begin() + state.data.assign(contents->begin() +
static_cast<std::ptrdiff_t>(dataOffset), contents->end()); static_cast<std::ptrdiff_t>(dataOffset),
contents->end());
return core_->restoreState(state); return core_->restoreState(state);
} }
@@ -432,9 +526,10 @@ namespace Echoion::Host
{ {
auto result = pluginManager_.load(path); auto result = pluginManager_.load(path);
if (!result) { if (!result) {
return Api::fail(Api::ErrorCode::PluginError, return Api::fail(
Api::ErrorCode::PluginError,
std::format("failed to load Core plugin: {}", std::format("failed to load Core plugin: {}",
Void::Plugin::to_string(result.error()))); Void::Plugin::to_string(result.error())));
} }
pluginName_ = std::move(*result); pluginName_ = std::move(*result);
if (auto refreshed = refreshCoreHandle(); !refreshed) { if (auto refreshed = refreshCoreHandle(); !refreshed) {
@@ -453,11 +548,12 @@ namespace Echoion::Host
pluginManager_.acquire(pluginName_)); pluginManager_.acquire(pluginName_));
if (!*pin) { if (!*pin) {
return Api::fail(Api::ErrorCode::PluginError, return Api::fail(Api::ErrorCode::PluginError,
"Core plugin disappeared from the registry"); "Core plugin disappeared from the registry");
} }
auto* interface = dynamic_cast<Api::ICoreInterface*>(pin->get()); auto* interface = dynamic_cast<Api::ICoreInterface*>(pin->get());
if (interface == nullptr) { if (interface == nullptr) {
return Api::fail(Api::ErrorCode::InvalidArgument, return Api::fail(
Api::ErrorCode::InvalidArgument,
"Void plugin does not implement Echoion Core interface"); "Void plugin does not implement Echoion Core interface");
} }
core_ = Api::CoreInterfacePtr{std::move(pin), interface}; core_ = Api::CoreInterfacePtr{std::move(pin), interface};
@@ -475,9 +571,10 @@ namespace Echoion::Host
core_.reset(); core_.reset();
if (!pluginName_.empty()) { if (!pluginName_.empty()) {
if (auto result = pluginManager_.unload(pluginName_); !result) { if (auto result = pluginManager_.unload(pluginName_); !result) {
return Api::fail(Api::ErrorCode::PluginError, return Api::fail(
Api::ErrorCode::PluginError,
std::format("failed to unload Core plugin: {}", std::format("failed to unload Core plugin: {}",
Void::Plugin::to_string(result.error()))); Void::Plugin::to_string(result.error())));
} }
pluginName_.clear(); pluginName_.clear();
} }