From 9ba13e312692a75a2f811eec4072bd19efcd3516 Mon Sep 17 00:00:00 2001 From: ReenigneArcher <42013603+ReenigneArcher@users.noreply.github.com> Date: Sun, 11 Oct 2026 13:21:44 -0400 Subject: [PATCH] refactor(runtime): own application infrastructure and logging --- src/entry_handler.cpp | 86 ++++++++++++++-- src/entry_handler.h | 112 ++++++++++++++++++--- src/globals.cpp | 36 ++++++- src/globals.h | 85 ++++++++++++---- src/logging.cpp | 54 +++++----- src/logging.h | 159 ++++++++++++++++++++++++++---- src/thread_pool.h | 6 +- src/thread_safe.h | 2 +- tests/tests_environment.h | 2 - tests/unit/test_entry_handler.cpp | 136 +++++++++++++++++++++++++ tests/unit/test_logging.cpp | 43 ++++++++ tests/unit/test_thread_safe.cpp | 39 ++++++++ 12 files changed, 658 insertions(+), 102 deletions(-) diff --git a/src/entry_handler.cpp b/src/entry_handler.cpp index c2249af0a..117cd1ee4 100644 --- a/src/entry_handler.cpp +++ b/src/entry_handler.cpp @@ -61,9 +61,10 @@ namespace args { #ifdef _WIN32 int restore_nvprefs_undo() { - if (nvprefs_instance.load()) { - nvprefs_instance.restore_from_and_delete_undo_file_if_exists(); - nvprefs_instance.unload(); + nvprefs::nvprefs_interface preferences; + if (preferences.load()) { + preferences.restore_from_and_delete_undo_file_if_exists(); + preferences.unload(); } return 0; } @@ -71,13 +72,20 @@ namespace args { } // namespace args namespace lifetime { - char **argv; ///< Command-line argument vector. - std::atomic_int desired_exit_code; ///< Desired exit code. + controller_t::controller_t(char **argv): + argv_ {argv} { + } - void exit_sunshine(int exit_code, bool async) { + controller_t::~controller_t() { + if (restart_action_) { + restart_action_(); + } + } + + void controller_t::exit_sunshine(int exit_code, bool async) { // Store the exit code of the first exit_sunshine() call int zero = 0; - desired_exit_code.compare_exchange_strong(zero, exit_code); + desired_exit_code_.compare_exchange_strong(zero, exit_code); // Raise SIGINT to start termination std::raise(SIGINT); @@ -97,8 +105,68 @@ namespace lifetime { #endif } - char **get_argv() { - return argv; + int controller_t::exit_code() const { + return desired_exit_code_.load(); + } + + char **controller_t::get_argv() const { + return argv_; + } + + void controller_t::restart_on_exit(std::function action) { + restart_action_ = std::move(action); + } + + std::atomic &signal_guard_t::native_binding() { + static std::atomic binding {nullptr}; + return binding; + } + + signal_guard_t::signal_guard_t(controller_t &controller): + controller_ {controller} { + signal_guard_t *empty = nullptr; + if (!native_binding().compare_exchange_strong(empty, this)) { + throw std::logic_error {"Native signal callbacks already have an application owner"}; + } + } + + signal_guard_t::~signal_guard_t() { + for (const auto &[signal, handler] : previous_handlers_) { + std::signal(signal, handler); + } + native_binding().store(nullptr); + } + + void signal_guard_t::on_signal(int signal, std::function handler) { + if (signal != SIGINT && signal != SIGTERM) { + throw std::invalid_argument {"Only application termination signals can be registered"}; + } + handlers_.insert_or_assign(signal, std::move(handler)); + if (!previous_handlers_.contains(signal)) { + const auto previous = std::signal(signal, &signal_guard_t::forward); + if (previous == SIG_ERR) { + handlers_.erase(signal); + throw std::runtime_error {"Failed to register application signal handler"}; + } + previous_handlers_.emplace(signal, previous); + } + } + + void signal_guard_t::forward(int signal) { + if (auto *guard = native_binding().load()) { + const auto handler = guard->handlers_.find(signal); + if (handler != guard->handlers_.end()) { + // The Windows CRT resets delivered handlers; retain repeated shutdown requests. + std::signal(signal, &signal_guard_t::forward); + handler->second(); + } + } + } + + void signal_guard_t::native_exit(int exit_code, bool async) { + if (auto *guard = native_binding().load()) { + guard->controller_.exit_sunshine(exit_code, async); + } } } // namespace lifetime diff --git a/src/entry_handler.h b/src/entry_handler.h index 886c76c04..01bcdc053 100644 --- a/src/entry_handler.h +++ b/src/entry_handler.h @@ -6,6 +6,9 @@ // standard includes #include +#include +#include +#include #include #include #include @@ -89,27 +92,112 @@ namespace args { * @brief Functions for handling the lifetime of Sunshine. */ namespace lifetime { - extern char **argv; - extern std::atomic_int desired_exit_code; + /** + * @brief Owns command arguments, exit status, and an optional process restart action. + */ + class controller_t { + public: + /** + * @brief Capture the original command arguments for this application lifetime. + * @param argv Original argument vector; valid for the controller lifetime. + */ + explicit controller_t(char **argv = nullptr); + controller_t(const controller_t &) = delete; + controller_t &operator=(const controller_t &) = delete; + + /** + * @brief Run a requested restart after the application's resources are released. + */ + ~controller_t(); + + /** + * @brief Request graceful shutdown and preserve the first nonzero exit status. + * @param exit_code Status returned by main(). + * @param async Whether the caller can return before shutdown completes. + */ + void exit_sunshine(int exit_code, bool async); + + /** + * @brief Read the status requested by application shutdown. + * @return Requested process exit status. + */ + int exit_code() const; + + /** + * @brief Read the original argument vector. + * @return Arguments captured at construction. + */ + char **get_argv() const; + + /** + * @brief Arrange a restart after this controller's dependents are destroyed. + * @param action Process relaunch operation. + */ + void restart_on_exit(std::function action); + + private: + char **argv_; ///< Original argument vector. + std::atomic_int desired_exit_code_ {}; ///< First nonzero requested exit status. + std::function restart_action_; ///< Relaunch operation owned by this lifetime. + }; /** - * @brief Terminates Sunshine gracefully with the provided exit code. - * @param exit_code The exit code to return from main(). - * @param async Specifies whether our termination will be non-blocking. + * @brief Owns signal callbacks and restores native handlers at the end of their scope. + * + * POSIX signals and Windows console callbacks cannot carry userdata. Only these + * native trampolines use the scoped active binding; application code receives + * its controller explicitly. */ - void exit_sunshine(int exit_code, bool async); + class signal_guard_t { + public: + /** + * @brief Bind native callbacks to one application lifetime. + * @param controller Application shutdown controller. + */ + explicit signal_guard_t(controller_t &controller); + signal_guard_t(const signal_guard_t &) = delete; + signal_guard_t &operator=(const signal_guard_t &) = delete; + /** + * @brief Restore the handlers replaced by this guard. + */ + ~signal_guard_t(); + + /** + * @brief Install an application callback for one POSIX signal. + * @param signal Application termination signal, SIGINT or SIGTERM. + * @param handler Callback invoked by the native trampoline. + */ + void on_signal(int signal, std::function handler); + + /** + * @brief Request shutdown from a native callback without a userdata argument. + * @param exit_code Requested process status. + * @param async Whether the callback can return before shutdown completes. + */ + static void native_exit(int exit_code, bool async); + + private: + /** + * @brief Obtain the binding used exclusively by native callback trampolines. + * @return Atomic pointer to the guard registered in the current scope. + */ + static std::atomic &native_binding(); + /** + * @brief Reinstall a native signal handler before forwarding to its owned callback. + * @param signal Signal delivered by the operating system. + */ + static void forward(int signal); + + controller_t &controller_; ///< Application lifetime receiving console shutdown. + std::map> handlers_; ///< Callbacks owned by this registration. + std::map previous_handlers_; ///< Native handlers restored on destruction. + }; /** * @brief Breaks into the debugger or terminates Sunshine if no debugger is attached. */ void debug_trap(); - /** - * @brief Get the argv array passed to main(). - * - * @return Original argument vector captured from main(). - */ - char **get_argv(); } // namespace lifetime /** diff --git a/src/globals.cpp b/src/globals.cpp index 60daf398a..aea4f3f88 100644 --- a/src/globals.cpp +++ b/src/globals.cpp @@ -1,14 +1,40 @@ /** * @file globals.cpp - * @brief Definitions for globally accessible variables and functions. + * @brief Definitions for application infrastructure ownership. */ // local includes #include "globals.h" -safe::mail_t mail::man; -thread_pool_util::ThreadPool task_pool; -bool display_cursor = true; +namespace runtime { + infrastructure_t::infrastructure_t(char **argv): + lifetime_ {argv}, + mailbox_ {std::make_shared()} { + } + + infrastructure_t::~infrastructure_t() { + scheduler_.stop(); + scheduler_.join(); + } + + thread_pool_util::ThreadPool &infrastructure_t::scheduler() { + return scheduler_; + } + + safe::mail_t infrastructure_t::mailbox() const { + return mailbox_; + } + + bool &infrastructure_t::cursor() { + return cursor_; + } + + lifetime::controller_t &infrastructure_t::lifetime() { + return lifetime_; + } #ifdef _WIN32 -nvprefs::nvprefs_interface nvprefs_instance; + nvprefs::nvprefs_interface &infrastructure_t::preferences() { + return preferences_; + } #endif +} // namespace runtime diff --git a/src/globals.h b/src/globals.h index 2c7ee9b12..e39a500a6 100644 --- a/src/globals.h +++ b/src/globals.h @@ -1,6 +1,6 @@ /** * @file globals.h - * @brief Declarations for globally accessible variables and functions. + * @brief Application infrastructure ownership and mailbox identifiers. */ #pragma once @@ -8,26 +8,74 @@ #include "entry_handler.h" #include "thread_pool.h" -/** - * @brief A thread pool for processing tasks. - */ -extern thread_pool_util::ThreadPool task_pool; +#ifdef _WIN32 + #include "platform/windows/nvprefs/nvprefs_interface.h" +#endif -/** - * @brief A boolean flag to indicate whether the cursor should be displayed. - */ -extern bool display_cursor; +namespace runtime { + /** + * @brief Infrastructure owned by one invocation of the Sunshine application. + * + * Subsystems receive individual dependencies from this object. The lifetime + * controller is destroyed last so a requested restart runs after workers and + * platform resources have been released. + */ + class infrastructure_t { + public: + /** + * @brief Construct the application's mailbox and inactive task scheduler. + * @param argv Original command arguments used when restarting. + */ + explicit infrastructure_t(char **argv = nullptr); + + /** + * @brief Stop and join queued work before releasing its infrastructure dependencies. + */ + ~infrastructure_t(); + + /** + * @brief Obtain the scheduler shared by host input and shutdown tasks. + * @return Application-owned scheduler. + */ + thread_pool_util::ThreadPool &scheduler(); + + /** + * @brief Obtain the host mailbox shared by packet and lifecycle workers. + * @return Shared mailbox handle. + */ + safe::mail_t mailbox() const; + + /** + * @brief Obtain the cursor preference shared by input and capture. + * @return Host cursor preference. + */ + bool &cursor(); + + /** + * @brief Obtain the controller for this application's shutdown and restart. + * @return Application lifetime controller. + */ + lifetime::controller_t &lifetime(); #ifdef _WIN32 - // Declare global singleton used for NVIDIA control panel modifications - #include "platform/windows/nvprefs/nvprefs_interface.h" - -/** - * @brief A global singleton used for NVIDIA control panel modifications. - */ -extern nvprefs::nvprefs_interface nvprefs_instance; + /** + * @brief Obtain the owner of NVIDIA control-panel preference modifications. + * @return Application-owned NVIDIA preferences. + */ + nvprefs::nvprefs_interface &preferences(); #endif + private: + lifetime::controller_t lifetime_; ///< Destroyed after all dependent infrastructure. + thread_pool_util::ThreadPool scheduler_; ///< Host task scheduler. + safe::mail_t mailbox_; ///< Host communication bus. + bool cursor_ = true; ///< Shared cursor visibility preference. +#ifdef _WIN32 + nvprefs::nvprefs_interface preferences_; ///< NVIDIA preference and recovery owner. +#endif + }; +} // namespace runtime + /** * @brief Handles process-wide communication. */ @@ -41,11 +89,6 @@ namespace mail { #x \ } - /** - * @brief A process-wide communication mechanism. - */ - extern safe::mail_t man; - // Global mail MAIL(shutdown); ///< Shutdown. MAIL(broadcast_shutdown); ///< Broadcast shutdown. diff --git a/src/logging.cpp b/src/logging.cpp index 39a3f0071..44e90622e 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -36,29 +36,23 @@ using namespace std::literals; namespace bl = boost::log; -boost::shared_ptr> sink; ///< Sink. - -bl::sources::severity_logger verbose {0}; ///< Dominating output. -bl::sources::severity_logger debug {1}; ///< Follow what is happening. -bl::sources::severity_logger info {2}; ///< Should be informed about. -bl::sources::severity_logger warning {3}; ///< Strange events. -bl::sources::severity_logger error {4}; ///< Recoverable errors. -bl::sources::severity_logger fatal {5}; ///< Unrecoverable errors. -#ifdef SUNSHINE_TESTS -bl::sources::severity_logger tests {10}; ///< Automatic tests output. -#endif - BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", int) namespace logging { - deinit_t::~deinit_t() { - deinit(); + deinit_t::deinit_t(boost::shared_ptr sink, boost::shared_ptr platform_sink): + sink_ {std::move(sink)}, + platform_sink_ {std::move(platform_sink)} { } - void deinit() { - log_flush(); - bl::core::get()->remove_sink(sink); - sink.reset(); + deinit_t::~deinit_t() { + auto core = bl::core::get(); + core->remove_sink(sink_); + if (platform_sink_) { + core->remove_sink(platform_sink_); + platform_sink_->flush(); + } + sink_->stop(); + sink_->flush(); } /** @@ -152,11 +146,6 @@ namespace logging { #endif [[nodiscard]] std::unique_ptr init(int min_log_level, const std::string &log_file) { - if (sink) { - // Deinitialize the logging system before reinitializing it. This can probably only ever be hit in tests. - deinit(); - } - const auto log_path = std::filesystem::path {std::u8string {log_file.begin(), log_file.end()}}; if (const auto rotation_error = rotate_log_file(log_path)) { std::cerr << "Failed to rotate log file '" << log_file << "': " << rotation_error.message() << '\n'; @@ -167,7 +156,7 @@ namespace logging { setup_libdisplaydevice_logging(min_log_level); #endif - sink = boost::make_shared(); + auto sink = boost::make_shared(); #ifndef SUNSHINE_TESTS boost::shared_ptr stream {&std::cout, boost::null_deleter()}; @@ -187,13 +176,16 @@ namespace logging { // This is particularly important when running from a Windows service. sink->locked_backend()->auto_flush(true); - bl::core::get()->add_sink(sink); - + boost::shared_ptr platform_sink; #ifdef __ANDROID__ - auto android_sink = boost::make_shared>(); - bl::core::get()->add_sink(android_sink); + platform_sink = boost::make_shared>(); #endif - return std::make_unique(); + auto owner = std::make_unique(sink, platform_sink); + bl::core::get()->add_sink(sink); + if (platform_sink) { + bl::core::get()->add_sink(platform_sink); + } + return owner; } #ifndef __ANDROID__ @@ -257,9 +249,7 @@ namespace logging { #endif void log_flush() { - if (sink) { - sink->flush(); - } + bl::core::get()->flush(); } void print_help(const char *name) { diff --git a/src/logging.h b/src/logging.h index cb33988b4..72154980e 100644 --- a/src/logging.h +++ b/src/logging.h @@ -14,20 +14,138 @@ // lib includes #include #include +#include +#include /** * @brief Boost.Log asynchronous text sink used by Sunshine logging. */ using text_sink = boost::log::sinks::asynchronous_sink; -extern boost::log::sources::severity_logger verbose; ///< Verbose. -extern boost::log::sources::severity_logger debug; ///< Debug. -extern boost::log::sources::severity_logger info; ///< Info. -extern boost::log::sources::severity_logger warning; ///< Warning. -extern boost::log::sources::severity_logger error; ///< Error. -extern boost::log::sources::severity_logger fatal; ///< Fatal. +namespace logging { + /** + * @brief Boost-managed, thread-safe verbose logging source. + */ + BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(verbose_source, boost::log::sources::severity_logger_mt, (0)) + /** + * @brief Boost-managed, thread-safe debug logging source. + */ + BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(debug_source, boost::log::sources::severity_logger_mt, (1)) + /** + * @brief Boost-managed, thread-safe informational logging source. + */ + BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(info_source, boost::log::sources::severity_logger_mt, (2)) + /** + * @brief Boost-managed, thread-safe warning logging source. + */ + BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(warning_source, boost::log::sources::severity_logger_mt, (3)) + /** + * @brief Boost-managed, thread-safe error logging source. + */ + BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(error_source, boost::log::sources::severity_logger_mt, (4)) + /** + * @brief Boost-managed, thread-safe fatal logging source. + */ + BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(fatal_source, boost::log::sources::severity_logger_mt, (5)) #ifdef SUNSHINE_TESTS -extern boost::log::sources::severity_logger tests; + /** + * @brief Boost-managed source for test output. + */ + BOOST_LOG_INLINE_GLOBAL_LOGGER_CTOR_ARGS(tests_source, boost::log::sources::severity_logger_mt, (10)) +#endif + + /** + * @brief Immutable severity handle preserving existing BOOST_LOG call sites. + * + * Boost.Log global storage initializes and synchronizes the mutable source. + */ + class logger_t { + public: + using logger_type = boost::log::sources::severity_logger_mt; ///< Managed source type. + using char_type = logger_type::char_type; ///< Character type required by Boost.Log. + + /** + * @brief Select the managed source for a severity. + * @param severity Default severity for this handle. + */ + constexpr explicit logger_t(int severity): + severity_ {severity} { + } + + /** + * @brief Access the Boost-managed source for this severity. + * @return Thread-safe logging source. + */ + logger_type &get() const { + switch (severity_) { + case 0: + return verbose_source::get(); + case 1: + return debug_source::get(); + case 2: + return info_source::get(); + case 3: + return warning_source::get(); + case 4: + return error_source::get(); + case 5: + return fatal_source::get(); +#ifdef SUNSHINE_TESTS + case 10: + return tests_source::get(); +#endif + default: + throw std::invalid_argument {"Unsupported log severity"}; + } + } + + /** + * @brief Convert a severity handle for periodic logger construction. + * @return Managed logging source. + */ + operator logger_type &() const { + return get(); + } + + /** + * @brief Open a record using the managed source. + * @return Record accepted by the configured sinks. + */ + boost::log::record open_record() const { + return get().open_record(); + } + + /** + * @brief Open a record with Boost.Log named arguments. + * @param args Named attributes supplied by Boost.Log. + * @return Record accepted by the configured sinks. + */ + template + boost::log::record open_record(const Args &args) const { + return get().open_record(args); + } + + /** + * @brief Submit a completed record to the configured sinks. + * @param record Record to publish. + */ + void push_record(boost::log::record &&record) const { + get().push_record(std::move(record)); + } + + private: + int severity_; ///< Severity selected by the immutable handle. + }; +} // namespace logging + +inline constexpr logging::logger_t verbose {0}; ///< Verbose. +inline constexpr logging::logger_t debug {1}; ///< Debug. +inline constexpr logging::logger_t info {2}; ///< Info. +inline constexpr logging::logger_t warning {3}; ///< Warning. +inline constexpr logging::logger_t error {4}; ///< Error. +inline constexpr logging::logger_t fatal {5}; ///< Fatal. +#ifdef SUNSHINE_TESTS +inline constexpr logging::logger_t tests {10}; ///< Automatic test output. #endif #include "config.h" @@ -83,19 +201,24 @@ namespace logging { */ class deinit_t { public: + /** + * @brief Own the sinks registered by one logging initialization. + * @param sink Asynchronous text sink. + * @param platform_sink Additional platform sink, when present. + */ + deinit_t(boost::shared_ptr sink, boost::shared_ptr platform_sink = {}); + + deinit_t(const deinit_t &) = delete; + deinit_t &operator=(const deinit_t &) = delete; /** * @brief Restores logging state when the logging subsystem shuts down. */ ~deinit_t(); - }; - /** - * @brief Deinitialize the logging system. - * @examples - * deinit(); - * @examples_end - */ - void deinit(); + private: + boost::shared_ptr sink_; ///< Sink whose registration this owner controls. + boost::shared_ptr platform_sink_; ///< Optional platform sink. + }; /** * @brief Format a Boost.Log record for Sunshine log output. @@ -169,7 +292,7 @@ namespace logging { * @param units Unit label appended to tracked numeric values. * @param interval_in_seconds Interval in seconds. */ - min_max_avg_periodic_logger(boost::log::sources::severity_logger &severity, std::string_view message, std::string_view units, std::chrono::seconds interval_in_seconds = std::chrono::seconds(20)): + min_max_avg_periodic_logger(boost::log::sources::severity_logger_mt &severity, std::string_view message, std::string_view units, std::chrono::seconds interval_in_seconds = std::chrono::seconds(20)): severity(severity), message(message), units(units), @@ -226,7 +349,7 @@ namespace logging { } private: - std::reference_wrapper> severity; + std::reference_wrapper> severity; std::string message; std::string units; std::chrono::seconds interval; @@ -258,7 +381,7 @@ namespace logging { * @param message Message text to log or report. * @param interval_in_seconds Interval in seconds. */ - time_delta_periodic_logger(boost::log::sources::severity_logger &severity, std::string_view message, std::chrono::seconds interval_in_seconds = std::chrono::seconds(20)): + time_delta_periodic_logger(boost::log::sources::severity_logger_mt &severity, std::string_view message, std::chrono::seconds interval_in_seconds = std::chrono::seconds(20)): logger(severity, message, "ms", interval_in_seconds) { } diff --git a/src/thread_pool.h b/src/thread_pool.h index d4d9b7625..d59fb170c 100644 --- a/src/thread_pool.h +++ b/src/thread_pool.h @@ -128,11 +128,13 @@ namespace thread_pool_util { } /** - * @brief Wait for worker threads owned by the session to exit. + * @brief Wait for worker threads owned by the session to exit, including repeated calls. */ void join() { for (auto &t : _thread) { - t.join(); + if (t.joinable()) { + t.join(); + } } } diff --git a/src/thread_safe.h b/src/thread_safe.h index f3061e2b6..e0a2aee0e 100644 --- a/src/thread_safe.h +++ b/src/thread_safe.h @@ -722,7 +722,7 @@ namespace safe { std::array _object_buf; - std::uint32_t _count; + std::uint32_t _count {0}; std::mutex _lock; }; diff --git a/tests/tests_environment.h b/tests/tests_environment.h index 68a1dbab2..fb7d9c86c 100644 --- a/tests/tests_environment.h +++ b/tests/tests_environment.h @@ -9,13 +9,11 @@ struct SunshineEnvironment: testing::Environment { void SetUp() override { - mail::man = std::make_shared(); deinit_log = logging::init(0, "test_sunshine.log"); } void TearDown() override { deinit_log = {}; - mail::man = {}; } std::unique_ptr deinit_log; diff --git a/tests/unit/test_entry_handler.cpp b/tests/unit/test_entry_handler.cpp index 9fb64d210..787ed0436 100644 --- a/tests/unit/test_entry_handler.cpp +++ b/tests/unit/test_entry_handler.cpp @@ -70,3 +70,139 @@ TEST(EntryHandlerTests, LogPublisherDataTest) { ASSERT_TRUE(log_checker::line_starts_with("test_sunshine.log", "Info: Publisher Website: ")); ASSERT_TRUE(log_checker::line_starts_with("test_sunshine.log", "Info: Get support: ")); } + +TEST(EntryHandlerTests, ControllersKeepArgumentsAndExitStatusIndependent) { + char first_name[] = "first"; + char second_name[] = "second"; + char *first_args[] {first_name, nullptr}; + char *second_args[] {second_name, nullptr}; + lifetime::controller_t first {first_args}; + lifetime::controller_t second {second_args}; + EXPECT_EQ(first.get_argv(), first_args); + EXPECT_EQ(second.get_argv(), second_args); + EXPECT_EQ(first.exit_code(), 0); + EXPECT_EQ(second.exit_code(), 0); + + int signals = 0; + lifetime::signal_guard_t guard {first}; +/** + * @brief Termination signals remain registered before callbacks issue another signal. + */ +TEST(EntryHandlerTests, RearmsTerminationSignalsBeforeInvokingOwnedCallbacks) { + for (const auto signal : {SIGINT, SIGTERM}) { + lifetime::controller_t controller; + lifetime::signal_guard_t guard {controller}; + int signals = 0; + int repeated_result = -1; + guard.on_signal(signal, [&]() { + if (++signals == 1) { + repeated_result = std::raise(signal); + } + }); + EXPECT_EQ(std::raise(signal), 0); + EXPECT_EQ(repeated_result, 0); + EXPECT_EQ(signals, 2); + EXPECT_EQ(std::raise(signal), 0); + EXPECT_EQ(signals, 3); + } +} + + guard.on_signal(SIGINT, [&signals]() { + ++signals; + }); + first.exit_sunshine(7, true); + first.exit_sunshine(9, true); + EXPECT_EQ(first.exit_code(), 7); + EXPECT_EQ(second.exit_code(), 0); + EXPECT_EQ(signals, 2); +} + +TEST(EntryHandlerTests, NativeCallbackBindingIsScopedAndRestoresPreviousHandler) { + lifetime::controller_t controller; + const auto expected = +[](int) { + }; + const auto previous = std::signal(SIGINT, expected); + ASSERT_NE(previous, SIG_ERR); + auto restore = util::fail_guard([previous]() { + std::signal(SIGINT, previous); + }); + int signals = 0; + { + lifetime::signal_guard_t guard {controller}; + guard.on_signal(SIGINT, [&signals]() { + ++signals; + }); + lifetime::signal_guard_t::native_exit(11, true); + EXPECT_EQ(controller.exit_code(), 11); + EXPECT_EQ(signals, 1); + EXPECT_THROW(lifetime::signal_guard_t {controller}, std::logic_error); + EXPECT_THROW(guard.on_signal(-1, []() { + }), + std::invalid_argument); + } + EXPECT_EQ(std::signal(SIGINT, expected), expected); + lifetime::signal_guard_t::native_exit(13, true); + EXPECT_EQ(signals, 1); +} + +TEST(EntryHandlerTests, RequestedRestartRunsAfterDependentCleanup) { + bool cleaned = false; + bool restarted = false; + { + lifetime::controller_t controller; + +/** + * @brief Infrastructure destruction waits for active work before releasing its dependencies. + */ +TEST(EntryHandlerTests, InfrastructureDestructionJoinsWorkBeforeDependencyCleanup) { + auto infrastructure = std::make_unique(); + auto *owner = infrastructure.get(); + const std::weak_ptr mailbox = owner->mailbox(); +#ifdef _WIN32 + auto *preferences = &owner->preferences(); +#endif + std::promise started; + std::promise release; + const auto released = release.get_future().share(); + owner->scheduler().start(1); + auto task = owner->scheduler().push([&]() { + started.set_value(); + released.wait(); + const bool dependencies_alive = !mailbox.expired() && owner->cursor(); +#ifdef _WIN32 + return dependencies_alive && &owner->preferences() == preferences; +#else + return dependencies_alive; +#endif + }); + started.get_future().get(); + auto destruction = std::async(std::launch::async, [infrastructure = std::move(infrastructure)]() mutable { + infrastructure.reset(); + }); + EXPECT_EQ(destruction.wait_for(std::chrono::milliseconds(0)), std::future_status::timeout); + release.set_value(); + destruction.get(); + EXPECT_TRUE(task.get()); + EXPECT_TRUE(mailbox.expired()); +} + +/** + * @brief Infrastructure destruction accepts a scheduler already stopped and joined by its caller. + */ +TEST(EntryHandlerTests, InfrastructureDestructionAcceptsPreviouslyJoinedScheduler) { + runtime::infrastructure_t infrastructure; + infrastructure.scheduler().start(1); + infrastructure.scheduler().stop(); + infrastructure.scheduler().join(); + infrastructure.scheduler().join(); +} + controller.restart_on_exit([&]() { + EXPECT_TRUE(cleaned); + restarted = true; + }); + auto dependent = util::fail_guard([&cleaned]() { + cleaned = true; + }); + } + EXPECT_TRUE(restarted); +} diff --git a/tests/unit/test_logging.cpp b/tests/unit/test_logging.cpp index bd69c9159..4209b7cc9 100644 --- a/tests/unit/test_logging.cpp +++ b/tests/unit/test_logging.cpp @@ -15,6 +15,7 @@ #include #include #include +#include // local includes #include @@ -150,3 +151,45 @@ TEST_P(LogLevelsTest, PutMessage) { ASSERT_TRUE(log_checker::line_contains(log_file, test_message)); } + +TEST_F(LogRotationTest, LoggingOwnerRemovesOnlyItsOwnSink) { + const auto second_path = test_directory / "second.log"; + auto first = logging::init(0, log_path.string()); + auto second = logging::init(0, second_path.string()); + + BOOST_LOG(info) << "both sinks receive this record"; + logging::log_flush(); + EXPECT_NE(read_log_file(log_path).find("both sinks receive this record"), std::string::npos); + EXPECT_NE(read_log_file(second_path).find("both sinks receive this record"), std::string::npos); + + first.reset(); + BOOST_LOG(info) << "remaining sink receives this record"; + logging::log_flush(); + EXPECT_EQ(read_log_file(log_path).find("remaining sink receives this record"), std::string::npos); + EXPECT_NE(read_log_file(second_path).find("remaining sink receives this record"), std::string::npos); +} + +TEST_F(LogRotationTest, ManagedLoggerAcceptsConcurrentWriters) { + auto owner = logging::init(0, log_path.string()); + std::vector writers; + for (int writer = 0; writer < 4; ++writer) { + writers.emplace_back([writer]() { + for (int record = 0; record < 20; ++record) { + BOOST_LOG(info) << std::format("writer {} record {}", writer, record); + } + }); + } + writers.clear(); + owner.reset(); + + const auto content = read_log_file(log_path); + for (int writer = 0; writer < 4; ++writer) { + for (int record = 0; record < 20; ++record) { + EXPECT_NE(content.find(std::format("writer {} record {}", writer, record)), std::string::npos); + } + } +} + +TEST_F(BaseTest, RejectsUnsupportedLoggerSeverity) { + EXPECT_THROW(logging::logger_t {99}.get(), std::invalid_argument); +} diff --git a/tests/unit/test_thread_safe.cpp b/tests/unit/test_thread_safe.cpp index 8ef951e14..d0e52597e 100644 --- a/tests/unit/test_thread_safe.cpp +++ b/tests/unit/test_thread_safe.cpp @@ -45,3 +45,42 @@ TEST(ThreadSafeQueue, RejectsItemsAfterStop) { EXPECT_FALSE(queue.raise(1)); } + +TEST(ThreadSafeShared, InitializesIndependentAutomaticOwnersAndRecreatesReleasedValues) { + int first_constructions = 0; + int second_constructions = 0; + int destructions = 0; + auto first = safe::make_shared([&](int &value) { + value = ++first_constructions; + return 0; + }, + [&](int &) { + ++destructions; + }); + auto second = safe::make_shared([&](int &value) { + value = 100 + ++second_constructions; + return 0; + }, + [&](int &) { + ++destructions; + }); + + { + auto first_value = first.ref(); + auto second_value = second.ref(); + ASSERT_TRUE(first_value); + ASSERT_TRUE(second_value); + EXPECT_EQ(*first_value.get(), 1); + EXPECT_EQ(*second_value.get(), 101); + auto same_first_value = first.ref(); + EXPECT_EQ(same_first_value.get(), first_value.get()); + EXPECT_EQ(first_constructions, 1); + } + EXPECT_EQ(destructions, 2); + { + auto recreated = first.ref(); + ASSERT_TRUE(recreated); + EXPECT_EQ(*recreated.get(), 2); + } + EXPECT_EQ(destructions, 3); +}