Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-25 23:44:48 +03:00
1 parent 11850b1a8d
commit 46ff4068cf
9 files changed
+4657 -96

No files matched your search

+78 -4
View File
@@ -19,6 +19,44 @@ pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus)
find_package(Threads REQUIRED)
find_package(OpenSSL REQUIRED)
set(ECHOION_UPDATE_FEED_URL "" CACHE STRING
"Build-time default URL for the official signed update feed")
set(ECHOION_UPDATE_PUBLIC_KEYS_JSON "[]" CACHE STRING
"Build-time Ed25519 trust anchors as [{\"id\":...,\"ed25519\":...}]")
set(ECHOION_RUNTIME_VERSION "${PROJECT_VERSION}" CACHE STRING
"Canonical SemVer reported when no installed release manifest is present")
string(LENGTH "${ECHOION_RUNTIME_VERSION}" _runtime_version_length)
if(_runtime_version_length GREATER 64 OR
NOT ECHOION_RUNTIME_VERSION MATCHES
"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$")
message(FATAL_ERROR
"ECHOION_RUNTIME_VERSION must be canonical SemVer without build metadata")
endif()
if(ECHOION_RUNTIME_VERSION MATCHES "-([^+]+)$")
set(_runtime_prerelease "${CMAKE_MATCH_1}")
string(REPLACE "." ";" _runtime_prerelease_identifiers
"${_runtime_prerelease}")
foreach(_identifier IN LISTS _runtime_prerelease_identifiers)
if(_identifier MATCHES "^0[0-9]+$")
message(FATAL_ERROR
"ECHOION_RUNTIME_VERSION has a non-canonical numeric prerelease identifier")
endif()
endforeach()
endif()
foreach(_update_default IN ITEMS
ECHOION_UPDATE_FEED_URL ECHOION_UPDATE_PUBLIC_KEYS_JSON
ECHOION_RUNTIME_VERSION)
if("${${_update_default}}" MATCHES "\\)ECHOION_UPDATE\\\"")
message(FATAL_ERROR "${_update_default} contains the generated-header delimiter")
endif()
endforeach()
set(ECHOION_TOOLCHAIN_ABI
"${CMAKE_CXX_COMPILER_ID}-${CMAKE_CXX_COMPILER_VERSION}-${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}")
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/standalone/UpdateBuildDefaults.hpp.in"
"${CMAKE_CURRENT_BINARY_DIR}/generated/echoion/standalone/UpdateBuildDefaults.hpp"
@ONLY)
add_executable(EchoionStandalone
src/main.cpp
src/StandaloneClientInterface.cpp
@@ -27,10 +65,12 @@ add_executable(EchoionStandalone
src/ReleaseManifest.cpp
src/RuntimePaths.cpp
src/EventCallbackGate.cpp
src/UpdateService.cpp
)
target_include_directories(EchoionStandalone PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include"
"${CMAKE_CURRENT_BINARY_DIR}/generated"
)
target_link_libraries(EchoionStandalone PRIVATE
@@ -47,6 +87,11 @@ target_link_libraries(EchoionStandalone PRIVATE
Void::Log
Void::System
Void::Stacktrace
Void::Archive
Void::Crypto
Void::Net
Void::Plugin
Void::Update
Threads::Threads
PkgConfig::SWRESAMPLE
PkgConfig::OPUS
@@ -121,8 +166,37 @@ if(BUILD_TESTS)
add_test(NAME echoion_event_callback_gate_tests
COMMAND echoion_event_callback_gate_tests)
add_test(NAME echoion_stage_release_tests
COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_stage_release.sh"
"${CMAKE_SOURCE_DIR}/scripts/stage-release.sh"
$<TARGET_FILE:EchoionStandalone>)
add_executable(echoion_update_service_tests
tests/test_update_service.cpp
src/UpdateService.cpp
)
target_include_directories(echoion_update_service_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include"
)
target_compile_features(echoion_update_service_tests PRIVATE cxx_std_26)
target_link_libraries(echoion_update_service_tests PRIVATE
Echoion::ApiBase Echoion::ApiConfig
Void::Archive Void::Crypto Void::Data Void::Log Void::Net Void::Plugin
Void::System Void::Update Threads::Threads)
add_test(NAME echoion_update_service_tests
COMMAND echoion_update_service_tests)
add_executable(echoion_update_build_defaults_tests
tests/test_update_build_defaults.cpp)
target_include_directories(echoion_update_build_defaults_tests PRIVATE
"${CMAKE_CURRENT_BINARY_DIR}/generated")
target_compile_features(echoion_update_build_defaults_tests PRIVATE
cxx_std_20)
target_compile_definitions(echoion_update_build_defaults_tests PRIVATE
"ECHOION_EXPECTED_RUNTIME_VERSION=\"${ECHOION_RUNTIME_VERSION}\"")
add_test(NAME echoion_update_build_defaults_tests
COMMAND echoion_update_build_defaults_tests)
if(TARGET EchoionUpdater)
add_test(NAME echoion_stage_release_tests
COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_stage_release.sh"
"${CMAKE_SOURCE_DIR}/scripts/stage-release.sh"
$<TARGET_FILE:EchoionUpdater>
"${CMAKE_SOURCE_DIR}/packaging/service")
endif()
endif()
@@ -10,6 +10,7 @@
#include <Void/TeamSpeak/TeamSpeak.hpp>
#include <atomic>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
@@ -124,6 +125,12 @@ namespace Echoion::Standalone
// Events
void registerEventCallback(const Api::EventCallback& cb) override;
void unregisterEventCallback(const Api::EventCallback& cb) override;
[[nodiscard]] Api::Result<std::string>
hostControl(const std::string& method,
const std::string& requestJson) override;
using HostControlHandler = std::function<Api::Result<std::string>(
const std::string&, const std::string&)>;
void setHostControlHandler(HostControlHandler handler);
// Prevent new event dispatches, release registered callbacks and
// wait until every callback already in flight has returned. The
// host must call this before unloading code that owns an event
@@ -157,6 +164,8 @@ namespace Echoion::Standalone
std::map<uint64_t, std::string> avatarPaths_;
std::vector<uint64_t> whisperList_;
std::jthread snapshotThread_;
mutable std::mutex hostControlMutex_;
HostControlHandler hostControlHandler_;
EventCallbackGate eventCallbacks_;
};
@@ -0,0 +1,17 @@
#pragma once
#include <string_view>
namespace Echoion::Standalone::UpdateBuildDefaults
{
inline constexpr std::string_view FeedUrl =
R"ECHOION_UPDATE(@ECHOION_UPDATE_FEED_URL@)ECHOION_UPDATE";
inline constexpr std::string_view PublicKeysJson =
R"ECHOION_UPDATE(@ECHOION_UPDATE_PUBLIC_KEYS_JSON@)ECHOION_UPDATE";
inline constexpr std::string_view RuntimeVersion =
R"ECHOION_UPDATE(@ECHOION_RUNTIME_VERSION@)ECHOION_UPDATE";
inline constexpr std::string_view ApiVersion =
R"ECHOION_UPDATE(@PROJECT_VERSION@)ECHOION_UPDATE";
inline constexpr std::string_view ToolchainAbi =
R"ECHOION_UPDATE(@ECHOION_TOOLCHAIN_ABI@)ECHOION_UPDATE";
}
@@ -0,0 +1,83 @@
#pragma once
#include <Types.hpp>
#include <filesystem>
#include <functional>
#include <memory>
#include <string>
namespace Echoion::Standalone
{
// Roll back any uncommitted managed-plugin activation before Core loads and
// discovers plugin `current` links. This must run before PluginHost
// startup.
[[nodiscard]] Api::Result<void> reconcileManagedPluginUpdates(
const std::filesystem::path& stateDirectory);
// Host-owned update coordinator. Core only forwards authenticated RPC
// requests across the append-only host interface; all trust, download,
// staging and activation decisions remain in the long-lived daemon.
class UpdateService final
{
public:
struct Options {
std::filesystem::path configPath;
std::filesystem::path stateDirectory;
std::filesystem::path installRoot;
std::filesystem::path runningExecutable;
std::filesystem::path currentCore;
std::filesystem::path releaseManifestPath;
std::string officialFeedUrl;
std::string officialPublicKeysJson = "[]";
std::string runtimeVersion;
std::string apiVersion;
std::string toolchainAbi;
// Trusted administrator drop directory for file://
// feeds/artifacts. Empty selects stateDirectory /
// "incoming".
std::filesystem::path incomingDirectory;
};
struct Hooks {
std::function<Api::Result<void>(
const std::filesystem::path&)>
replaceCore;
std::function<Api::Result<std::string>(const std::string&)>
managePlugins;
std::function<Api::Result<std::string>(const std::string&)>
manageRuntime;
std::function<bool()> playbackActive;
std::function<std::string()> coreVersion;
};
UpdateService(Options options, Hooks hooks);
~UpdateService();
UpdateService(const UpdateService&) = delete;
UpdateService& operator=(const UpdateService&) = delete;
UpdateService(UpdateService&&) noexcept;
UpdateService& operator=(UpdateService&&) noexcept;
[[nodiscard]] Api::Result<void> start();
void stop() noexcept;
// Execute host mutations which must not run on the Core RPC stack.
// The daemon calls this from its polling loop after an RPC has
// returned.
void processPendingHostActions();
// Methods are the internal `updates.*` names forwarded by Core.
// Requests and successful responses are JSON documents matching the
// web contract.
[[nodiscard]] Api::Result<std::string>
handle(const std::string& method,
const std::string& requestJson);
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace Echoion::Standalone
+23
View File
@@ -1225,6 +1225,29 @@ namespace Echoion::Standalone
quiesceEventCallbacks();
}
Api::Result<std::string>
StandaloneClientInterface::hostControl(const std::string& method,
const std::string& requestJson)
{
HostControlHandler handler;
{
std::lock_guard lock(hostControlMutex_);
handler = hostControlHandler_;
}
if (!handler) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"host control plane is not ready");
}
return handler(method, requestJson);
}
void StandaloneClientInterface::setHostControlHandler(
HostControlHandler handler)
{
std::lock_guard lock(hostControlMutex_);
hostControlHandler_ = std::move(handler);
}
void StandaloneClientInterface::quiesceEventCallbacks()
{
eventCallbacks_.quiesce();
File diff suppressed because it is too large. Load diff
+514 -85
View File
@@ -5,48 +5,47 @@
#include "echoion/standalone/ReleaseManifest.hpp"
#include "echoion/standalone/RuntimePaths.hpp"
#include "echoion/standalone/StandaloneClientInterface.hpp"
#include "echoion/standalone/UpdateBuildDefaults.hpp"
#include "echoion/standalone/UpdateService.hpp"
#include <CoreInterface.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Stacktrace/Stacktrace.hpp>
#include <Void/System/FileWatcher.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Process.hpp>
#include <Void/System/SignalWatcher.hpp>
#include <Void/TeamSpeak/Identity.hpp>
#include <Void/Update/Update.hpp>
#include <algorithm>
#include <array>
#include <atomic>
#include <condition_variable>
#include <csignal>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <filesystem>
#include <iostream>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <vector>
#ifndef _WIN32
#include <unistd.h>
#endif
namespace
{
std::atomic<bool> g_stop{false};
std::atomic<bool> g_updateRequested{false};
std::condition_variable g_cv;
std::mutex g_mu;
void onSignal(int)
{
g_stop = true;
g_cv.notify_all();
}
void requestUpdate()
{
g_updateRequested = true;
g_cv.notify_all();
}
void requestUpdate() { g_updateRequested = true; }
std::optional<std::string_view> argumentValue(int argc, char** argv,
std::string_view name)
@@ -101,6 +100,255 @@ namespace
return (error ? path : absolute).lexically_normal();
}
struct RuntimeHandoff {
std::filesystem::path manifestPath;
std::string state;
std::string version;
std::string previousVersion;
std::uint32_t retainHealthyVersions = 2;
};
[[nodiscard]] std::optional<std::uint32_t>
retainHealthyVersions(const Void::Json::Value& object)
{
const auto* value = object.find("retainHealthyVersions");
if (value == nullptr) {
return 2U;
}
if (!value->is_number()) {
return std::nullopt;
}
const double number = value->as_number();
if (!std::isfinite(number) || std::trunc(number) != number ||
number < 1.0 || number > 10.0) {
return std::nullopt;
}
return static_cast<std::uint32_t>(number);
}
[[nodiscard]] bool pathWithin(const std::filesystem::path& path,
const std::filesystem::path& root)
{
auto pathIterator = path.begin();
for (auto rootIterator = root.begin(); rootIterator != root.end();
++rootIterator, ++pathIterator) {
if (pathIterator == path.end() || *pathIterator != *rootIterator) {
return false;
}
}
return true;
}
std::optional<RuntimeHandoff>
readRuntimeHandoff(const std::filesystem::path& handoff,
const std::filesystem::path& installationPrefix)
{
auto contents = Void::FileSystem::read_file(handoff);
if (!contents) {
return std::nullopt;
}
auto parsed = Void::Json::parse(*contents);
if (!parsed || !parsed->is_object()) {
return std::nullopt;
}
const auto stringField = [&parsed](std::string_view name) {
const auto* value = parsed->find(name);
return value && value->is_string() ? value->as_string()
: std::string{};
};
const auto manifestValue = stringField("manifestPath");
const auto state = stringField("state");
const auto version = stringField("version");
const auto retention = retainHealthyVersions(*parsed);
if (manifestValue.empty() || state.empty() || version.empty() ||
!retention.has_value()) {
return std::nullopt;
}
const std::filesystem::path relativeManifest{manifestValue};
if (relativeManifest.is_absolute()) {
return std::nullopt;
}
std::error_code error;
const auto manifest = std::filesystem::canonical(
installationPrefix / relativeManifest, error);
if (error) {
return std::nullopt;
}
const auto versions =
std::filesystem::canonical(installationPrefix / "versions", error);
if (error || !std::filesystem::is_regular_file(manifest)) {
return std::nullopt;
}
if (!pathWithin(manifest, versions)) {
return std::nullopt;
}
return RuntimeHandoff{.manifestPath = manifest,
.state = state,
.version = version,
.previousVersion = stringField("previousVersion"),
.retainHealthyVersions = *retention};
}
[[nodiscard]] std::filesystem::path
installationPrefix(const std::filesystem::path& installRoot)
{
std::error_code error;
if (installRoot.filename() == "current" &&
std::filesystem::is_symlink(
std::filesystem::symlink_status(installRoot, error))) {
return installRoot.parent_path();
}
return installRoot;
}
[[nodiscard]] std::filesystem::path
updaterIncomingDirectory(const std::filesystem::path& root,
const std::filesystem::path& stateDirectory)
{
if (const auto configured = environmentPath("ECHOION_INCOMING_DIR")) {
return absolutePath(*configured);
}
if (auto record =
Void::FileSystem::read_file(root / ".echoion-install")) {
constexpr std::string_view prefix{"incoming_dir="};
std::string_view contents{*record};
while (!contents.empty()) {
const auto end = contents.find('\n');
const auto line = contents.substr(0, end);
if (line.starts_with(prefix) && line.size() > prefix.size()) {
std::filesystem::path path{line.substr(prefix.size())};
return absolutePath(path.is_absolute() ? path
: root / path);
}
if (end == std::string_view::npos) {
break;
}
contents.remove_prefix(end + 1);
}
}
return stateDirectory / "incoming";
}
[[nodiscard]] std::optional<Echoion::Standalone::ReleaseManifest>
runningReleaseManifest(const std::filesystem::path& executable,
const std::filesystem::path& installRoot)
{
const std::array candidates{executable.parent_path().parent_path() /
"manifest.json",
installRoot / "manifest.json"};
for (const auto& candidate : candidates) {
if (auto manifest =
Echoion::Standalone::ReleaseManifest::load(candidate)) {
return std::move(*manifest);
}
}
return std::nullopt;
}
[[nodiscard]] std::filesystem::path
reconcileManagedCore(const std::filesystem::path& stateDirectory,
const std::filesystem::path& fallback)
{
Void::Update::VersionStore store(stateDirectory / "updates" /
"components" / "core");
if (auto initialized = store.initialize(); !initialized) {
Void::Log::warn("main", "Cannot initialize managed Core store: {}",
initialized.error().message());
return fallback;
}
if (auto reconciled = store.reconcile(); !reconciled) {
Void::Log::warn("main", "Cannot reconcile managed Core store: {}",
reconciled.error().message());
return fallback;
}
auto current = store.currentVersion();
if (!current || !*current) {
return fallback;
}
const auto managed = store.versionPath(**current) / fallback.filename();
return std::filesystem::is_regular_file(managed) ? managed : fallback;
}
[[nodiscard]] Echoion::Api::Result<std::string>
invokeRuntimeHelper(const std::filesystem::path& helper,
const std::filesystem::path& root,
std::string_view operationJson)
{
auto operation = Void::Json::parse(operationJson);
if (!operation || !operation->is_object()) {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::ParseError,
"runtime update operation must be a JSON object");
}
const auto field = [&operation](std::string_view name) {
const auto* value = operation->find(name);
return value && value->is_string() ? value->as_string()
: std::string{};
};
const auto action = field("action");
const auto version = field("version");
const auto retention = retainHealthyVersions(*operation);
if (!retention.has_value()) {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::InvalidArgument,
"retainHealthyVersions must be an integer from 1 to 10");
}
std::string command;
std::vector<std::string> options;
if (action == "activate") {
command = "activate-runtime";
options = {"--staging", field("stagingId"),
"--version", version,
"--manifest-sha256", field("manifestSha256")};
} else if (action == "rollback") {
command = "rollback-runtime";
options = {"--version", version};
} else if (action == "commit") {
command = "commit-runtime";
options = {"--version", version};
} else {
return Echoion::Api::fail(Echoion::Api::ErrorCode::InvalidArgument,
"unknown runtime update operation");
}
if (version.empty() ||
std::ranges::any_of(
options, [](const auto& value) { return value.empty(); })) {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::InvalidArgument,
"runtime update operation is missing required fields");
}
options.insert(options.end(), {"--retain", std::to_string(*retention)});
bool direct = false;
#ifndef _WIN32
direct = ::access((root / "versions").c_str(), W_OK) == 0;
#endif
std::vector<std::string> arguments{"--root", root.string()};
if (!direct) {
arguments.insert(arguments.end(), {"request", command});
} else {
arguments.push_back(command);
}
arguments.insert(arguments.end(), options.begin(), options.end());
if (!direct) {
arguments.insert(arguments.end(), {"--origin", "daemon"});
}
auto result =
Void::Process::run(helper, arguments, {}, std::chrono::seconds{30});
if (!result) {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::ServiceUnavailable,
result.error().message());
}
if (result->exit_code != 0) {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::ServiceUnavailable,
result->err.empty() ? "runtime update helper failed"
: result->err);
}
return result->out.empty() ? std::string{"{}"} : std::move(result->out);
}
std::filesystem::path configDir()
{
if (const char* x = std::getenv("XDG_CONFIG_HOME")) {
@@ -298,6 +546,7 @@ int main(int argc, char** argv)
}
const auto installRoot = Echoion::Standalone::deriveInstallRoot(
*runningExecutable, environmentPath("ECHOION_HOME"));
const auto updateRoot = installationPrefix(installRoot);
if (hasArgument(argc, argv, "--validate-install")) {
const auto requestedRoot =
optionalArgumentPath(argc, argv, "--validate-install");
@@ -334,6 +583,13 @@ int main(int argc, char** argv)
environmentState.has_value())) {
return 2;
}
auto signalWatcherResult = Void::Process::SignalWatcher::create();
if (!signalWatcherResult) {
std::cerr << "Cannot install signal watcher: "
<< signalWatcherResult.error().message() << '\n';
return 2;
}
auto signalWatcher = std::move(*signalWatcherResult);
recordInterruptedRelease(stateDirectory);
const auto identityPath = absolutePath(std::filesystem::path(envOr(
@@ -348,9 +604,26 @@ int main(int argc, char** argv)
requestedRestore ? std::optional{absolutePath(*requestedRestore)}
: std::nullopt;
const auto requestedManifest = environmentPath("ECHOION_RELEASE_MANIFEST");
const std::optional<std::filesystem::path> releaseManifestPath =
requestedManifest ? std::optional{absolutePath(*requestedManifest)}
: std::nullopt;
const auto activationHandoff =
stateDirectory / "updates" / "activated-runtime.json";
const auto releaseTriggerPath = requestedManifest
? absolutePath(*requestedManifest)
: activationHandoff;
const bool releaseTriggerIsHandoff = !requestedManifest.has_value();
const auto runningManifest =
runningReleaseManifest(*runningExecutable, installRoot);
const auto runtimeVersion =
runningManifest
? runningManifest->version
: std::string{
Echoion::Standalone::UpdateBuildDefaults::RuntimeVersion};
if (auto recovered =
Echoion::Standalone::reconcileManagedPluginUpdates(stateDirectory);
!recovered) {
Void::Log::error("main", "cannot recover managed plugin updates: {}",
recovered.error().message);
return 1;
}
Echoion::Standalone::StandaloneSettings settings;
settings.identityPath = identityPath.string();
@@ -371,8 +644,17 @@ int main(int argc, char** argv)
loader.setConfigPath(cfgPath);
const auto executableDirectory = runningExecutable->parent_path();
const auto corePathResolved = Echoion::Standalone::resolveCorePath(
installRoot, executableDirectory, environmentPath("ECHOION_CORE_PATH"));
const auto configuredCoreOverride = environmentPath("ECHOION_CORE_PATH");
const auto configuredCorePath = Echoion::Standalone::resolveCorePath(
installRoot, executableDirectory, configuredCoreOverride);
const bool customCoreOverride =
configuredCoreOverride &&
absolutePath(*configuredCoreOverride) !=
absolutePath(installRoot / "lib" / "Echoion.ts");
const auto corePathResolved =
customCoreOverride
? configuredCorePath
: reconcileManagedCore(stateDirectory, configuredCorePath);
if (const auto workingDirectory =
Echoion::Standalone::runtimeWorkingDirectory(installRoot,
executableDirectory)) {
@@ -423,21 +705,95 @@ int main(int argc, char** argv)
}
});
core->triggerAutoConnect();
std::unique_ptr<Void::FileSystem::FileWatcher> releaseWatcher;
if (releaseManifestPath) {
releaseWatcher = std::make_unique<Void::FileSystem::FileWatcher>();
releaseWatcher->watch(
*releaseManifestPath,
[](const Void::FileSystem::FileWatcher::Event& event) {
if (event.exists) {
requestUpdate();
const auto updaterExecutable =
runningExecutable->parent_path() / "echoion-updater";
auto updateService = std::make_unique<Echoion::Standalone::UpdateService>(
Echoion::Standalone::UpdateService::Options{
.configPath = cfgPath,
.stateDirectory = stateDirectory,
.installRoot = updateRoot,
.runningExecutable = *runningExecutable,
.currentCore = corePathResolved,
.releaseManifestPath = runningManifest
? runningManifest->root / "manifest.json"
: std::filesystem::path{},
.officialFeedUrl =
std::string{Echoion::Standalone::UpdateBuildDefaults::FeedUrl},
.officialPublicKeysJson =
std::string{
Echoion::Standalone::UpdateBuildDefaults::PublicKeysJson},
.runtimeVersion = runtimeVersion,
.apiVersion = Echoion::Api::VERSION_STRING,
.toolchainAbi =
std::string{
Echoion::Standalone::UpdateBuildDefaults::ToolchainAbi},
.incomingDirectory =
updaterIncomingDirectory(updateRoot, stateDirectory)},
Echoion::Standalone::UpdateService::Hooks{
.replaceCore =
[&loader](const std::filesystem::path& path) {
return loader.hotReload(path);
},
.managePlugins = [&loader](const std::string& request)
-> Echoion::Api::Result<std::string> {
if (auto loadedCore = loader.getCore()) {
return loadedCore->managePluginsJson(request);
}
return Echoion::Api::fail(
Echoion::Api::ErrorCode::ServiceUnavailable,
"Core is not available");
},
.manageRuntime =
[updaterExecutable, updateRoot](const std::string& request) {
return invokeRuntimeHelper(updaterExecutable, updateRoot,
request);
},
.playbackActive =
[&loader] {
auto loadedCore = loader.getCore();
if (!loadedCore) {
return false;
}
auto playback = loadedCore->getPlaybackSummary();
return playback && playback->isPlaying &&
playback->currentTrack.has_value();
},
.coreVersion =
[&loader] {
if (auto loadedCore = loader.getCore()) {
return loadedCore->getVersion();
}
return std::string{};
}});
if (auto started = updateService->start(); !started) {
Void::Log::error("main", "Updater disabled: {}",
started.error().message);
updateService.reset();
} else {
interface->setHostControlHandler(
[service = updateService.get()](const std::string& method,
const std::string& request) {
return service->handle(method, request);
});
Void::Log::info("main", "Watching release manifest {}",
releaseManifestPath->string());
} else if (!std::filesystem::is_regular_file(installRoot /
"manifest.json")) {
}
core->triggerAutoConnect();
core.reset();
auto releaseWatcher = std::make_unique<Void::FileSystem::FileWatcher>();
releaseWatcher->watch(
releaseTriggerPath,
[](const Void::FileSystem::FileWatcher::Event& event) {
if (event.exists) {
requestUpdate();
}
});
Void::Log::info("main", "Watching runtime update trigger {}",
releaseTriggerPath.string());
if (std::filesystem::is_regular_file(releaseTriggerPath)) {
requestUpdate();
}
if (!std::filesystem::is_regular_file(installRoot / "manifest.json")) {
// Compatibility mode for development. Production release bundles use
// transactional daemon re-exec instead of replacing Core in isolation.
loader.enableAutoReload();
@@ -447,72 +803,143 @@ int main(int argc, char** argv)
"Core auto-reload is disabled for an installed release payload");
}
std::signal(SIGINT, onSignal);
std::signal(SIGTERM, onSignal);
Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop.");
std::optional<std::string> healthVersion;
if (const char* version = std::getenv("ECHOION_REEXEC_VERSION")) {
std::ignore = Void::FileSystem::atomic_write(
stateDirectory / "release-health", version);
std::ignore = Void::FileSystem::remove_path(stateDirectory /
"release-transaction");
std::ignore =
Void::FileSystem::remove_path(stateDirectory / "failed-release");
::unsetenv("ECHOION_REEXEC_VERSION");
Void::Log::info("main", "Release {} passed startup health check",
version);
healthVersion = version;
Void::Log::info("main", "Release {} entered its 30 second health check",
*healthVersion);
}
auto healthDeadline =
std::chrono::steady_clock::now() + std::chrono::seconds{30};
std::optional<Echoion::Standalone::ReleaseManifest> pendingRelease;
std::filesystem::path checkpointPath;
while (!g_stop.load() && !pendingRelease) {
{
std::unique_lock<std::mutex> lock(g_mu);
g_cv.wait(lock,
[] { return g_stop.load() || g_updateRequested.load(); });
bool stopRequested = false;
while (!stopRequested && !pendingRelease) {
if (updateService) {
updateService->processPendingHostActions();
}
if (g_stop.load() || !releaseManifestPath) {
break;
if (healthVersion &&
std::chrono::steady_clock::now() >= healthDeadline) {
bool committed = true;
const auto handoff =
readRuntimeHandoff(activationHandoff, updateRoot);
if (handoff && handoff->state == "pending" &&
handoff->version == *healthVersion) {
Void::Json::Value operation = Void::Json::object();
operation.as_object().emplace_back("action",
Void::Json::Value{"commit"});
operation.as_object().emplace_back(
"version", Void::Json::Value{*healthVersion});
operation.as_object().emplace_back(
"retainHealthyVersions",
Void::Json::Value{static_cast<long long>(
handoff->retainHealthyVersions)});
auto result =
invokeRuntimeHelper(updaterExecutable, updateRoot,
Void::Json::serialize(operation));
if (!result) {
committed = false;
Void::Log::error("main",
"Cannot confirm runtime {} health: {}",
*healthVersion, result.error().message);
}
}
if (committed) {
std::ignore = Void::FileSystem::atomic_write(
stateDirectory / "release-health", *healthVersion);
std::ignore = Void::FileSystem::remove_path(
stateDirectory / "release-transaction");
std::ignore = Void::FileSystem::remove_path(stateDirectory /
"failed-release");
Void::Log::info("main", "Release {} passed its health check",
*healthVersion);
healthVersion.reset();
::unsetenv("ECHOION_REEXEC_VERSION");
} else {
healthDeadline =
std::chrono::steady_clock::now() + std::chrono::seconds{5};
}
}
g_updateRequested = false;
auto manifest =
Echoion::Standalone::ReleaseManifest::load(*releaseManifestPath);
if (!manifest) {
Void::Log::error("main", "release rejected: {}",
manifest.error().message);
if (g_updateRequested.exchange(false)) {
auto manifestPath = releaseTriggerPath;
if (releaseTriggerIsHandoff) {
auto handoff =
readRuntimeHandoff(releaseTriggerPath, updateRoot);
if (!handoff) {
Void::Log::error("main",
"runtime activation handoff is invalid");
continue;
}
if (handoff->version == runtimeVersion) {
continue;
}
manifestPath = handoff->manifestPath;
}
auto manifest =
Echoion::Standalone::ReleaseManifest::load(manifestPath);
if (!manifest) {
Void::Log::error("main", "release rejected: {}",
manifest.error().message);
continue;
}
if (manifest->version == runtimeVersion) {
continue;
}
if (auto failed = Void::FileSystem::read_file(stateDirectory /
"failed-release");
failed && *failed == manifest->version) {
Void::Log::error(
"main",
"Release {} was previously rolled back; publish a new "
"version to retry",
manifest->version);
continue;
}
auto validation = Void::Process::run(
*runningExecutable,
{"--validate-release", manifestPath.string()}, {},
std::chrono::seconds{30});
if (!validation || validation->exit_code != 0) {
Void::Log::error("main", "release validation failed: {}",
validation ? validation->err
: validation.error().message());
continue;
}
checkpointPath = stateDirectory / "restart-state.bin";
if (auto checkpoint = loader.checkpoint(checkpointPath);
!checkpoint) {
Void::Log::error("main", "release checkpoint failed: {}",
checkpoint.error().message);
continue;
}
pendingRelease = std::move(*manifest);
continue;
}
if (auto failed =
Void::FileSystem::read_file(stateDirectory / "failed-release");
failed && *failed == manifest->version) {
Void::Log::error("main",
"Release {} was previously rolled back; publish a "
"new version to retry",
manifest->version);
continue;
auto observedSignal =
signalWatcher.wait(std::chrono::milliseconds{250});
if (!observedSignal) {
Void::Log::error("main", "signal watcher failed: {}",
observedSignal.error().message());
stopRequested = true;
} else if (observedSignal->has_value()) {
stopRequested = true;
}
auto validation = Void::Process::run(
*runningExecutable,
{"--validate-release", releaseManifestPath->string()}, {},
std::chrono::seconds{30});
if (!validation || validation->exit_code != 0) {
Void::Log::error("main", "release validation failed: {}",
validation ? validation->err
: validation.error().message());
continue;
}
checkpointPath = stateDirectory / "restart-state.bin";
if (auto checkpoint = loader.checkpoint(checkpointPath); !checkpoint) {
Void::Log::error("main", "release checkpoint failed: {}",
checkpoint.error().message);
continue;
}
pendingRelease = std::move(*manifest);
}
releaseWatcher.reset();
Void::Log::info("main", "{}",
pendingRelease ? "Applying validated release..."
: "Shutting down...");
interface->setHostControlHandler({});
if (updateService) {
updateService->stop();
}
updateService.reset();
loader.disableAutoReload();
(void)interface->disconnectFromServer();
interface->quiesceEventCallbacks();
@@ -529,7 +956,9 @@ int main(int argc, char** argv)
}
const auto pendingRoot =
Echoion::Standalone::deriveInstallRoot(pendingRelease->executable);
const auto pendingRootString = pendingRoot.string();
const auto pendingHome =
releaseTriggerIsHandoff ? updateRoot / "current" : pendingRoot;
const auto pendingRootString = pendingHome.string();
const auto pendingCoreString = pendingRelease->core.string();
if (::setenv("ECHOION_HOME", pendingRootString.c_str(), 1) != 0 ||
::setenv("ECHOION_CORE_PATH", pendingCoreString.c_str(), 1) != 0 ||
+21 -7
View File
@@ -2,8 +2,10 @@
set -euo pipefail
stage_script=$1
validator=$2
updater=$2
service_templates=$3
generator=$(dirname -- "$stage_script")/generate-release-manifest.py
manifest_validator=$(dirname -- "$stage_script")/validate-release-manifest.py
root=$(mktemp -d)
trap 'rm -rf -- "$root"' EXIT
@@ -12,31 +14,43 @@ mkdir -p -- \
"$bundle/bin" \
"$bundle/lib" \
"$bundle/service" \
"$bundle/share/echoion/tools" \
"$bundle/share/echoion/web"
printf '#!/bin/sh\nexit 0\n' > "$bundle/bin/echoiond"
printf '#!/bin/sh\necho "echoiond must not run during release staging" >&2\nexit 97\n' \
> "$bundle/bin/echoiond"
chmod 0755 "$bundle/bin/echoiond"
install -m 0755 -- "$updater" "$bundle/bin/echoion-updater"
printf 'test core\n' > "$bundle/lib/Echoion.ts"
printf '[Service]\nExecStart=@ECHOION_EXECUTABLE@\n' \
> "$bundle/service/echoion.service.in"
install -m 0644 -- \
"$service_templates/echoion.service.in" \
"$service_templates/echoion-updater.service.in" \
"$service_templates/echoion-updater.timer.in" \
"$bundle/service/"
printf '{"webRoot":"./web"}\n' > "$bundle/share/echoion/config.example.json"
install -m 0755 -- "$manifest_validator" \
"$bundle/share/echoion/tools/validate-release-manifest.py"
printf '<!doctype html>\n' > "$bundle/share/echoion/web/index.html"
ln -s -- Echoion.ts "$bundle/lib/libEchoionCore.so"
python3 "$generator" --root "$bundle" --version 1.2.3
"$validator" --validate-install "$bundle"
python3 "$manifest_validator" --root "$bundle" --version 1.2.3
bash "$stage_script" "$root/releases" 1.2.3 "$bundle"
manifest=$root/releases/pending-release.json
test -x "$root/releases/1.2.3/bin/echoiond"
test -x "$root/releases/1.2.3/bin/echoion-updater"
test -f "$root/releases/1.2.3/lib/Echoion.ts"
test -L "$root/releases/1.2.3/lib/libEchoionCore.so"
grep -q '"version": "1.2.3"' "$manifest"
grep -q '"executable": "1.2.3/bin/echoiond"' "$manifest"
grep -q '"updater": "1.2.3/bin/echoion-updater"' "$manifest"
grep -q '"path": "1.2.3/share/echoion/web/index.html"' "$manifest"
"$validator" --validate-release "$manifest"
python3 "$manifest_validator" --root "$root/releases/1.2.3" --version 1.2.3
printf 'tampered\n' >> "$root/releases/1.2.3/lib/Echoion.ts"
if "$validator" --validate-release "$manifest" >/dev/null 2>&1; then
if python3 "$manifest_validator" --root "$root/releases/1.2.3" --version 1.2.3 \
>/dev/null 2>&1; then
echo "tampered Core artifact was accepted" >&2
exit 1
fi
+691
View File
@@ -0,0 +1,691 @@
#include "echoion/standalone/UpdateService.hpp"
#include <Void/Crypto/Crypto.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Text/Hex.hpp>
#include <Void/Update/Update.hpp>
#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
#include <random>
#include <string>
#include <string_view>
namespace
{
class TemporaryTree
{
public:
TemporaryTree()
{
std::random_device random;
path_ =
std::filesystem::temp_directory_path() /
("echoion-update-service-" +
std::to_string(static_cast<unsigned long long>(random())));
std::filesystem::create_directories(path_);
}
~TemporaryTree()
{
std::error_code error;
std::filesystem::remove_all(path_, error);
}
TemporaryTree(const TemporaryTree&) = delete;
TemporaryTree& operator=(const TemporaryTree&) = delete;
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return path_;
}
private:
std::filesystem::path path_;
};
bool writeFile(const std::filesystem::path& path, std::string_view contents)
{
std::filesystem::create_directories(path.parent_path());
std::ofstream output(path, std::ios::binary);
output.write(contents.data(),
static_cast<std::streamsize>(contents.size()));
return output.good();
}
std::string readFile(const std::filesystem::path& path)
{
std::ifstream input(path, std::ios::binary);
return {std::istreambuf_iterator<char>{input},
std::istreambuf_iterator<char>{}};
}
bool publishHistoricalVersion(const std::filesystem::path& root,
std::string_view versionText,
const std::filesystem::path& filename,
std::string_view contents)
{
const auto version = Void::Semver::parse_strict(versionText);
if (!version) {
return false;
}
Void::Update::VersionStore store(root);
if (auto initialized = store.initialize(); !initialized) {
return false;
}
auto staging = store.prepare(*version);
if (!staging || !writeFile(*staging / filename, contents)) {
return false;
}
if (auto published = store.publish(*version, *staging); !published) {
return false;
}
return store.recordHealthy(*version).has_value();
}
bool activatePublishedVersion(const std::filesystem::path& root,
std::string_view versionText)
{
const auto version = Void::Semver::parse_strict(versionText);
if (!version) {
return false;
}
Void::Update::VersionStore store(root);
if (auto initialized = store.initialize(); !initialized) {
return false;
}
if (auto activated = store.activate(*version); !activated) {
return false;
}
return store.commit().has_value();
}
std::string sha256(std::string_view contents)
{
auto digest = Void::Crypto::sha256(contents);
return digest ? Void::Encoding::Hex::encode(*digest) : std::string{};
}
std::string architecture()
{
#if defined(__x86_64__) || defined(_M_X64)
return "x86_64";
#elif defined(__aarch64__) || defined(_M_ARM64)
return "aarch64";
#elif defined(__i386__) || defined(_M_IX86)
return "x86";
#else
return "unknown";
#endif
}
std::string configDocument(const std::filesystem::path& feed)
{
return R"json({"updates":{"enabled":false,"retainHealthyVersions":1,"sources":{"official":{"url":"file://)json" +
feed.string() +
R"json(","publicKeys":[],"allowUnsigned":true,"bearerTokenEnv":""}},"runtime":{"enabled":false,"source":"official","channel":"stable","autoApply":false},"core":{"enabled":true,"source":"official","channel":"stable","autoApply":false},"plugins":{"enabled":true,"source":"official","channel":"stable","autoApply":false,"managedOnly":true,"overrides":{}}}})json";
}
std::string release(std::string_view component, std::string_view artifactId,
std::string_view version,
const std::filesystem::path& artifact,
std::string_view contents)
{
return std::format(
R"json({{"component":"{}","artifactId":"{}","channel":"stable","version":"{}","cohort":"test","platform":"linux","arch":"{}","url":"file://{}","size":{},"sha256":"{}","packageType":"file","compatibility":{{"versionContracts":{{}},"exactContracts":{{}}}},"releaseManifestSha256":"0000000000000000000000000000000000000000000000000000000000000000"}})json",
component, artifactId, version, architecture(), artifact.string(),
contents.size(), sha256(contents));
}
std::string feedDocument(const std::filesystem::path& coreArtifact,
std::string_view coreContents,
const std::filesystem::path& pluginArtifact,
std::string_view pluginContents,
std::uint64_t sequence = 1)
{
return std::format(
R"json({{"schemaVersion":1,"feedId":"test","sequence":{},"generatedAt":"2026-01-01T00:00:00Z","expiresAt":"2099-01-01T00:00:00Z","releases":[{},{}]}})json",
sequence,
release("core", "", "2.0.0", coreArtifact, coreContents),
release("plugin", "fixture", "4.0.0", pluginArtifact,
pluginContents));
}
const Void::Json::Value*
parseResponse(const Echoion::Api::Result<std::string>& response,
std::optional<Void::Json::Value>& storage)
{
if (!response) {
return nullptr;
}
auto parsed = Void::Json::parse(*response);
if (!parsed) {
return nullptr;
}
storage = std::move(*parsed);
return &*storage;
}
std::string coreCandidateId(const Void::Json::Value& status)
{
const auto* components = status.find("components");
const auto* core = components ? components->find("core") : nullptr;
const auto* candidate = core ? core->find("candidate") : nullptr;
const auto* id = candidate ? candidate->find("id") : nullptr;
return id && id->is_string() ? id->as_string() : std::string{};
}
std::string pluginCandidateId(const Void::Json::Value& status)
{
const auto* plugins = status.find("plugins");
if (!plugins || !plugins->is_array()) {
return {};
}
for (const auto& plugin : plugins->as_array()) {
if (plugin.get_str("id") != "fixture") {
continue;
}
const auto* candidate = plugin.find("candidate");
const auto* id = candidate ? candidate->find("id") : nullptr;
return id && id->is_string() ? id->as_string() : std::string{};
}
return {};
}
std::string componentRollbackVersion(const Void::Json::Value& status,
std::string_view componentId)
{
const auto* components = status.find("components");
const auto* component =
components ? components->find(componentId) : nullptr;
return component ? component->get_str("rollbackVersion")
: std::string{};
}
std::string pluginRollbackVersion(const Void::Json::Value& status,
std::string_view pluginId)
{
const auto* plugins = status.find("plugins");
if (!plugins || !plugins->is_array()) {
return {};
}
for (const auto& plugin : plugins->as_array()) {
if (plugin.get_str("id") == pluginId) {
return plugin.get_str("rollbackVersion");
}
}
return {};
}
std::string confirmationToken(Echoion::Standalone::UpdateService& service,
std::string_view component,
std::string_view pluginId,
std::string_view candidateId,
std::string_view version)
{
const auto request = std::format(
R"json({{"component":"{}","pluginId":"{}","candidateId":"{}","version":"{}","confirmation":"UNSIGNED {}"}})json",
component, pluginId, candidateId, version, version);
auto response = service.handle("updates.confirmUnsigned", request);
if (!response) {
return {};
}
auto parsed = Void::Json::parse(*response);
return parsed ? parsed->get_str("confirmationToken") : std::string{};
}
} // namespace
int main()
{
int failures{};
const auto check = [&failures](bool condition, std::string_view message) {
if (!condition) {
std::cerr << message << '\n';
++failures;
}
};
TemporaryTree tree;
const auto state = tree.path() / "state";
const auto incoming = tree.path() / "incoming";
const auto currentCore = tree.path() / "installed" / "Echoion.ts";
const auto currentPlugin = tree.path() / "installed" / "fixture.so";
const auto installRoot = tree.path() / "runtime";
const auto runningExecutable = installRoot / "bin" / "echoiond";
const auto coreArtifact = incoming / "Echoion-2.0.0.ts";
const auto pluginArtifact = incoming / "fixture-4.0.0.so";
const auto feed = incoming / "feed.json";
const auto config = tree.path() / "config.json";
constexpr std::string_view oldCore = "old-core";
constexpr std::string_view newCore = "new-core";
constexpr std::string_view oldPlugin = "old-plugin";
constexpr std::string_view newPlugin = "new-plugin";
check(writeFile(currentCore, oldCore), "failed to write current Core");
check(writeFile(currentPlugin, oldPlugin),
"failed to write current plugin");
check(writeFile(coreArtifact, newCore), "failed to write Core artifact");
check(writeFile(pluginArtifact, newPlugin),
"failed to write plugin artifact");
check(writeFile(feed,
feedDocument(coreArtifact, newCore, pluginArtifact,
newPlugin, 9)),
"failed to write update feed");
check(writeFile(config, configDocument(feed)), "failed to write config");
check(publishHistoricalVersion(state / "updates" / "components" / "core",
"0.9.0", "Echoion.ts", "historical-core"),
"failed to seed a historical Core version");
check(publishHistoricalVersion(state / "plugins" / ".managed" / "fixture",
"1.0.0", "fixture.so", "oldest-plugin"),
"failed to seed the oldest historical plugin version");
check(publishHistoricalVersion(state / "plugins" / ".managed" / "fixture",
"2.0.0", "fixture.so", "historical-plugin"),
"failed to seed a historical plugin version");
check(publishHistoricalVersion(installRoot, "0.8.0", "bin/echoiond",
"previous-runtime"),
"failed to seed a runtime rollback version");
check(publishHistoricalVersion(installRoot, "0.9.0", "bin/not-echoiond",
"invalid-runtime-rollback"),
"failed to seed a runtime rollback decoy");
check(publishHistoricalVersion(installRoot, "1.0.0", "bin/echoiond",
"current-runtime"),
"failed to seed the current runtime version");
check(activatePublishedVersion(installRoot, "1.0.0"),
"failed to activate the current runtime version");
std::string coreVersion = "1.0.0";
std::string pluginVersion = "3.0.0";
std::filesystem::path activatedCore;
std::filesystem::path activatedPlugin;
int coreReplacements{};
int pluginReplacements{};
bool rejectCore{};
Void::Update::VersionStore pluginStore(state / "plugins" / ".managed" /
"fixture");
const auto makeService = [&] {
return Echoion::Standalone::UpdateService(
Echoion::Standalone::UpdateService::Options{
.configPath = config,
.stateDirectory = state,
.installRoot = installRoot,
.runningExecutable = runningExecutable,
.currentCore = currentCore,
.releaseManifestPath = {},
.officialFeedUrl = {},
.officialPublicKeysJson = "[]",
.runtimeVersion = "1.0.0",
.apiVersion = "1.1.0",
.toolchainAbi = "test",
.incomingDirectory = incoming},
Echoion::Standalone::UpdateService::Hooks{
.replaceCore = [&](const std::filesystem::path& path)
-> Echoion::Api::Result<void> {
++coreReplacements;
if (rejectCore) {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::PluginError,
"rejected by test");
}
activatedCore = path;
coreVersion = path.parent_path().filename().string();
return {};
},
.managePlugins = [&](const std::string& request)
-> Echoion::Api::Result<std::string> {
auto parsed = Void::Json::parse(request);
if (!parsed) {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::ParseError,
"invalid test request");
}
if (parsed->get_str("action") == "status") {
return std::format(
R"json({{"plugins":[{{"id":"fixture","name":"Fixture","version":"{}","path":"{}","managed":true}}]}})json",
pluginVersion, currentPlugin.string());
}
if (parsed->get_str("action") != "replace") {
return Echoion::Api::fail(
Echoion::Api::ErrorCode::InvalidArgument,
"unexpected test plugin action");
}
++pluginReplacements;
activatedPlugin = parsed->get_str("path");
pluginVersion = parsed->get_str("version");
return "{}";
},
.manageRuntime = {},
.playbackActive = [] { return false; },
.coreVersion = [&] { return coreVersion; }});
};
auto service = makeService();
check(service.start().has_value(), "UpdateService did not start");
check(!std::filesystem::exists(
pluginStore.versionPath(*Void::Semver::parse("1.0.0"))),
"managed plugin startup retention did not prune the oldest version");
auto checked = service.handle("updates.check", "{}");
std::optional<Void::Json::Value> checkedJson;
const auto* checkedStatus = parseResponse(checked, checkedJson);
check(checkedStatus != nullptr, "manual update check failed");
const auto coreId = checkedStatus ? coreCandidateId(*checkedStatus) : "";
const auto pluginId =
checkedStatus ? pluginCandidateId(*checkedStatus) : "";
if ((coreId.empty() || pluginId.empty()) && checked) {
std::cerr << "update check response: " << *checked << '\n';
}
check(!coreId.empty(), "Core candidate was not selected");
check(!pluginId.empty(), "plugin candidate was not selected");
check(checkedStatus && !checkedStatus->get_bool("checking", true),
"completed manual check was returned as still running");
auto repeatedCheck = service.handle("updates.check", "{}");
std::optional<Void::Json::Value> repeatedJson;
const auto* repeatedStatus = parseResponse(repeatedCheck, repeatedJson);
check(repeatedStatus && coreCandidateId(*repeatedStatus) == coreId &&
pluginCandidateId(*repeatedStatus) == pluginId,
"an unchanged feed sequence was incorrectly treated as a replay");
const auto replacementFeed = incoming / "replacement-feed.json";
check(writeFile(
replacementFeed,
feedDocument(coreArtifact, newCore, pluginArtifact, newPlugin)),
"failed to write replacement update feed");
auto replacementConfig = Void::Json::parse(configDocument(replacementFeed));
const auto* replacementUpdates =
replacementConfig ? replacementConfig->find("updates") : nullptr;
check(replacementUpdates != nullptr,
"failed to construct replacement updater configuration");
bool replacementSaved = false;
if (replacementUpdates) {
replacementSaved =
service
.handle("updates.setConfig",
std::format(R"({{"config":{}}})",
Void::Json::serialize(*replacementUpdates)))
.has_value();
}
check(replacementSaved, "custom source URL could not be saved");
auto replacementCheck = service.handle("updates.check", "{}");
std::optional<Void::Json::Value> replacementJson;
const auto* replacementStatus =
parseResponse(replacementCheck, replacementJson);
check(replacementStatus && coreCandidateId(*replacementStatus) == coreId &&
pluginCandidateId(*replacementStatus) == pluginId,
"changing a custom source URL inherited the old feed replay floor");
const auto rejectedCoreToken =
confirmationToken(service, "core", "", coreId, "2.0.0");
check(!rejectedCoreToken.empty(), "Core unsigned confirmation failed");
rejectCore = true;
auto rejectedCoreApply = service.handle(
"updates.apply",
std::format(
R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json",
coreId, rejectedCoreToken));
check(rejectedCoreApply.has_value(), "failing Core apply did not queue");
service.processPendingHostActions();
check(coreReplacements == 1,
"failing queued Core replacement did not run exactly once");
auto replayedCoreApply = service.handle(
"updates.apply",
std::format(
R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json",
coreId, rejectedCoreToken));
check(!replayedCoreApply.has_value(),
"failed unsigned Core apply reused a consumed confirmation token");
const auto coreToken =
confirmationToken(service, "core", "", coreId, "2.0.0");
check(!coreToken.empty(), "fresh Core unsigned confirmation failed");
rejectCore = false;
auto coreApply = service.handle(
"updates.apply",
std::format(
R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json",
coreId, coreToken));
check(coreApply.has_value(), "Core apply did not queue");
check(coreReplacements == 1,
"Core was replaced synchronously on the RPC call stack");
service.processPendingHostActions();
check(coreReplacements == 2, "queued Core replacement did not run");
check(readFile(activatedCore) == newCore,
"queued Core replacement used the wrong artifact");
Void::Update::VersionStore coreStore(state / "updates" / "components" /
"core");
auto activeCoreVersion = coreStore.currentVersion();
check(activeCoreVersion && activeCoreVersion->has_value() &&
(*activeCoreVersion)->to_string() == "2.0.0",
"Core activation was not committed");
check(readFile(coreStore.versionPath(*Void::Semver::parse("1.0.0")) /
"Echoion.ts") == oldCore,
"initial Core was not seeded for rollback");
check(!std::filesystem::exists(
coreStore.versionPath(*Void::Semver::parse("0.9.0"))),
"Core retention did not remove an excess healthy version");
const auto pluginToken =
confirmationToken(service, "plugins", "fixture", pluginId, "4.0.0");
check(!pluginToken.empty(), "plugin unsigned confirmation failed");
auto pluginApply = service.handle(
"updates.apply",
std::format(
R"json({{"component":"plugins","pluginId":"fixture","candidateId":"{}","version":"4.0.0","confirmationToken":"{}"}})json",
pluginId, pluginToken));
check(pluginApply.has_value(), "plugin apply failed");
check(pluginReplacements == 1 && readFile(activatedPlugin) == newPlugin,
"plugin replacement used the wrong artifact");
check(readFile(pluginStore.versionPath(*Void::Semver::parse("3.0.0")) /
"fixture.so") == oldPlugin,
"initial plugin was not seeded for rollback");
check(!std::filesystem::exists(
pluginStore.versionPath(*Void::Semver::parse("2.0.0"))),
"plugin retention did not remove an excess healthy version");
auto unsafePluginRollback = service.handle(
"updates.rollback",
R"({"component":"plugins","pluginId":"../escape","version":"3.0.0"})");
check(!unsafePluginRollback.has_value(),
"plugin rollback accepted a path-traversal plugin id");
auto pluginRollback = service.handle(
"updates.rollback",
R"({"component":"plugins","pluginId":"fixture","version":"3.0.0"})");
check(pluginRollback.has_value() && pluginReplacements == 2 &&
readFile(activatedPlugin) == oldPlugin,
"plugin rollback did not restore the seeded version");
auto unadvertisedRollback = service.handle(
"updates.rollback", R"({"component":"core","version":"2.0.0"})");
check(!unadvertisedRollback.has_value(),
"Core rollback accepted a version that was not advertised healthy");
auto rollback = service.handle("updates.rollback",
R"({"component":"core","version":"1.0.0"})");
check(rollback.has_value(), "Core rollback did not queue");
check(coreReplacements == 2,
"Core rollback ran synchronously on the RPC call stack");
service.processPendingHostActions();
check(coreReplacements == 3 && readFile(activatedCore) == oldCore,
"queued Core rollback did not restore the seed");
rejectCore = true;
auto failedRollback = service.handle(
"updates.rollback", R"({"component":"core","version":"2.0.0"})");
check(failedRollback.has_value(), "failing Core rollback did not queue");
service.processPendingHostActions();
activeCoreVersion = coreStore.currentVersion();
check(coreReplacements == 4 && activeCoreVersion &&
activeCoreVersion->has_value() &&
(*activeCoreVersion)->to_string() == "1.0.0",
"failed Core replacement did not roll back the VersionStore");
auto finalStatus = service.handle("updates.getStatus", "{}");
check(finalStatus && finalStatus->contains("rejected by test"),
"failed deferred activation was not reported in status/history");
const auto plugin4 = *Void::Semver::parse("4.0.0");
check(pluginStore.activate(plugin4).has_value(),
"could not stage an interrupted plugin activation");
check(Echoion::Standalone::reconcileManagedPluginUpdates(state).has_value(),
"managed plugin startup reconciliation failed");
auto recoveredPluginVersion = pluginStore.currentVersion();
check(recoveredPluginVersion && recoveredPluginVersion->has_value() &&
(*recoveredPluginVersion)->to_string() == "3.0.0",
"startup reconciliation did not roll back the interrupted plugin");
const auto sequenceState = state / "updates" / "sequences.json";
std::filesystem::remove(sequenceState);
std::filesystem::create_directory(sequenceState);
check(!service.handle("updates.check", "{}").has_value(),
"update check ignored a replay-floor persistence failure");
std::filesystem::remove(sequenceState);
service.stop();
auto restarted = makeService();
check(restarted.start().has_value(),
"restarted UpdateService did not start");
auto restartedStatusResponse = restarted.handle("updates.getStatus", "{}");
std::optional<Void::Json::Value> restartedStatusJson;
const auto* restartedStatus =
parseResponse(restartedStatusResponse, restartedStatusJson);
check(restartedStatus != nullptr,
"restarted UpdateService did not return status");
check(restartedStatus &&
componentRollbackVersion(*restartedStatus, "runtime") == "0.8.0",
"runtime rollback metadata was not reconstructed or accepted an "
"invalid payload");
check(restartedStatus &&
componentRollbackVersion(*restartedStatus, "core") == "2.0.0",
"Core rollback metadata was not reconstructed after restart");
check(restartedStatus &&
pluginRollbackVersion(*restartedStatus, "fixture") == "4.0.0",
"plugin rollback metadata was not reconstructed after restart");
check(readFile(coreStore.versionPath(*Void::Semver::parse("2.0.0")) /
"Echoion.ts") == newCore,
"retained Core rollback payload was unavailable after restart");
check(readFile(pluginStore.versionPath(*Void::Semver::parse("4.0.0")) /
"fixture.so") == newPlugin,
"retained plugin rollback payload was unavailable after restart");
Void::Update::VersionStore runtimeStore(installRoot);
check(readFile(runtimeStore.versionPath(*Void::Semver::parse("0.8.0")) /
"bin" / "echoiond") == "previous-runtime",
"retained runtime rollback payload was unavailable after restart");
restarted.stop();
check(writeFile(sequenceState, "{not-json"),
"failed to write corrupt replay-floor fixture");
auto corruptReplayState = makeService();
const auto corruptReplayStart = corruptReplayState.start();
check(
!corruptReplayStart &&
corruptReplayStart.error().message.contains("replay-floor"),
"corrupt replay-floor state silently disabled anti-replay persistence");
std::filesystem::remove(sequenceState);
#ifndef _WIN32
const auto runtimeLock = installRoot / ".update.lock";
const auto runtimeHealth = installRoot / "health.log";
std::filesystem::permissions(runtimeLock, std::filesystem::perms::none,
std::filesystem::perm_options::replace);
std::filesystem::permissions(runtimeHealth, std::filesystem::perms::none,
std::filesystem::perm_options::replace);
std::ifstream unreadableProbe{runtimeLock, std::ios::binary};
if (!unreadableProbe) {
auto legacy = makeService();
check(legacy.start().has_value(),
"unreadable legacy runtime metadata disabled UpdateService");
auto legacyStatusResponse = legacy.handle("updates.getStatus", "{}");
std::optional<Void::Json::Value> legacyStatusJson;
const auto* legacyStatus =
parseResponse(legacyStatusResponse, legacyStatusJson);
check(legacyStatus &&
componentRollbackVersion(*legacyStatus, "runtime").empty(),
"unreadable legacy metadata exposed a runtime rollback");
legacy.stop();
}
const auto readableMetadata = std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write |
std::filesystem::perms::group_read |
std::filesystem::perms::others_read;
std::filesystem::permissions(runtimeLock, readableMetadata,
std::filesystem::perm_options::replace);
std::filesystem::permissions(runtimeHealth, readableMetadata,
std::filesystem::perm_options::replace);
#endif
TemporaryTree freshTree;
const auto freshState = freshTree.path() / "state";
const auto freshIncoming = freshTree.path() / "incoming";
const auto freshFeed = freshIncoming / "feed.json";
const auto freshConfig = freshTree.path() / "config.json";
const auto freshCore = freshTree.path() / "installed" / "Echoion.ts";
const auto freshInstall = freshTree.path() / "runtime";
check(writeFile(freshFeed, "{}"),
"failed to write fresh-install feed fixture");
check(writeFile(freshConfig, configDocument(freshFeed)),
"failed to write fresh-install config fixture");
check(writeFile(freshCore, oldCore),
"failed to write fresh-install Core fixture");
check(writeFile(freshInstall / "versions" / "1.0.0" / "bin" / "echoiond",
"fresh-runtime"),
"failed to write fresh-install runtime fixture");
std::filesystem::create_directory_symlink(
std::filesystem::path{"versions"} / "1.0.0", freshInstall / "current");
Echoion::Standalone::UpdateService freshService(
Echoion::Standalone::UpdateService::Options{
.configPath = freshConfig,
.stateDirectory = freshState,
.installRoot = freshInstall,
.runningExecutable = freshInstall / "bin" / "echoiond",
.currentCore = freshCore,
.releaseManifestPath = {},
.officialFeedUrl = {},
.officialPublicKeysJson = "[]",
.runtimeVersion = "1.0.0",
.apiVersion = "1.1.0",
.toolchainAbi = "test",
.incomingDirectory = freshIncoming},
Echoion::Standalone::UpdateService::Hooks{});
check(freshService.start().has_value(),
"fresh install without VersionStore metadata did not start");
auto freshStatusResponse = freshService.handle("updates.getStatus", "{}");
std::optional<Void::Json::Value> freshStatusJson;
const auto* freshStatus =
parseResponse(freshStatusResponse, freshStatusJson);
check(freshStatus &&
componentRollbackVersion(*freshStatus, "runtime").empty(),
"fresh install synthesized runtime rollback metadata");
freshService.stop();
TemporaryTree blockedTree;
const auto blockedState = blockedTree.path() / "state";
const auto blockedIncoming = blockedTree.path() / "incoming";
const auto blockedFeed = blockedIncoming / "feed.json";
const auto blockedConfig = blockedTree.path() / "config.json";
const auto blockedCore = blockedTree.path() / "installed" / "Echoion.ts";
check(writeFile(blockedFeed, "{}"),
"failed to write blocked-start feed fixture");
check(writeFile(blockedConfig, configDocument(blockedFeed)),
"failed to write blocked-start config fixture");
check(writeFile(blockedCore, oldCore),
"failed to write blocked-start Core fixture");
check(writeFile(blockedState / "updates" / "downloads", "not-a-directory"),
"failed to create blocked updater directory fixture");
Echoion::Standalone::UpdateService blockedService(
Echoion::Standalone::UpdateService::Options{
.configPath = blockedConfig,
.stateDirectory = blockedState,
.installRoot = blockedTree.path() / "runtime",
.runningExecutable =
blockedTree.path() / "runtime" / "bin" / "echoiond",
.currentCore = blockedCore,
.releaseManifestPath = {},
.officialFeedUrl = {},
.officialPublicKeysJson = "[]",
.runtimeVersion = "1.0.0",
.apiVersion = "1.1.0",
.toolchainAbi = "test",
.incomingDirectory = blockedIncoming},
Echoion::Standalone::UpdateService::Hooks{});
const auto blockedStart = blockedService.start();
check(!blockedStart && blockedStart.error().message.contains("downloads"),
"startup masked an earlier updater directory creation failure");
blockedService.stop();
return failures == 0 ? 0 : 1;
}